xml-fold.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. CodeMirror.tagRangeFinder = (function() {
  2. var nameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
  3. var nameChar = nameStartChar + "\-\:\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
  4. var xmlTagStart = new RegExp("<(/?)([" + nameStartChar + "][" + nameChar + "]*)", "g");
  5. return function(cm, start) {
  6. var line = start.line, ch = start.ch, lineText = cm.getLine(line);
  7. function nextLine() {
  8. if (line >= cm.lastLine()) return;
  9. ch = 0;
  10. lineText = cm.getLine(++line);
  11. return true;
  12. }
  13. function toTagEnd() {
  14. for (;;) {
  15. var gt = lineText.indexOf(">", ch);
  16. if (gt == -1) { if (nextLine()) continue; else return; }
  17. var lastSlash = lineText.lastIndexOf("/", gt);
  18. var selfClose = lastSlash > -1 && /^\s*$/.test(lineText.slice(lastSlash + 1, gt));
  19. ch = gt + 1;
  20. return selfClose ? "selfClose" : "regular";
  21. }
  22. }
  23. function toNextTag() {
  24. for (;;) {
  25. xmlTagStart.lastIndex = ch;
  26. var found = xmlTagStart.exec(lineText);
  27. if (!found) { if (nextLine()) continue; else return; }
  28. ch = found.index + found[0].length;
  29. return found;
  30. }
  31. }
  32. var stack = [], startCh;
  33. for (;;) {
  34. var openTag = toNextTag(), end;
  35. if (!openTag || line != start.line || !(end = toTagEnd())) return;
  36. if (!openTag[1] && end != "selfClose") {
  37. stack.push(openTag[2]);
  38. startCh = ch;
  39. break;
  40. }
  41. }
  42. for (;;) {
  43. var next = toNextTag(), end, tagLine = line, tagCh = ch - (next ? next[0].length : 0);
  44. if (!next || !(end = toTagEnd())) return;
  45. if (end == "selfClose") continue;
  46. if (next[1]) { // closing tag
  47. for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == next[2]) {
  48. stack.length = i;
  49. break;
  50. }
  51. if (!stack.length) return {
  52. from: CodeMirror.Pos(start.line, startCh),
  53. to: CodeMirror.Pos(tagLine, tagCh)
  54. };
  55. } else { // opening tag
  56. stack.push(next[2]);
  57. }
  58. }
  59. };
  60. })();