comment-fold.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. CodeMirror.registerHelper("fold", "comment", function(cm, start) {
  2. var mode = cm.getModeAt(start), startToken = mode.blockCommentStart, endToken = mode.blockCommentEnd;
  3. if (!startToken || !endToken) return;
  4. var line = start.line, lineText = cm.getLine(line);
  5. var startCh;
  6. for (var at = start.ch, pass = 0;;) {
  7. var found = at <= 0 ? -1 : lineText.lastIndexOf(startToken, at - 1);
  8. if (found == -1) {
  9. if (pass == 1) return;
  10. pass = 1;
  11. at = lineText.length;
  12. continue;
  13. }
  14. if (pass == 1 && found < start.ch) return;
  15. if (/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1)))) {
  16. startCh = found + startToken.length;
  17. break;
  18. }
  19. at = found - 1;
  20. }
  21. var depth = 1, lastLine = cm.lastLine(), end, endCh;
  22. outer: for (var i = line; i <= lastLine; ++i) {
  23. var text = cm.getLine(i), pos = i == line ? startCh : 0;
  24. for (;;) {
  25. var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
  26. if (nextOpen < 0) nextOpen = text.length;
  27. if (nextClose < 0) nextClose = text.length;
  28. pos = Math.min(nextOpen, nextClose);
  29. if (pos == text.length) break;
  30. if (pos == nextOpen) ++depth;
  31. else if (!--depth) { end = i; endCh = pos; break outer; }
  32. ++pos;
  33. }
  34. }
  35. if (end == null || line == end && endCh == startCh) return;
  36. return {from: CodeMirror.Pos(line, startCh),
  37. to: CodeMirror.Pos(end, endCh)};
  38. });