indent-fold.js 1.6 KB

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