1 | // CodeMirror, copyright (c) by Marijn Haverbeke and others |
---|
2 | // Distributed under an MIT license: http://codemirror.net/LICENSE |
---|
3 | |
---|
4 | (function(mod) { |
---|
5 | if (typeof exports == "object" && typeof module == "object") // CommonJS |
---|
6 | mod(require("../../lib/codemirror")); |
---|
7 | else if (typeof define == "function" && define.amd) // AMD |
---|
8 | define(["../../lib/codemirror"], mod); |
---|
9 | else // Plain browser env |
---|
10 | mod(CodeMirror); |
---|
11 | })(function(CodeMirror) { |
---|
12 | "use strict"; |
---|
13 | |
---|
14 | CodeMirror.registerHelper("fold", "markdown", function(cm, start) { |
---|
15 | var maxDepth = 100; |
---|
16 | |
---|
17 | function isHeader(lineNo) { |
---|
18 | var tokentype = cm.getTokenTypeAt(CodeMirror.Pos(lineNo, 0)); |
---|
19 | return tokentype && /\bheader\b/.test(tokentype); |
---|
20 | } |
---|
21 | |
---|
22 | function headerLevel(lineNo, line, nextLine) { |
---|
23 | var match = line && line.match(/^#+/); |
---|
24 | if (match && isHeader(lineNo)) return match[0].length; |
---|
25 | match = nextLine && nextLine.match(/^[=\-]+\s*$/); |
---|
26 | if (match && isHeader(lineNo + 1)) return nextLine[0] == "=" ? 1 : 2; |
---|
27 | return maxDepth; |
---|
28 | } |
---|
29 | |
---|
30 | var firstLine = cm.getLine(start.line), nextLine = cm.getLine(start.line + 1); |
---|
31 | var level = headerLevel(start.line, firstLine, nextLine); |
---|
32 | if (level === maxDepth) return undefined; |
---|
33 | |
---|
34 | var lastLineNo = cm.lastLine(); |
---|
35 | var end = start.line, nextNextLine = cm.getLine(end + 2); |
---|
36 | while (end < lastLineNo) { |
---|
37 | if (headerLevel(end + 1, nextLine, nextNextLine) <= level) break; |
---|
38 | ++end; |
---|
39 | nextLine = nextNextLine; |
---|
40 | nextNextLine = cm.getLine(end + 2); |
---|
41 | } |
---|
42 | |
---|
43 | return { |
---|
44 | from: CodeMirror.Pos(start.line, firstLine.length), |
---|
45 | to: CodeMirror.Pos(end, cm.getLine(end).length) |
---|
46 | }; |
---|
47 | }); |
---|
48 | |
---|
49 | }); |
---|