markdown-fold.js 1.4 KB

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