indent-fold.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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", "indent", function(cm, start) {
  11. var tabSize = cm.getOption("tabSize"), firstLine = cm.getLine(start.line);
  12. if (!/\S/.test(firstLine)) return;
  13. var getIndent = function(line) {
  14. return CodeMirror.countColumn(line, null, tabSize);
  15. };
  16. var myIndent = getIndent(firstLine);
  17. var lastLineInFold = null;
  18. // Go through lines until we find a line that definitely doesn't belong in
  19. // the block we're folding, or to the end.
  20. for (var i = start.line + 1, end = cm.lastLine(); i <= end; ++i) {
  21. var curLine = cm.getLine(i);
  22. var curIndent = getIndent(curLine);
  23. if (curIndent > myIndent) {
  24. // Lines with a greater indent are considered part of the block.
  25. lastLineInFold = i;
  26. } else if (!/\S/.test(curLine)) {
  27. // Empty lines might be breaks within the block we're trying to fold.
  28. } else {
  29. // A non-empty line at an indent equal to or less than ours marks the
  30. // start of another block.
  31. break;
  32. }
  33. }
  34. if (lastLineInFold) return {
  35. from: CodeMirror.Pos(start.line, firstLine.length),
  36. to: CodeMirror.Pos(lastLineInFold, cm.getLine(lastLineInFold).length)
  37. };
  38. });
  39. });