| 1 |
import { foldService } from "@codemirror/language"; |
| 2 |
|
| 3 |
const MAXDEPTH = 100; |
| 4 |
|
| 5 |
function headerLevel(line: string): number { |
| 6 |
const match = /^\*+/.exec(line); |
| 7 |
return match?.[0]?.length ?? MAXDEPTH; |
| 8 |
} |
| 9 |
|
| 10 |
export const beancountFold = foldService.of(({ doc }, lineStart, lineEnd) => { |
| 11 |
const startLine = doc.lineAt(lineStart); |
| 12 |
const totalLines = doc.lines; |
| 13 |
const level = headerLevel(startLine.text); |
| 14 |
if (level === MAXDEPTH) { |
| 15 |
return null; |
| 16 |
} |
| 17 |
let lineNo = startLine.number; |
| 18 |
let end = startLine.to; |
| 19 |
while (lineNo < totalLines) { |
| 20 |
lineNo += 1; |
| 21 |
const line = doc.line(lineNo); |
| 22 |
if (headerLevel(line.text) <= level) { |
| 23 |
break; |
| 24 |
} |
| 25 |
end = line.to; |
| 26 |
} |
| 27 |
return { from: lineEnd, to: end }; |
| 28 |
}); |