/
index.ts
62 lines (48 loc) · 1.39 KB
/
index.ts
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
import { foldService } from '@codemirror/language';
const countLeadingSpaces = (str: string) => {
let count = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === ' ') {
count++;
} else if (str[i] === '\t') {
count += 4;
} else {
break;
}
}
return count;
};
const isEmptyLine = (text: string) => {
return /^[ \t]*$/.test(text);
};
export const foldByIndent = () => {
return foldService.of((state, lineStart, lineEnd) => {
const line = state.doc.lineAt(lineStart);
const lineCount = state.doc.lines;
let indents = countLeadingSpaces(line.text);
let foldStart = lineStart;
let foldEnd = lineEnd;
let nextLine = line;
while (nextLine.number < lineCount) {
nextLine = state.doc.line(nextLine.number + 1);
if (nextLine.text === '' || isEmptyLine(nextLine.text)) continue;
let nextIndents = countLeadingSpaces(nextLine.text);
if (nextIndents > indents && !isEmptyLine(nextLine.text)) {
foldEnd = nextLine.to;
} else {
break;
}
}
if (
state.doc.lineAt(foldStart).number === state.doc.lineAt(foldEnd).number
) {
return null;
}
foldStart = line.to;
const lineAtFoldStart = state.doc.lineAt(foldStart);
if (lineAtFoldStart.text === '' || isEmptyLine(lineAtFoldStart.text)) {
return null;
}
return { from: foldStart, to: foldEnd };
});
};