-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathregion-fold.js
More file actions
74 lines (67 loc) · 3.11 KB
/
region-fold.js
File metadata and controls
74 lines (67 loc) · 3.11 KB
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
// Function based on brace-fold.js addon in CodeMirror Library with minor altering.
// Modified for brackets by Patrick Oladimeji.
// CodeMirror 4.1.1, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, eqeq:true */
/*global define, brackets*/
define(function (require, exports, module) {
"use strict";
var CodeMirror = brackets.getModule("thirdparty/CodeMirror2/lib/codemirror"),
Preferences = require("Preferences"),
space = /\s/;
function regionFold(cm, start) {
var startWord = Preferences.get("startRegionWord"),
endWord = Preferences.get("endRegionWord"),
startRegionRegex = new RegExp("\\W+" + startWord, ["i"]),
endRegionRegex = new RegExp("\\W+" + endWord, ["i"]);
var line = start.line, i, j;
var startCh = 0, stack = [], token;
var lastLine = cm.lastLine(), end, endCh, nextOpen, nextClose;
//no need to fold on single line files
if (line === lastLine) {
return;
}
for (i = line; i <= lastLine; ++i) {
var text = cm.getLine(i), pos = startCh;
for (j = pos; j < text.length; true) {
//skip all blank lines at begining of text
if (space.test(text[j])) {
j++;
} else {
token = cm.getTokenAt(CodeMirror.Pos(i, j + 1));
if (token) {
if (token.string.length && token.type === "comment") {
nextOpen = token.string.toLowerCase().match(startRegionRegex) ?
(token.start + token.string.toLowerCase().indexOf(startWord)) : -1;
nextClose = token.string.toLowerCase().match(endRegionRegex) ? token.end : -1;
if (nextOpen > -1) {
stack.push(nextOpen);
}
if (nextClose > -1) {
if (stack.length === 1) {
endCh = nextClose;
end = i;
return {from: CodeMirror.Pos(line, stack[0]),
to: CodeMirror.Pos(end, endCh)};
}
stack.pop();
}
} else {
break; //break out of loop if the first non-space character is not a comment
}
}
j = token ? token.end + 1 : text.length;
}
}
if (stack.length === 0) {
break;
}
}
if (end === null || end === undefined || (line == end && endCh == startCh)) {
return;
}
return {from: CodeMirror.Pos(line, stack[0]),
to: CodeMirror.Pos(end, endCh)};
}
module.exports = regionFold;
});