1
0

markdown-fold.js 1.6 KB

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