indent-fold.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. function lineIndent(cm, lineNo) {
  15. var text = cm.getLine(lineNo)
  16. var spaceTo = text.search(/\S/)
  17. if (spaceTo == -1 || /\bcomment\b/.test(cm.getTokenTypeAt(CodeMirror.Pos(lineNo, spaceTo + 1)))) return -1
  18. return CodeMirror.countColumn(text, null, cm.getOption('tabSize'))
  19. }
  20. CodeMirror.registerHelper('fold', 'indent', function (cm, start) {
  21. var myIndent = lineIndent(cm, start.line)
  22. if (myIndent < 0) return
  23. var lastLineInFold = null
  24. // Go through lines until we find a line that definitely doesn't belong in
  25. // the block we're folding, or to the end.
  26. for (var i = start.line + 1, end = cm.lastLine(); i <= end; ++i) {
  27. var indent = lineIndent(cm, i)
  28. if (indent == -1) {
  29. } else if (indent > myIndent) {
  30. // Lines with a greater indent are considered part of the block.
  31. lastLineInFold = i
  32. } else {
  33. // If this line has non-space, non-comment content, and is
  34. // indented less or equal to the start line, it is the start of
  35. // another block.
  36. break
  37. }
  38. }
  39. if (lastLineInFold)
  40. return {
  41. from: CodeMirror.Pos(start.line, cm.getLine(start.line).length),
  42. to: CodeMirror.Pos(lastLineInFold, cm.getLine(lastLineInFold).length),
  43. }
  44. })
  45. })