comment-fold.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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.registerGlobalHelper("fold", "comment", function(mode) {
  11. return mode.blockCommentStart && mode.blockCommentEnd;
  12. }, function(cm, start) {
  13. var mode = cm.getModeAt(start), startToken = mode.blockCommentStart, endToken = mode.blockCommentEnd;
  14. if (!startToken || !endToken) return;
  15. var line = start.line, lineText = cm.getLine(line);
  16. var startCh;
  17. for (var at = start.ch, pass = 0;;) {
  18. var found = at <= 0 ? -1 : lineText.lastIndexOf(startToken, at - 1);
  19. if (found == -1) {
  20. if (pass == 1) return;
  21. pass = 1;
  22. at = lineText.length;
  23. continue;
  24. }
  25. if (pass == 1 && found < start.ch) return;
  26. if (/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1)))) {
  27. startCh = found + startToken.length;
  28. break;
  29. }
  30. at = found - 1;
  31. }
  32. var depth = 1, lastLine = cm.lastLine(), end, endCh;
  33. outer: for (var i = line; i <= lastLine; ++i) {
  34. var text = cm.getLine(i), pos = i == line ? startCh : 0;
  35. for (;;) {
  36. var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
  37. if (nextOpen < 0) nextOpen = text.length;
  38. if (nextClose < 0) nextClose = text.length;
  39. pos = Math.min(nextOpen, nextClose);
  40. if (pos == text.length) break;
  41. if (pos == nextOpen) ++depth;
  42. else if (!--depth) { end = i; endCh = pos; break outer; }
  43. ++pos;
  44. }
  45. }
  46. if (end == null || line == end && endCh == startCh) return;
  47. return {from: CodeMirror.Pos(line, startCh),
  48. to: CodeMirror.Pos(end, endCh)};
  49. });
  50. });