comment-fold.js 2.0 KB

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