markdown-fold.js 1.8 KB

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