github.com/elliott5/community@v0.14.1-0.20160709191136-823126fb026a/app/public/codemirror/addon/fold/comment-fold.js (about)

     1  // CodeMirror, copyright (c) by Marijn Haverbeke and others
     2  // Distributed under an MIT license: http://codemirror.net/LICENSE
     3  
     4  (function(mod) {
     5    if (typeof exports == "object" && typeof module == "object") // CommonJS
     6      mod(require("../../lib/codemirror"));
     7    else if (typeof define == "function" && define.amd) // AMD
     8      define(["../../lib/codemirror"], mod);
     9    else // Plain browser env
    10      mod(CodeMirror);
    11  })(function(CodeMirror) {
    12  "use strict";
    13  
    14  CodeMirror.registerGlobalHelper("fold", "comment", function(mode) {
    15    return mode.blockCommentStart && mode.blockCommentEnd;
    16  }, function(cm, start) {
    17    var mode = cm.getModeAt(start), startToken = mode.blockCommentStart, endToken = mode.blockCommentEnd;
    18    if (!startToken || !endToken) return;
    19    var line = start.line, lineText = cm.getLine(line);
    20  
    21    var startCh;
    22    for (var at = start.ch, pass = 0;;) {
    23      var found = at <= 0 ? -1 : lineText.lastIndexOf(startToken, at - 1);
    24      if (found == -1) {
    25        if (pass == 1) return;
    26        pass = 1;
    27        at = lineText.length;
    28        continue;
    29      }
    30      if (pass == 1 && found < start.ch) return;
    31      if (/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1))) &&
    32          (lineText.slice(found - endToken.length, found) == endToken ||
    33           !/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found))))) {
    34        startCh = found + startToken.length;
    35        break;
    36      }
    37      at = found - 1;
    38    }
    39  
    40    var depth = 1, lastLine = cm.lastLine(), end, endCh;
    41    outer: for (var i = line; i <= lastLine; ++i) {
    42      var text = cm.getLine(i), pos = i == line ? startCh : 0;
    43      for (;;) {
    44        var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
    45        if (nextOpen < 0) nextOpen = text.length;
    46        if (nextClose < 0) nextClose = text.length;
    47        pos = Math.min(nextOpen, nextClose);
    48        if (pos == text.length) break;
    49        if (pos == nextOpen) ++depth;
    50        else if (!--depth) { end = i; endCh = pos; break outer; }
    51        ++pos;
    52      }
    53    }
    54    if (end == null || line == end && endCh == startCh) return;
    55    return {from: CodeMirror.Pos(line, startCh),
    56            to: CodeMirror.Pos(end, endCh)};
    57  });
    58  
    59  });