-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathorgmode-fold.js
77 lines (70 loc) · 2.43 KB
/
orgmode-fold.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.registerHelper("fold", "orgmode", function(cm, start) {
// init
const levelToMatch = headerLevel(start.line);
// no folding needed
if(levelToMatch === null) return;
// find folding limits
const lastLine = cm.lastLine();
let end = start.line;
while(end < lastLine){
end += 1;
let level = headerLevel(end);
if(level && level <= levelToMatch) {
end = end - 1;
break;
};
}
return {
from: CodeMirror.Pos(start.line, cm.getLine(start.line).length),
to: CodeMirror.Pos(end, cm.getLine(end).length)
};
function headerLevel(lineNo) {
var line = cm.getLine(lineNo);
var match = /^\*+/.exec(line);
if(match && match.length === 1 && /header/.test(cm.getTokenTypeAt(CodeMirror.Pos(lineNo, 0)))){
return match[0].length;
}
return null;
}
});
CodeMirror.registerGlobalHelper("fold", "drawer", function(mode) {
return mode.name === 'orgmode' ? true : false;
}, function(cm, start) {
const drawer = isBeginningOfADrawer(start.line);
if(drawer === false) return;
// find folding limits
const lastLine = cm.lastLine();
let end = start.line;
while(end < lastLine){
end += 1;
if(isEndOfADrawer(end)){
break;
}
}
return {
from: CodeMirror.Pos(start.line, cm.getLine(start.line).length),
to: CodeMirror.Pos(end, cm.getLine(end).length)
};
function isBeginningOfADrawer(lineNo) {
var line = cm.getLine(lineNo);
var match = /^\:.*\:$/.exec(line);
if(match && match.length === 1 && match[0] !== ':END:'){
return true;
}
return false;
}
function isEndOfADrawer(lineNo){
var line = cm.getLine(lineNo);
return line.trim() === ':END:' ? true : false;
}
});
});