dew/src/main/resources/org/apidesign/bck2brwsr/dew/js/codemirror/codemirror.js
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 23 Jan 2013 13:18:46 +0100
branchdew
changeset 544 08ffdc3938e7
parent 460 launcher/src/main/resources/org/apidesign/bck2brwsr/dew/js/codemirror/codemirror.js@c0f1788183dd
permissions -rw-r--r--
Moving Development Environment for Web to own project
phrebejk@460
     1
// CodeMirror version 3.0
phrebejk@460
     2
//
phrebejk@460
     3
// CodeMirror is the only global var we claim
phrebejk@460
     4
window.CodeMirror = (function() {
phrebejk@460
     5
  "use strict";
phrebejk@460
     6
phrebejk@460
     7
  // BROWSER SNIFFING
phrebejk@460
     8
phrebejk@460
     9
  // Crude, but necessary to handle a number of hard-to-feature-detect
phrebejk@460
    10
  // bugs and behavior differences.
phrebejk@460
    11
  var gecko = /gecko\/\d/i.test(navigator.userAgent);
phrebejk@460
    12
  var ie = /MSIE \d/.test(navigator.userAgent);
phrebejk@460
    13
  var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent);
phrebejk@460
    14
  var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
phrebejk@460
    15
  var webkit = /WebKit\//.test(navigator.userAgent);
phrebejk@460
    16
  var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
phrebejk@460
    17
  var chrome = /Chrome\//.test(navigator.userAgent);
phrebejk@460
    18
  var opera = /Opera\//.test(navigator.userAgent);
phrebejk@460
    19
  var safari = /Apple Computer/.test(navigator.vendor);
phrebejk@460
    20
  var khtml = /KHTML\//.test(navigator.userAgent);
phrebejk@460
    21
  var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent);
phrebejk@460
    22
  var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
phrebejk@460
    23
  var phantom = /PhantomJS/.test(navigator.userAgent);
phrebejk@460
    24
phrebejk@460
    25
  var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
phrebejk@460
    26
  // This is woefully incomplete. Suggestions for alternative methods welcome.
phrebejk@460
    27
  var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|IEMobile/i.test(navigator.userAgent);
phrebejk@460
    28
  var mac = ios || /Mac/.test(navigator.platform);
phrebejk@460
    29
phrebejk@460
    30
  // Optimize some code when these features are not used
phrebejk@460
    31
  var sawReadOnlySpans = false, sawCollapsedSpans = false;
phrebejk@460
    32
phrebejk@460
    33
  // CONSTRUCTOR
phrebejk@460
    34
phrebejk@460
    35
  function CodeMirror(place, options) {
phrebejk@460
    36
    if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
phrebejk@460
    37
    
phrebejk@460
    38
    this.options = options = options || {};
phrebejk@460
    39
    // Determine effective options based on given values and defaults.
phrebejk@460
    40
    for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt))
phrebejk@460
    41
      options[opt] = defaults[opt];
phrebejk@460
    42
    setGuttersForLineNumbers(options);
phrebejk@460
    43
phrebejk@460
    44
    var display = this.display = makeDisplay(place);
phrebejk@460
    45
    display.wrapper.CodeMirror = this;
phrebejk@460
    46
    updateGutters(this);
phrebejk@460
    47
    if (options.autofocus && !mobile) focusInput(this);
phrebejk@460
    48
phrebejk@460
    49
    this.view = makeView(new BranchChunk([new LeafChunk([makeLine("", null, textHeight(display))])]));
phrebejk@460
    50
    this.nextOpId = 0;
phrebejk@460
    51
    loadMode(this);
phrebejk@460
    52
    themeChanged(this);
phrebejk@460
    53
    if (options.lineWrapping)
phrebejk@460
    54
      this.display.wrapper.className += " CodeMirror-wrap";
phrebejk@460
    55
phrebejk@460
    56
    // Initialize the content.
phrebejk@460
    57
    this.setValue(options.value || "");
phrebejk@460
    58
    // Override magic textarea content restore that IE sometimes does
phrebejk@460
    59
    // on our hidden textarea on reload
phrebejk@460
    60
    if (ie) setTimeout(bind(resetInput, this, true), 20);
phrebejk@460
    61
    this.view.history = makeHistory();
phrebejk@460
    62
phrebejk@460
    63
    registerEventHandlers(this);
phrebejk@460
    64
    // IE throws unspecified error in certain cases, when
phrebejk@460
    65
    // trying to access activeElement before onload
phrebejk@460
    66
    var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { }
phrebejk@460
    67
    if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20);
phrebejk@460
    68
    else onBlur(this);
phrebejk@460
    69
phrebejk@460
    70
    operation(this, function() {
phrebejk@460
    71
      for (var opt in optionHandlers)
phrebejk@460
    72
        if (optionHandlers.propertyIsEnumerable(opt))
phrebejk@460
    73
          optionHandlers[opt](this, options[opt], Init);
phrebejk@460
    74
      for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
phrebejk@460
    75
    })();
phrebejk@460
    76
  }
phrebejk@460
    77
phrebejk@460
    78
  // DISPLAY CONSTRUCTOR
phrebejk@460
    79
phrebejk@460
    80
  function makeDisplay(place) {
phrebejk@460
    81
    var d = {};
phrebejk@460
    82
    var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none;");
phrebejk@460
    83
    input.setAttribute("wrap", "off"); input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off");
phrebejk@460
    84
    // Wraps and hides input textarea
phrebejk@460
    85
    d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
phrebejk@460
    86
    // The actual fake scrollbars.
phrebejk@460
    87
    d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar");
phrebejk@460
    88
    d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar");
phrebejk@460
    89
    d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
phrebejk@460
    90
    // DIVs containing the selection and the actual code
phrebejk@460
    91
    d.lineDiv = elt("div");
phrebejk@460
    92
    d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
phrebejk@460
    93
    // Blinky cursor, and element used to ensure cursor fits at the end of a line
phrebejk@460
    94
    d.cursor = elt("pre", "\u00a0", "CodeMirror-cursor");
phrebejk@460
    95
    // Secondary cursor, shown when on a 'jump' in bi-directional text
phrebejk@460
    96
    d.otherCursor = elt("pre", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor");
phrebejk@460
    97
    // Used to measure text size
phrebejk@460
    98
    d.measure = elt("div", null, "CodeMirror-measure");
phrebejk@460
    99
    // Wraps everything that needs to exist inside the vertically-padded coordinate system
phrebejk@460
   100
    d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor],
phrebejk@460
   101
                         null, "position: relative; outline: none");
phrebejk@460
   102
    // Moved around its parent to cover visible view
phrebejk@460
   103
    d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
phrebejk@460
   104
    // Set to the height of the text, causes scrolling
phrebejk@460
   105
    d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
phrebejk@460
   106
    // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers
phrebejk@460
   107
    d.heightForcer = elt("div", "\u00a0", null, "position: absolute; height: " + scrollerCutOff + "px");
phrebejk@460
   108
    // Will contain the gutters, if any
phrebejk@460
   109
    d.gutters = elt("div", null, "CodeMirror-gutters");
phrebejk@460
   110
    d.lineGutter = null;
phrebejk@460
   111
    // Helper element to properly size the gutter backgrounds
phrebejk@460
   112
    var scrollerInner = elt("div", [d.sizer, d.heightForcer, d.gutters], null, "position: relative; min-height: 100%");
phrebejk@460
   113
    // Provides scrolling
phrebejk@460
   114
    d.scroller = elt("div", [scrollerInner], "CodeMirror-scroll");
phrebejk@460
   115
    d.scroller.setAttribute("tabIndex", "-1");
phrebejk@460
   116
    // The element in which the editor lives.
phrebejk@460
   117
    d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV,
phrebejk@460
   118
                            d.scrollbarFiller, d.scroller], "CodeMirror");
phrebejk@460
   119
    // Work around IE7 z-index bug
phrebejk@460
   120
    if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
phrebejk@460
   121
    if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper);
phrebejk@460
   122
phrebejk@460
   123
    // Needed to hide big blue blinking cursor on Mobile Safari
phrebejk@460
   124
    if (ios) input.style.width = "0px";
phrebejk@460
   125
    if (!webkit) d.scroller.draggable = true;
phrebejk@460
   126
    // Needed to handle Tab key in KHTML
phrebejk@460
   127
    if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
phrebejk@460
   128
    // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
phrebejk@460
   129
    else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px";
phrebejk@460
   130
phrebejk@460
   131
    // Current visible range (may be bigger than the view window).
phrebejk@460
   132
    d.viewOffset = d.showingFrom = d.showingTo = d.lastSizeC = 0;
phrebejk@460
   133
phrebejk@460
   134
    // Used to only resize the line number gutter when necessary (when
phrebejk@460
   135
    // the amount of lines crosses a boundary that makes its width change)
phrebejk@460
   136
    d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
phrebejk@460
   137
    // See readInput and resetInput
phrebejk@460
   138
    d.prevInput = "";
phrebejk@460
   139
    // Set to true when a non-horizontal-scrolling widget is added. As
phrebejk@460
   140
    // an optimization, widget aligning is skipped when d is false.
phrebejk@460
   141
    d.alignWidgets = false;
phrebejk@460
   142
    // Flag that indicates whether we currently expect input to appear
phrebejk@460
   143
    // (after some event like 'keypress' or 'input') and are polling
phrebejk@460
   144
    // intensively.
phrebejk@460
   145
    d.pollingFast = false;
phrebejk@460
   146
    // Self-resetting timeout for the poller
phrebejk@460
   147
    d.poll = new Delayed();
phrebejk@460
   148
    // True when a drag from the editor is active
phrebejk@460
   149
    d.draggingText = false;
phrebejk@460
   150
phrebejk@460
   151
    d.cachedCharWidth = d.cachedTextHeight = null;
phrebejk@460
   152
    d.measureLineCache = [];
phrebejk@460
   153
    d.measureLineCachePos = 0;
phrebejk@460
   154
phrebejk@460
   155
    // Tracks when resetInput has punted to just putting a short
phrebejk@460
   156
    // string instead of the (large) selection.
phrebejk@460
   157
    d.inaccurateSelection = false;
phrebejk@460
   158
phrebejk@460
   159
    // Used to adjust overwrite behaviour when a paste has been
phrebejk@460
   160
    // detected
phrebejk@460
   161
    d.pasteIncoming = false;
phrebejk@460
   162
phrebejk@460
   163
    return d;
phrebejk@460
   164
  }
phrebejk@460
   165
phrebejk@460
   166
  // VIEW CONSTRUCTOR
phrebejk@460
   167
phrebejk@460
   168
  function makeView(doc) {
phrebejk@460
   169
    var selPos = {line: 0, ch: 0};
phrebejk@460
   170
    return {
phrebejk@460
   171
      doc: doc,
phrebejk@460
   172
      // frontier is the point up to which the content has been parsed,
phrebejk@460
   173
      frontier: 0, highlight: new Delayed(),
phrebejk@460
   174
      sel: {from: selPos, to: selPos, head: selPos, anchor: selPos, shift: false, extend: false},
phrebejk@460
   175
      scrollTop: 0, scrollLeft: 0,
phrebejk@460
   176
      overwrite: false, focused: false,
phrebejk@460
   177
      // Tracks the maximum line length so that
phrebejk@460
   178
      // the horizontal scrollbar can be kept
phrebejk@460
   179
      // static when scrolling.
phrebejk@460
   180
      maxLine: getLine(doc, 0),
phrebejk@460
   181
      maxLineLength: 0,
phrebejk@460
   182
      maxLineChanged: false,
phrebejk@460
   183
      suppressEdits: false,
phrebejk@460
   184
      goalColumn: null,
phrebejk@460
   185
      cantEdit: false,
phrebejk@460
   186
      keyMaps: []
phrebejk@460
   187
    };
phrebejk@460
   188
  }
phrebejk@460
   189
phrebejk@460
   190
  // STATE UPDATES
phrebejk@460
   191
phrebejk@460
   192
  // Used to get the editor into a consistent state again when options change.
phrebejk@460
   193
phrebejk@460
   194
  function loadMode(cm) {
phrebejk@460
   195
    var doc = cm.view.doc;
phrebejk@460
   196
    cm.view.mode = CodeMirror.getMode(cm.options, cm.options.mode);
phrebejk@460
   197
    doc.iter(0, doc.size, function(line) { line.stateAfter = null; });
phrebejk@460
   198
    cm.view.frontier = 0;
phrebejk@460
   199
    startWorker(cm, 100);
phrebejk@460
   200
  }
phrebejk@460
   201
phrebejk@460
   202
  function wrappingChanged(cm) {
phrebejk@460
   203
    var doc = cm.view.doc, th = textHeight(cm.display);
phrebejk@460
   204
    if (cm.options.lineWrapping) {
phrebejk@460
   205
      cm.display.wrapper.className += " CodeMirror-wrap";
phrebejk@460
   206
      var perLine = cm.display.scroller.clientWidth / charWidth(cm.display) - 3;
phrebejk@460
   207
      doc.iter(0, doc.size, function(line) {
phrebejk@460
   208
        if (line.height == 0) return;
phrebejk@460
   209
        var guess = Math.ceil(line.text.length / perLine) || 1;
phrebejk@460
   210
        if (guess != 1) updateLineHeight(line, guess * th);
phrebejk@460
   211
      });
phrebejk@460
   212
      cm.display.sizer.style.minWidth = "";
phrebejk@460
   213
    } else {
phrebejk@460
   214
      cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", "");
phrebejk@460
   215
      computeMaxLength(cm.view);
phrebejk@460
   216
      doc.iter(0, doc.size, function(line) {
phrebejk@460
   217
        if (line.height != 0) updateLineHeight(line, th);
phrebejk@460
   218
      });
phrebejk@460
   219
    }
phrebejk@460
   220
    regChange(cm, 0, doc.size);
phrebejk@460
   221
    clearCaches(cm);
phrebejk@460
   222
    setTimeout(function(){updateScrollbars(cm.display, cm.view.doc.height);}, 100);
phrebejk@460
   223
  }
phrebejk@460
   224
phrebejk@460
   225
  function keyMapChanged(cm) {
phrebejk@460
   226
    var style = keyMap[cm.options.keyMap].style;
phrebejk@460
   227
    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
phrebejk@460
   228
      (style ? " cm-keymap-" + style : "");
phrebejk@460
   229
  }
phrebejk@460
   230
phrebejk@460
   231
  function themeChanged(cm) {
phrebejk@460
   232
    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
phrebejk@460
   233
      cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
phrebejk@460
   234
    clearCaches(cm);
phrebejk@460
   235
  }
phrebejk@460
   236
phrebejk@460
   237
  function guttersChanged(cm) {
phrebejk@460
   238
    updateGutters(cm);
phrebejk@460
   239
    updateDisplay(cm, true);
phrebejk@460
   240
  }
phrebejk@460
   241
phrebejk@460
   242
  function updateGutters(cm) {
phrebejk@460
   243
    var gutters = cm.display.gutters, specs = cm.options.gutters;
phrebejk@460
   244
    removeChildren(gutters);
phrebejk@460
   245
    for (var i = 0; i < specs.length; ++i) {
phrebejk@460
   246
      var gutterClass = specs[i];
phrebejk@460
   247
      var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
phrebejk@460
   248
      if (gutterClass == "CodeMirror-linenumbers") {
phrebejk@460
   249
        cm.display.lineGutter = gElt;
phrebejk@460
   250
        gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
phrebejk@460
   251
      }
phrebejk@460
   252
    }
phrebejk@460
   253
    gutters.style.display = i ? "" : "none";
phrebejk@460
   254
  }
phrebejk@460
   255
phrebejk@460
   256
  function lineLength(doc, line) {
phrebejk@460
   257
    if (line.height == 0) return 0;
phrebejk@460
   258
    var len = line.text.length, merged, cur = line;
phrebejk@460
   259
    while (merged = collapsedSpanAtStart(cur)) {
phrebejk@460
   260
      var found = merged.find();
phrebejk@460
   261
      cur = getLine(doc, found.from.line);
phrebejk@460
   262
      len += found.from.ch - found.to.ch;
phrebejk@460
   263
    }
phrebejk@460
   264
    cur = line;
phrebejk@460
   265
    while (merged = collapsedSpanAtEnd(cur)) {
phrebejk@460
   266
      var found = merged.find();
phrebejk@460
   267
      len -= cur.text.length - found.from.ch;
phrebejk@460
   268
      cur = getLine(doc, found.to.line);
phrebejk@460
   269
      len += cur.text.length - found.to.ch;
phrebejk@460
   270
    }
phrebejk@460
   271
    return len;
phrebejk@460
   272
  }
phrebejk@460
   273
phrebejk@460
   274
  function computeMaxLength(view) {
phrebejk@460
   275
    view.maxLine = getLine(view.doc, 0);
phrebejk@460
   276
    view.maxLineLength = lineLength(view.doc, view.maxLine);
phrebejk@460
   277
    view.maxLineChanged = true;
phrebejk@460
   278
    view.doc.iter(1, view.doc.size, function(line) {
phrebejk@460
   279
      var len = lineLength(view.doc, line);
phrebejk@460
   280
      if (len > view.maxLineLength) {
phrebejk@460
   281
        view.maxLineLength = len;
phrebejk@460
   282
        view.maxLine = line;
phrebejk@460
   283
      }
phrebejk@460
   284
    });
phrebejk@460
   285
  }
phrebejk@460
   286
phrebejk@460
   287
  // Make sure the gutters options contains the element
phrebejk@460
   288
  // "CodeMirror-linenumbers" when the lineNumbers option is true.
phrebejk@460
   289
  function setGuttersForLineNumbers(options) {
phrebejk@460
   290
    var found = false;
phrebejk@460
   291
    for (var i = 0; i < options.gutters.length; ++i) {
phrebejk@460
   292
      if (options.gutters[i] == "CodeMirror-linenumbers") {
phrebejk@460
   293
        if (options.lineNumbers) found = true;
phrebejk@460
   294
        else options.gutters.splice(i--, 1);
phrebejk@460
   295
      }
phrebejk@460
   296
    }
phrebejk@460
   297
    if (!found && options.lineNumbers)
phrebejk@460
   298
      options.gutters.push("CodeMirror-linenumbers");
phrebejk@460
   299
  }
phrebejk@460
   300
phrebejk@460
   301
  // SCROLLBARS
phrebejk@460
   302
phrebejk@460
   303
  // Re-synchronize the fake scrollbars with the actual size of the
phrebejk@460
   304
  // content. Optionally force a scrollTop.
phrebejk@460
   305
  function updateScrollbars(d /* display */, docHeight) {
phrebejk@460
   306
    var totalHeight = docHeight + 2 * paddingTop(d);
phrebejk@460
   307
    d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px";
phrebejk@460
   308
    var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight);
phrebejk@460
   309
    var needsH = d.scroller.scrollWidth > d.scroller.clientWidth;
phrebejk@460
   310
    var needsV = scrollHeight > d.scroller.clientHeight;
phrebejk@460
   311
    if (needsV) {
phrebejk@460
   312
      d.scrollbarV.style.display = "block";
phrebejk@460
   313
      d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
phrebejk@460
   314
      d.scrollbarV.firstChild.style.height = 
phrebejk@460
   315
        (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px";
phrebejk@460
   316
    } else d.scrollbarV.style.display = "";
phrebejk@460
   317
    if (needsH) {
phrebejk@460
   318
      d.scrollbarH.style.display = "block";
phrebejk@460
   319
      d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
phrebejk@460
   320
      d.scrollbarH.firstChild.style.width =
phrebejk@460
   321
        (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px";
phrebejk@460
   322
    } else d.scrollbarH.style.display = "";
phrebejk@460
   323
    if (needsH && needsV) {
phrebejk@460
   324
      d.scrollbarFiller.style.display = "block";
phrebejk@460
   325
      d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
phrebejk@460
   326
    } else d.scrollbarFiller.style.display = "";
phrebejk@460
   327
phrebejk@460
   328
    if (mac_geLion && scrollbarWidth(d.measure) === 0)
phrebejk@460
   329
      d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px";
phrebejk@460
   330
  }
phrebejk@460
   331
phrebejk@460
   332
  function visibleLines(display, doc, viewPort) {
phrebejk@460
   333
    var top = display.scroller.scrollTop, height = display.wrapper.clientHeight;
phrebejk@460
   334
    if (typeof viewPort == "number") top = viewPort;
phrebejk@460
   335
    else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;}
phrebejk@460
   336
    top = Math.floor(top - paddingTop(display));
phrebejk@460
   337
    var bottom = Math.ceil(top + height);
phrebejk@460
   338
    return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)};
phrebejk@460
   339
  }
phrebejk@460
   340
phrebejk@460
   341
  // LINE NUMBERS
phrebejk@460
   342
phrebejk@460
   343
  function alignHorizontally(cm) {
phrebejk@460
   344
    var display = cm.display;
phrebejk@460
   345
    if (!display.alignWidgets && !display.gutters.firstChild) return;
phrebejk@460
   346
    var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.view.scrollLeft;
phrebejk@460
   347
    var gutterW = display.gutters.offsetWidth, l = comp + "px";
phrebejk@460
   348
    for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) {
phrebejk@460
   349
      for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l;
phrebejk@460
   350
    }
phrebejk@460
   351
    display.gutters.style.left = (comp + gutterW) + "px";
phrebejk@460
   352
  }
phrebejk@460
   353
phrebejk@460
   354
  function maybeUpdateLineNumberWidth(cm) {
phrebejk@460
   355
    if (!cm.options.lineNumbers) return false;
phrebejk@460
   356
    var doc = cm.view.doc, last = lineNumberFor(cm.options, doc.size - 1), display = cm.display;
phrebejk@460
   357
    if (last.length != display.lineNumChars) {
phrebejk@460
   358
      var test = display.measure.appendChild(elt("div", [elt("div", last)],
phrebejk@460
   359
                                                 "CodeMirror-linenumber CodeMirror-gutter-elt"));
phrebejk@460
   360
      var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
phrebejk@460
   361
      display.lineGutter.style.width = "";
phrebejk@460
   362
      display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
phrebejk@460
   363
      display.lineNumWidth = display.lineNumInnerWidth + padding;
phrebejk@460
   364
      display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
phrebejk@460
   365
      display.lineGutter.style.width = display.lineNumWidth + "px";
phrebejk@460
   366
      return true;
phrebejk@460
   367
    }
phrebejk@460
   368
    return false;
phrebejk@460
   369
  }
phrebejk@460
   370
phrebejk@460
   371
  function lineNumberFor(options, i) {
phrebejk@460
   372
    return String(options.lineNumberFormatter(i + options.firstLineNumber));
phrebejk@460
   373
  }
phrebejk@460
   374
  function compensateForHScroll(display) {
phrebejk@460
   375
    return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
phrebejk@460
   376
  }
phrebejk@460
   377
phrebejk@460
   378
  // DISPLAY DRAWING
phrebejk@460
   379
phrebejk@460
   380
  function updateDisplay(cm, changes, viewPort) {
phrebejk@460
   381
    var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo;
phrebejk@460
   382
    var updated = updateDisplayInner(cm, changes, viewPort);
phrebejk@460
   383
    if (updated) {
phrebejk@460
   384
      signalLater(cm, cm, "update", cm);
phrebejk@460
   385
      if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo)
phrebejk@460
   386
        signalLater(cm, cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo);
phrebejk@460
   387
    }
phrebejk@460
   388
    updateSelection(cm);
phrebejk@460
   389
    updateScrollbars(cm.display, cm.view.doc.height);
phrebejk@460
   390
phrebejk@460
   391
    return updated;
phrebejk@460
   392
  }
phrebejk@460
   393
phrebejk@460
   394
  // Uses a set of changes plus the current scroll position to
phrebejk@460
   395
  // determine which DOM updates have to be made, and makes the
phrebejk@460
   396
  // updates.
phrebejk@460
   397
  function updateDisplayInner(cm, changes, viewPort) {
phrebejk@460
   398
    var display = cm.display, doc = cm.view.doc;
phrebejk@460
   399
    if (!display.wrapper.clientWidth) {
phrebejk@460
   400
      display.showingFrom = display.showingTo = display.viewOffset = 0;
phrebejk@460
   401
      return;
phrebejk@460
   402
    }
phrebejk@460
   403
phrebejk@460
   404
    // Compute the new visible window
phrebejk@460
   405
    // If scrollTop is specified, use that to determine which lines
phrebejk@460
   406
    // to render instead of the current scrollbar position.
phrebejk@460
   407
    var visible = visibleLines(display, doc, viewPort);
phrebejk@460
   408
    // Bail out if the visible area is already rendered and nothing changed.
phrebejk@460
   409
    if (changes !== true && changes.length == 0 &&
phrebejk@460
   410
        visible.from > display.showingFrom && visible.to < display.showingTo)
phrebejk@460
   411
      return;
phrebejk@460
   412
phrebejk@460
   413
    if (changes && maybeUpdateLineNumberWidth(cm))
phrebejk@460
   414
      changes = true;
phrebejk@460
   415
    display.sizer.style.marginLeft = display.scrollbarH.style.left = display.gutters.offsetWidth + "px";
phrebejk@460
   416
phrebejk@460
   417
    // When merged lines are present, the line that needs to be
phrebejk@460
   418
    // redrawn might not be the one that was changed.
phrebejk@460
   419
    if (changes !== true && sawCollapsedSpans)
phrebejk@460
   420
      for (var i = 0; i < changes.length; ++i) {
phrebejk@460
   421
        var ch = changes[i], merged;
phrebejk@460
   422
        while (merged = collapsedSpanAtStart(getLine(doc, ch.from))) {
phrebejk@460
   423
          var from = merged.find().from.line;
phrebejk@460
   424
          if (ch.diff) ch.diff -= ch.from - from;
phrebejk@460
   425
          ch.from = from;
phrebejk@460
   426
        }
phrebejk@460
   427
      }
phrebejk@460
   428
phrebejk@460
   429
    // Used to determine which lines need their line numbers updated
phrebejk@460
   430
    var positionsChangedFrom = changes === true ? 0 : Infinity;
phrebejk@460
   431
    if (cm.options.lineNumbers && changes && changes !== true)
phrebejk@460
   432
      for (var i = 0; i < changes.length; ++i)
phrebejk@460
   433
        if (changes[i].diff) { positionsChangedFrom = changes[i].from; break; }
phrebejk@460
   434
phrebejk@460
   435
    var from = Math.max(visible.from - cm.options.viewportMargin, 0);
phrebejk@460
   436
    var to = Math.min(doc.size, visible.to + cm.options.viewportMargin);
phrebejk@460
   437
    if (display.showingFrom < from && from - display.showingFrom < 20) from = display.showingFrom;
phrebejk@460
   438
    if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(doc.size, display.showingTo);
phrebejk@460
   439
    if (sawCollapsedSpans) {
phrebejk@460
   440
      from = lineNo(visualLine(doc, getLine(doc, from)));
phrebejk@460
   441
      while (to < doc.size && lineIsHidden(getLine(doc, to))) ++to;
phrebejk@460
   442
    }
phrebejk@460
   443
phrebejk@460
   444
    // Create a range of theoretically intact lines, and punch holes
phrebejk@460
   445
    // in that using the change info.
phrebejk@460
   446
    var intact = changes === true ? [] :
phrebejk@460
   447
      computeIntact([{from: display.showingFrom, to: display.showingTo}], changes);
phrebejk@460
   448
    // Clip off the parts that won't be visible
phrebejk@460
   449
    var intactLines = 0;
phrebejk@460
   450
    for (var i = 0; i < intact.length; ++i) {
phrebejk@460
   451
      var range = intact[i];
phrebejk@460
   452
      if (range.from < from) range.from = from;
phrebejk@460
   453
      if (range.to > to) range.to = to;
phrebejk@460
   454
      if (range.from >= range.to) intact.splice(i--, 1);
phrebejk@460
   455
      else intactLines += range.to - range.from;
phrebejk@460
   456
    }
phrebejk@460
   457
    if (intactLines == to - from && from == display.showingFrom && to == display.showingTo)
phrebejk@460
   458
      return;
phrebejk@460
   459
    intact.sort(function(a, b) {return a.from - b.from;});
phrebejk@460
   460
phrebejk@460
   461
    if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none";
phrebejk@460
   462
    patchDisplay(cm, from, to, intact, positionsChangedFrom);
phrebejk@460
   463
    display.lineDiv.style.display = "";
phrebejk@460
   464
phrebejk@460
   465
    var different = from != display.showingFrom || to != display.showingTo ||
phrebejk@460
   466
      display.lastSizeC != display.wrapper.clientHeight;
phrebejk@460
   467
    // This is just a bogus formula that detects when the editor is
phrebejk@460
   468
    // resized or the font size changes.
phrebejk@460
   469
    if (different) display.lastSizeC = display.wrapper.clientHeight;
phrebejk@460
   470
    display.showingFrom = from; display.showingTo = to;
phrebejk@460
   471
    startWorker(cm, 100);
phrebejk@460
   472
phrebejk@460
   473
    var prevBottom = display.lineDiv.offsetTop;
phrebejk@460
   474
    for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) {
phrebejk@460
   475
      if (ie_lt8) {
phrebejk@460
   476
        var bot = node.offsetTop + node.offsetHeight;
phrebejk@460
   477
        height = bot - prevBottom;
phrebejk@460
   478
        prevBottom = bot;
phrebejk@460
   479
      } else {
phrebejk@460
   480
        var box = node.getBoundingClientRect();
phrebejk@460
   481
        height = box.bottom - box.top;
phrebejk@460
   482
      }
phrebejk@460
   483
      var diff = node.lineObj.height - height;
phrebejk@460
   484
      if (height < 2) height = textHeight(display);
phrebejk@460
   485
      if (diff > .001 || diff < -.001)
phrebejk@460
   486
        updateLineHeight(node.lineObj, height);
phrebejk@460
   487
    }
phrebejk@460
   488
    display.viewOffset = heightAtLine(cm, getLine(doc, from));
phrebejk@460
   489
    // Position the mover div to align with the current virtual scroll position
phrebejk@460
   490
    display.mover.style.top = display.viewOffset + "px";
phrebejk@460
   491
    return true;
phrebejk@460
   492
  }
phrebejk@460
   493
phrebejk@460
   494
  function computeIntact(intact, changes) {
phrebejk@460
   495
    for (var i = 0, l = changes.length || 0; i < l; ++i) {
phrebejk@460
   496
      var change = changes[i], intact2 = [], diff = change.diff || 0;
phrebejk@460
   497
      for (var j = 0, l2 = intact.length; j < l2; ++j) {
phrebejk@460
   498
        var range = intact[j];
phrebejk@460
   499
        if (change.to <= range.from && change.diff) {
phrebejk@460
   500
          intact2.push({from: range.from + diff, to: range.to + diff});
phrebejk@460
   501
        } else if (change.to <= range.from || change.from >= range.to) {
phrebejk@460
   502
          intact2.push(range);
phrebejk@460
   503
        } else {
phrebejk@460
   504
          if (change.from > range.from)
phrebejk@460
   505
            intact2.push({from: range.from, to: change.from});
phrebejk@460
   506
          if (change.to < range.to)
phrebejk@460
   507
            intact2.push({from: change.to + diff, to: range.to + diff});
phrebejk@460
   508
        }
phrebejk@460
   509
      }
phrebejk@460
   510
      intact = intact2;
phrebejk@460
   511
    }
phrebejk@460
   512
    return intact;
phrebejk@460
   513
  }
phrebejk@460
   514
phrebejk@460
   515
  function getDimensions(cm) {
phrebejk@460
   516
    var d = cm.display, left = {}, width = {};
phrebejk@460
   517
    for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
phrebejk@460
   518
      left[cm.options.gutters[i]] = n.offsetLeft;
phrebejk@460
   519
      width[cm.options.gutters[i]] = n.offsetWidth;
phrebejk@460
   520
    }
phrebejk@460
   521
    return {fixedPos: compensateForHScroll(d),
phrebejk@460
   522
            gutterTotalWidth: d.gutters.offsetWidth,
phrebejk@460
   523
            gutterLeft: left,
phrebejk@460
   524
            gutterWidth: width,
phrebejk@460
   525
            wrapperWidth: d.wrapper.clientWidth};
phrebejk@460
   526
  }
phrebejk@460
   527
phrebejk@460
   528
  function patchDisplay(cm, from, to, intact, updateNumbersFrom) {
phrebejk@460
   529
    var dims = getDimensions(cm);
phrebejk@460
   530
    var display = cm.display, lineNumbers = cm.options.lineNumbers;
phrebejk@460
   531
    // IE does bad things to nodes when .innerHTML = "" is used on a parent
phrebejk@460
   532
    // we still need widgets and markers intact to add back to the new content later
phrebejk@460
   533
    if (!intact.length && !ie && (!webkit || !cm.display.currentWheelTarget))
phrebejk@460
   534
      removeChildren(display.lineDiv);
phrebejk@460
   535
    var container = display.lineDiv, cur = container.firstChild;
phrebejk@460
   536
phrebejk@460
   537
    function rm(node) {
phrebejk@460
   538
      var next = node.nextSibling;
phrebejk@460
   539
      if (webkit && mac && cm.display.currentWheelTarget == node) {
phrebejk@460
   540
        node.style.display = "none";
phrebejk@460
   541
        node.lineObj = null;
phrebejk@460
   542
      } else {
phrebejk@460
   543
        container.removeChild(node);
phrebejk@460
   544
      }
phrebejk@460
   545
      return next;
phrebejk@460
   546
    }
phrebejk@460
   547
phrebejk@460
   548
    var nextIntact = intact.shift(), lineNo = from;
phrebejk@460
   549
    cm.view.doc.iter(from, to, function(line) {
phrebejk@460
   550
      if (nextIntact && nextIntact.to == lineNo) nextIntact = intact.shift();
phrebejk@460
   551
      if (lineIsHidden(line)) {
phrebejk@460
   552
        if (line.height != 0) updateLineHeight(line, 0);
phrebejk@460
   553
      } else if (nextIntact && nextIntact.from <= lineNo && nextIntact.to > lineNo) {
phrebejk@460
   554
        // This line is intact. Skip to the actual node. Update its
phrebejk@460
   555
        // line number if needed.
phrebejk@460
   556
        while (cur.lineObj != line) cur = rm(cur);
phrebejk@460
   557
        if (lineNumbers && updateNumbersFrom <= lineNo && cur.lineNumber)
phrebejk@460
   558
          setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineNo));
phrebejk@460
   559
        cur = cur.nextSibling;
phrebejk@460
   560
      } else {
phrebejk@460
   561
        // This line needs to be generated.
phrebejk@460
   562
        var lineNode = buildLineElement(cm, line, lineNo, dims);
phrebejk@460
   563
        container.insertBefore(lineNode, cur);
phrebejk@460
   564
        lineNode.lineObj = line;
phrebejk@460
   565
      }
phrebejk@460
   566
      ++lineNo;
phrebejk@460
   567
    });
phrebejk@460
   568
    while (cur) cur = rm(cur);
phrebejk@460
   569
  }
phrebejk@460
   570
phrebejk@460
   571
  function buildLineElement(cm, line, lineNo, dims) {
phrebejk@460
   572
    var lineElement = lineContent(cm, line);
phrebejk@460
   573
    var markers = line.gutterMarkers, display = cm.display;
phrebejk@460
   574
phrebejk@460
   575
    if (!cm.options.lineNumbers && !markers && !line.bgClass && !line.wrapClass &&
phrebejk@460
   576
        (!line.widgets || !line.widgets.length)) return lineElement;
phrebejk@460
   577
phrebejk@460
   578
    // Lines with gutter elements or a background class need
phrebejk@460
   579
    // to be wrapped again, and have the extra elements added
phrebejk@460
   580
    // to the wrapper div
phrebejk@460
   581
phrebejk@460
   582
    var wrap = elt("div", null, line.wrapClass, "position: relative");
phrebejk@460
   583
    if (cm.options.lineNumbers || markers) {
phrebejk@460
   584
      var gutterWrap = wrap.appendChild(elt("div", null, null, "position: absolute; left: " +
phrebejk@460
   585
                                            dims.fixedPos + "px"));
phrebejk@460
   586
      wrap.alignable = [gutterWrap];
phrebejk@460
   587
      if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
phrebejk@460
   588
        wrap.lineNumber = gutterWrap.appendChild(
phrebejk@460
   589
          elt("div", lineNumberFor(cm.options, lineNo),
phrebejk@460
   590
              "CodeMirror-linenumber CodeMirror-gutter-elt",
phrebejk@460
   591
              "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
phrebejk@460
   592
              + display.lineNumInnerWidth + "px"));
phrebejk@460
   593
      if (markers)
phrebejk@460
   594
        for (var k = 0; k < cm.options.gutters.length; ++k) {
phrebejk@460
   595
          var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
phrebejk@460
   596
          if (found)
phrebejk@460
   597
            gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
phrebejk@460
   598
                                       dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
phrebejk@460
   599
        }
phrebejk@460
   600
    }
phrebejk@460
   601
    // Kludge to make sure the styled element lies behind the selection (by z-index)
phrebejk@460
   602
    if (line.bgClass)
phrebejk@460
   603
      wrap.appendChild(elt("div", "\u00a0", line.bgClass + " CodeMirror-linebackground"));
phrebejk@460
   604
    wrap.appendChild(lineElement);
phrebejk@460
   605
    if (line.widgets)
phrebejk@460
   606
      for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
phrebejk@460
   607
        var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
phrebejk@460
   608
        node.widget = widget;
phrebejk@460
   609
        if (widget.noHScroll) {
phrebejk@460
   610
          (wrap.alignable || (wrap.alignable = [])).push(node);
phrebejk@460
   611
          var width = dims.wrapperWidth;
phrebejk@460
   612
          node.style.left = dims.fixedPos + "px";
phrebejk@460
   613
          if (!widget.coverGutter) {
phrebejk@460
   614
            width -= dims.gutterTotalWidth;
phrebejk@460
   615
            node.style.paddingLeft = dims.gutterTotalWidth + "px";
phrebejk@460
   616
          }
phrebejk@460
   617
          node.style.width = width + "px";
phrebejk@460
   618
        }
phrebejk@460
   619
        if (widget.coverGutter) {
phrebejk@460
   620
          node.style.zIndex = 5;
phrebejk@460
   621
          node.style.position = "relative";
phrebejk@460
   622
          if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
phrebejk@460
   623
        }
phrebejk@460
   624
        if (widget.above)
phrebejk@460
   625
          wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement);
phrebejk@460
   626
        else
phrebejk@460
   627
          wrap.appendChild(node);
phrebejk@460
   628
      }
phrebejk@460
   629
phrebejk@460
   630
    if (ie_lt8) wrap.style.zIndex = 2;
phrebejk@460
   631
    return wrap;
phrebejk@460
   632
  }
phrebejk@460
   633
phrebejk@460
   634
  // SELECTION / CURSOR
phrebejk@460
   635
phrebejk@460
   636
  function updateSelection(cm) {
phrebejk@460
   637
    var display = cm.display;
phrebejk@460
   638
    var collapsed = posEq(cm.view.sel.from, cm.view.sel.to);
phrebejk@460
   639
    if (collapsed || cm.options.showCursorWhenSelecting)
phrebejk@460
   640
      updateSelectionCursor(cm);
phrebejk@460
   641
    else
phrebejk@460
   642
      display.cursor.style.display = display.otherCursor.style.display = "none";
phrebejk@460
   643
    if (!collapsed)
phrebejk@460
   644
      updateSelectionRange(cm);
phrebejk@460
   645
    else
phrebejk@460
   646
      display.selectionDiv.style.display = "none";
phrebejk@460
   647
phrebejk@460
   648
    // Move the hidden textarea near the cursor to prevent scrolling artifacts
phrebejk@460
   649
    var headPos = cursorCoords(cm, cm.view.sel.head, "div");
phrebejk@460
   650
    var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
phrebejk@460
   651
    display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
phrebejk@460
   652
                                                      headPos.top + lineOff.top - wrapOff.top)) + "px";
phrebejk@460
   653
    display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
phrebejk@460
   654
                                                       headPos.left + lineOff.left - wrapOff.left)) + "px";
phrebejk@460
   655
  }
phrebejk@460
   656
phrebejk@460
   657
  // No selection, plain cursor
phrebejk@460
   658
  function updateSelectionCursor(cm) {
phrebejk@460
   659
    var display = cm.display, pos = cursorCoords(cm, cm.view.sel.head, "div");
phrebejk@460
   660
    display.cursor.style.left = pos.left + "px";
phrebejk@460
   661
    display.cursor.style.top = pos.top + "px";
phrebejk@460
   662
    display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
phrebejk@460
   663
    display.cursor.style.display = "";
phrebejk@460
   664
phrebejk@460
   665
    if (pos.other) {
phrebejk@460
   666
      display.otherCursor.style.display = "";
phrebejk@460
   667
      display.otherCursor.style.left = pos.other.left + "px";
phrebejk@460
   668
      display.otherCursor.style.top = pos.other.top + "px";
phrebejk@460
   669
      display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
phrebejk@460
   670
    } else { display.otherCursor.style.display = "none"; }
phrebejk@460
   671
  }
phrebejk@460
   672
phrebejk@460
   673
  // Highlight selection
phrebejk@460
   674
  function updateSelectionRange(cm) {
phrebejk@460
   675
    var display = cm.display, doc = cm.view.doc, sel = cm.view.sel;
phrebejk@460
   676
    var fragment = document.createDocumentFragment();
phrebejk@460
   677
    var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display);
phrebejk@460
   678
phrebejk@460
   679
    function add(left, top, width, bottom) {
phrebejk@460
   680
      if (top < 0) top = 0;
phrebejk@460
   681
      fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
phrebejk@460
   682
                               "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) +
phrebejk@460
   683
                               "px; height: " + (bottom - top) + "px"));
phrebejk@460
   684
    }
phrebejk@460
   685
phrebejk@460
   686
    function drawForLine(line, fromArg, toArg, retTop) {
phrebejk@460
   687
      var lineObj = getLine(doc, line);
phrebejk@460
   688
      var lineLen = lineObj.text.length, rVal = retTop ? Infinity : -Infinity;
phrebejk@460
   689
      function coords(ch) {
phrebejk@460
   690
        return charCoords(cm, {line: line, ch: ch}, "div", lineObj);
phrebejk@460
   691
      }
phrebejk@460
   692
phrebejk@460
   693
      iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
phrebejk@460
   694
        var leftPos = coords(dir == "rtl" ? to - 1 : from);
phrebejk@460
   695
        var rightPos = coords(dir == "rtl" ? from : to - 1);
phrebejk@460
   696
        var left = leftPos.left, right = rightPos.right;
phrebejk@460
   697
        if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
phrebejk@460
   698
          add(left, leftPos.top, null, leftPos.bottom);
phrebejk@460
   699
          left = pl;
phrebejk@460
   700
          if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
phrebejk@460
   701
        }
phrebejk@460
   702
        if (toArg == null && to == lineLen) right = clientWidth;
phrebejk@460
   703
        if (fromArg == null && from == 0) left = pl;
phrebejk@460
   704
        rVal = retTop ? Math.min(rightPos.top, rVal) : Math.max(rightPos.bottom, rVal);
phrebejk@460
   705
        if (left < pl + 1) left = pl;
phrebejk@460
   706
        add(left, rightPos.top, right - left, rightPos.bottom);
phrebejk@460
   707
      });
phrebejk@460
   708
      return rVal;
phrebejk@460
   709
    }
phrebejk@460
   710
phrebejk@460
   711
    if (sel.from.line == sel.to.line) {
phrebejk@460
   712
      drawForLine(sel.from.line, sel.from.ch, sel.to.ch);
phrebejk@460
   713
    } else {
phrebejk@460
   714
      var fromObj = getLine(doc, sel.from.line);
phrebejk@460
   715
      var cur = fromObj, merged, path = [sel.from.line, sel.from.ch], singleLine;
phrebejk@460
   716
      while (merged = collapsedSpanAtEnd(cur)) {
phrebejk@460
   717
        var found = merged.find();
phrebejk@460
   718
        path.push(found.from.ch, found.to.line, found.to.ch);
phrebejk@460
   719
        if (found.to.line == sel.to.line) {
phrebejk@460
   720
          path.push(sel.to.ch);
phrebejk@460
   721
          singleLine = true;
phrebejk@460
   722
          break;
phrebejk@460
   723
        }
phrebejk@460
   724
        cur = getLine(doc, found.to.line);
phrebejk@460
   725
      }
phrebejk@460
   726
phrebejk@460
   727
      // This is a single, merged line
phrebejk@460
   728
      if (singleLine) {
phrebejk@460
   729
        for (var i = 0; i < path.length; i += 3)
phrebejk@460
   730
          drawForLine(path[i], path[i+1], path[i+2]);
phrebejk@460
   731
      } else {
phrebejk@460
   732
        var middleTop, middleBot, toObj = getLine(doc, sel.to.line);
phrebejk@460
   733
        if (sel.from.ch)
phrebejk@460
   734
          // Draw the first line of selection.
phrebejk@460
   735
          middleTop = drawForLine(sel.from.line, sel.from.ch, null, false);
phrebejk@460
   736
        else
phrebejk@460
   737
          // Simply include it in the middle block.
phrebejk@460
   738
          middleTop = heightAtLine(cm, fromObj) - display.viewOffset;
phrebejk@460
   739
phrebejk@460
   740
        if (!sel.to.ch)
phrebejk@460
   741
          middleBot = heightAtLine(cm, toObj) - display.viewOffset;
phrebejk@460
   742
        else
phrebejk@460
   743
          middleBot = drawForLine(sel.to.line, collapsedSpanAtStart(toObj) ? null : 0, sel.to.ch, true);
phrebejk@460
   744
phrebejk@460
   745
        if (middleTop < middleBot) add(pl, middleTop, null, middleBot);
phrebejk@460
   746
      }
phrebejk@460
   747
    }
phrebejk@460
   748
phrebejk@460
   749
    removeChildrenAndAdd(display.selectionDiv, fragment);
phrebejk@460
   750
    display.selectionDiv.style.display = "";
phrebejk@460
   751
  }
phrebejk@460
   752
phrebejk@460
   753
  // Cursor-blinking
phrebejk@460
   754
  function restartBlink(cm) {
phrebejk@460
   755
    var display = cm.display;
phrebejk@460
   756
    clearInterval(display.blinker);
phrebejk@460
   757
    var on = true;
phrebejk@460
   758
    display.cursor.style.visibility = display.otherCursor.style.visibility = "";
phrebejk@460
   759
    display.blinker = setInterval(function() {
phrebejk@460
   760
      if (!display.cursor.offsetHeight) return;
phrebejk@460
   761
      display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden";
phrebejk@460
   762
    }, cm.options.cursorBlinkRate);
phrebejk@460
   763
  }
phrebejk@460
   764
phrebejk@460
   765
  // HIGHLIGHT WORKER
phrebejk@460
   766
phrebejk@460
   767
  function startWorker(cm, time) {
phrebejk@460
   768
    if (cm.view.frontier < cm.display.showingTo)
phrebejk@460
   769
      cm.view.highlight.set(time, bind(highlightWorker, cm));
phrebejk@460
   770
  }
phrebejk@460
   771
phrebejk@460
   772
  function highlightWorker(cm) {
phrebejk@460
   773
    var view = cm.view, doc = view.doc;
phrebejk@460
   774
    if (view.frontier >= cm.display.showingTo) return;
phrebejk@460
   775
    var end = +new Date + cm.options.workTime;
phrebejk@460
   776
    var state = copyState(view.mode, getStateBefore(cm, view.frontier));
phrebejk@460
   777
    var changed = [], prevChange;
phrebejk@460
   778
    doc.iter(view.frontier, Math.min(doc.size, cm.display.showingTo + 500), function(line) {
phrebejk@460
   779
      if (view.frontier >= cm.display.showingFrom) { // Visible
phrebejk@460
   780
        if (highlightLine(cm, line, state) && view.frontier >= cm.display.showingFrom) {
phrebejk@460
   781
          if (prevChange && prevChange.end == view.frontier) prevChange.end++;
phrebejk@460
   782
          else changed.push(prevChange = {start: view.frontier, end: view.frontier + 1});
phrebejk@460
   783
        }
phrebejk@460
   784
        line.stateAfter = copyState(view.mode, state);
phrebejk@460
   785
      } else {
phrebejk@460
   786
        processLine(cm, line, state);
phrebejk@460
   787
        line.stateAfter = view.frontier % 5 == 0 ? copyState(view.mode, state) : null;
phrebejk@460
   788
      }
phrebejk@460
   789
      ++view.frontier;
phrebejk@460
   790
      if (+new Date > end) {
phrebejk@460
   791
        startWorker(cm, cm.options.workDelay);
phrebejk@460
   792
        return true;
phrebejk@460
   793
      }
phrebejk@460
   794
    });
phrebejk@460
   795
    if (changed.length)
phrebejk@460
   796
      operation(cm, function() {
phrebejk@460
   797
        for (var i = 0; i < changed.length; ++i)
phrebejk@460
   798
          regChange(this, changed[i].start, changed[i].end);
phrebejk@460
   799
      })();
phrebejk@460
   800
  }
phrebejk@460
   801
phrebejk@460
   802
  // Finds the line to start with when starting a parse. Tries to
phrebejk@460
   803
  // find a line with a stateAfter, so that it can start with a
phrebejk@460
   804
  // valid state. If that fails, it returns the line with the
phrebejk@460
   805
  // smallest indentation, which tends to need the least context to
phrebejk@460
   806
  // parse correctly.
phrebejk@460
   807
  function findStartLine(cm, n) {
phrebejk@460
   808
    var minindent, minline, doc = cm.view.doc;
phrebejk@460
   809
    for (var search = n, lim = n - 100; search > lim; --search) {
phrebejk@460
   810
      if (search == 0) return 0;
phrebejk@460
   811
      var line = getLine(doc, search-1);
phrebejk@460
   812
      if (line.stateAfter) return search;
phrebejk@460
   813
      var indented = countColumn(line.text, null, cm.options.tabSize);
phrebejk@460
   814
      if (minline == null || minindent > indented) {
phrebejk@460
   815
        minline = search - 1;
phrebejk@460
   816
        minindent = indented;
phrebejk@460
   817
      }
phrebejk@460
   818
    }
phrebejk@460
   819
    return minline;
phrebejk@460
   820
  }
phrebejk@460
   821
phrebejk@460
   822
  function getStateBefore(cm, n) {
phrebejk@460
   823
    var view = cm.view;
phrebejk@460
   824
    var pos = findStartLine(cm, n), state = pos && getLine(view.doc, pos-1).stateAfter;
phrebejk@460
   825
    if (!state) state = startState(view.mode);
phrebejk@460
   826
    else state = copyState(view.mode, state);
phrebejk@460
   827
    view.doc.iter(pos, n, function(line) {
phrebejk@460
   828
      processLine(cm, line, state);
phrebejk@460
   829
      var save = pos == n - 1 || pos % 5 == 0 || pos >= view.showingFrom && pos < view.showingTo;
phrebejk@460
   830
      line.stateAfter = save ? copyState(view.mode, state) : null;
phrebejk@460
   831
      ++pos;
phrebejk@460
   832
    });
phrebejk@460
   833
    return state;
phrebejk@460
   834
  }
phrebejk@460
   835
phrebejk@460
   836
  // POSITION MEASUREMENT
phrebejk@460
   837
  
phrebejk@460
   838
  function paddingTop(display) {return display.lineSpace.offsetTop;}
phrebejk@460
   839
  function paddingLeft(display) {
phrebejk@460
   840
    var e = removeChildrenAndAdd(display.measure, elt("pre")).appendChild(elt("span", "x"));
phrebejk@460
   841
    return e.offsetLeft;
phrebejk@460
   842
  }
phrebejk@460
   843
phrebejk@460
   844
  function measureChar(cm, line, ch, data) {
phrebejk@460
   845
    var data = data || measureLine(cm, line), dir = -1;
phrebejk@460
   846
    for (var pos = ch;; pos += dir) {
phrebejk@460
   847
      var r = data[pos];
phrebejk@460
   848
      if (r) break;
phrebejk@460
   849
      if (dir < 0 && pos == 0) dir = 1;
phrebejk@460
   850
    }
phrebejk@460
   851
    return {left: pos < ch ? r.right : r.left,
phrebejk@460
   852
            right: pos > ch ? r.left : r.right,
phrebejk@460
   853
            top: r.top, bottom: r.bottom};
phrebejk@460
   854
  }
phrebejk@460
   855
phrebejk@460
   856
  function measureLine(cm, line) {
phrebejk@460
   857
    // First look in the cache
phrebejk@460
   858
    var display = cm.display, cache = cm.display.measureLineCache;
phrebejk@460
   859
    for (var i = 0; i < cache.length; ++i) {
phrebejk@460
   860
      var memo = cache[i];
phrebejk@460
   861
      if (memo.text == line.text && memo.markedSpans == line.markedSpans &&
phrebejk@460
   862
          display.scroller.clientWidth == memo.width)
phrebejk@460
   863
        return memo.measure;
phrebejk@460
   864
    }
phrebejk@460
   865
    
phrebejk@460
   866
    var measure = measureLineInner(cm, line);
phrebejk@460
   867
    // Store result in the cache
phrebejk@460
   868
    var memo = {text: line.text, width: display.scroller.clientWidth,
phrebejk@460
   869
                markedSpans: line.markedSpans, measure: measure};
phrebejk@460
   870
    if (cache.length == 16) cache[++display.measureLineCachePos % 16] = memo;
phrebejk@460
   871
    else cache.push(memo);
phrebejk@460
   872
    return measure;
phrebejk@460
   873
  }
phrebejk@460
   874
phrebejk@460
   875
  function measureLineInner(cm, line) {
phrebejk@460
   876
    var display = cm.display, measure = emptyArray(line.text.length);
phrebejk@460
   877
    var pre = lineContent(cm, line, measure);
phrebejk@460
   878
phrebejk@460
   879
    // IE does not cache element positions of inline elements between
phrebejk@460
   880
    // calls to getBoundingClientRect. This makes the loop below,
phrebejk@460
   881
    // which gathers the positions of all the characters on the line,
phrebejk@460
   882
    // do an amount of layout work quadratic to the number of
phrebejk@460
   883
    // characters. When line wrapping is off, we try to improve things
phrebejk@460
   884
    // by first subdividing the line into a bunch of inline blocks, so
phrebejk@460
   885
    // that IE can reuse most of the layout information from caches
phrebejk@460
   886
    // for those blocks. This does interfere with line wrapping, so it
phrebejk@460
   887
    // doesn't work when wrapping is on, but in that case the
phrebejk@460
   888
    // situation is slightly better, since IE does cache line-wrapping
phrebejk@460
   889
    // information and only recomputes per-line.
phrebejk@460
   890
    if (ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) {
phrebejk@460
   891
      var fragment = document.createDocumentFragment();
phrebejk@460
   892
      var chunk = 10, n = pre.childNodes.length;
phrebejk@460
   893
      for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) {
phrebejk@460
   894
        var wrap = elt("div", null, null, "display: inline-block");
phrebejk@460
   895
        for (var j = 0; j < chunk && n; ++j) {
phrebejk@460
   896
          wrap.appendChild(pre.firstChild);
phrebejk@460
   897
          --n;
phrebejk@460
   898
        }
phrebejk@460
   899
        fragment.appendChild(wrap);
phrebejk@460
   900
      }
phrebejk@460
   901
      pre.appendChild(fragment);
phrebejk@460
   902
    }
phrebejk@460
   903
phrebejk@460
   904
    removeChildrenAndAdd(display.measure, pre);
phrebejk@460
   905
phrebejk@460
   906
    var outer = display.lineDiv.getBoundingClientRect();
phrebejk@460
   907
    var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight;
phrebejk@460
   908
    for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) {
phrebejk@460
   909
      var size = cur.getBoundingClientRect();
phrebejk@460
   910
      var top = Math.max(0, size.top - outer.top), bot = Math.min(size.bottom - outer.top, maxBot);
phrebejk@460
   911
      for (var j = 0; j < vranges.length; j += 2) {
phrebejk@460
   912
        var rtop = vranges[j], rbot = vranges[j+1];
phrebejk@460
   913
        if (rtop > bot || rbot < top) continue;
phrebejk@460
   914
        if (rtop <= top && rbot >= bot ||
phrebejk@460
   915
            top <= rtop && bot >= rbot ||
phrebejk@460
   916
            Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) {
phrebejk@460
   917
          vranges[j] = Math.min(top, rtop);
phrebejk@460
   918
          vranges[j+1] = Math.max(bot, rbot);
phrebejk@460
   919
          break;
phrebejk@460
   920
        }
phrebejk@460
   921
      }
phrebejk@460
   922
      if (j == vranges.length) vranges.push(top, bot);
phrebejk@460
   923
      data[i] = {left: size.left - outer.left, right: size.right - outer.left, top: j};
phrebejk@460
   924
    }
phrebejk@460
   925
    for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) {
phrebejk@460
   926
      var vr = cur.top;
phrebejk@460
   927
      cur.top = vranges[vr]; cur.bottom = vranges[vr+1];
phrebejk@460
   928
    }
phrebejk@460
   929
    return data;
phrebejk@460
   930
  }
phrebejk@460
   931
phrebejk@460
   932
  function clearCaches(cm) {
phrebejk@460
   933
    cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0;
phrebejk@460
   934
    cm.display.cachedCharWidth = cm.display.cachedTextHeight = null;
phrebejk@460
   935
    cm.view.maxLineChanged = true;
phrebejk@460
   936
  }
phrebejk@460
   937
phrebejk@460
   938
  // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page"
phrebejk@460
   939
  function intoCoordSystem(cm, lineObj, rect, context) {
phrebejk@460
   940
    if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
phrebejk@460
   941
      var size = lineObj.widgets[i].node.offsetHeight;
phrebejk@460
   942
      rect.top += size; rect.bottom += size;
phrebejk@460
   943
    }
phrebejk@460
   944
    if (context == "line") return rect;
phrebejk@460
   945
    if (!context) context = "local";
phrebejk@460
   946
    var yOff = heightAtLine(cm, lineObj);
phrebejk@460
   947
    if (context != "local") yOff -= cm.display.viewOffset;
phrebejk@460
   948
    if (context == "page") {
phrebejk@460
   949
      var lOff = cm.display.lineSpace.getBoundingClientRect();
phrebejk@460
   950
      yOff += lOff.top + (window.pageYOffset || (document.documentElement || document.body).scrollTop);
phrebejk@460
   951
      var xOff = lOff.left + (window.pageXOffset || (document.documentElement || document.body).scrollLeft);
phrebejk@460
   952
      rect.left += xOff; rect.right += xOff;
phrebejk@460
   953
    }
phrebejk@460
   954
    rect.top += yOff; rect.bottom += yOff;
phrebejk@460
   955
    return rect;
phrebejk@460
   956
  }
phrebejk@460
   957
phrebejk@460
   958
  function charCoords(cm, pos, context, lineObj) {
phrebejk@460
   959
    if (!lineObj) lineObj = getLine(cm.view.doc, pos.line);
phrebejk@460
   960
    return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch), context);
phrebejk@460
   961
  }
phrebejk@460
   962
phrebejk@460
   963
  function cursorCoords(cm, pos, context, lineObj, measurement) {
phrebejk@460
   964
    lineObj = lineObj || getLine(cm.view.doc, pos.line);
phrebejk@460
   965
    if (!measurement) measurement = measureLine(cm, lineObj);
phrebejk@460
   966
    function get(ch, right) {
phrebejk@460
   967
      var m = measureChar(cm, lineObj, ch, measurement);
phrebejk@460
   968
      if (right) m.left = m.right; else m.right = m.left;
phrebejk@460
   969
      return intoCoordSystem(cm, lineObj, m, context);
phrebejk@460
   970
    }
phrebejk@460
   971
    var order = getOrder(lineObj), ch = pos.ch;
phrebejk@460
   972
    if (!order) return get(ch);
phrebejk@460
   973
    var main, other, linedir = order[0].level;
phrebejk@460
   974
    for (var i = 0; i < order.length; ++i) {
phrebejk@460
   975
      var part = order[i], rtl = part.level % 2, nb, here;
phrebejk@460
   976
      if (part.from < ch && part.to > ch) return get(ch, rtl);
phrebejk@460
   977
      var left = rtl ? part.to : part.from, right = rtl ? part.from : part.to;
phrebejk@460
   978
      if (left == ch) {
phrebejk@460
   979
        // Opera and IE return bogus offsets and widths for edges
phrebejk@460
   980
        // where the direction flips, but only for the side with the
phrebejk@460
   981
        // lower level. So we try to use the side with the higher
phrebejk@460
   982
        // level.
phrebejk@460
   983
        if (i && part.level < (nb = order[i-1]).level) here = get(nb.level % 2 ? nb.from : nb.to - 1, true);
phrebejk@460
   984
        else here = get(rtl && part.from != part.to ? ch - 1 : ch);
phrebejk@460
   985
        if (rtl == linedir) main = here; else other = here;
phrebejk@460
   986
      } else if (right == ch) {
phrebejk@460
   987
        var nb = i < order.length - 1 && order[i+1];
phrebejk@460
   988
        if (!rtl && nb && nb.from == nb.to) continue;
phrebejk@460
   989
        if (nb && part.level < nb.level) here = get(nb.level % 2 ? nb.to - 1 : nb.from);
phrebejk@460
   990
        else here = get(rtl ? ch : ch - 1, true);
phrebejk@460
   991
        if (rtl == linedir) main = here; else other = here;
phrebejk@460
   992
      }
phrebejk@460
   993
    }
phrebejk@460
   994
    if (linedir && !ch) other = get(order[0].to - 1);
phrebejk@460
   995
    if (!main) return other;
phrebejk@460
   996
    if (other) main.other = other;
phrebejk@460
   997
    return main;
phrebejk@460
   998
  }
phrebejk@460
   999
phrebejk@460
  1000
  // Coords must be lineSpace-local
phrebejk@460
  1001
  function coordsChar(cm, x, y) {
phrebejk@460
  1002
    var doc = cm.view.doc;
phrebejk@460
  1003
    y += cm.display.viewOffset;
phrebejk@460
  1004
    if (y < 0) return {line: 0, ch: 0, outside: true};
phrebejk@460
  1005
    var lineNo = lineAtHeight(doc, y);
phrebejk@460
  1006
    if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc, doc.size - 1).text.length};
phrebejk@460
  1007
    if (x < 0) x = 0;
phrebejk@460
  1008
phrebejk@460
  1009
    for (;;) {
phrebejk@460
  1010
      var lineObj = getLine(doc, lineNo);
phrebejk@460
  1011
      var found = coordsCharInner(cm, lineObj, lineNo, x, y);
phrebejk@460
  1012
      var merged = collapsedSpanAtEnd(lineObj);
phrebejk@460
  1013
      if (merged && found.ch == lineRight(lineObj))
phrebejk@460
  1014
        lineNo = merged.find().to.line;
phrebejk@460
  1015
      else
phrebejk@460
  1016
        return found;
phrebejk@460
  1017
    }
phrebejk@460
  1018
  }
phrebejk@460
  1019
phrebejk@460
  1020
  function coordsCharInner(cm, lineObj, lineNo, x, y) {
phrebejk@460
  1021
    var innerOff = y - heightAtLine(cm, lineObj);
phrebejk@460
  1022
    var wrongLine = false, cWidth = cm.display.wrapper.clientWidth;
phrebejk@460
  1023
    var measurement = measureLine(cm, lineObj);
phrebejk@460
  1024
phrebejk@460
  1025
    function getX(ch) {
phrebejk@460
  1026
      var sp = cursorCoords(cm, {line: lineNo, ch: ch}, "line",
phrebejk@460
  1027
                            lineObj, measurement);
phrebejk@460
  1028
      wrongLine = true;
phrebejk@460
  1029
      if (innerOff > sp.bottom) return Math.max(0, sp.left - cWidth);
phrebejk@460
  1030
      else if (innerOff < sp.top) return sp.left + cWidth;
phrebejk@460
  1031
      else wrongLine = false;
phrebejk@460
  1032
      return sp.left;
phrebejk@460
  1033
    }
phrebejk@460
  1034
phrebejk@460
  1035
    var bidi = getOrder(lineObj), dist = lineObj.text.length;
phrebejk@460
  1036
    var from = lineLeft(lineObj), to = lineRight(lineObj);
phrebejk@460
  1037
    var fromX = paddingLeft(cm.display), toX = getX(to);
phrebejk@460
  1038
phrebejk@460
  1039
    if (x > toX) return {line: lineNo, ch: to, outside: wrongLine};
phrebejk@460
  1040
    // Do a binary search between these bounds.
phrebejk@460
  1041
    for (;;) {
phrebejk@460
  1042
      if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
phrebejk@460
  1043
        var after = x - fromX < toX - x, ch = after ? from : to;
phrebejk@460
  1044
        while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch;
phrebejk@460
  1045
        return {line: lineNo, ch: ch, after: after, outside: wrongLine};
phrebejk@460
  1046
      }
phrebejk@460
  1047
      var step = Math.ceil(dist / 2), middle = from + step;
phrebejk@460
  1048
      if (bidi) {
phrebejk@460
  1049
        middle = from;
phrebejk@460
  1050
        for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
phrebejk@460
  1051
      }
phrebejk@460
  1052
      var middleX = getX(middle);
phrebejk@460
  1053
      if (middleX > x) {to = middle; toX = middleX; if (wrongLine) toX += 1000; dist -= step;}
phrebejk@460
  1054
      else {from = middle; fromX = middleX; dist = step;}
phrebejk@460
  1055
    }
phrebejk@460
  1056
  }
phrebejk@460
  1057
phrebejk@460
  1058
  var measureText;
phrebejk@460
  1059
  function textHeight(display) {
phrebejk@460
  1060
    if (display.cachedTextHeight != null) return display.cachedTextHeight;
phrebejk@460
  1061
    if (measureText == null) {
phrebejk@460
  1062
      measureText = elt("pre");
phrebejk@460
  1063
      // Measure a bunch of lines, for browsers that compute
phrebejk@460
  1064
      // fractional heights.
phrebejk@460
  1065
      for (var i = 0; i < 49; ++i) {
phrebejk@460
  1066
        measureText.appendChild(document.createTextNode("x"));
phrebejk@460
  1067
        measureText.appendChild(elt("br"));
phrebejk@460
  1068
      }
phrebejk@460
  1069
      measureText.appendChild(document.createTextNode("x"));
phrebejk@460
  1070
    }
phrebejk@460
  1071
    removeChildrenAndAdd(display.measure, measureText);
phrebejk@460
  1072
    var height = measureText.offsetHeight / 50;
phrebejk@460
  1073
    if (height > 3) display.cachedTextHeight = height;
phrebejk@460
  1074
    removeChildren(display.measure);
phrebejk@460
  1075
    return height || 1;
phrebejk@460
  1076
  }
phrebejk@460
  1077
phrebejk@460
  1078
  function charWidth(display) {
phrebejk@460
  1079
    if (display.cachedCharWidth != null) return display.cachedCharWidth;
phrebejk@460
  1080
    var anchor = elt("span", "x");
phrebejk@460
  1081
    var pre = elt("pre", [anchor]);
phrebejk@460
  1082
    removeChildrenAndAdd(display.measure, pre);
phrebejk@460
  1083
    var width = anchor.offsetWidth;
phrebejk@460
  1084
    if (width > 2) display.cachedCharWidth = width;
phrebejk@460
  1085
    return width || 10;
phrebejk@460
  1086
  }
phrebejk@460
  1087
phrebejk@460
  1088
  // OPERATIONS
phrebejk@460
  1089
phrebejk@460
  1090
  // Operations are used to wrap changes in such a way that each
phrebejk@460
  1091
  // change won't have to update the cursor and display (which would
phrebejk@460
  1092
  // be awkward, slow, and error-prone), but instead updates are
phrebejk@460
  1093
  // batched and then all combined and executed at once.
phrebejk@460
  1094
phrebejk@460
  1095
  function startOperation(cm) {
phrebejk@460
  1096
    if (cm.curOp) ++cm.curOp.depth;
phrebejk@460
  1097
    else cm.curOp = {
phrebejk@460
  1098
      // Nested operations delay update until the outermost one
phrebejk@460
  1099
      // finishes.
phrebejk@460
  1100
      depth: 1,
phrebejk@460
  1101
      // An array of ranges of lines that have to be updated. See
phrebejk@460
  1102
      // updateDisplay.
phrebejk@460
  1103
      changes: [],
phrebejk@460
  1104
      delayedCallbacks: [],
phrebejk@460
  1105
      updateInput: null,
phrebejk@460
  1106
      userSelChange: null,
phrebejk@460
  1107
      textChanged: null,
phrebejk@460
  1108
      selectionChanged: false,
phrebejk@460
  1109
      updateMaxLine: false,
phrebejk@460
  1110
      id: ++cm.nextOpId
phrebejk@460
  1111
    };
phrebejk@460
  1112
  }
phrebejk@460
  1113
phrebejk@460
  1114
  function endOperation(cm) {
phrebejk@460
  1115
    var op = cm.curOp;
phrebejk@460
  1116
    if (--op.depth) return;
phrebejk@460
  1117
    cm.curOp = null;
phrebejk@460
  1118
    var view = cm.view, display = cm.display;
phrebejk@460
  1119
    if (op.updateMaxLine) computeMaxLength(view);
phrebejk@460
  1120
    if (view.maxLineChanged && !cm.options.lineWrapping) {
phrebejk@460
  1121
      var width = measureChar(cm, view.maxLine, view.maxLine.text.length).right;
phrebejk@460
  1122
      display.sizer.style.minWidth = (width + 3 + scrollerCutOff) + "px";
phrebejk@460
  1123
      view.maxLineChanged = false;
phrebejk@460
  1124
    }
phrebejk@460
  1125
    var newScrollPos, updated;
phrebejk@460
  1126
    if (op.selectionChanged) {
phrebejk@460
  1127
      var coords = cursorCoords(cm, view.sel.head);
phrebejk@460
  1128
      newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom);
phrebejk@460
  1129
    }
phrebejk@460
  1130
    if (op.changes.length || newScrollPos && newScrollPos.scrollTop != null)
phrebejk@460
  1131
      updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop);
phrebejk@460
  1132
    if (!updated && op.selectionChanged) updateSelection(cm);
phrebejk@460
  1133
    if (newScrollPos) scrollCursorIntoView(cm);
phrebejk@460
  1134
    if (op.selectionChanged) restartBlink(cm);
phrebejk@460
  1135
phrebejk@460
  1136
    if (view.focused && op.updateInput)
phrebejk@460
  1137
      resetInput(cm, op.userSelChange);
phrebejk@460
  1138
phrebejk@460
  1139
    if (op.textChanged)
phrebejk@460
  1140
      signal(cm, "change", cm, op.textChanged);
phrebejk@460
  1141
    if (op.selectionChanged) signal(cm, "cursorActivity", cm);
phrebejk@460
  1142
    for (var i = 0; i < op.delayedCallbacks.length; ++i) op.delayedCallbacks[i](cm);
phrebejk@460
  1143
  }
phrebejk@460
  1144
phrebejk@460
  1145
  // Wraps a function in an operation. Returns the wrapped function.
phrebejk@460
  1146
  function operation(cm1, f) {
phrebejk@460
  1147
    return function() {
phrebejk@460
  1148
      var cm = cm1 || this;
phrebejk@460
  1149
      startOperation(cm);
phrebejk@460
  1150
      try {var result = f.apply(cm, arguments);}
phrebejk@460
  1151
      finally {endOperation(cm);}
phrebejk@460
  1152
      return result;
phrebejk@460
  1153
    };
phrebejk@460
  1154
  }
phrebejk@460
  1155
phrebejk@460
  1156
  function regChange(cm, from, to, lendiff) {
phrebejk@460
  1157
    cm.curOp.changes.push({from: from, to: to, diff: lendiff});
phrebejk@460
  1158
  }
phrebejk@460
  1159
phrebejk@460
  1160
  // INPUT HANDLING
phrebejk@460
  1161
phrebejk@460
  1162
  function slowPoll(cm) {
phrebejk@460
  1163
    if (cm.view.pollingFast) return;
phrebejk@460
  1164
    cm.display.poll.set(cm.options.pollInterval, function() {
phrebejk@460
  1165
      readInput(cm);
phrebejk@460
  1166
      if (cm.view.focused) slowPoll(cm);
phrebejk@460
  1167
    });
phrebejk@460
  1168
  }
phrebejk@460
  1169
phrebejk@460
  1170
  function fastPoll(cm) {
phrebejk@460
  1171
    var missed = false;
phrebejk@460
  1172
    cm.display.pollingFast = true;
phrebejk@460
  1173
    function p() {
phrebejk@460
  1174
      var changed = readInput(cm);
phrebejk@460
  1175
      if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
phrebejk@460
  1176
      else {cm.display.pollingFast = false; slowPoll(cm);}
phrebejk@460
  1177
    }
phrebejk@460
  1178
    cm.display.poll.set(20, p);
phrebejk@460
  1179
  }
phrebejk@460
  1180
phrebejk@460
  1181
  // prevInput is a hack to work with IME. If we reset the textarea
phrebejk@460
  1182
  // on every change, that breaks IME. So we look for changes
phrebejk@460
  1183
  // compared to the previous content instead. (Modern browsers have
phrebejk@460
  1184
  // events that indicate IME taking place, but these are not widely
phrebejk@460
  1185
  // supported or compatible enough yet to rely on.)
phrebejk@460
  1186
  function readInput(cm) {
phrebejk@460
  1187
    var input = cm.display.input, prevInput = cm.display.prevInput, view = cm.view, sel = view.sel;
phrebejk@460
  1188
    if (!view.focused || hasSelection(input) || isReadOnly(cm)) return false;
phrebejk@460
  1189
    var text = input.value;
phrebejk@460
  1190
    if (text == prevInput && posEq(sel.from, sel.to)) return false;
phrebejk@460
  1191
    startOperation(cm);
phrebejk@460
  1192
    view.sel.shift = false;
phrebejk@460
  1193
    var same = 0, l = Math.min(prevInput.length, text.length);
phrebejk@460
  1194
    while (same < l && prevInput[same] == text[same]) ++same;
phrebejk@460
  1195
    var from = sel.from, to = sel.to;
phrebejk@460
  1196
    if (same < prevInput.length)
phrebejk@460
  1197
      from = {line: from.line, ch: from.ch - (prevInput.length - same)};
phrebejk@460
  1198
    else if (view.overwrite && posEq(from, to) && !cm.display.pasteIncoming)
phrebejk@460
  1199
      to = {line: to.line, ch: Math.min(getLine(cm.view.doc, to.line).text.length, to.ch + (text.length - same))};
phrebejk@460
  1200
    var updateInput = cm.curOp.updateInput;
phrebejk@460
  1201
    updateDoc(cm, from, to, splitLines(text.slice(same)), "end",
phrebejk@460
  1202
              cm.display.pasteIncoming ? "paste" : "input", {from: from, to: to});
phrebejk@460
  1203
    cm.curOp.updateInput = updateInput;
phrebejk@460
  1204
    if (text.length > 1000) input.value = cm.display.prevInput = "";
phrebejk@460
  1205
    else cm.display.prevInput = text;
phrebejk@460
  1206
    endOperation(cm);
phrebejk@460
  1207
    cm.display.pasteIncoming = false;
phrebejk@460
  1208
    return true;
phrebejk@460
  1209
  }
phrebejk@460
  1210
phrebejk@460
  1211
  function resetInput(cm, user) {
phrebejk@460
  1212
    var view = cm.view, minimal, selected;
phrebejk@460
  1213
    if (!posEq(view.sel.from, view.sel.to)) {
phrebejk@460
  1214
      cm.display.prevInput = "";
phrebejk@460
  1215
      minimal = hasCopyEvent &&
phrebejk@460
  1216
        (view.sel.to.line - view.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000);
phrebejk@460
  1217
      if (minimal) cm.display.input.value = "-";
phrebejk@460
  1218
      else cm.display.input.value = selected || cm.getSelection();
phrebejk@460
  1219
      if (view.focused) selectInput(cm.display.input);
phrebejk@460
  1220
    } else if (user) cm.display.prevInput = cm.display.input.value = "";
phrebejk@460
  1221
    cm.display.inaccurateSelection = minimal;
phrebejk@460
  1222
  }
phrebejk@460
  1223
phrebejk@460
  1224
  function focusInput(cm) {
phrebejk@460
  1225
    if (cm.options.readOnly != "nocursor" && (ie || document.activeElement != cm.display.input))
phrebejk@460
  1226
      cm.display.input.focus();
phrebejk@460
  1227
  }
phrebejk@460
  1228
phrebejk@460
  1229
  function isReadOnly(cm) {
phrebejk@460
  1230
    return cm.options.readOnly || cm.view.cantEdit;
phrebejk@460
  1231
  }
phrebejk@460
  1232
phrebejk@460
  1233
  // EVENT HANDLERS
phrebejk@460
  1234
phrebejk@460
  1235
  function registerEventHandlers(cm) {
phrebejk@460
  1236
    var d = cm.display;
phrebejk@460
  1237
    on(d.scroller, "mousedown", operation(cm, onMouseDown));
phrebejk@460
  1238
    on(d.scroller, "dblclick", operation(cm, e_preventDefault));
phrebejk@460
  1239
    on(d.lineSpace, "selectstart", function(e) {
phrebejk@460
  1240
      if (!mouseEventInWidget(d, e)) e_preventDefault(e);
phrebejk@460
  1241
    });
phrebejk@460
  1242
    // Gecko browsers fire contextmenu *after* opening the menu, at
phrebejk@460
  1243
    // which point we can't mess with it anymore. Context menu is
phrebejk@460
  1244
    // handled in onMouseDown for Gecko.
phrebejk@460
  1245
    if (!gecko) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
phrebejk@460
  1246
phrebejk@460
  1247
    on(d.scroller, "scroll", function() {
phrebejk@460
  1248
      setScrollTop(cm, d.scroller.scrollTop);
phrebejk@460
  1249
      setScrollLeft(cm, d.scroller.scrollLeft, true);
phrebejk@460
  1250
      signal(cm, "scroll", cm);
phrebejk@460
  1251
    });
phrebejk@460
  1252
    on(d.scrollbarV, "scroll", function() {
phrebejk@460
  1253
      setScrollTop(cm, d.scrollbarV.scrollTop);
phrebejk@460
  1254
    });
phrebejk@460
  1255
    on(d.scrollbarH, "scroll", function() {
phrebejk@460
  1256
      setScrollLeft(cm, d.scrollbarH.scrollLeft);
phrebejk@460
  1257
    });
phrebejk@460
  1258
phrebejk@460
  1259
    on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
phrebejk@460
  1260
    on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
phrebejk@460
  1261
phrebejk@460
  1262
    function reFocus() { if (cm.view.focused) setTimeout(bind(focusInput, cm), 0); }
phrebejk@460
  1263
    on(d.scrollbarH, "mousedown", reFocus);
phrebejk@460
  1264
    on(d.scrollbarV, "mousedown", reFocus);
phrebejk@460
  1265
    // Prevent wrapper from ever scrolling
phrebejk@460
  1266
    on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
phrebejk@460
  1267
    on(window, "resize", function resizeHandler() {
phrebejk@460
  1268
      // Might be a text scaling operation, clear size caches.
phrebejk@460
  1269
      d.cachedCharWidth = d.cachedTextHeight = null;
phrebejk@460
  1270
      clearCaches(cm);
phrebejk@460
  1271
      if (d.wrapper.parentNode) updateDisplay(cm, true);
phrebejk@460
  1272
      else off(window, "resize", resizeHandler);
phrebejk@460
  1273
    });
phrebejk@460
  1274
phrebejk@460
  1275
    on(d.input, "keyup", operation(cm, function(e) {
phrebejk@460
  1276
      if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
phrebejk@460
  1277
      if (e_prop(e, "keyCode") == 16) cm.view.sel.shift = false;
phrebejk@460
  1278
    }));
phrebejk@460
  1279
    on(d.input, "input", bind(fastPoll, cm));
phrebejk@460
  1280
    on(d.input, "keydown", operation(cm, onKeyDown));
phrebejk@460
  1281
    on(d.input, "keypress", operation(cm, onKeyPress));
phrebejk@460
  1282
    on(d.input, "focus", bind(onFocus, cm));
phrebejk@460
  1283
    on(d.input, "blur", bind(onBlur, cm));
phrebejk@460
  1284
phrebejk@460
  1285
    function drag_(e) {
phrebejk@460
  1286
      if (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return;
phrebejk@460
  1287
      e_stop(e);
phrebejk@460
  1288
    }
phrebejk@460
  1289
    if (cm.options.dragDrop) {
phrebejk@460
  1290
      on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
phrebejk@460
  1291
      on(d.scroller, "dragenter", drag_);
phrebejk@460
  1292
      on(d.scroller, "dragover", drag_);
phrebejk@460
  1293
      on(d.scroller, "drop", operation(cm, onDrop));
phrebejk@460
  1294
    }
phrebejk@460
  1295
    on(d.scroller, "paste", function(){focusInput(cm); fastPoll(cm);});
phrebejk@460
  1296
    on(d.input, "paste", function() {
phrebejk@460
  1297
      d.pasteIncoming = true;
phrebejk@460
  1298
      fastPoll(cm);
phrebejk@460
  1299
    });
phrebejk@460
  1300
phrebejk@460
  1301
    function prepareCopy() {
phrebejk@460
  1302
      if (d.inaccurateSelection) {
phrebejk@460
  1303
        d.prevInput = "";
phrebejk@460
  1304
        d.inaccurateSelection = false;
phrebejk@460
  1305
        d.input.value = cm.getSelection();
phrebejk@460
  1306
        selectInput(d.input);
phrebejk@460
  1307
      }
phrebejk@460
  1308
    }
phrebejk@460
  1309
    on(d.input, "cut", prepareCopy);
phrebejk@460
  1310
    on(d.input, "copy", prepareCopy);
phrebejk@460
  1311
phrebejk@460
  1312
    // Needed to handle Tab key in KHTML
phrebejk@460
  1313
    if (khtml) on(d.sizer, "mouseup", function() {
phrebejk@460
  1314
        if (document.activeElement == d.input) d.input.blur();
phrebejk@460
  1315
        focusInput(cm);
phrebejk@460
  1316
    });
phrebejk@460
  1317
  }
phrebejk@460
  1318
phrebejk@460
  1319
  function mouseEventInWidget(display, e) {
phrebejk@460
  1320
    for (var n = e_target(e); n != display.wrapper; n = n.parentNode)
phrebejk@460
  1321
      if (/\bCodeMirror-(?:line)?widget\b/.test(n.className) ||
phrebejk@460
  1322
          n.parentNode == display.sizer && n != display.mover) return true;
phrebejk@460
  1323
  }
phrebejk@460
  1324
phrebejk@460
  1325
  function posFromMouse(cm, e, liberal) {
phrebejk@460
  1326
    var display = cm.display;
phrebejk@460
  1327
    if (!liberal) {
phrebejk@460
  1328
      var target = e_target(e);
phrebejk@460
  1329
      if (target == display.scrollbarH || target == display.scrollbarH.firstChild ||
phrebejk@460
  1330
          target == display.scrollbarV || target == display.scrollbarV.firstChild ||
phrebejk@460
  1331
          target == display.scrollbarFiller) return null;
phrebejk@460
  1332
    }
phrebejk@460
  1333
    var x, y, space = display.lineSpace.getBoundingClientRect();
phrebejk@460
  1334
    // Fails unpredictably on IE[67] when mouse is dragged around quickly.
phrebejk@460
  1335
    try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
phrebejk@460
  1336
    return coordsChar(cm, x - space.left, y - space.top);
phrebejk@460
  1337
  }
phrebejk@460
  1338
phrebejk@460
  1339
  var lastClick, lastDoubleClick;
phrebejk@460
  1340
  function onMouseDown(e) {
phrebejk@460
  1341
    var cm = this, display = cm.display, view = cm.view, sel = view.sel, doc = view.doc;
phrebejk@460
  1342
    sel.shift = e_prop(e, "shiftKey");
phrebejk@460
  1343
phrebejk@460
  1344
    if (mouseEventInWidget(display, e)) {
phrebejk@460
  1345
      if (!webkit) {
phrebejk@460
  1346
        display.scroller.draggable = false;
phrebejk@460
  1347
        setTimeout(function(){display.scroller.draggable = true;}, 100);
phrebejk@460
  1348
      }
phrebejk@460
  1349
      return;
phrebejk@460
  1350
    }
phrebejk@460
  1351
    if (clickInGutter(cm, e)) return;
phrebejk@460
  1352
    var start = posFromMouse(cm, e);
phrebejk@460
  1353
phrebejk@460
  1354
    switch (e_button(e)) {
phrebejk@460
  1355
    case 3:
phrebejk@460
  1356
      if (gecko) onContextMenu.call(cm, cm, e);
phrebejk@460
  1357
      return;
phrebejk@460
  1358
    case 2:
phrebejk@460
  1359
      if (start) extendSelection(cm, start);
phrebejk@460
  1360
      setTimeout(bind(focusInput, cm), 20);
phrebejk@460
  1361
      e_preventDefault(e);
phrebejk@460
  1362
      return;
phrebejk@460
  1363
    }
phrebejk@460
  1364
    // For button 1, if it was clicked inside the editor
phrebejk@460
  1365
    // (posFromMouse returning non-null), we have to adjust the
phrebejk@460
  1366
    // selection.
phrebejk@460
  1367
    if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;}
phrebejk@460
  1368
phrebejk@460
  1369
    if (!view.focused) onFocus(cm);
phrebejk@460
  1370
phrebejk@460
  1371
    var now = +new Date, type = "single";
phrebejk@460
  1372
    if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
phrebejk@460
  1373
      type = "triple";
phrebejk@460
  1374
      e_preventDefault(e);
phrebejk@460
  1375
      setTimeout(bind(focusInput, cm), 20);
phrebejk@460
  1376
      selectLine(cm, start.line);
phrebejk@460
  1377
    } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
phrebejk@460
  1378
      type = "double";
phrebejk@460
  1379
      lastDoubleClick = {time: now, pos: start};
phrebejk@460
  1380
      e_preventDefault(e);
phrebejk@460
  1381
      var word = findWordAt(getLine(doc, start.line).text, start);
phrebejk@460
  1382
      extendSelection(cm, word.from, word.to);
phrebejk@460
  1383
    } else { lastClick = {time: now, pos: start}; }
phrebejk@460
  1384
phrebejk@460
  1385
    var last = start;
phrebejk@460
  1386
    if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) &&
phrebejk@460
  1387
        !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") {
phrebejk@460
  1388
      var dragEnd = operation(cm, function(e2) {
phrebejk@460
  1389
        if (webkit) display.scroller.draggable = false;
phrebejk@460
  1390
        view.draggingText = false;
phrebejk@460
  1391
        off(document, "mouseup", dragEnd);
phrebejk@460
  1392
        off(display.scroller, "drop", dragEnd);
phrebejk@460
  1393
        if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
phrebejk@460
  1394
          e_preventDefault(e2);
phrebejk@460
  1395
          extendSelection(cm, start);
phrebejk@460
  1396
          focusInput(cm);
phrebejk@460
  1397
        }
phrebejk@460
  1398
      });
phrebejk@460
  1399
      // Let the drag handler handle this.
phrebejk@460
  1400
      if (webkit) display.scroller.draggable = true;
phrebejk@460
  1401
      view.draggingText = dragEnd;
phrebejk@460
  1402
      // IE's approach to draggable
phrebejk@460
  1403
      if (display.scroller.dragDrop) display.scroller.dragDrop();
phrebejk@460
  1404
      on(document, "mouseup", dragEnd);
phrebejk@460
  1405
      on(display.scroller, "drop", dragEnd);
phrebejk@460
  1406
      return;
phrebejk@460
  1407
    }
phrebejk@460
  1408
    e_preventDefault(e);
phrebejk@460
  1409
    if (type == "single") extendSelection(cm, clipPos(doc, start));
phrebejk@460
  1410
phrebejk@460
  1411
    var startstart = sel.from, startend = sel.to;
phrebejk@460
  1412
phrebejk@460
  1413
    function doSelect(cur) {
phrebejk@460
  1414
      if (type == "single") {
phrebejk@460
  1415
        extendSelection(cm, clipPos(doc, start), cur);
phrebejk@460
  1416
        return;
phrebejk@460
  1417
      }
phrebejk@460
  1418
phrebejk@460
  1419
      startstart = clipPos(doc, startstart);
phrebejk@460
  1420
      startend = clipPos(doc, startend);
phrebejk@460
  1421
      if (type == "double") {
phrebejk@460
  1422
        var word = findWordAt(getLine(doc, cur.line).text, cur);
phrebejk@460
  1423
        if (posLess(cur, startstart)) extendSelection(cm, word.from, startend);
phrebejk@460
  1424
        else extendSelection(cm, startstart, word.to);
phrebejk@460
  1425
      } else if (type == "triple") {
phrebejk@460
  1426
        if (posLess(cur, startstart)) extendSelection(cm, startend, clipPos(doc, {line: cur.line, ch: 0}));
phrebejk@460
  1427
        else extendSelection(cm, startstart, clipPos(doc, {line: cur.line + 1, ch: 0}));
phrebejk@460
  1428
      }
phrebejk@460
  1429
    }
phrebejk@460
  1430
phrebejk@460
  1431
    var editorSize = display.wrapper.getBoundingClientRect();
phrebejk@460
  1432
    // Used to ensure timeout re-tries don't fire when another extend
phrebejk@460
  1433
    // happened in the meantime (clearTimeout isn't reliable -- at
phrebejk@460
  1434
    // least on Chrome, the timeouts still happen even when cleared,
phrebejk@460
  1435
    // if the clear happens after their scheduled firing time).
phrebejk@460
  1436
    var counter = 0;
phrebejk@460
  1437
phrebejk@460
  1438
    function extend(e) {
phrebejk@460
  1439
      var curCount = ++counter;
phrebejk@460
  1440
      var cur = posFromMouse(cm, e, true);
phrebejk@460
  1441
      if (!cur) return;
phrebejk@460
  1442
      if (!posEq(cur, last)) {
phrebejk@460
  1443
        if (!view.focused) onFocus(cm);
phrebejk@460
  1444
        last = cur;
phrebejk@460
  1445
        doSelect(cur);
phrebejk@460
  1446
        var visible = visibleLines(display, doc);
phrebejk@460
  1447
        if (cur.line >= visible.to || cur.line < visible.from)
phrebejk@460
  1448
          setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
phrebejk@460
  1449
      } else {
phrebejk@460
  1450
        var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
phrebejk@460
  1451
        if (outside) setTimeout(operation(cm, function() {
phrebejk@460
  1452
          if (counter != curCount) return;
phrebejk@460
  1453
          display.scroller.scrollTop += outside;
phrebejk@460
  1454
          extend(e);
phrebejk@460
  1455
        }), 50);
phrebejk@460
  1456
      }
phrebejk@460
  1457
    }
phrebejk@460
  1458
phrebejk@460
  1459
    function done(e) {
phrebejk@460
  1460
      counter = Infinity;
phrebejk@460
  1461
      var cur = posFromMouse(cm, e);
phrebejk@460
  1462
      if (cur) doSelect(cur);
phrebejk@460
  1463
      e_preventDefault(e);
phrebejk@460
  1464
      focusInput(cm);
phrebejk@460
  1465
      off(document, "mousemove", move);
phrebejk@460
  1466
      off(document, "mouseup", up);
phrebejk@460
  1467
    }
phrebejk@460
  1468
phrebejk@460
  1469
    var move = operation(cm, function(e) {
phrebejk@460
  1470
      if (!ie && !e_button(e)) done(e);
phrebejk@460
  1471
      else extend(e);
phrebejk@460
  1472
    });
phrebejk@460
  1473
    var up = operation(cm, done);
phrebejk@460
  1474
    on(document, "mousemove", move);
phrebejk@460
  1475
    on(document, "mouseup", up);
phrebejk@460
  1476
  }
phrebejk@460
  1477
phrebejk@460
  1478
  function onDrop(e) {
phrebejk@460
  1479
    var cm = this;
phrebejk@460
  1480
    if (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return;
phrebejk@460
  1481
    e_preventDefault(e);
phrebejk@460
  1482
    var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
phrebejk@460
  1483
    if (!pos || isReadOnly(cm)) return;
phrebejk@460
  1484
    if (files && files.length && window.FileReader && window.File) {
phrebejk@460
  1485
      var n = files.length, text = Array(n), read = 0;
phrebejk@460
  1486
      var loadFile = function(file, i) {
phrebejk@460
  1487
        var reader = new FileReader;
phrebejk@460
  1488
        reader.onload = function() {
phrebejk@460
  1489
          text[i] = reader.result;
phrebejk@460
  1490
          if (++read == n) {
phrebejk@460
  1491
            pos = clipPos(cm.view.doc, pos);
phrebejk@460
  1492
            operation(cm, function() {
phrebejk@460
  1493
              var end = replaceRange(cm, text.join(""), pos, pos, "paste");
phrebejk@460
  1494
              setSelection(cm, pos, end);
phrebejk@460
  1495
            })();
phrebejk@460
  1496
          }
phrebejk@460
  1497
        };
phrebejk@460
  1498
        reader.readAsText(file);
phrebejk@460
  1499
      };
phrebejk@460
  1500
      for (var i = 0; i < n; ++i) loadFile(files[i], i);
phrebejk@460
  1501
    } else {
phrebejk@460
  1502
      // Don't do a replace if the drop happened inside of the selected text.
phrebejk@460
  1503
      if (cm.view.draggingText && !(posLess(pos, cm.view.sel.from) || posLess(cm.view.sel.to, pos))) {
phrebejk@460
  1504
        cm.view.draggingText(e);
phrebejk@460
  1505
        if (ie) setTimeout(bind(focusInput, cm), 50);
phrebejk@460
  1506
        return;
phrebejk@460
  1507
      }
phrebejk@460
  1508
      try {
phrebejk@460
  1509
        var text = e.dataTransfer.getData("Text");
phrebejk@460
  1510
        if (text) {
phrebejk@460
  1511
          var curFrom = cm.view.sel.from, curTo = cm.view.sel.to;
phrebejk@460
  1512
          setSelection(cm, pos, pos);
phrebejk@460
  1513
          if (cm.view.draggingText) replaceRange(cm, "", curFrom, curTo, "paste");
phrebejk@460
  1514
          cm.replaceSelection(text, null, "paste");
phrebejk@460
  1515
          focusInput(cm);
phrebejk@460
  1516
          onFocus(cm);
phrebejk@460
  1517
        }
phrebejk@460
  1518
      }
phrebejk@460
  1519
      catch(e){}
phrebejk@460
  1520
    }
phrebejk@460
  1521
  }
phrebejk@460
  1522
phrebejk@460
  1523
  function clickInGutter(cm, e) {
phrebejk@460
  1524
    var display = cm.display;
phrebejk@460
  1525
    try { var mX = e.clientX, mY = e.clientY; }
phrebejk@460
  1526
    catch(e) { return false; }
phrebejk@460
  1527
phrebejk@460
  1528
    if (mX >= Math.floor(display.gutters.getBoundingClientRect().right)) return false;
phrebejk@460
  1529
    e_preventDefault(e);
phrebejk@460
  1530
    if (!hasHandler(cm, "gutterClick")) return true;
phrebejk@460
  1531
phrebejk@460
  1532
    var lineBox = display.lineDiv.getBoundingClientRect();
phrebejk@460
  1533
    if (mY > lineBox.bottom) return true;
phrebejk@460
  1534
    mY -= lineBox.top - display.viewOffset;
phrebejk@460
  1535
phrebejk@460
  1536
    for (var i = 0; i < cm.options.gutters.length; ++i) {
phrebejk@460
  1537
      var g = display.gutters.childNodes[i];
phrebejk@460
  1538
      if (g && g.getBoundingClientRect().right >= mX) {
phrebejk@460
  1539
        var line = lineAtHeight(cm.view.doc, mY);
phrebejk@460
  1540
        var gutter = cm.options.gutters[i];
phrebejk@460
  1541
        signalLater(cm, cm, "gutterClick", cm, line, gutter, e);
phrebejk@460
  1542
        break;
phrebejk@460
  1543
      }
phrebejk@460
  1544
    }
phrebejk@460
  1545
    return true;
phrebejk@460
  1546
  }
phrebejk@460
  1547
phrebejk@460
  1548
  function onDragStart(cm, e) {
phrebejk@460
  1549
    var txt = cm.getSelection();
phrebejk@460
  1550
    e.dataTransfer.setData("Text", txt);
phrebejk@460
  1551
phrebejk@460
  1552
    // Use dummy image instead of default browsers image.
phrebejk@460
  1553
    // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
phrebejk@460
  1554
    if (e.dataTransfer.setDragImage && !safari)
phrebejk@460
  1555
      e.dataTransfer.setDragImage(elt('img'), 0, 0);
phrebejk@460
  1556
  }
phrebejk@460
  1557
phrebejk@460
  1558
  function setScrollTop(cm, val) {
phrebejk@460
  1559
    if (Math.abs(cm.view.scrollTop - val) < 2) return;
phrebejk@460
  1560
    cm.view.scrollTop = val;
phrebejk@460
  1561
    if (!gecko) updateDisplay(cm, [], val);
phrebejk@460
  1562
    if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
phrebejk@460
  1563
    if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
phrebejk@460
  1564
    if (gecko) updateDisplay(cm, []);
phrebejk@460
  1565
  }
phrebejk@460
  1566
  function setScrollLeft(cm, val, isScroller) {
phrebejk@460
  1567
    if (isScroller ? val == cm.view.scrollLeft : Math.abs(cm.view.scrollLeft - val) < 2) return;
phrebejk@460
  1568
    cm.view.scrollLeft = val;
phrebejk@460
  1569
    alignHorizontally(cm);
phrebejk@460
  1570
    if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
phrebejk@460
  1571
    if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
phrebejk@460
  1572
  }
phrebejk@460
  1573
phrebejk@460
  1574
  // Since the delta values reported on mouse wheel events are
phrebejk@460
  1575
  // unstandardized between browsers and even browser versions, and
phrebejk@460
  1576
  // generally horribly unpredictable, this code starts by measuring
phrebejk@460
  1577
  // the scroll effect that the first few mouse wheel events have,
phrebejk@460
  1578
  // and, from that, detects the way it can convert deltas to pixel
phrebejk@460
  1579
  // offsets afterwards.
phrebejk@460
  1580
  //
phrebejk@460
  1581
  // The reason we want to know the amount a wheel event will scroll
phrebejk@460
  1582
  // is that it gives us a chance to update the display before the
phrebejk@460
  1583
  // actual scrolling happens, reducing flickering.
phrebejk@460
  1584
phrebejk@460
  1585
  var wheelSamples = 0, wheelDX, wheelDY, wheelStartX, wheelStartY, wheelPixelsPerUnit = null;
phrebejk@460
  1586
  // Fill in a browser-detected starting value on browsers where we
phrebejk@460
  1587
  // know one. These don't have to be accurate -- the result of them
phrebejk@460
  1588
  // being wrong would just be a slight flicker on the first wheel
phrebejk@460
  1589
  // scroll (if it is large enough).
phrebejk@460
  1590
  if (ie) wheelPixelsPerUnit = -.53;
phrebejk@460
  1591
  else if (gecko) wheelPixelsPerUnit = 15;
phrebejk@460
  1592
  else if (chrome) wheelPixelsPerUnit = -.7;
phrebejk@460
  1593
  else if (safari) wheelPixelsPerUnit = -1/3;
phrebejk@460
  1594
phrebejk@460
  1595
  function onScrollWheel(cm, e) {
phrebejk@460
  1596
    var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
phrebejk@460
  1597
    if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
phrebejk@460
  1598
    if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
phrebejk@460
  1599
    else if (dy == null) dy = e.wheelDelta;
phrebejk@460
  1600
phrebejk@460
  1601
    // Webkit browsers on OS X abort momentum scrolls when the target
phrebejk@460
  1602
    // of the scroll event is removed from the scrollable element.
phrebejk@460
  1603
    // This hack (see related code in patchDisplay) makes sure the
phrebejk@460
  1604
    // element is kept around.
phrebejk@460
  1605
    if (dy && mac && webkit) {
phrebejk@460
  1606
      for (var cur = e.target; cur != scroll; cur = cur.parentNode) {
phrebejk@460
  1607
        if (cur.lineObj) {
phrebejk@460
  1608
          cm.display.currentWheelTarget = cur;
phrebejk@460
  1609
          break;
phrebejk@460
  1610
        }
phrebejk@460
  1611
      }
phrebejk@460
  1612
    }
phrebejk@460
  1613
phrebejk@460
  1614
    var scroll = cm.display.scroller;
phrebejk@460
  1615
    // On some browsers, horizontal scrolling will cause redraws to
phrebejk@460
  1616
    // happen before the gutter has been realigned, causing it to
phrebejk@460
  1617
    // wriggle around in a most unseemly way. When we have an
phrebejk@460
  1618
    // estimated pixels/delta value, we just handle horizontal
phrebejk@460
  1619
    // scrolling entirely here. It'll be slightly off from native, but
phrebejk@460
  1620
    // better than glitching out.
phrebejk@460
  1621
    if (dx && !gecko && !opera && wheelPixelsPerUnit != null) {
phrebejk@460
  1622
      if (dy)
phrebejk@460
  1623
        setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
phrebejk@460
  1624
      setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
phrebejk@460
  1625
      e_preventDefault(e);
phrebejk@460
  1626
      wheelStartX = null; // Abort measurement, if in progress
phrebejk@460
  1627
      return;
phrebejk@460
  1628
    }
phrebejk@460
  1629
phrebejk@460
  1630
    if (dy && wheelPixelsPerUnit != null) {
phrebejk@460
  1631
      var pixels = dy * wheelPixelsPerUnit;
phrebejk@460
  1632
      var top = cm.view.scrollTop, bot = top + cm.display.wrapper.clientHeight;
phrebejk@460
  1633
      if (pixels < 0) top = Math.max(0, top + pixels - 50);
phrebejk@460
  1634
      else bot = Math.min(cm.view.doc.height, bot + pixels + 50);
phrebejk@460
  1635
      updateDisplay(cm, [], {top: top, bottom: bot});
phrebejk@460
  1636
    }
phrebejk@460
  1637
phrebejk@460
  1638
    if (wheelSamples < 20) {
phrebejk@460
  1639
      if (wheelStartX == null) {
phrebejk@460
  1640
        wheelStartX = scroll.scrollLeft; wheelStartY = scroll.scrollTop;
phrebejk@460
  1641
        wheelDX = dx; wheelDY = dy;
phrebejk@460
  1642
        setTimeout(function() {
phrebejk@460
  1643
          if (wheelStartX == null) return;
phrebejk@460
  1644
          var movedX = scroll.scrollLeft - wheelStartX;
phrebejk@460
  1645
          var movedY = scroll.scrollTop - wheelStartY;
phrebejk@460
  1646
          var sample = (movedY && wheelDY && movedY / wheelDY) ||
phrebejk@460
  1647
            (movedX && wheelDX && movedX / wheelDX);
phrebejk@460
  1648
          wheelStartX = wheelStartY = null;
phrebejk@460
  1649
          if (!sample) return;
phrebejk@460
  1650
          wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
phrebejk@460
  1651
          ++wheelSamples;
phrebejk@460
  1652
        }, 200);
phrebejk@460
  1653
      } else {
phrebejk@460
  1654
        wheelDX += dx; wheelDY += dy;
phrebejk@460
  1655
      }
phrebejk@460
  1656
    }
phrebejk@460
  1657
  }
phrebejk@460
  1658
phrebejk@460
  1659
  function doHandleBinding(cm, bound, dropShift) {
phrebejk@460
  1660
    if (typeof bound == "string") {
phrebejk@460
  1661
      bound = commands[bound];
phrebejk@460
  1662
      if (!bound) return false;
phrebejk@460
  1663
    }
phrebejk@460
  1664
    // Ensure previous input has been read, so that the handler sees a
phrebejk@460
  1665
    // consistent view of the document
phrebejk@460
  1666
    if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
phrebejk@460
  1667
    var view = cm.view, prevShift = view.sel.shift;
phrebejk@460
  1668
    try {
phrebejk@460
  1669
      if (isReadOnly(cm)) view.suppressEdits = true;
phrebejk@460
  1670
      if (dropShift) view.sel.shift = false;
phrebejk@460
  1671
      bound(cm);
phrebejk@460
  1672
    } catch(e) {
phrebejk@460
  1673
      if (e != Pass) throw e;
phrebejk@460
  1674
      return false;
phrebejk@460
  1675
    } finally {
phrebejk@460
  1676
      view.sel.shift = prevShift;
phrebejk@460
  1677
      view.suppressEdits = false;
phrebejk@460
  1678
    }
phrebejk@460
  1679
    return true;
phrebejk@460
  1680
  }
phrebejk@460
  1681
phrebejk@460
  1682
  function allKeyMaps(cm) {
phrebejk@460
  1683
    var maps = cm.view.keyMaps.slice(0);
phrebejk@460
  1684
    maps.push(cm.options.keyMap);
phrebejk@460
  1685
    if (cm.options.extraKeys) maps.unshift(cm.options.extraKeys);
phrebejk@460
  1686
    return maps;
phrebejk@460
  1687
  }
phrebejk@460
  1688
phrebejk@460
  1689
  var maybeTransition;
phrebejk@460
  1690
  function handleKeyBinding(cm, e) {
phrebejk@460
  1691
    // Handle auto keymap transitions
phrebejk@460
  1692
    var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
phrebejk@460
  1693
    clearTimeout(maybeTransition);
phrebejk@460
  1694
    if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
phrebejk@460
  1695
      if (getKeyMap(cm.options.keyMap) == startMap)
phrebejk@460
  1696
        cm.options.keyMap = (next.call ? next.call(null, cm) : next);
phrebejk@460
  1697
    }, 50);
phrebejk@460
  1698
phrebejk@460
  1699
    var name = keyNames[e_prop(e, "keyCode")], handled = false;
phrebejk@460
  1700
    var flipCtrlCmd = mac && (opera || qtwebkit);
phrebejk@460
  1701
    if (name == null || e.altGraphKey) return false;
phrebejk@460
  1702
    if (e_prop(e, "altKey")) name = "Alt-" + name;
phrebejk@460
  1703
    if (e_prop(e, flipCtrlCmd ? "metaKey" : "ctrlKey")) name = "Ctrl-" + name;
phrebejk@460
  1704
    if (e_prop(e, flipCtrlCmd ? "ctrlKey" : "metaKey")) name = "Cmd-" + name;
phrebejk@460
  1705
phrebejk@460
  1706
    var stopped = false;
phrebejk@460
  1707
    function stop() { stopped = true; }
phrebejk@460
  1708
    var keymaps = allKeyMaps(cm);
phrebejk@460
  1709
phrebejk@460
  1710
    if (e_prop(e, "shiftKey")) {
phrebejk@460
  1711
      handled = lookupKey("Shift-" + name, keymaps,
phrebejk@460
  1712
                          function(b) {return doHandleBinding(cm, b, true);}, stop)
phrebejk@460
  1713
        || lookupKey(name, keymaps, function(b) {
phrebejk@460
  1714
          if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(cm, b);
phrebejk@460
  1715
        }, stop);
phrebejk@460
  1716
    } else {
phrebejk@460
  1717
      handled = lookupKey(name, keymaps,
phrebejk@460
  1718
                          function(b) { return doHandleBinding(cm, b); }, stop);
phrebejk@460
  1719
    }
phrebejk@460
  1720
    if (stopped) handled = false;
phrebejk@460
  1721
    if (handled) {
phrebejk@460
  1722
      e_preventDefault(e);
phrebejk@460
  1723
      restartBlink(cm);
phrebejk@460
  1724
      if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
phrebejk@460
  1725
    }
phrebejk@460
  1726
    return handled;
phrebejk@460
  1727
  }
phrebejk@460
  1728
phrebejk@460
  1729
  function handleCharBinding(cm, e, ch) {
phrebejk@460
  1730
    var handled = lookupKey("'" + ch + "'", allKeyMaps(cm),
phrebejk@460
  1731
                            function(b) { return doHandleBinding(cm, b, true); });
phrebejk@460
  1732
    if (handled) {
phrebejk@460
  1733
      e_preventDefault(e);
phrebejk@460
  1734
      restartBlink(cm);
phrebejk@460
  1735
    }
phrebejk@460
  1736
    return handled;
phrebejk@460
  1737
  }
phrebejk@460
  1738
phrebejk@460
  1739
  var lastStoppedKey = null;
phrebejk@460
  1740
  function onKeyDown(e) {
phrebejk@460
  1741
    var cm = this;
phrebejk@460
  1742
    if (!cm.view.focused) onFocus(cm);
phrebejk@460
  1743
    if (ie && e.keyCode == 27) { e.returnValue = false; }
phrebejk@460
  1744
    if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
phrebejk@460
  1745
    var code = e_prop(e, "keyCode");
phrebejk@460
  1746
    // IE does strange things with escape.
phrebejk@460
  1747
    cm.view.sel.shift = code == 16 || e_prop(e, "shiftKey");
phrebejk@460
  1748
    // First give onKeyEvent option a chance to handle this.
phrebejk@460
  1749
    var handled = handleKeyBinding(cm, e);
phrebejk@460
  1750
    if (opera) {
phrebejk@460
  1751
      lastStoppedKey = handled ? code : null;
phrebejk@460
  1752
      // Opera has no cut event... we try to at least catch the key combo
phrebejk@460
  1753
      if (!handled && code == 88 && !hasCopyEvent && e_prop(e, mac ? "metaKey" : "ctrlKey"))
phrebejk@460
  1754
        cm.replaceSelection("");
phrebejk@460
  1755
    }
phrebejk@460
  1756
  }
phrebejk@460
  1757
phrebejk@460
  1758
  function onKeyPress(e) {
phrebejk@460
  1759
    var cm = this;
phrebejk@460
  1760
    if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
phrebejk@460
  1761
    var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode");
phrebejk@460
  1762
    if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
phrebejk@460
  1763
    if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
phrebejk@460
  1764
    var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
phrebejk@460
  1765
    if (this.options.electricChars && this.view.mode.electricChars &&
phrebejk@460
  1766
        this.options.smartIndent && !isReadOnly(this) &&
phrebejk@460
  1767
        this.view.mode.electricChars.indexOf(ch) > -1)
phrebejk@460
  1768
      setTimeout(operation(cm, function() {indentLine(cm, cm.view.sel.to.line, "smart");}), 75);
phrebejk@460
  1769
    if (handleCharBinding(cm, e, ch)) return;
phrebejk@460
  1770
    fastPoll(cm);
phrebejk@460
  1771
  }
phrebejk@460
  1772
phrebejk@460
  1773
  function onFocus(cm) {
phrebejk@460
  1774
    if (cm.options.readOnly == "nocursor") return;
phrebejk@460
  1775
    if (!cm.view.focused) {
phrebejk@460
  1776
      signal(cm, "focus", cm);
phrebejk@460
  1777
      cm.view.focused = true;
phrebejk@460
  1778
      if (cm.display.scroller.className.search(/\bCodeMirror-focused\b/) == -1)
phrebejk@460
  1779
        cm.display.scroller.className += " CodeMirror-focused";
phrebejk@460
  1780
      resetInput(cm, true);
phrebejk@460
  1781
    }
phrebejk@460
  1782
    slowPoll(cm);
phrebejk@460
  1783
    restartBlink(cm);
phrebejk@460
  1784
  }
phrebejk@460
  1785
  function onBlur(cm) {
phrebejk@460
  1786
    if (cm.view.focused) {
phrebejk@460
  1787
      signal(cm, "blur", cm);
phrebejk@460
  1788
      cm.view.focused = false;
phrebejk@460
  1789
      cm.display.scroller.className = cm.display.scroller.className.replace(" CodeMirror-focused", "");
phrebejk@460
  1790
    }
phrebejk@460
  1791
    clearInterval(cm.display.blinker);
phrebejk@460
  1792
    setTimeout(function() {if (!cm.view.focused) cm.view.sel.shift = false;}, 150);
phrebejk@460
  1793
  }
phrebejk@460
  1794
phrebejk@460
  1795
  var detectingSelectAll;
phrebejk@460
  1796
  function onContextMenu(cm, e) {
phrebejk@460
  1797
    var display = cm.display, sel = cm.view.sel;
phrebejk@460
  1798
    var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
phrebejk@460
  1799
    if (!pos || opera) return; // Opera is difficult.
phrebejk@460
  1800
    if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
phrebejk@460
  1801
      operation(cm, setSelection)(cm, pos, pos);
phrebejk@460
  1802
phrebejk@460
  1803
    var oldCSS = display.input.style.cssText;
phrebejk@460
  1804
    display.inputDiv.style.position = "absolute";
phrebejk@460
  1805
    display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
phrebejk@460
  1806
      "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" +
phrebejk@460
  1807
      "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
phrebejk@460
  1808
    focusInput(cm);
phrebejk@460
  1809
    resetInput(cm, true);
phrebejk@460
  1810
    // Adds "Select all" to context menu in FF
phrebejk@460
  1811
    if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " ";
phrebejk@460
  1812
phrebejk@460
  1813
    function rehide() {
phrebejk@460
  1814
      display.inputDiv.style.position = "relative";
phrebejk@460
  1815
      display.input.style.cssText = oldCSS;
phrebejk@460
  1816
      if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
phrebejk@460
  1817
      slowPoll(cm);
phrebejk@460
  1818
phrebejk@460
  1819
      // Try to detect the user choosing select-all 
phrebejk@460
  1820
      if (display.input.selectionStart != null) {
phrebejk@460
  1821
        clearTimeout(detectingSelectAll);
phrebejk@460
  1822
        var extval = display.input.value = " " + (posEq(sel.from, sel.to) ? "" : display.input.value), i = 0;
phrebejk@460
  1823
        display.prevInput = " ";
phrebejk@460
  1824
        display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
phrebejk@460
  1825
        detectingSelectAll = setTimeout(function poll(){
phrebejk@460
  1826
          if (display.prevInput == " " && display.input.selectionStart == 0)
phrebejk@460
  1827
            operation(cm, commands.selectAll)(cm);
phrebejk@460
  1828
          else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
phrebejk@460
  1829
          else resetInput(cm);
phrebejk@460
  1830
        }, 200);
phrebejk@460
  1831
      }
phrebejk@460
  1832
    }
phrebejk@460
  1833
phrebejk@460
  1834
    if (gecko) {
phrebejk@460
  1835
      e_stop(e);
phrebejk@460
  1836
      on(window, "mouseup", function mouseup() {
phrebejk@460
  1837
        off(window, "mouseup", mouseup);
phrebejk@460
  1838
        setTimeout(rehide, 20);
phrebejk@460
  1839
      });
phrebejk@460
  1840
    } else {
phrebejk@460
  1841
      setTimeout(rehide, 50);
phrebejk@460
  1842
    }
phrebejk@460
  1843
  }
phrebejk@460
  1844
phrebejk@460
  1845
  // UPDATING
phrebejk@460
  1846
phrebejk@460
  1847
  // Replace the range from from to to by the strings in newText.
phrebejk@460
  1848
  // Afterwards, set the selection to selFrom, selTo.
phrebejk@460
  1849
  function updateDoc(cm, from, to, newText, selUpdate, origin) {
phrebejk@460
  1850
    // Possibly split or suppress the update based on the presence
phrebejk@460
  1851
    // of read-only spans in its range.
phrebejk@460
  1852
    var split = sawReadOnlySpans &&
phrebejk@460
  1853
      removeReadOnlyRanges(cm.view.doc, from, to);
phrebejk@460
  1854
    if (split) {
phrebejk@460
  1855
      for (var i = split.length - 1; i >= 1; --i)
phrebejk@460
  1856
        updateDocInner(cm, split[i].from, split[i].to, [""], origin);
phrebejk@460
  1857
      if (split.length)
phrebejk@460
  1858
        return updateDocInner(cm, split[0].from, split[0].to, newText, selUpdate, origin);
phrebejk@460
  1859
    } else {
phrebejk@460
  1860
      return updateDocInner(cm, from, to, newText, selUpdate, origin);
phrebejk@460
  1861
    }
phrebejk@460
  1862
  }
phrebejk@460
  1863
phrebejk@460
  1864
  function updateDocInner(cm, from, to, newText, selUpdate, origin) {
phrebejk@460
  1865
    if (cm.view.suppressEdits) return;
phrebejk@460
  1866
phrebejk@460
  1867
    var view = cm.view, doc = view.doc, old = [];
phrebejk@460
  1868
    doc.iter(from.line, to.line + 1, function(line) {
phrebejk@460
  1869
      old.push(newHL(line.text, line.markedSpans));
phrebejk@460
  1870
    });
phrebejk@460
  1871
    var startSelFrom = view.sel.from, startSelTo = view.sel.to;
phrebejk@460
  1872
    var lines = updateMarkedSpans(hlSpans(old[0]), hlSpans(lst(old)), from.ch, to.ch, newText);
phrebejk@460
  1873
    var retval = updateDocNoUndo(cm, from, to, lines, selUpdate, origin);
phrebejk@460
  1874
    if (view.history) addChange(cm, from.line, newText.length, old, origin,
phrebejk@460
  1875
                                startSelFrom, startSelTo, view.sel.from, view.sel.to);
phrebejk@460
  1876
    return retval;
phrebejk@460
  1877
  }
phrebejk@460
  1878
phrebejk@460
  1879
  function unredoHelper(cm, type) {
phrebejk@460
  1880
    var doc = cm.view.doc, hist = cm.view.history;
phrebejk@460
  1881
    var set = (type == "undo" ? hist.done : hist.undone).pop();
phrebejk@460
  1882
    if (!set) return;
phrebejk@460
  1883
    var anti = {events: [], fromBefore: set.fromAfter, toBefore: set.toAfter,
phrebejk@460
  1884
                fromAfter: set.fromBefore, toAfter: set.toBefore};
phrebejk@460
  1885
    for (var i = set.events.length - 1; i >= 0; i -= 1) {
phrebejk@460
  1886
      hist.dirtyCounter += type == "undo" ? -1 : 1;
phrebejk@460
  1887
      var change = set.events[i];
phrebejk@460
  1888
      var replaced = [], end = change.start + change.added;
phrebejk@460
  1889
      doc.iter(change.start, end, function(line) { replaced.push(newHL(line.text, line.markedSpans)); });
phrebejk@460
  1890
      anti.events.push({start: change.start, added: change.old.length, old: replaced});
phrebejk@460
  1891
      var selPos = i ? null : {from: set.fromBefore, to: set.toBefore};
phrebejk@460
  1892
      updateDocNoUndo(cm, {line: change.start, ch: 0}, {line: end - 1, ch: getLine(doc, end-1).text.length},
phrebejk@460
  1893
                      change.old, selPos, type);
phrebejk@460
  1894
    }
phrebejk@460
  1895
    (type == "undo" ? hist.undone : hist.done).push(anti);
phrebejk@460
  1896
  }
phrebejk@460
  1897
phrebejk@460
  1898
  function updateDocNoUndo(cm, from, to, lines, selUpdate, origin) {
phrebejk@460
  1899
    var view = cm.view, doc = view.doc, display = cm.display;
phrebejk@460
  1900
    if (view.suppressEdits) return;
phrebejk@460
  1901
phrebejk@460
  1902
    var nlines = to.line - from.line, firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
phrebejk@460
  1903
    var recomputeMaxLength = false, checkWidthStart = from.line;
phrebejk@460
  1904
    if (!cm.options.lineWrapping) {
phrebejk@460
  1905
      checkWidthStart = lineNo(visualLine(doc, firstLine));
phrebejk@460
  1906
      doc.iter(checkWidthStart, to.line + 1, function(line) {
phrebejk@460
  1907
        if (lineLength(doc, line) == view.maxLineLength) {
phrebejk@460
  1908
          recomputeMaxLength = true;
phrebejk@460
  1909
          return true;
phrebejk@460
  1910
        }
phrebejk@460
  1911
      });
phrebejk@460
  1912
    }
phrebejk@460
  1913
phrebejk@460
  1914
    var lastHL = lst(lines), th = textHeight(display);
phrebejk@460
  1915
phrebejk@460
  1916
    // First adjust the line structure
phrebejk@460
  1917
    if (from.ch == 0 && to.ch == 0 && hlText(lastHL) == "") {
phrebejk@460
  1918
      // This is a whole-line replace. Treated specially to make
phrebejk@460
  1919
      // sure line objects move the way they are supposed to.
phrebejk@460
  1920
      var added = [];
phrebejk@460
  1921
      for (var i = 0, e = lines.length - 1; i < e; ++i)
phrebejk@460
  1922
        added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th));
phrebejk@460
  1923
      updateLine(cm, lastLine, lastLine.text, hlSpans(lastHL));
phrebejk@460
  1924
      if (nlines) doc.remove(from.line, nlines, cm);
phrebejk@460
  1925
      if (added.length) doc.insert(from.line, added);
phrebejk@460
  1926
    } else if (firstLine == lastLine) {
phrebejk@460
  1927
      if (lines.length == 1) {
phrebejk@460
  1928
        updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]) +
phrebejk@460
  1929
                   firstLine.text.slice(to.ch), hlSpans(lines[0]));
phrebejk@460
  1930
      } else {
phrebejk@460
  1931
        for (var added = [], i = 1, e = lines.length - 1; i < e; ++i)
phrebejk@460
  1932
          added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th));
phrebejk@460
  1933
        added.push(makeLine(hlText(lastHL) + firstLine.text.slice(to.ch), hlSpans(lastHL), th));
phrebejk@460
  1934
        updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0]));
phrebejk@460
  1935
        doc.insert(from.line + 1, added);
phrebejk@460
  1936
      }
phrebejk@460
  1937
    } else if (lines.length == 1) {
phrebejk@460
  1938
      updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]) +
phrebejk@460
  1939
                 lastLine.text.slice(to.ch), hlSpans(lines[0]));
phrebejk@460
  1940
      doc.remove(from.line + 1, nlines, cm);
phrebejk@460
  1941
    } else {
phrebejk@460
  1942
      var added = [];
phrebejk@460
  1943
      updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0]));
phrebejk@460
  1944
      updateLine(cm, lastLine, hlText(lastHL) + lastLine.text.slice(to.ch), hlSpans(lastHL));
phrebejk@460
  1945
      for (var i = 1, e = lines.length - 1; i < e; ++i)
phrebejk@460
  1946
        added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th));
phrebejk@460
  1947
      if (nlines > 1) doc.remove(from.line + 1, nlines - 1, cm);
phrebejk@460
  1948
      doc.insert(from.line + 1, added);
phrebejk@460
  1949
    }
phrebejk@460
  1950
phrebejk@460
  1951
    if (cm.options.lineWrapping) {
phrebejk@460
  1952
      var perLine = Math.max(5, display.scroller.clientWidth / charWidth(display) - 3);
phrebejk@460
  1953
      doc.iter(from.line, from.line + lines.length, function(line) {
phrebejk@460
  1954
        if (line.height == 0) return;
phrebejk@460
  1955
        var guess = (Math.ceil(line.text.length / perLine) || 1) * th;
phrebejk@460
  1956
        if (guess != line.height) updateLineHeight(line, guess);
phrebejk@460
  1957
      });
phrebejk@460
  1958
    } else {
phrebejk@460
  1959
      doc.iter(checkWidthStart, from.line + lines.length, function(line) {
phrebejk@460
  1960
        var len = lineLength(doc, line);
phrebejk@460
  1961
        if (len > view.maxLineLength) {
phrebejk@460
  1962
          view.maxLine = line;
phrebejk@460
  1963
          view.maxLineLength = len;
phrebejk@460
  1964
          view.maxLineChanged = true;
phrebejk@460
  1965
          recomputeMaxLength = false;
phrebejk@460
  1966
        }
phrebejk@460
  1967
      });
phrebejk@460
  1968
      if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
phrebejk@460
  1969
    }
phrebejk@460
  1970
phrebejk@460
  1971
    // Adjust frontier, schedule worker
phrebejk@460
  1972
    view.frontier = Math.min(view.frontier, from.line);
phrebejk@460
  1973
    startWorker(cm, 400);
phrebejk@460
  1974
phrebejk@460
  1975
    var lendiff = lines.length - nlines - 1;
phrebejk@460
  1976
    // Remember that these lines changed, for updating the display
phrebejk@460
  1977
    regChange(cm, from.line, to.line + 1, lendiff);
phrebejk@460
  1978
    if (hasHandler(cm, "change")) {
phrebejk@460
  1979
      // Normalize lines to contain only strings, since that's what
phrebejk@460
  1980
      // the change event handler expects
phrebejk@460
  1981
      for (var i = 0; i < lines.length; ++i)
phrebejk@460
  1982
        if (typeof lines[i] != "string") lines[i] = lines[i].text;
phrebejk@460
  1983
      var changeObj = {from: from, to: to, text: lines, origin: origin};
phrebejk@460
  1984
      if (cm.curOp.textChanged) {
phrebejk@460
  1985
        for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {}
phrebejk@460
  1986
        cur.next = changeObj;
phrebejk@460
  1987
      } else cm.curOp.textChanged = changeObj;
phrebejk@460
  1988
    }
phrebejk@460
  1989
phrebejk@460
  1990
    // Update the selection
phrebejk@460
  1991
    var newSelFrom, newSelTo, end = {line: from.line + lines.length - 1,
phrebejk@460
  1992
                                     ch: hlText(lastHL).length  + (lines.length == 1 ? from.ch : 0)};
phrebejk@460
  1993
    if (selUpdate && typeof selUpdate != "string") {
phrebejk@460
  1994
      if (selUpdate.from) { newSelFrom = selUpdate.from; newSelTo = selUpdate.to; }
phrebejk@460
  1995
      else newSelFrom = newSelTo = selUpdate;
phrebejk@460
  1996
    } else if (selUpdate == "end") {
phrebejk@460
  1997
      newSelFrom = newSelTo = end;
phrebejk@460
  1998
    } else if (selUpdate == "start") {
phrebejk@460
  1999
      newSelFrom = newSelTo = from;
phrebejk@460
  2000
    } else if (selUpdate == "around") {
phrebejk@460
  2001
      newSelFrom = from; newSelTo = end;
phrebejk@460
  2002
    } else {
phrebejk@460
  2003
      var adjustPos = function(pos) {
phrebejk@460
  2004
        if (posLess(pos, from)) return pos;
phrebejk@460
  2005
        if (!posLess(to, pos)) return end;
phrebejk@460
  2006
        var line = pos.line + lendiff;
phrebejk@460
  2007
        var ch = pos.ch;
phrebejk@460
  2008
        if (pos.line == to.line)
phrebejk@460
  2009
          ch += hlText(lastHL).length - (to.ch - (to.line == from.line ? from.ch : 0));
phrebejk@460
  2010
        return {line: line, ch: ch};
phrebejk@460
  2011
      };
phrebejk@460
  2012
      newSelFrom = adjustPos(view.sel.from);
phrebejk@460
  2013
      newSelTo = adjustPos(view.sel.to);
phrebejk@460
  2014
    }
phrebejk@460
  2015
    setSelection(cm, newSelFrom, newSelTo, null, true);
phrebejk@460
  2016
    return end;
phrebejk@460
  2017
  }
phrebejk@460
  2018
phrebejk@460
  2019
  function replaceRange(cm, code, from, to, origin) {
phrebejk@460
  2020
    if (!to) to = from;
phrebejk@460
  2021
    if (posLess(to, from)) { var tmp = to; to = from; from = tmp; }
phrebejk@460
  2022
    return updateDoc(cm, from, to, splitLines(code), null, origin);
phrebejk@460
  2023
  }
phrebejk@460
  2024
phrebejk@460
  2025
  // SELECTION
phrebejk@460
  2026
phrebejk@460
  2027
  function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
phrebejk@460
  2028
  function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
phrebejk@460
  2029
  function copyPos(x) {return {line: x.line, ch: x.ch};}
phrebejk@460
  2030
phrebejk@460
  2031
  function clipLine(doc, n) {return Math.max(0, Math.min(n, doc.size-1));}
phrebejk@460
  2032
  function clipPos(doc, pos) {
phrebejk@460
  2033
    if (pos.line < 0) return {line: 0, ch: 0};
phrebejk@460
  2034
    if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc, doc.size-1).text.length};
phrebejk@460
  2035
    var ch = pos.ch, linelen = getLine(doc, pos.line).text.length;
phrebejk@460
  2036
    if (ch == null || ch > linelen) return {line: pos.line, ch: linelen};
phrebejk@460
  2037
    else if (ch < 0) return {line: pos.line, ch: 0};
phrebejk@460
  2038
    else return pos;
phrebejk@460
  2039
  }
phrebejk@460
  2040
  function isLine(doc, l) {return l >= 0 && l < doc.size;}
phrebejk@460
  2041
phrebejk@460
  2042
  // If shift is held, this will move the selection anchor. Otherwise,
phrebejk@460
  2043
  // it'll set the whole selection.
phrebejk@460
  2044
  function extendSelection(cm, pos, other, bias) {
phrebejk@460
  2045
    var sel = cm.view.sel;
phrebejk@460
  2046
    if (sel.shift || sel.extend) {
phrebejk@460
  2047
      var anchor = sel.anchor;
phrebejk@460
  2048
      if (other) {
phrebejk@460
  2049
        var posBefore = posLess(pos, anchor);
phrebejk@460
  2050
        if (posBefore != posLess(other, anchor)) {
phrebejk@460
  2051
          anchor = pos;
phrebejk@460
  2052
          pos = other;
phrebejk@460
  2053
        } else if (posBefore != posLess(pos, other)) {
phrebejk@460
  2054
          pos = other;
phrebejk@460
  2055
        }
phrebejk@460
  2056
      }
phrebejk@460
  2057
      setSelection(cm, anchor, pos, bias);
phrebejk@460
  2058
    } else {
phrebejk@460
  2059
      setSelection(cm, pos, other || pos, bias);
phrebejk@460
  2060
    }
phrebejk@460
  2061
    cm.curOp.userSelChange = true;
phrebejk@460
  2062
  }
phrebejk@460
  2063
phrebejk@460
  2064
  // Update the selection. Last two args are only used by
phrebejk@460
  2065
  // updateDoc, since they have to be expressed in the line
phrebejk@460
  2066
  // numbers before the update.
phrebejk@460
  2067
  function setSelection(cm, anchor, head, bias, checkAtomic) {
phrebejk@460
  2068
    cm.view.goalColumn = null;
phrebejk@460
  2069
    var sel = cm.view.sel;
phrebejk@460
  2070
    // Skip over atomic spans.
phrebejk@460
  2071
    if (checkAtomic || !posEq(anchor, sel.anchor))
phrebejk@460
  2072
      anchor = skipAtomic(cm, anchor, bias, checkAtomic != "push");
phrebejk@460
  2073
    if (checkAtomic || !posEq(head, sel.head))
phrebejk@460
  2074
      head = skipAtomic(cm, head, bias, checkAtomic != "push");
phrebejk@460
  2075
phrebejk@460
  2076
    if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return;
phrebejk@460
  2077
phrebejk@460
  2078
    sel.anchor = anchor; sel.head = head;
phrebejk@460
  2079
    var inv = posLess(head, anchor);
phrebejk@460
  2080
    sel.from = inv ? head : anchor;
phrebejk@460
  2081
    sel.to = inv ? anchor : head;
phrebejk@460
  2082
phrebejk@460
  2083
    cm.curOp.updateInput = true;
phrebejk@460
  2084
    cm.curOp.selectionChanged = true;
phrebejk@460
  2085
  }
phrebejk@460
  2086
phrebejk@460
  2087
  function reCheckSelection(cm) {
phrebejk@460
  2088
    setSelection(cm, cm.view.sel.from, cm.view.sel.to, null, "push");
phrebejk@460
  2089
  }
phrebejk@460
  2090
phrebejk@460
  2091
  function skipAtomic(cm, pos, bias, mayClear) {
phrebejk@460
  2092
    var doc = cm.view.doc, flipped = false, curPos = pos;
phrebejk@460
  2093
    var dir = bias || 1;
phrebejk@460
  2094
    cm.view.cantEdit = false;
phrebejk@460
  2095
    search: for (;;) {
phrebejk@460
  2096
      var line = getLine(doc, curPos.line), toClear;
phrebejk@460
  2097
      if (line.markedSpans) {
phrebejk@460
  2098
        for (var i = 0; i < line.markedSpans.length; ++i) {
phrebejk@460
  2099
          var sp = line.markedSpans[i], m = sp.marker;
phrebejk@460
  2100
          if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
phrebejk@460
  2101
              (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
phrebejk@460
  2102
            if (mayClear && m.clearOnEnter) {
phrebejk@460
  2103
              (toClear || (toClear = [])).push(m);
phrebejk@460
  2104
              continue;
phrebejk@460
  2105
            } else if (!m.atomic) continue;
phrebejk@460
  2106
            var newPos = m.find()[dir < 0 ? "from" : "to"];
phrebejk@460
  2107
            if (posEq(newPos, curPos)) {
phrebejk@460
  2108
              newPos.ch += dir;
phrebejk@460
  2109
              if (newPos.ch < 0) {
phrebejk@460
  2110
                if (newPos.line) newPos = clipPos(doc, {line: newPos.line - 1});
phrebejk@460
  2111
                else newPos = null;
phrebejk@460
  2112
              } else if (newPos.ch > line.text.length) {
phrebejk@460
  2113
                if (newPos.line < doc.size - 1) newPos = {line: newPos.line + 1, ch: 0};
phrebejk@460
  2114
                else newPos = null;
phrebejk@460
  2115
              }
phrebejk@460
  2116
              if (!newPos) {
phrebejk@460
  2117
                if (flipped) {
phrebejk@460
  2118
                  // Driven in a corner -- no valid cursor position found at all
phrebejk@460
  2119
                  // -- try again *with* clearing, if we didn't already
phrebejk@460
  2120
                  if (!mayClear) return skipAtomic(cm, pos, bias, true);
phrebejk@460
  2121
                  // Otherwise, turn off editing until further notice, and return the start of the doc
phrebejk@460
  2122
                  cm.view.cantEdit = true;
phrebejk@460
  2123
                  return {line: 0, ch: 0};
phrebejk@460
  2124
                }
phrebejk@460
  2125
                flipped = true; newPos = pos; dir = -dir;
phrebejk@460
  2126
              }
phrebejk@460
  2127
            }
phrebejk@460
  2128
            curPos = newPos;
phrebejk@460
  2129
            continue search;
phrebejk@460
  2130
          }
phrebejk@460
  2131
        }
phrebejk@460
  2132
        if (toClear) for (var i = 0; i < toClear.length; ++i) toClear[i].clear();
phrebejk@460
  2133
      }
phrebejk@460
  2134
      return curPos;
phrebejk@460
  2135
    }
phrebejk@460
  2136
  }
phrebejk@460
  2137
phrebejk@460
  2138
  // SCROLLING
phrebejk@460
  2139
phrebejk@460
  2140
  function scrollCursorIntoView(cm) {
phrebejk@460
  2141
    var view = cm.view;
phrebejk@460
  2142
    var coords = scrollPosIntoView(cm, view.sel.head);
phrebejk@460
  2143
    if (!view.focused) return;
phrebejk@460
  2144
    var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
phrebejk@460
  2145
    if (coords.top + box.top < 0) doScroll = true;
phrebejk@460
  2146
    else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
phrebejk@460
  2147
    if (doScroll != null && !phantom) {
phrebejk@460
  2148
      var hidden = display.cursor.style.display == "none";
phrebejk@460
  2149
      if (hidden) {
phrebejk@460
  2150
        display.cursor.style.display = "";
phrebejk@460
  2151
        display.cursor.style.left = coords.left + "px";
phrebejk@460
  2152
        display.cursor.style.top = (coords.top - display.viewOffset) + "px";
phrebejk@460
  2153
      }
phrebejk@460
  2154
      display.cursor.scrollIntoView(doScroll);
phrebejk@460
  2155
      if (hidden) display.cursor.style.display = "none";
phrebejk@460
  2156
    }
phrebejk@460
  2157
  }
phrebejk@460
  2158
phrebejk@460
  2159
  function scrollPosIntoView(cm, pos) {
phrebejk@460
  2160
    for (;;) {
phrebejk@460
  2161
      var changed = false, coords = cursorCoords(cm, pos);
phrebejk@460
  2162
      var scrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom);
phrebejk@460
  2163
      var startTop = cm.view.scrollTop, startLeft = cm.view.scrollLeft;
phrebejk@460
  2164
      if (scrollPos.scrollTop != null) {
phrebejk@460
  2165
        setScrollTop(cm, scrollPos.scrollTop);
phrebejk@460
  2166
        if (Math.abs(cm.view.scrollTop - startTop) > 1) changed = true;
phrebejk@460
  2167
      }
phrebejk@460
  2168
      if (scrollPos.scrollLeft != null) {
phrebejk@460
  2169
        setScrollLeft(cm, scrollPos.scrollLeft);
phrebejk@460
  2170
        if (Math.abs(cm.view.scrollLeft - startLeft) > 1) changed = true;
phrebejk@460
  2171
      }
phrebejk@460
  2172
      if (!changed) return coords;
phrebejk@460
  2173
    }
phrebejk@460
  2174
  }
phrebejk@460
  2175
phrebejk@460
  2176
  function scrollIntoView(cm, x1, y1, x2, y2) {
phrebejk@460
  2177
    var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
phrebejk@460
  2178
    if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
phrebejk@460
  2179
    if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
phrebejk@460
  2180
  }
phrebejk@460
  2181
phrebejk@460
  2182
  function calculateScrollPos(cm, x1, y1, x2, y2) {
phrebejk@460
  2183
    var display = cm.display, pt = paddingTop(display);
phrebejk@460
  2184
    y1 += pt; y2 += pt;
phrebejk@460
  2185
    var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {};
phrebejk@460
  2186
    var docBottom = cm.view.doc.height + 2 * pt;
phrebejk@460
  2187
    var atTop = y1 < pt + 10, atBottom = y2 + pt > docBottom - 10;
phrebejk@460
  2188
    if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1);
phrebejk@460
  2189
    else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2) - screen;
phrebejk@460
  2190
phrebejk@460
  2191
    var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft;
phrebejk@460
  2192
    x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
phrebejk@460
  2193
    var gutterw = display.gutters.offsetWidth;
phrebejk@460
  2194
    var atLeft = x1 < gutterw + 10;
phrebejk@460
  2195
    if (x1 < screenleft + gutterw || atLeft) {
phrebejk@460
  2196
      if (atLeft) x1 = 0;
phrebejk@460
  2197
      result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
phrebejk@460
  2198
    } else if (x2 > screenw + screenleft - 3) {
phrebejk@460
  2199
      result.scrollLeft = x2 + 10 - screenw;
phrebejk@460
  2200
    }
phrebejk@460
  2201
    return result;
phrebejk@460
  2202
  }
phrebejk@460
  2203
phrebejk@460
  2204
  // API UTILITIES
phrebejk@460
  2205
phrebejk@460
  2206
  function indentLine(cm, n, how, aggressive) {
phrebejk@460
  2207
    var doc = cm.view.doc;
phrebejk@460
  2208
    if (!how) how = "add";
phrebejk@460
  2209
    if (how == "smart") {
phrebejk@460
  2210
      if (!cm.view.mode.indent) how = "prev";
phrebejk@460
  2211
      else var state = getStateBefore(cm, n);
phrebejk@460
  2212
    }
phrebejk@460
  2213
phrebejk@460
  2214
    var tabSize = cm.options.tabSize;
phrebejk@460
  2215
    var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
phrebejk@460
  2216
    var curSpaceString = line.text.match(/^\s*/)[0], indentation;
phrebejk@460
  2217
    if (how == "smart") {
phrebejk@460
  2218
      indentation = cm.view.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
phrebejk@460
  2219
      if (indentation == Pass) {
phrebejk@460
  2220
        if (!aggressive) return;
phrebejk@460
  2221
        how = "prev";
phrebejk@460
  2222
      }
phrebejk@460
  2223
    }
phrebejk@460
  2224
    if (how == "prev") {
phrebejk@460
  2225
      if (n) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
phrebejk@460
  2226
      else indentation = 0;
phrebejk@460
  2227
    }
phrebejk@460
  2228
    else if (how == "add") indentation = curSpace + cm.options.indentUnit;
phrebejk@460
  2229
    else if (how == "subtract") indentation = curSpace - cm.options.indentUnit;
phrebejk@460
  2230
    indentation = Math.max(0, indentation);
phrebejk@460
  2231
phrebejk@460
  2232
    var indentString = "", pos = 0;
phrebejk@460
  2233
    if (cm.options.indentWithTabs)
phrebejk@460
  2234
      for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
phrebejk@460
  2235
    if (pos < indentation) indentString += spaceStr(indentation - pos);
phrebejk@460
  2236
phrebejk@460
  2237
    if (indentString != curSpaceString)
phrebejk@460
  2238
      replaceRange(cm, indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length}, "input");
phrebejk@460
  2239
    line.stateAfter = null;
phrebejk@460
  2240
  }
phrebejk@460
  2241
phrebejk@460
  2242
  function changeLine(cm, handle, op) {
phrebejk@460
  2243
    var no = handle, line = handle, doc = cm.view.doc;
phrebejk@460
  2244
    if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
phrebejk@460
  2245
    else no = lineNo(handle);
phrebejk@460
  2246
    if (no == null) return null;
phrebejk@460
  2247
    if (op(line, no)) regChange(cm, no, no + 1);
phrebejk@460
  2248
    else return null;
phrebejk@460
  2249
    return line;
phrebejk@460
  2250
  }
phrebejk@460
  2251
phrebejk@460
  2252
  function findPosH(cm, dir, unit, visually) {
phrebejk@460
  2253
    var doc = cm.view.doc, end = cm.view.sel.head, line = end.line, ch = end.ch;
phrebejk@460
  2254
    var lineObj = getLine(doc, line);
phrebejk@460
  2255
    function findNextLine() {
phrebejk@460
  2256
      var l = line + dir;
phrebejk@460
  2257
      if (l < 0 || l == doc.size) return false;
phrebejk@460
  2258
      line = l;
phrebejk@460
  2259
      return lineObj = getLine(doc, l);
phrebejk@460
  2260
    }
phrebejk@460
  2261
    function moveOnce(boundToLine) {
phrebejk@460
  2262
      var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
phrebejk@460
  2263
      if (next == null) {
phrebejk@460
  2264
        if (!boundToLine && findNextLine()) {
phrebejk@460
  2265
          if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
phrebejk@460
  2266
          else ch = dir < 0 ? lineObj.text.length : 0;
phrebejk@460
  2267
        } else return false;
phrebejk@460
  2268
      } else ch = next;
phrebejk@460
  2269
      return true;
phrebejk@460
  2270
    }
phrebejk@460
  2271
    if (unit == "char") moveOnce();
phrebejk@460
  2272
    else if (unit == "column") moveOnce(true);
phrebejk@460
  2273
    else if (unit == "word") {
phrebejk@460
  2274
      var sawWord = false;
phrebejk@460
  2275
      for (;;) {
phrebejk@460
  2276
        if (dir < 0) if (!moveOnce()) break;
phrebejk@460
  2277
        if (isWordChar(lineObj.text.charAt(ch))) sawWord = true;
phrebejk@460
  2278
        else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;}
phrebejk@460
  2279
        if (dir > 0) if (!moveOnce()) break;
phrebejk@460
  2280
      }
phrebejk@460
  2281
    }
phrebejk@460
  2282
    return skipAtomic(cm, {line: line, ch: ch}, dir, true);
phrebejk@460
  2283
  }
phrebejk@460
  2284
phrebejk@460
  2285
  function findWordAt(line, pos) {
phrebejk@460
  2286
    var start = pos.ch, end = pos.ch;
phrebejk@460
  2287
    if (line) {
phrebejk@460
  2288
      if (pos.after === false || end == line.length) --start; else ++end;
phrebejk@460
  2289
      var startChar = line.charAt(start);
phrebejk@460
  2290
      var check = isWordChar(startChar) ? isWordChar :
phrebejk@460
  2291
        /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} :
phrebejk@460
  2292
      function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
phrebejk@460
  2293
      while (start > 0 && check(line.charAt(start - 1))) --start;
phrebejk@460
  2294
      while (end < line.length && check(line.charAt(end))) ++end;
phrebejk@460
  2295
    }
phrebejk@460
  2296
    return {from: {line: pos.line, ch: start}, to: {line: pos.line, ch: end}};
phrebejk@460
  2297
  }
phrebejk@460
  2298
phrebejk@460
  2299
  function selectLine(cm, line) {
phrebejk@460
  2300
    extendSelection(cm, {line: line, ch: 0}, clipPos(cm.view.doc, {line: line + 1, ch: 0}));
phrebejk@460
  2301
  }
phrebejk@460
  2302
phrebejk@460
  2303
  // PROTOTYPE
phrebejk@460
  2304
phrebejk@460
  2305
  // The publicly visible API. Note that operation(null, f) means
phrebejk@460
  2306
  // 'wrap f in an operation, performed on its `this` parameter'
phrebejk@460
  2307
phrebejk@460
  2308
  CodeMirror.prototype = {
phrebejk@460
  2309
    getValue: function(lineSep) {
phrebejk@460
  2310
      var text = [], doc = this.view.doc;
phrebejk@460
  2311
      doc.iter(0, doc.size, function(line) { text.push(line.text); });
phrebejk@460
  2312
      return text.join(lineSep || "\n");
phrebejk@460
  2313
    },
phrebejk@460
  2314
phrebejk@460
  2315
    setValue: operation(null, function(code) {
phrebejk@460
  2316
      var doc = this.view.doc, top = {line: 0, ch: 0}, lastLen = getLine(doc, doc.size-1).text.length;
phrebejk@460
  2317
      updateDocInner(this, top, {line: doc.size - 1, ch: lastLen}, splitLines(code), top, top, "setValue");
phrebejk@460
  2318
    }),
phrebejk@460
  2319
phrebejk@460
  2320
    getSelection: function(lineSep) { return this.getRange(this.view.sel.from, this.view.sel.to, lineSep); },
phrebejk@460
  2321
phrebejk@460
  2322
    replaceSelection: operation(null, function(code, collapse, origin) {
phrebejk@460
  2323
      var sel = this.view.sel;
phrebejk@460
  2324
      updateDoc(this, sel.from, sel.to, splitLines(code), collapse || "around", origin);
phrebejk@460
  2325
    }),
phrebejk@460
  2326
phrebejk@460
  2327
    focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);},
phrebejk@460
  2328
phrebejk@460
  2329
    setOption: function(option, value) {
phrebejk@460
  2330
      var options = this.options, old = options[option];
phrebejk@460
  2331
      if (options[option] == value && option != "mode") return;
phrebejk@460
  2332
      options[option] = value;
phrebejk@460
  2333
      if (optionHandlers.hasOwnProperty(option))
phrebejk@460
  2334
        operation(this, optionHandlers[option])(this, value, old);
phrebejk@460
  2335
    },
phrebejk@460
  2336
phrebejk@460
  2337
    getOption: function(option) {return this.options[option];},
phrebejk@460
  2338
phrebejk@460
  2339
    getMode: function() {return this.view.mode;},
phrebejk@460
  2340
phrebejk@460
  2341
    addKeyMap: function(map) {
phrebejk@460
  2342
      this.view.keyMaps.push(map);
phrebejk@460
  2343
    },
phrebejk@460
  2344
phrebejk@460
  2345
    removeKeyMap: function(map) {
phrebejk@460
  2346
      var maps = this.view.keyMaps;
phrebejk@460
  2347
      for (var i = 0; i < maps.length; ++i)
phrebejk@460
  2348
        if ((typeof map == "string" ? maps[i].name : maps[i]) == map) {
phrebejk@460
  2349
          maps.splice(i, 1);
phrebejk@460
  2350
          return true;
phrebejk@460
  2351
        }
phrebejk@460
  2352
    },
phrebejk@460
  2353
phrebejk@460
  2354
    undo: operation(null, function() {unredoHelper(this, "undo");}),
phrebejk@460
  2355
    redo: operation(null, function() {unredoHelper(this, "redo");}),
phrebejk@460
  2356
phrebejk@460
  2357
    indentLine: operation(null, function(n, dir, aggressive) {
phrebejk@460
  2358
      if (typeof dir != "string") {
phrebejk@460
  2359
        if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
phrebejk@460
  2360
        else dir = dir ? "add" : "subtract";
phrebejk@460
  2361
      }
phrebejk@460
  2362
      if (isLine(this.view.doc, n)) indentLine(this, n, dir, aggressive);
phrebejk@460
  2363
    }),
phrebejk@460
  2364
phrebejk@460
  2365
    indentSelection: operation(null, function(how) {
phrebejk@460
  2366
      var sel = this.view.sel;
phrebejk@460
  2367
      if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how);
phrebejk@460
  2368
      var e = sel.to.line - (sel.to.ch ? 0 : 1);
phrebejk@460
  2369
      for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how);
phrebejk@460
  2370
    }),
phrebejk@460
  2371
phrebejk@460
  2372
    historySize: function() {
phrebejk@460
  2373
      var hist = this.view.history;
phrebejk@460
  2374
      return {undo: hist.done.length, redo: hist.undone.length};
phrebejk@460
  2375
    },
phrebejk@460
  2376
phrebejk@460
  2377
    clearHistory: function() {this.view.history = makeHistory();},
phrebejk@460
  2378
phrebejk@460
  2379
    markClean: function() {
phrebejk@460
  2380
      this.view.history.dirtyCounter = 0;
phrebejk@460
  2381
      this.view.history.lastOp = this.view.history.lastOrigin = null;
phrebejk@460
  2382
    },
phrebejk@460
  2383
phrebejk@460
  2384
    isClean: function () {return this.view.history.dirtyCounter == 0;},
phrebejk@460
  2385
      
phrebejk@460
  2386
    getHistory: function() {
phrebejk@460
  2387
      var hist = this.view.history;
phrebejk@460
  2388
      function cp(arr) {
phrebejk@460
  2389
        for (var i = 0, nw = [], nwelt; i < arr.length; ++i) {
phrebejk@460
  2390
          var set = arr[i];
phrebejk@460
  2391
          nw.push({events: nwelt = [], fromBefore: set.fromBefore, toBefore: set.toBefore,
phrebejk@460
  2392
                   fromAfter: set.fromAfter, toAfter: set.toAfter});
phrebejk@460
  2393
          for (var j = 0, elt = set.events; j < elt.length; ++j) {
phrebejk@460
  2394
            var old = [], cur = elt[j];
phrebejk@460
  2395
            nwelt.push({start: cur.start, added: cur.added, old: old});
phrebejk@460
  2396
            for (var k = 0; k < cur.old.length; ++k) old.push(hlText(cur.old[k]));
phrebejk@460
  2397
          }
phrebejk@460
  2398
        }
phrebejk@460
  2399
        return nw;
phrebejk@460
  2400
      }
phrebejk@460
  2401
      return {done: cp(hist.done), undone: cp(hist.undone)};
phrebejk@460
  2402
    },
phrebejk@460
  2403
phrebejk@460
  2404
    setHistory: function(histData) {
phrebejk@460
  2405
      var hist = this.view.history = makeHistory();
phrebejk@460
  2406
      hist.done = histData.done;
phrebejk@460
  2407
      hist.undone = histData.undone;
phrebejk@460
  2408
    },
phrebejk@460
  2409
phrebejk@460
  2410
    // Fetch the parser token for a given character. Useful for hacks
phrebejk@460
  2411
    // that want to inspect the mode state (say, for completion).
phrebejk@460
  2412
    getTokenAt: function(pos) {
phrebejk@460
  2413
      var doc = this.view.doc;
phrebejk@460
  2414
      pos = clipPos(doc, pos);
phrebejk@460
  2415
      var state = getStateBefore(this, pos.line), mode = this.view.mode;
phrebejk@460
  2416
      var line = getLine(doc, pos.line);
phrebejk@460
  2417
      var stream = new StringStream(line.text, this.options.tabSize);
phrebejk@460
  2418
      while (stream.pos < pos.ch && !stream.eol()) {
phrebejk@460
  2419
        stream.start = stream.pos;
phrebejk@460
  2420
        var style = mode.token(stream, state);
phrebejk@460
  2421
      }
phrebejk@460
  2422
      return {start: stream.start,
phrebejk@460
  2423
              end: stream.pos,
phrebejk@460
  2424
              string: stream.current(),
phrebejk@460
  2425
              className: style || null, // Deprecated, use 'type' instead
phrebejk@460
  2426
              type: style || null,
phrebejk@460
  2427
              state: state};
phrebejk@460
  2428
    },
phrebejk@460
  2429
phrebejk@460
  2430
    getStateAfter: function(line) {
phrebejk@460
  2431
      var doc = this.view.doc;
phrebejk@460
  2432
      line = clipLine(doc, line == null ? doc.size - 1: line);
phrebejk@460
  2433
      return getStateBefore(this, line + 1);
phrebejk@460
  2434
    },
phrebejk@460
  2435
phrebejk@460
  2436
    cursorCoords: function(start, mode) {
phrebejk@460
  2437
      var pos, sel = this.view.sel;
phrebejk@460
  2438
      if (start == null) pos = sel.head;
phrebejk@460
  2439
      else if (typeof start == "object") pos = clipPos(this.view.doc, start);
phrebejk@460
  2440
      else pos = start ? sel.from : sel.to;
phrebejk@460
  2441
      return cursorCoords(this, pos, mode || "page");
phrebejk@460
  2442
    },
phrebejk@460
  2443
phrebejk@460
  2444
    charCoords: function(pos, mode) {
phrebejk@460
  2445
      return charCoords(this, clipPos(this.view.doc, pos), mode || "page");
phrebejk@460
  2446
    },
phrebejk@460
  2447
phrebejk@460
  2448
    coordsChar: function(coords) {
phrebejk@460
  2449
      var off = this.display.lineSpace.getBoundingClientRect();
phrebejk@460
  2450
      return coordsChar(this, coords.left - off.left, coords.top - off.top);
phrebejk@460
  2451
    },
phrebejk@460
  2452
phrebejk@460
  2453
    defaultTextHeight: function() { return textHeight(this.display); },
phrebejk@460
  2454
phrebejk@460
  2455
    markText: operation(null, function(from, to, options) {
phrebejk@460
  2456
      return markText(this, clipPos(this.view.doc, from), clipPos(this.view.doc, to),
phrebejk@460
  2457
                      options, "range");
phrebejk@460
  2458
    }),
phrebejk@460
  2459
phrebejk@460
  2460
    setBookmark: operation(null, function(pos, widget) {
phrebejk@460
  2461
      pos = clipPos(this.view.doc, pos);
phrebejk@460
  2462
      return markText(this, pos, pos, widget ? {replacedWith: widget} : {}, "bookmark");
phrebejk@460
  2463
    }),
phrebejk@460
  2464
phrebejk@460
  2465
    findMarksAt: function(pos) {
phrebejk@460
  2466
      var doc = this.view.doc;
phrebejk@460
  2467
      pos = clipPos(doc, pos);
phrebejk@460
  2468
      var markers = [], spans = getLine(doc, pos.line).markedSpans;
phrebejk@460
  2469
      if (spans) for (var i = 0; i < spans.length; ++i) {
phrebejk@460
  2470
        var span = spans[i];
phrebejk@460
  2471
        if ((span.from == null || span.from <= pos.ch) &&
phrebejk@460
  2472
            (span.to == null || span.to >= pos.ch))
phrebejk@460
  2473
          markers.push(span.marker);
phrebejk@460
  2474
      }
phrebejk@460
  2475
      return markers;
phrebejk@460
  2476
    },
phrebejk@460
  2477
phrebejk@460
  2478
    setGutterMarker: operation(null, function(line, gutterID, value) {
phrebejk@460
  2479
      return changeLine(this, line, function(line) {
phrebejk@460
  2480
        var markers = line.gutterMarkers || (line.gutterMarkers = {});
phrebejk@460
  2481
        markers[gutterID] = value;
phrebejk@460
  2482
        if (!value && isEmpty(markers)) line.gutterMarkers = null;
phrebejk@460
  2483
        return true;
phrebejk@460
  2484
      });
phrebejk@460
  2485
    }),
phrebejk@460
  2486
phrebejk@460
  2487
    clearGutter: operation(null, function(gutterID) {
phrebejk@460
  2488
      var i = 0, cm = this, doc = cm.view.doc;
phrebejk@460
  2489
      doc.iter(0, doc.size, function(line) {
phrebejk@460
  2490
        if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
phrebejk@460
  2491
          line.gutterMarkers[gutterID] = null;
phrebejk@460
  2492
          regChange(cm, i, i + 1);
phrebejk@460
  2493
          if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
phrebejk@460
  2494
        }
phrebejk@460
  2495
        ++i;
phrebejk@460
  2496
      });
phrebejk@460
  2497
    }),
phrebejk@460
  2498
phrebejk@460
  2499
    addLineClass: operation(null, function(handle, where, cls) {
phrebejk@460
  2500
      return changeLine(this, handle, function(line) {
phrebejk@460
  2501
        var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
phrebejk@460
  2502
        if (!line[prop]) line[prop] = cls;
phrebejk@460
  2503
        else if (new RegExp("\\b" + cls + "\\b").test(line[prop])) return false;
phrebejk@460
  2504
        else line[prop] += " " + cls;
phrebejk@460
  2505
        return true;
phrebejk@460
  2506
      });
phrebejk@460
  2507
    }),
phrebejk@460
  2508
phrebejk@460
  2509
    removeLineClass: operation(null, function(handle, where, cls) {
phrebejk@460
  2510
      return changeLine(this, handle, function(line) {
phrebejk@460
  2511
        var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
phrebejk@460
  2512
        var cur = line[prop];
phrebejk@460
  2513
        if (!cur) return false;
phrebejk@460
  2514
        else if (cls == null) line[prop] = null;
phrebejk@460
  2515
        else {
phrebejk@460
  2516
          var upd = cur.replace(new RegExp("^" + cls + "\\b\\s*|\\s*\\b" + cls + "\\b"), "");
phrebejk@460
  2517
          if (upd == cur) return false;
phrebejk@460
  2518
          line[prop] = upd || null;
phrebejk@460
  2519
        }
phrebejk@460
  2520
        return true;
phrebejk@460
  2521
      });
phrebejk@460
  2522
    }),
phrebejk@460
  2523
phrebejk@460
  2524
    addLineWidget: operation(null, function(handle, node, options) {
phrebejk@460
  2525
      var widget = options || {};
phrebejk@460
  2526
      widget.node = node;
phrebejk@460
  2527
      if (widget.noHScroll) this.display.alignWidgets = true;
phrebejk@460
  2528
      changeLine(this, handle, function(line) {
phrebejk@460
  2529
        (line.widgets || (line.widgets = [])).push(widget);
phrebejk@460
  2530
        widget.line = line;
phrebejk@460
  2531
        return true;
phrebejk@460
  2532
      });
phrebejk@460
  2533
      return widget;
phrebejk@460
  2534
    }),
phrebejk@460
  2535
phrebejk@460
  2536
    removeLineWidget: operation(null, function(widget) {
phrebejk@460
  2537
      var ws = widget.line.widgets, no = lineNo(widget.line);
phrebejk@460
  2538
      if (no == null) return;
phrebejk@460
  2539
      for (var i = 0; i < ws.length; ++i) if (ws[i] == widget) ws.splice(i--, 1);
phrebejk@460
  2540
      regChange(this, no, no + 1);
phrebejk@460
  2541
    }),
phrebejk@460
  2542
phrebejk@460
  2543
    lineInfo: function(line) {
phrebejk@460
  2544
      if (typeof line == "number") {
phrebejk@460
  2545
        if (!isLine(this.view.doc, line)) return null;
phrebejk@460
  2546
        var n = line;
phrebejk@460
  2547
        line = getLine(this.view.doc, line);
phrebejk@460
  2548
        if (!line) return null;
phrebejk@460
  2549
      } else {
phrebejk@460
  2550
        var n = lineNo(line);
phrebejk@460
  2551
        if (n == null) return null;
phrebejk@460
  2552
      }
phrebejk@460
  2553
      return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
phrebejk@460
  2554
              textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
phrebejk@460
  2555
              widgets: line.widgets};
phrebejk@460
  2556
    },
phrebejk@460
  2557
phrebejk@460
  2558
    getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};},
phrebejk@460
  2559
phrebejk@460
  2560
    addWidget: function(pos, node, scroll, vert, horiz) {
phrebejk@460
  2561
      var display = this.display;
phrebejk@460
  2562
      pos = cursorCoords(this, clipPos(this.view.doc, pos));
phrebejk@460
  2563
      var top = pos.top, left = pos.left;
phrebejk@460
  2564
      node.style.position = "absolute";
phrebejk@460
  2565
      display.sizer.appendChild(node);
phrebejk@460
  2566
      if (vert == "over") top = pos.top;
phrebejk@460
  2567
      else if (vert == "near") {
phrebejk@460
  2568
        var vspace = Math.max(display.wrapper.clientHeight, this.view.doc.height),
phrebejk@460
  2569
        hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
phrebejk@460
  2570
        if (pos.bottom + node.offsetHeight > vspace && pos.top > node.offsetHeight)
phrebejk@460
  2571
          top = pos.top - node.offsetHeight;
phrebejk@460
  2572
        if (left + node.offsetWidth > hspace)
phrebejk@460
  2573
          left = hspace - node.offsetWidth;
phrebejk@460
  2574
      }
phrebejk@460
  2575
      node.style.top = (top + paddingTop(display)) + "px";
phrebejk@460
  2576
      node.style.left = node.style.right = "";
phrebejk@460
  2577
      if (horiz == "right") {
phrebejk@460
  2578
        left = display.sizer.clientWidth - node.offsetWidth;
phrebejk@460
  2579
        node.style.right = "0px";
phrebejk@460
  2580
      } else {
phrebejk@460
  2581
        if (horiz == "left") left = 0;
phrebejk@460
  2582
        else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
phrebejk@460
  2583
        node.style.left = left + "px";
phrebejk@460
  2584
      }
phrebejk@460
  2585
      if (scroll)
phrebejk@460
  2586
        scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
phrebejk@460
  2587
    },
phrebejk@460
  2588
phrebejk@460
  2589
    lineCount: function() {return this.view.doc.size;},
phrebejk@460
  2590
phrebejk@460
  2591
    clipPos: function(pos) {return clipPos(this.view.doc, pos);},
phrebejk@460
  2592
phrebejk@460
  2593
    getCursor: function(start) {
phrebejk@460
  2594
      var sel = this.view.sel, pos;
phrebejk@460
  2595
      if (start == null || start == "head") pos = sel.head;
phrebejk@460
  2596
      else if (start == "anchor") pos = sel.anchor;
phrebejk@460
  2597
      else if (start == "end" || start === false) pos = sel.to;
phrebejk@460
  2598
      else pos = sel.from;
phrebejk@460
  2599
      return copyPos(pos);
phrebejk@460
  2600
    },
phrebejk@460
  2601
phrebejk@460
  2602
    somethingSelected: function() {return !posEq(this.view.sel.from, this.view.sel.to);},
phrebejk@460
  2603
phrebejk@460
  2604
    setCursor: operation(null, function(line, ch, extend) {
phrebejk@460
  2605
      var pos = clipPos(this.view.doc, typeof line == "number" ? {line: line, ch: ch || 0} : line);
phrebejk@460
  2606
      if (extend) extendSelection(this, pos);
phrebejk@460
  2607
      else setSelection(this, pos, pos);
phrebejk@460
  2608
    }),
phrebejk@460
  2609
phrebejk@460
  2610
    setSelection: operation(null, function(anchor, head) {
phrebejk@460
  2611
      var doc = this.view.doc;
phrebejk@460
  2612
      setSelection(this, clipPos(doc, anchor), clipPos(doc, head || anchor));
phrebejk@460
  2613
    }),
phrebejk@460
  2614
phrebejk@460
  2615
    extendSelection: operation(null, function(from, to) {
phrebejk@460
  2616
      var doc = this.view.doc;
phrebejk@460
  2617
      extendSelection(this, clipPos(doc, from), to && clipPos(doc, to));
phrebejk@460
  2618
    }),
phrebejk@460
  2619
phrebejk@460
  2620
    setExtending: function(val) {this.view.sel.extend = val;},
phrebejk@460
  2621
phrebejk@460
  2622
    getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
phrebejk@460
  2623
phrebejk@460
  2624
    getLineHandle: function(line) {
phrebejk@460
  2625
      var doc = this.view.doc;
phrebejk@460
  2626
      if (isLine(doc, line)) return getLine(doc, line);
phrebejk@460
  2627
    },
phrebejk@460
  2628
phrebejk@460
  2629
    getLineNumber: function(line) {return lineNo(line);},
phrebejk@460
  2630
phrebejk@460
  2631
    setLine: operation(null, function(line, text) {
phrebejk@460
  2632
      if (isLine(this.view.doc, line))
phrebejk@460
  2633
        replaceRange(this, text, {line: line, ch: 0}, {line: line, ch: getLine(this.view.doc, line).text.length});
phrebejk@460
  2634
    }),
phrebejk@460
  2635
phrebejk@460
  2636
    removeLine: operation(null, function(line) {
phrebejk@460
  2637
      if (isLine(this.view.doc, line))
phrebejk@460
  2638
        replaceRange(this, "", {line: line, ch: 0}, clipPos(this.view.doc, {line: line+1, ch: 0}));
phrebejk@460
  2639
    }),
phrebejk@460
  2640
phrebejk@460
  2641
    replaceRange: operation(null, function(code, from, to) {
phrebejk@460
  2642
      var doc = this.view.doc;
phrebejk@460
  2643
      from = clipPos(doc, from);
phrebejk@460
  2644
      to = to ? clipPos(doc, to) : from;
phrebejk@460
  2645
      return replaceRange(this, code, from, to);
phrebejk@460
  2646
    }),
phrebejk@460
  2647
phrebejk@460
  2648
    getRange: function(from, to, lineSep) {
phrebejk@460
  2649
      var doc = this.view.doc;
phrebejk@460
  2650
      from = clipPos(doc, from); to = clipPos(doc, to);
phrebejk@460
  2651
      var l1 = from.line, l2 = to.line;
phrebejk@460
  2652
      if (l1 == l2) return getLine(doc, l1).text.slice(from.ch, to.ch);
phrebejk@460
  2653
      var code = [getLine(doc, l1).text.slice(from.ch)];
phrebejk@460
  2654
      doc.iter(l1 + 1, l2, function(line) { code.push(line.text); });
phrebejk@460
  2655
      code.push(getLine(doc, l2).text.slice(0, to.ch));
phrebejk@460
  2656
      return code.join(lineSep || "\n");
phrebejk@460
  2657
    },
phrebejk@460
  2658
phrebejk@460
  2659
    triggerOnKeyDown: operation(null, onKeyDown),
phrebejk@460
  2660
phrebejk@460
  2661
    execCommand: function(cmd) {return commands[cmd](this);},
phrebejk@460
  2662
phrebejk@460
  2663
    // Stuff used by commands, probably not much use to outside code.
phrebejk@460
  2664
    moveH: operation(null, function(dir, unit) {
phrebejk@460
  2665
      var sel = this.view.sel, pos = dir < 0 ? sel.from : sel.to;
phrebejk@460
  2666
      if (sel.shift || sel.extend || posEq(sel.from, sel.to)) pos = findPosH(this, dir, unit, true);
phrebejk@460
  2667
      extendSelection(this, pos, pos, dir);
phrebejk@460
  2668
    }),
phrebejk@460
  2669
phrebejk@460
  2670
    deleteH: operation(null, function(dir, unit) {
phrebejk@460
  2671
      var sel = this.view.sel;
phrebejk@460
  2672
      if (!posEq(sel.from, sel.to)) replaceRange(this, "", sel.from, sel.to, "delete");
phrebejk@460
  2673
      else replaceRange(this, "", sel.from, findPosH(this, dir, unit, false), "delete");
phrebejk@460
  2674
      this.curOp.userSelChange = true;
phrebejk@460
  2675
    }),
phrebejk@460
  2676
phrebejk@460
  2677
    moveV: operation(null, function(dir, unit) {
phrebejk@460
  2678
      var view = this.view, doc = view.doc, display = this.display;
phrebejk@460
  2679
      var cur = view.sel.head, pos = cursorCoords(this, cur, "div");
phrebejk@460
  2680
      var x = pos.left, y;
phrebejk@460
  2681
      if (view.goalColumn != null) x = view.goalColumn;
phrebejk@460
  2682
      if (unit == "page") {
phrebejk@460
  2683
        var pageSize = Math.min(display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
phrebejk@460
  2684
        y = pos.top + dir * pageSize;
phrebejk@460
  2685
      } else if (unit == "line") {
phrebejk@460
  2686
        y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
phrebejk@460
  2687
      }
phrebejk@460
  2688
      do {
phrebejk@460
  2689
        var target = coordsChar(this, x, y);
phrebejk@460
  2690
        y += dir * 5;
phrebejk@460
  2691
      } while (target.outside && (dir < 0 ? y > 0 : y < doc.height));
phrebejk@460
  2692
phrebejk@460
  2693
      if (unit == "page") display.scrollbarV.scrollTop += charCoords(this, target, "div").top - pos.top;
phrebejk@460
  2694
      extendSelection(this, target, target, dir);
phrebejk@460
  2695
      view.goalColumn = x;
phrebejk@460
  2696
    }),
phrebejk@460
  2697
phrebejk@460
  2698
    toggleOverwrite: function() {
phrebejk@460
  2699
      if (this.view.overwrite = !this.view.overwrite)
phrebejk@460
  2700
        this.display.cursor.className += " CodeMirror-overwrite";
phrebejk@460
  2701
      else
phrebejk@460
  2702
        this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", "");
phrebejk@460
  2703
    },
phrebejk@460
  2704
phrebejk@460
  2705
    posFromIndex: function(off) {
phrebejk@460
  2706
      var lineNo = 0, ch, doc = this.view.doc;
phrebejk@460
  2707
      doc.iter(0, doc.size, function(line) {
phrebejk@460
  2708
        var sz = line.text.length + 1;
phrebejk@460
  2709
        if (sz > off) { ch = off; return true; }
phrebejk@460
  2710
        off -= sz;
phrebejk@460
  2711
        ++lineNo;
phrebejk@460
  2712
      });
phrebejk@460
  2713
      return clipPos(doc, {line: lineNo, ch: ch});
phrebejk@460
  2714
    },
phrebejk@460
  2715
    indexFromPos: function (coords) {
phrebejk@460
  2716
      if (coords.line < 0 || coords.ch < 0) return 0;
phrebejk@460
  2717
      var index = coords.ch;
phrebejk@460
  2718
      this.view.doc.iter(0, coords.line, function (line) {
phrebejk@460
  2719
        index += line.text.length + 1;
phrebejk@460
  2720
      });
phrebejk@460
  2721
      return index;
phrebejk@460
  2722
    },
phrebejk@460
  2723
phrebejk@460
  2724
    scrollTo: function(x, y) {
phrebejk@460
  2725
      if (x != null) this.display.scrollbarH.scrollLeft = this.display.scroller.scrollLeft = x;
phrebejk@460
  2726
      if (y != null) this.display.scrollbarV.scrollTop = this.display.scroller.scrollTop = y;
phrebejk@460
  2727
      updateDisplay(this, []);
phrebejk@460
  2728
    },
phrebejk@460
  2729
    getScrollInfo: function() {
phrebejk@460
  2730
      var scroller = this.display.scroller, co = scrollerCutOff;
phrebejk@460
  2731
      return {left: scroller.scrollLeft, top: scroller.scrollTop,
phrebejk@460
  2732
              height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,
phrebejk@460
  2733
              clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};
phrebejk@460
  2734
    },
phrebejk@460
  2735
phrebejk@460
  2736
    scrollIntoView: function(pos) {
phrebejk@460
  2737
      if (typeof pos == "number") pos = {line: pos, ch: 0};
phrebejk@460
  2738
      pos = pos ? clipPos(this.view.doc, pos) : this.view.sel.head;
phrebejk@460
  2739
      scrollPosIntoView(this, pos);
phrebejk@460
  2740
    },
phrebejk@460
  2741
phrebejk@460
  2742
    setSize: function(width, height) {
phrebejk@460
  2743
      function interpret(val) {
phrebejk@460
  2744
        return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
phrebejk@460
  2745
      }
phrebejk@460
  2746
      if (width != null) this.display.wrapper.style.width = interpret(width);
phrebejk@460
  2747
      if (height != null) this.display.wrapper.style.height = interpret(height);
phrebejk@460
  2748
      this.refresh();
phrebejk@460
  2749
    },
phrebejk@460
  2750
phrebejk@460
  2751
    on: function(type, f) {on(this, type, f);},
phrebejk@460
  2752
    off: function(type, f) {off(this, type, f);},
phrebejk@460
  2753
phrebejk@460
  2754
    operation: function(f){return operation(this, f)();},
phrebejk@460
  2755
phrebejk@460
  2756
    refresh: function() {
phrebejk@460
  2757
      clearCaches(this);
phrebejk@460
  2758
      if (this.display.scroller.scrollHeight > this.view.scrollTop)
phrebejk@460
  2759
        this.display.scrollbarV.scrollTop = this.display.scroller.scrollTop = this.view.scrollTop;
phrebejk@460
  2760
      updateDisplay(this, true);
phrebejk@460
  2761
    },
phrebejk@460
  2762
phrebejk@460
  2763
    getInputField: function(){return this.display.input;},
phrebejk@460
  2764
    getWrapperElement: function(){return this.display.wrapper;},
phrebejk@460
  2765
    getScrollerElement: function(){return this.display.scroller;},
phrebejk@460
  2766
    getGutterElement: function(){return this.display.gutters;}
phrebejk@460
  2767
  };
phrebejk@460
  2768
phrebejk@460
  2769
  // OPTION DEFAULTS
phrebejk@460
  2770
phrebejk@460
  2771
  var optionHandlers = CodeMirror.optionHandlers = {};
phrebejk@460
  2772
phrebejk@460
  2773
  // The default configuration options.
phrebejk@460
  2774
  var defaults = CodeMirror.defaults = {};
phrebejk@460
  2775
phrebejk@460
  2776
  function option(name, deflt, handle, notOnInit) {
phrebejk@460
  2777
    CodeMirror.defaults[name] = deflt;
phrebejk@460
  2778
    if (handle) optionHandlers[name] =
phrebejk@460
  2779
      notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
phrebejk@460
  2780
  }
phrebejk@460
  2781
phrebejk@460
  2782
  var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
phrebejk@460
  2783
phrebejk@460
  2784
  // These two are, on init, called from the constructor because they
phrebejk@460
  2785
  // have to be initialized before the editor can start at all.
phrebejk@460
  2786
  option("value", "", function(cm, val) {cm.setValue(val);}, true);
phrebejk@460
  2787
  option("mode", null, loadMode, true);
phrebejk@460
  2788
phrebejk@460
  2789
  option("indentUnit", 2, loadMode, true);
phrebejk@460
  2790
  option("indentWithTabs", false);
phrebejk@460
  2791
  option("smartIndent", true);
phrebejk@460
  2792
  option("tabSize", 4, function(cm) {
phrebejk@460
  2793
    loadMode(cm);
phrebejk@460
  2794
    clearCaches(cm);
phrebejk@460
  2795
    updateDisplay(cm, true);
phrebejk@460
  2796
  }, true);
phrebejk@460
  2797
  option("electricChars", true);
phrebejk@460
  2798
phrebejk@460
  2799
  option("theme", "default", function(cm) {
phrebejk@460
  2800
    themeChanged(cm);
phrebejk@460
  2801
    guttersChanged(cm);
phrebejk@460
  2802
  }, true);
phrebejk@460
  2803
  option("keyMap", "default", keyMapChanged);
phrebejk@460
  2804
  option("extraKeys", null);
phrebejk@460
  2805
phrebejk@460
  2806
  option("onKeyEvent", null);
phrebejk@460
  2807
  option("onDragEvent", null);
phrebejk@460
  2808
phrebejk@460
  2809
  option("lineWrapping", false, wrappingChanged, true);
phrebejk@460
  2810
  option("gutters", [], function(cm) {
phrebejk@460
  2811
    setGuttersForLineNumbers(cm.options);
phrebejk@460
  2812
    guttersChanged(cm);
phrebejk@460
  2813
  }, true);
phrebejk@460
  2814
  option("lineNumbers", false, function(cm) {
phrebejk@460
  2815
    setGuttersForLineNumbers(cm.options);
phrebejk@460
  2816
    guttersChanged(cm);
phrebejk@460
  2817
  }, true);
phrebejk@460
  2818
  option("firstLineNumber", 1, guttersChanged, true);
phrebejk@460
  2819
  option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
phrebejk@460
  2820
  option("showCursorWhenSelecting", false, updateSelection, true);
phrebejk@460
  2821
  
phrebejk@460
  2822
  option("readOnly", false, function(cm, val) {
phrebejk@460
  2823
    if (val == "nocursor") {onBlur(cm); cm.display.input.blur();}
phrebejk@460
  2824
    else if (!val) resetInput(cm, true);
phrebejk@460
  2825
  });
phrebejk@460
  2826
  option("dragDrop", true);
phrebejk@460
  2827
phrebejk@460
  2828
  option("cursorBlinkRate", 530);
phrebejk@460
  2829
  option("cursorHeight", 1);
phrebejk@460
  2830
  option("workTime", 100);
phrebejk@460
  2831
  option("workDelay", 100);
phrebejk@460
  2832
  option("flattenSpans", true);
phrebejk@460
  2833
  option("pollInterval", 100);
phrebejk@460
  2834
  option("undoDepth", 40);
phrebejk@460
  2835
  option("viewportMargin", 10, function(cm){cm.refresh();}, true);
phrebejk@460
  2836
phrebejk@460
  2837
  option("tabindex", null, function(cm, val) {
phrebejk@460
  2838
    cm.display.input.tabIndex = val || "";
phrebejk@460
  2839
  });
phrebejk@460
  2840
  option("autofocus", null);
phrebejk@460
  2841
phrebejk@460
  2842
  // MODE DEFINITION AND QUERYING
phrebejk@460
  2843
phrebejk@460
  2844
  // Known modes, by name and by MIME
phrebejk@460
  2845
  var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
phrebejk@460
  2846
phrebejk@460
  2847
  CodeMirror.defineMode = function(name, mode) {
phrebejk@460
  2848
    if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
phrebejk@460
  2849
    if (arguments.length > 2) {
phrebejk@460
  2850
      mode.dependencies = [];
phrebejk@460
  2851
      for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
phrebejk@460
  2852
    }
phrebejk@460
  2853
    modes[name] = mode;
phrebejk@460
  2854
  };
phrebejk@460
  2855
phrebejk@460
  2856
  CodeMirror.defineMIME = function(mime, spec) {
phrebejk@460
  2857
    mimeModes[mime] = spec;
phrebejk@460
  2858
  };
phrebejk@460
  2859
phrebejk@460
  2860
  CodeMirror.resolveMode = function(spec) {
phrebejk@460
  2861
    if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
phrebejk@460
  2862
      spec = mimeModes[spec];
phrebejk@460
  2863
    else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec))
phrebejk@460
  2864
      return CodeMirror.resolveMode("application/xml");
phrebejk@460
  2865
    if (typeof spec == "string") return {name: spec};
phrebejk@460
  2866
    else return spec || {name: "null"};
phrebejk@460
  2867
  };
phrebejk@460
  2868
phrebejk@460
  2869
  CodeMirror.getMode = function(options, spec) {
phrebejk@460
  2870
    var spec = CodeMirror.resolveMode(spec);
phrebejk@460
  2871
    var mfactory = modes[spec.name];
phrebejk@460
  2872
    if (!mfactory) return CodeMirror.getMode(options, "text/plain");
phrebejk@460
  2873
    var modeObj = mfactory(options, spec);
phrebejk@460
  2874
    if (modeExtensions.hasOwnProperty(spec.name)) {
phrebejk@460
  2875
      var exts = modeExtensions[spec.name];
phrebejk@460
  2876
      for (var prop in exts) {
phrebejk@460
  2877
        if (!exts.hasOwnProperty(prop)) continue;
phrebejk@460
  2878
        if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
phrebejk@460
  2879
        modeObj[prop] = exts[prop];
phrebejk@460
  2880
      }
phrebejk@460
  2881
    }
phrebejk@460
  2882
    modeObj.name = spec.name;
phrebejk@460
  2883
    return modeObj;
phrebejk@460
  2884
  };
phrebejk@460
  2885
phrebejk@460
  2886
  CodeMirror.defineMode("null", function() {
phrebejk@460
  2887
    return {token: function(stream) {stream.skipToEnd();}};
phrebejk@460
  2888
  });
phrebejk@460
  2889
  CodeMirror.defineMIME("text/plain", "null");
phrebejk@460
  2890
phrebejk@460
  2891
  var modeExtensions = CodeMirror.modeExtensions = {};
phrebejk@460
  2892
  CodeMirror.extendMode = function(mode, properties) {
phrebejk@460
  2893
    var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
phrebejk@460
  2894
    for (var prop in properties) if (properties.hasOwnProperty(prop))
phrebejk@460
  2895
      exts[prop] = properties[prop];
phrebejk@460
  2896
  };
phrebejk@460
  2897
phrebejk@460
  2898
  // EXTENSIONS
phrebejk@460
  2899
phrebejk@460
  2900
  CodeMirror.defineExtension = function(name, func) {
phrebejk@460
  2901
    CodeMirror.prototype[name] = func;
phrebejk@460
  2902
  };
phrebejk@460
  2903
phrebejk@460
  2904
  CodeMirror.defineOption = option;
phrebejk@460
  2905
phrebejk@460
  2906
  var initHooks = [];
phrebejk@460
  2907
  CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
phrebejk@460
  2908
phrebejk@460
  2909
  // MODE STATE HANDLING
phrebejk@460
  2910
phrebejk@460
  2911
  // Utility functions for working with state. Exported because modes
phrebejk@460
  2912
  // sometimes need to do this.
phrebejk@460
  2913
  function copyState(mode, state) {
phrebejk@460
  2914
    if (state === true) return state;
phrebejk@460
  2915
    if (mode.copyState) return mode.copyState(state);
phrebejk@460
  2916
    var nstate = {};
phrebejk@460
  2917
    for (var n in state) {
phrebejk@460
  2918
      var val = state[n];
phrebejk@460
  2919
      if (val instanceof Array) val = val.concat([]);
phrebejk@460
  2920
      nstate[n] = val;
phrebejk@460
  2921
    }
phrebejk@460
  2922
    return nstate;
phrebejk@460
  2923
  }
phrebejk@460
  2924
  CodeMirror.copyState = copyState;
phrebejk@460
  2925
phrebejk@460
  2926
  function startState(mode, a1, a2) {
phrebejk@460
  2927
    return mode.startState ? mode.startState(a1, a2) : true;
phrebejk@460
  2928
  }
phrebejk@460
  2929
  CodeMirror.startState = startState;
phrebejk@460
  2930
phrebejk@460
  2931
  CodeMirror.innerMode = function(mode, state) {
phrebejk@460
  2932
    while (mode.innerMode) {
phrebejk@460
  2933
      var info = mode.innerMode(state);
phrebejk@460
  2934
      state = info.state;
phrebejk@460
  2935
      mode = info.mode;
phrebejk@460
  2936
    }
phrebejk@460
  2937
    return info || {mode: mode, state: state};
phrebejk@460
  2938
  };
phrebejk@460
  2939
phrebejk@460
  2940
  // STANDARD COMMANDS
phrebejk@460
  2941
phrebejk@460
  2942
  var commands = CodeMirror.commands = {
phrebejk@460
  2943
    selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});},
phrebejk@460
  2944
    killLine: function(cm) {
phrebejk@460
  2945
      var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
phrebejk@460
  2946
      if (!sel && cm.getLine(from.line).length == from.ch)
phrebejk@460
  2947
        cm.replaceRange("", from, {line: from.line + 1, ch: 0}, "delete");
phrebejk@460
  2948
      else cm.replaceRange("", from, sel ? to : {line: from.line}, "delete");
phrebejk@460
  2949
    },
phrebejk@460
  2950
    deleteLine: function(cm) {
phrebejk@460
  2951
      var l = cm.getCursor().line;
phrebejk@460
  2952
      cm.replaceRange("", {line: l, ch: 0}, {line: l}, "delete");
phrebejk@460
  2953
    },
phrebejk@460
  2954
    undo: function(cm) {cm.undo();},
phrebejk@460
  2955
    redo: function(cm) {cm.redo();},
phrebejk@460
  2956
    goDocStart: function(cm) {cm.extendSelection({line: 0, ch: 0});},
phrebejk@460
  2957
    goDocEnd: function(cm) {cm.extendSelection({line: cm.lineCount() - 1});},
phrebejk@460
  2958
    goLineStart: function(cm) {
phrebejk@460
  2959
      cm.extendSelection(lineStart(cm, cm.getCursor().line));
phrebejk@460
  2960
    },
phrebejk@460
  2961
    goLineStartSmart: function(cm) {
phrebejk@460
  2962
      var cur = cm.getCursor(), start = lineStart(cm, cur.line);
phrebejk@460
  2963
      var line = cm.getLineHandle(start.line);
phrebejk@460
  2964
      var order = getOrder(line);
phrebejk@460
  2965
      if (!order || order[0].level == 0) {
phrebejk@460
  2966
        var firstNonWS = Math.max(0, line.text.search(/\S/));
phrebejk@460
  2967
        var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch;
phrebejk@460
  2968
        cm.extendSelection({line: start.line, ch: inWS ? 0 : firstNonWS});
phrebejk@460
  2969
      } else cm.extendSelection(start);
phrebejk@460
  2970
    },
phrebejk@460
  2971
    goLineEnd: function(cm) {
phrebejk@460
  2972
      cm.extendSelection(lineEnd(cm, cm.getCursor().line));
phrebejk@460
  2973
    },
phrebejk@460
  2974
    goLineUp: function(cm) {cm.moveV(-1, "line");},
phrebejk@460
  2975
    goLineDown: function(cm) {cm.moveV(1, "line");},
phrebejk@460
  2976
    goPageUp: function(cm) {cm.moveV(-1, "page");},
phrebejk@460
  2977
    goPageDown: function(cm) {cm.moveV(1, "page");},
phrebejk@460
  2978
    goCharLeft: function(cm) {cm.moveH(-1, "char");},
phrebejk@460
  2979
    goCharRight: function(cm) {cm.moveH(1, "char");},
phrebejk@460
  2980
    goColumnLeft: function(cm) {cm.moveH(-1, "column");},
phrebejk@460
  2981
    goColumnRight: function(cm) {cm.moveH(1, "column");},
phrebejk@460
  2982
    goWordLeft: function(cm) {cm.moveH(-1, "word");},
phrebejk@460
  2983
    goWordRight: function(cm) {cm.moveH(1, "word");},
phrebejk@460
  2984
    delCharBefore: function(cm) {cm.deleteH(-1, "char");},
phrebejk@460
  2985
    delCharAfter: function(cm) {cm.deleteH(1, "char");},
phrebejk@460
  2986
    delWordBefore: function(cm) {cm.deleteH(-1, "word");},
phrebejk@460
  2987
    delWordAfter: function(cm) {cm.deleteH(1, "word");},
phrebejk@460
  2988
    indentAuto: function(cm) {cm.indentSelection("smart");},
phrebejk@460
  2989
    indentMore: function(cm) {cm.indentSelection("add");},
phrebejk@460
  2990
    indentLess: function(cm) {cm.indentSelection("subtract");},
phrebejk@460
  2991
    insertTab: function(cm) {cm.replaceSelection("\t", "end", "input");},
phrebejk@460
  2992
    defaultTab: function(cm) {
phrebejk@460
  2993
      if (cm.somethingSelected()) cm.indentSelection("add");
phrebejk@460
  2994
      else cm.replaceSelection("\t", "end", "input");
phrebejk@460
  2995
    },
phrebejk@460
  2996
    transposeChars: function(cm) {
phrebejk@460
  2997
      var cur = cm.getCursor(), line = cm.getLine(cur.line);
phrebejk@460
  2998
      if (cur.ch > 0 && cur.ch < line.length - 1)
phrebejk@460
  2999
        cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
phrebejk@460
  3000
                        {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1});
phrebejk@460
  3001
    },
phrebejk@460
  3002
    newlineAndIndent: function(cm) {
phrebejk@460
  3003
      operation(cm, function() {
phrebejk@460
  3004
        cm.replaceSelection("\n", "end", "input");
phrebejk@460
  3005
        cm.indentLine(cm.getCursor().line, null, true);
phrebejk@460
  3006
      })();
phrebejk@460
  3007
    },
phrebejk@460
  3008
    toggleOverwrite: function(cm) {cm.toggleOverwrite();}
phrebejk@460
  3009
  };
phrebejk@460
  3010
phrebejk@460
  3011
  // STANDARD KEYMAPS
phrebejk@460
  3012
phrebejk@460
  3013
  var keyMap = CodeMirror.keyMap = {};
phrebejk@460
  3014
  keyMap.basic = {
phrebejk@460
  3015
    "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
phrebejk@460
  3016
    "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
phrebejk@460
  3017
    "Delete": "delCharAfter", "Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto",
phrebejk@460
  3018
    "Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
phrebejk@460
  3019
  };
phrebejk@460
  3020
  // Note that the save and find-related commands aren't defined by
phrebejk@460
  3021
  // default. Unknown commands are simply ignored.
phrebejk@460
  3022
  keyMap.pcDefault = {
phrebejk@460
  3023
    "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
phrebejk@460
  3024
    "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
phrebejk@460
  3025
    "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
phrebejk@460
  3026
    "Ctrl-Backspace": "delWordBefore", "Ctrl-Delete": "delWordAfter", "Ctrl-S": "save", "Ctrl-F": "find",
phrebejk@460
  3027
    "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
phrebejk@460
  3028
    "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
phrebejk@460
  3029
    fallthrough: "basic"
phrebejk@460
  3030
  };
phrebejk@460
  3031
  keyMap.macDefault = {
phrebejk@460
  3032
    "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
phrebejk@460
  3033
    "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft",
phrebejk@460
  3034
    "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordBefore",
phrebejk@460
  3035
    "Ctrl-Alt-Backspace": "delWordAfter", "Alt-Delete": "delWordAfter", "Cmd-S": "save", "Cmd-F": "find",
phrebejk@460
  3036
    "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
phrebejk@460
  3037
    "Cmd-[": "indentLess", "Cmd-]": "indentMore",
phrebejk@460
  3038
    fallthrough: ["basic", "emacsy"]
phrebejk@460
  3039
  };
phrebejk@460
  3040
  keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
phrebejk@460
  3041
  keyMap.emacsy = {
phrebejk@460
  3042
    "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
phrebejk@460
  3043
    "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
phrebejk@460
  3044
    "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
phrebejk@460
  3045
    "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
phrebejk@460
  3046
  };
phrebejk@460
  3047
phrebejk@460
  3048
  // KEYMAP DISPATCH
phrebejk@460
  3049
phrebejk@460
  3050
  function getKeyMap(val) {
phrebejk@460
  3051
    if (typeof val == "string") return keyMap[val];
phrebejk@460
  3052
    else return val;
phrebejk@460
  3053
  }
phrebejk@460
  3054
phrebejk@460
  3055
  function lookupKey(name, maps, handle, stop) {
phrebejk@460
  3056
    function lookup(map) {
phrebejk@460
  3057
      map = getKeyMap(map);
phrebejk@460
  3058
      var found = map[name];
phrebejk@460
  3059
      if (found === false) {
phrebejk@460
  3060
        if (stop) stop();
phrebejk@460
  3061
        return true;
phrebejk@460
  3062
      }
phrebejk@460
  3063
      if (found != null && handle(found)) return true;
phrebejk@460
  3064
      if (map.nofallthrough) {
phrebejk@460
  3065
        if (stop) stop();
phrebejk@460
  3066
        return true;
phrebejk@460
  3067
      }
phrebejk@460
  3068
      var fallthrough = map.fallthrough;
phrebejk@460
  3069
      if (fallthrough == null) return false;
phrebejk@460
  3070
      if (Object.prototype.toString.call(fallthrough) != "[object Array]")
phrebejk@460
  3071
        return lookup(fallthrough);
phrebejk@460
  3072
      for (var i = 0, e = fallthrough.length; i < e; ++i) {
phrebejk@460
  3073
        if (lookup(fallthrough[i])) return true;
phrebejk@460
  3074
      }
phrebejk@460
  3075
      return false;
phrebejk@460
  3076
    }
phrebejk@460
  3077
phrebejk@460
  3078
    for (var i = 0; i < maps.length; ++i)
phrebejk@460
  3079
      if (lookup(maps[i])) return true;
phrebejk@460
  3080
  }
phrebejk@460
  3081
  function isModifierKey(event) {
phrebejk@460
  3082
    var name = keyNames[e_prop(event, "keyCode")];
phrebejk@460
  3083
    return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
phrebejk@460
  3084
  }
phrebejk@460
  3085
  CodeMirror.isModifierKey = isModifierKey;
phrebejk@460
  3086
phrebejk@460
  3087
  // FROMTEXTAREA
phrebejk@460
  3088
phrebejk@460
  3089
  CodeMirror.fromTextArea = function(textarea, options) {
phrebejk@460
  3090
    if (!options) options = {};
phrebejk@460
  3091
    options.value = textarea.value;
phrebejk@460
  3092
    if (!options.tabindex && textarea.tabindex)
phrebejk@460
  3093
      options.tabindex = textarea.tabindex;
phrebejk@460
  3094
    // Set autofocus to true if this textarea is focused, or if it has
phrebejk@460
  3095
    // autofocus and no other element is focused.
phrebejk@460
  3096
    if (options.autofocus == null) {
phrebejk@460
  3097
      var hasFocus = document.body;
phrebejk@460
  3098
      // doc.activeElement occasionally throws on IE
phrebejk@460
  3099
      try { hasFocus = document.activeElement; } catch(e) {}
phrebejk@460
  3100
      options.autofocus = hasFocus == textarea ||
phrebejk@460
  3101
        textarea.getAttribute("autofocus") != null && hasFocus == document.body;
phrebejk@460
  3102
    }
phrebejk@460
  3103
phrebejk@460
  3104
    function save() {textarea.value = cm.getValue();}
phrebejk@460
  3105
    if (textarea.form) {
phrebejk@460
  3106
      // Deplorable hack to make the submit method do the right thing.
phrebejk@460
  3107
      on(textarea.form, "submit", save);
phrebejk@460
  3108
      var form = textarea.form, realSubmit = form.submit;
phrebejk@460
  3109
      try {
phrebejk@460
  3110
        form.submit = function wrappedSubmit() {
phrebejk@460
  3111
          save();
phrebejk@460
  3112
          form.submit = realSubmit;
phrebejk@460
  3113
          form.submit();
phrebejk@460
  3114
          form.submit = wrappedSubmit;
phrebejk@460
  3115
        };
phrebejk@460
  3116
      } catch(e) {}
phrebejk@460
  3117
    }
phrebejk@460
  3118
phrebejk@460
  3119
    textarea.style.display = "none";
phrebejk@460
  3120
    var cm = CodeMirror(function(node) {
phrebejk@460
  3121
      textarea.parentNode.insertBefore(node, textarea.nextSibling);
phrebejk@460
  3122
    }, options);
phrebejk@460
  3123
    cm.save = save;
phrebejk@460
  3124
    cm.getTextArea = function() { return textarea; };
phrebejk@460
  3125
    cm.toTextArea = function() {
phrebejk@460
  3126
      save();
phrebejk@460
  3127
      textarea.parentNode.removeChild(cm.getWrapperElement());
phrebejk@460
  3128
      textarea.style.display = "";
phrebejk@460
  3129
      if (textarea.form) {
phrebejk@460
  3130
        off(textarea.form, "submit", save);
phrebejk@460
  3131
        if (typeof textarea.form.submit == "function")
phrebejk@460
  3132
          textarea.form.submit = realSubmit;
phrebejk@460
  3133
      }
phrebejk@460
  3134
    };
phrebejk@460
  3135
    return cm;
phrebejk@460
  3136
  };
phrebejk@460
  3137
phrebejk@460
  3138
  // STRING STREAM
phrebejk@460
  3139
phrebejk@460
  3140
  // Fed to the mode parsers, provides helper functions to make
phrebejk@460
  3141
  // parsers more succinct.
phrebejk@460
  3142
phrebejk@460
  3143
  // The character stream used by a mode's parser.
phrebejk@460
  3144
  function StringStream(string, tabSize) {
phrebejk@460
  3145
    this.pos = this.start = 0;
phrebejk@460
  3146
    this.string = string;
phrebejk@460
  3147
    this.tabSize = tabSize || 8;
phrebejk@460
  3148
  }
phrebejk@460
  3149
phrebejk@460
  3150
  StringStream.prototype = {
phrebejk@460
  3151
    eol: function() {return this.pos >= this.string.length;},
phrebejk@460
  3152
    sol: function() {return this.pos == 0;},
phrebejk@460
  3153
    peek: function() {return this.string.charAt(this.pos) || undefined;},
phrebejk@460
  3154
    next: function() {
phrebejk@460
  3155
      if (this.pos < this.string.length)
phrebejk@460
  3156
        return this.string.charAt(this.pos++);
phrebejk@460
  3157
    },
phrebejk@460
  3158
    eat: function(match) {
phrebejk@460
  3159
      var ch = this.string.charAt(this.pos);
phrebejk@460
  3160
      if (typeof match == "string") var ok = ch == match;
phrebejk@460
  3161
      else var ok = ch && (match.test ? match.test(ch) : match(ch));
phrebejk@460
  3162
      if (ok) {++this.pos; return ch;}
phrebejk@460
  3163
    },
phrebejk@460
  3164
    eatWhile: function(match) {
phrebejk@460
  3165
      var start = this.pos;
phrebejk@460
  3166
      while (this.eat(match)){}
phrebejk@460
  3167
      return this.pos > start;
phrebejk@460
  3168
    },
phrebejk@460
  3169
    eatSpace: function() {
phrebejk@460
  3170
      var start = this.pos;
phrebejk@460
  3171
      while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
phrebejk@460
  3172
      return this.pos > start;
phrebejk@460
  3173
    },
phrebejk@460
  3174
    skipToEnd: function() {this.pos = this.string.length;},
phrebejk@460
  3175
    skipTo: function(ch) {
phrebejk@460
  3176
      var found = this.string.indexOf(ch, this.pos);
phrebejk@460
  3177
      if (found > -1) {this.pos = found; return true;}
phrebejk@460
  3178
    },
phrebejk@460
  3179
    backUp: function(n) {this.pos -= n;},
phrebejk@460
  3180
    column: function() {return countColumn(this.string, this.start, this.tabSize);},
phrebejk@460
  3181
    indentation: function() {return countColumn(this.string, null, this.tabSize);},
phrebejk@460
  3182
    match: function(pattern, consume, caseInsensitive) {
phrebejk@460
  3183
      if (typeof pattern == "string") {
phrebejk@460
  3184
        var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
phrebejk@460
  3185
        if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
phrebejk@460
  3186
          if (consume !== false) this.pos += pattern.length;
phrebejk@460
  3187
          return true;
phrebejk@460
  3188
        }
phrebejk@460
  3189
      } else {
phrebejk@460
  3190
        var match = this.string.slice(this.pos).match(pattern);
phrebejk@460
  3191
        if (match && match.index > 0) return null;
phrebejk@460
  3192
        if (match && consume !== false) this.pos += match[0].length;
phrebejk@460
  3193
        return match;
phrebejk@460
  3194
      }
phrebejk@460
  3195
    },
phrebejk@460
  3196
    current: function(){return this.string.slice(this.start, this.pos);}
phrebejk@460
  3197
  };
phrebejk@460
  3198
  CodeMirror.StringStream = StringStream;
phrebejk@460
  3199
phrebejk@460
  3200
  // TEXTMARKERS
phrebejk@460
  3201
phrebejk@460
  3202
  function TextMarker(cm, type) {
phrebejk@460
  3203
    this.lines = [];
phrebejk@460
  3204
    this.type = type;
phrebejk@460
  3205
    this.cm = cm;
phrebejk@460
  3206
  }
phrebejk@460
  3207
phrebejk@460
  3208
  TextMarker.prototype.clear = function() {
phrebejk@460
  3209
    if (this.explicitlyCleared) return;
phrebejk@460
  3210
    startOperation(this.cm);
phrebejk@460
  3211
    var min = null, max = null;
phrebejk@460
  3212
    for (var i = 0; i < this.lines.length; ++i) {
phrebejk@460
  3213
      var line = this.lines[i];
phrebejk@460
  3214
      var span = getMarkedSpanFor(line.markedSpans, this);
phrebejk@460
  3215
      if (span.to != null) max = lineNo(line);
phrebejk@460
  3216
      line.markedSpans = removeMarkedSpan(line.markedSpans, span);
phrebejk@460
  3217
      if (span.from != null)
phrebejk@460
  3218
        min = lineNo(line);
phrebejk@460
  3219
      else if (this.collapsed && !lineIsHidden(line))
phrebejk@460
  3220
        updateLineHeight(line, textHeight(this.cm.display));
phrebejk@460
  3221
    }
phrebejk@460
  3222
    if (min != null) regChange(this.cm, min, max + 1);
phrebejk@460
  3223
    this.lines.length = 0;
phrebejk@460
  3224
    this.explicitlyCleared = true;
phrebejk@460
  3225
    if (this.collapsed && this.cm.view.cantEdit) {
phrebejk@460
  3226
      this.cm.view.cantEdit = false;
phrebejk@460
  3227
      reCheckSelection(this.cm);
phrebejk@460
  3228
    }
phrebejk@460
  3229
    endOperation(this.cm);
phrebejk@460
  3230
    signalLater(this.cm, this, "clear");
phrebejk@460
  3231
  };
phrebejk@460
  3232
phrebejk@460
  3233
  TextMarker.prototype.find = function() {
phrebejk@460
  3234
    var from, to;
phrebejk@460
  3235
    for (var i = 0; i < this.lines.length; ++i) {
phrebejk@460
  3236
      var line = this.lines[i];
phrebejk@460
  3237
      var span = getMarkedSpanFor(line.markedSpans, this);
phrebejk@460
  3238
      if (span.from != null || span.to != null) {
phrebejk@460
  3239
        var found = lineNo(line);
phrebejk@460
  3240
        if (span.from != null) from = {line: found, ch: span.from};
phrebejk@460
  3241
        if (span.to != null) to = {line: found, ch: span.to};
phrebejk@460
  3242
      }
phrebejk@460
  3243
    }
phrebejk@460
  3244
    if (this.type == "bookmark") return from;
phrebejk@460
  3245
    return from && {from: from, to: to};
phrebejk@460
  3246
  };
phrebejk@460
  3247
phrebejk@460
  3248
  function markText(cm, from, to, options, type) {
phrebejk@460
  3249
    var doc = cm.view.doc;
phrebejk@460
  3250
    var marker = new TextMarker(cm, type);
phrebejk@460
  3251
    if (type == "range" && !posLess(from, to)) return marker;
phrebejk@460
  3252
    if (options) for (var opt in options) if (options.hasOwnProperty(opt))
phrebejk@460
  3253
      marker[opt] = options[opt];
phrebejk@460
  3254
    if (marker.replacedWith) {
phrebejk@460
  3255
      marker.collapsed = true;
phrebejk@460
  3256
      marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget");
phrebejk@460
  3257
    }
phrebejk@460
  3258
    if (marker.collapsed) sawCollapsedSpans = true;
phrebejk@460
  3259
phrebejk@460
  3260
    var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd;
phrebejk@460
  3261
    doc.iter(curLine, to.line + 1, function(line) {
phrebejk@460
  3262
      var span = {from: null, to: null, marker: marker};
phrebejk@460
  3263
      size += line.text.length;
phrebejk@460
  3264
      if (curLine == from.line) {span.from = from.ch; size -= from.ch;}
phrebejk@460
  3265
      if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;}
phrebejk@460
  3266
      if (marker.collapsed) {
phrebejk@460
  3267
        if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch);
phrebejk@460
  3268
        if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch);
phrebejk@460
  3269
        else updateLineHeight(line, 0);
phrebejk@460
  3270
      }
phrebejk@460
  3271
      addMarkedSpan(line, span);
phrebejk@460
  3272
      if (marker.collapsed && curLine == from.line && lineIsHidden(line))
phrebejk@460
  3273
        updateLineHeight(line, 0);
phrebejk@460
  3274
      ++curLine;
phrebejk@460
  3275
    });
phrebejk@460
  3276
phrebejk@460
  3277
    if (marker.readOnly) {
phrebejk@460
  3278
      sawReadOnlySpans = true;
phrebejk@460
  3279
      if (cm.view.history.done.length || cm.view.history.undone.length)
phrebejk@460
  3280
        cm.clearHistory();
phrebejk@460
  3281
    }
phrebejk@460
  3282
    if (marker.collapsed) {
phrebejk@460
  3283
      if (collapsedAtStart != collapsedAtEnd)
phrebejk@460
  3284
        throw new Error("Inserting collapsed marker overlapping an existing one");
phrebejk@460
  3285
      marker.size = size;
phrebejk@460
  3286
      marker.atomic = true;
phrebejk@460
  3287
    }
phrebejk@460
  3288
    if (marker.className || marker.startStyle || marker.endStyle || marker.collapsed)
phrebejk@460
  3289
      regChange(cm, from.line, to.line + 1);
phrebejk@460
  3290
    if (marker.atomic) reCheckSelection(cm);
phrebejk@460
  3291
    return marker;
phrebejk@460
  3292
  }
phrebejk@460
  3293
phrebejk@460
  3294
  // TEXTMARKER SPANS
phrebejk@460
  3295
phrebejk@460
  3296
  function getMarkedSpanFor(spans, marker) {
phrebejk@460
  3297
    if (spans) for (var i = 0; i < spans.length; ++i) {
phrebejk@460
  3298
      var span = spans[i];
phrebejk@460
  3299
      if (span.marker == marker) return span;
phrebejk@460
  3300
    }
phrebejk@460
  3301
  }
phrebejk@460
  3302
  function removeMarkedSpan(spans, span) {
phrebejk@460
  3303
    for (var r, i = 0; i < spans.length; ++i)
phrebejk@460
  3304
      if (spans[i] != span) (r || (r = [])).push(spans[i]);
phrebejk@460
  3305
    return r;
phrebejk@460
  3306
  }
phrebejk@460
  3307
  function addMarkedSpan(line, span) {
phrebejk@460
  3308
    line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
phrebejk@460
  3309
    span.marker.lines.push(line);
phrebejk@460
  3310
  }
phrebejk@460
  3311
phrebejk@460
  3312
  function markedSpansBefore(old, startCh) {
phrebejk@460
  3313
    if (old) for (var i = 0, nw; i < old.length; ++i) {
phrebejk@460
  3314
      var span = old[i], marker = span.marker;
phrebejk@460
  3315
      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
phrebejk@460
  3316
      if (startsBefore || marker.type == "bookmark" && span.from == startCh) {
phrebejk@460
  3317
        var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
phrebejk@460
  3318
        (nw || (nw = [])).push({from: span.from,
phrebejk@460
  3319
                                to: endsAfter ? null : span.to,
phrebejk@460
  3320
                                marker: marker});
phrebejk@460
  3321
      }
phrebejk@460
  3322
    }
phrebejk@460
  3323
    return nw;
phrebejk@460
  3324
  }
phrebejk@460
  3325
phrebejk@460
  3326
  function markedSpansAfter(old, startCh, endCh) {
phrebejk@460
  3327
    if (old) for (var i = 0, nw; i < old.length; ++i) {
phrebejk@460
  3328
      var span = old[i], marker = span.marker;
phrebejk@460
  3329
      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
phrebejk@460
  3330
      if (endsAfter || marker.type == "bookmark" && span.from == endCh && span.from != startCh) {
phrebejk@460
  3331
        var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
phrebejk@460
  3332
        (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh,
phrebejk@460
  3333
                                to: span.to == null ? null : span.to - endCh,
phrebejk@460
  3334
                                marker: marker});
phrebejk@460
  3335
      }
phrebejk@460
  3336
    }
phrebejk@460
  3337
    return nw;
phrebejk@460
  3338
  }
phrebejk@460
  3339
phrebejk@460
  3340
  function updateMarkedSpans(oldFirst, oldLast, startCh, endCh, newText) {
phrebejk@460
  3341
    if (!oldFirst && !oldLast) return newText;
phrebejk@460
  3342
    // Get the spans that 'stick out' on both sides
phrebejk@460
  3343
    var first = markedSpansBefore(oldFirst, startCh);
phrebejk@460
  3344
    var last = markedSpansAfter(oldLast, startCh, endCh);
phrebejk@460
  3345
phrebejk@460
  3346
    // Next, merge those two ends
phrebejk@460
  3347
    var sameLine = newText.length == 1, offset = lst(newText).length + (sameLine ? startCh : 0);
phrebejk@460
  3348
    if (first) {
phrebejk@460
  3349
      // Fix up .to properties of first
phrebejk@460
  3350
      for (var i = 0; i < first.length; ++i) {
phrebejk@460
  3351
        var span = first[i];
phrebejk@460
  3352
        if (span.to == null) {
phrebejk@460
  3353
          var found = getMarkedSpanFor(last, span.marker);
phrebejk@460
  3354
          if (!found) span.to = startCh;
phrebejk@460
  3355
          else if (sameLine) span.to = found.to == null ? null : found.to + offset;
phrebejk@460
  3356
        }
phrebejk@460
  3357
      }
phrebejk@460
  3358
    }
phrebejk@460
  3359
    if (last) {
phrebejk@460
  3360
      // Fix up .from in last (or move them into first in case of sameLine)
phrebejk@460
  3361
      for (var i = 0; i < last.length; ++i) {
phrebejk@460
  3362
        var span = last[i];
phrebejk@460
  3363
        if (span.to != null) span.to += offset;
phrebejk@460
  3364
        if (span.from == null) {
phrebejk@460
  3365
          var found = getMarkedSpanFor(first, span.marker);
phrebejk@460
  3366
          if (!found) {
phrebejk@460
  3367
            span.from = offset;
phrebejk@460
  3368
            if (sameLine) (first || (first = [])).push(span);
phrebejk@460
  3369
          }
phrebejk@460
  3370
        } else {
phrebejk@460
  3371
          span.from += offset;
phrebejk@460
  3372
          if (sameLine) (first || (first = [])).push(span);
phrebejk@460
  3373
        }
phrebejk@460
  3374
      }
phrebejk@460
  3375
    }
phrebejk@460
  3376
phrebejk@460
  3377
    var newMarkers = [newHL(newText[0], first)];
phrebejk@460
  3378
    if (!sameLine) {
phrebejk@460
  3379
      // Fill gap with whole-line-spans
phrebejk@460
  3380
      var gap = newText.length - 2, gapMarkers;
phrebejk@460
  3381
      if (gap > 0 && first)
phrebejk@460
  3382
        for (var i = 0; i < first.length; ++i)
phrebejk@460
  3383
          if (first[i].to == null)
phrebejk@460
  3384
            (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker});
phrebejk@460
  3385
      for (var i = 0; i < gap; ++i)
phrebejk@460
  3386
        newMarkers.push(newHL(newText[i+1], gapMarkers));
phrebejk@460
  3387
      newMarkers.push(newHL(lst(newText), last));
phrebejk@460
  3388
    }
phrebejk@460
  3389
    return newMarkers;
phrebejk@460
  3390
  }
phrebejk@460
  3391
phrebejk@460
  3392
  function removeReadOnlyRanges(doc, from, to) {
phrebejk@460
  3393
    var markers = null;
phrebejk@460
  3394
    doc.iter(from.line, to.line + 1, function(line) {
phrebejk@460
  3395
      if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
phrebejk@460
  3396
        var mark = line.markedSpans[i].marker;
phrebejk@460
  3397
        if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
phrebejk@460
  3398
          (markers || (markers = [])).push(mark);
phrebejk@460
  3399
      }
phrebejk@460
  3400
    });
phrebejk@460
  3401
    if (!markers) return null;
phrebejk@460
  3402
    var parts = [{from: from, to: to}];
phrebejk@460
  3403
    for (var i = 0; i < markers.length; ++i) {
phrebejk@460
  3404
      var m = markers[i].find();
phrebejk@460
  3405
      for (var j = 0; j < parts.length; ++j) {
phrebejk@460
  3406
        var p = parts[j];
phrebejk@460
  3407
        if (!posLess(m.from, p.to) || posLess(m.to, p.from)) continue;
phrebejk@460
  3408
        var newParts = [j, 1];
phrebejk@460
  3409
        if (posLess(p.from, m.from)) newParts.push({from: p.from, to: m.from});
phrebejk@460
  3410
        if (posLess(m.to, p.to)) newParts.push({from: m.to, to: p.to});
phrebejk@460
  3411
        parts.splice.apply(parts, newParts);
phrebejk@460
  3412
        j += newParts.length - 1;
phrebejk@460
  3413
      }
phrebejk@460
  3414
    }
phrebejk@460
  3415
    return parts;
phrebejk@460
  3416
  }
phrebejk@460
  3417
phrebejk@460
  3418
  function collapsedSpanAt(line, ch) {
phrebejk@460
  3419
    var sps = sawCollapsedSpans && line.markedSpans, found;
phrebejk@460
  3420
    if (sps) for (var sp, i = 0; i < sps.length; ++i) {
phrebejk@460
  3421
      sp = sps[i];
phrebejk@460
  3422
      if (!sp.marker.collapsed) continue;
phrebejk@460
  3423
      if ((sp.from == null || sp.from < ch) &&
phrebejk@460
  3424
          (sp.to == null || sp.to > ch) &&
phrebejk@460
  3425
          (!found || found.width < sp.marker.width))
phrebejk@460
  3426
        found = sp.marker;
phrebejk@460
  3427
    }
phrebejk@460
  3428
    return found;
phrebejk@460
  3429
  }
phrebejk@460
  3430
  function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); }
phrebejk@460
  3431
  function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); }
phrebejk@460
  3432
phrebejk@460
  3433
  function visualLine(doc, line) {
phrebejk@460
  3434
    var merged;
phrebejk@460
  3435
    while (merged = collapsedSpanAtStart(line))
phrebejk@460
  3436
      line = getLine(doc, merged.find().from.line);
phrebejk@460
  3437
    return line;
phrebejk@460
  3438
  }
phrebejk@460
  3439
phrebejk@460
  3440
  function lineIsHidden(line) {
phrebejk@460
  3441
    var sps = sawCollapsedSpans && line.markedSpans;
phrebejk@460
  3442
    if (sps) for (var sp, i = 0; i < sps.length; ++i) {
phrebejk@460
  3443
      sp = sps[i];
phrebejk@460
  3444
      if (!sp.marker.collapsed) continue;
phrebejk@460
  3445
      if (sp.from == null) return true;
phrebejk@460
  3446
      if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(line, sp))
phrebejk@460
  3447
        return true;
phrebejk@460
  3448
    }
phrebejk@460
  3449
  }
phrebejk@460
  3450
  window.lineIsHidden = lineIsHidden;
phrebejk@460
  3451
  function lineIsHiddenInner(line, span) {
phrebejk@460
  3452
    if (span.to == null || span.marker.inclusiveRight && span.to == line.text.length)
phrebejk@460
  3453
      return true;
phrebejk@460
  3454
    for (var sp, i = 0; i < line.markedSpans.length; ++i) {
phrebejk@460
  3455
      sp = line.markedSpans[i];
phrebejk@460
  3456
      if (sp.marker.collapsed && sp.from == span.to &&
phrebejk@460
  3457
          (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
phrebejk@460
  3458
          lineIsHiddenInner(line, sp)) return true;
phrebejk@460
  3459
    }
phrebejk@460
  3460
  }
phrebejk@460
  3461
phrebejk@460
  3462
  // hl stands for history-line, a data structure that can be either a
phrebejk@460
  3463
  // string (line without markers) or a {text, markedSpans} object.
phrebejk@460
  3464
  function hlText(val) { return typeof val == "string" ? val : val.text; }
phrebejk@460
  3465
  function hlSpans(val) {
phrebejk@460
  3466
    if (typeof val == "string") return null;
phrebejk@460
  3467
    var spans = val.markedSpans, out = null;
phrebejk@460
  3468
    for (var i = 0; i < spans.length; ++i) {
phrebejk@460
  3469
      if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
phrebejk@460
  3470
      else if (out) out.push(spans[i]);
phrebejk@460
  3471
    }
phrebejk@460
  3472
    return !out ? spans : out.length ? out : null;
phrebejk@460
  3473
  }
phrebejk@460
  3474
  function newHL(text, spans) { return spans ? {text: text, markedSpans: spans} : text; }
phrebejk@460
  3475
phrebejk@460
  3476
  function detachMarkedSpans(line) {
phrebejk@460
  3477
    var spans = line.markedSpans;
phrebejk@460
  3478
    if (!spans) return;
phrebejk@460
  3479
    for (var i = 0; i < spans.length; ++i) {
phrebejk@460
  3480
      var lines = spans[i].marker.lines;
phrebejk@460
  3481
      var ix = indexOf(lines, line);
phrebejk@460
  3482
      lines.splice(ix, 1);
phrebejk@460
  3483
    }
phrebejk@460
  3484
    line.markedSpans = null;
phrebejk@460
  3485
  }
phrebejk@460
  3486
phrebejk@460
  3487
  function attachMarkedSpans(line, spans) {
phrebejk@460
  3488
    if (!spans) return;
phrebejk@460
  3489
    for (var i = 0; i < spans.length; ++i)
phrebejk@460
  3490
      spans[i].marker.lines.push(line);
phrebejk@460
  3491
    line.markedSpans = spans;
phrebejk@460
  3492
  }
phrebejk@460
  3493
phrebejk@460
  3494
  // LINE DATA STRUCTURE
phrebejk@460
  3495
phrebejk@460
  3496
  // Line objects. These hold state related to a line, including
phrebejk@460
  3497
  // highlighting info (the styles array).
phrebejk@460
  3498
  function makeLine(text, markedSpans, height) {
phrebejk@460
  3499
    var line = {text: text, height: height};
phrebejk@460
  3500
    attachMarkedSpans(line, markedSpans);
phrebejk@460
  3501
    if (lineIsHidden(line)) line.height = 0;
phrebejk@460
  3502
    return line;
phrebejk@460
  3503
  }
phrebejk@460
  3504
phrebejk@460
  3505
  function updateLine(cm, line, text, markedSpans) {
phrebejk@460
  3506
    line.text = text;
phrebejk@460
  3507
    line.stateAfter = line.styles = null;
phrebejk@460
  3508
    if (line.order != null) line.order = null;
phrebejk@460
  3509
    detachMarkedSpans(line);
phrebejk@460
  3510
    attachMarkedSpans(line, markedSpans);
phrebejk@460
  3511
    if (lineIsHidden(line)) line.height = 0;
phrebejk@460
  3512
    else if (!line.height) line.height = textHeight(cm.display);
phrebejk@460
  3513
    signalLater(cm, line, "change");
phrebejk@460
  3514
  }
phrebejk@460
  3515
phrebejk@460
  3516
  function cleanUpLine(line) {
phrebejk@460
  3517
    line.parent = null;
phrebejk@460
  3518
    detachMarkedSpans(line);
phrebejk@460
  3519
  }
phrebejk@460
  3520
phrebejk@460
  3521
  // Run the given mode's parser over a line, update the styles
phrebejk@460
  3522
  // array, which contains alternating fragments of text and CSS
phrebejk@460
  3523
  // classes.
phrebejk@460
  3524
  function highlightLine(cm, line, state) {
phrebejk@460
  3525
    var mode = cm.view.mode, flattenSpans = cm.options.flattenSpans;
phrebejk@460
  3526
    var changed = !line.styles, pos = 0, curText = "", curStyle = null;
phrebejk@460
  3527
    var stream = new StringStream(line.text, cm.options.tabSize), st = line.styles || (line.styles = []);
phrebejk@460
  3528
    if (line.text == "" && mode.blankLine) mode.blankLine(state);
phrebejk@460
  3529
    while (!stream.eol()) {
phrebejk@460
  3530
      var style = mode.token(stream, state), substr = stream.current();
phrebejk@460
  3531
      stream.start = stream.pos;
phrebejk@460
  3532
      if (!flattenSpans || curStyle != style) {
phrebejk@460
  3533
        if (curText) {
phrebejk@460
  3534
          changed = changed || pos >= st.length || curText != st[pos] || curStyle != st[pos+1];
phrebejk@460
  3535
          st[pos++] = curText; st[pos++] = curStyle;
phrebejk@460
  3536
        }
phrebejk@460
  3537
        curText = substr; curStyle = style;
phrebejk@460
  3538
      } else curText = curText + substr;
phrebejk@460
  3539
      // Give up when line is ridiculously long
phrebejk@460
  3540
      if (stream.pos > 5000) break;
phrebejk@460
  3541
    }
phrebejk@460
  3542
    if (curText) {
phrebejk@460
  3543
      changed = changed || pos >= st.length || curText != st[pos] || curStyle != st[pos+1];
phrebejk@460
  3544
      st[pos++] = curText; st[pos++] = curStyle;
phrebejk@460
  3545
    }
phrebejk@460
  3546
    if (stream.pos > 5000) { st[pos++] = line.text.slice(stream.pos); st[pos++] = null; }
phrebejk@460
  3547
    if (pos != st.length) { st.length = pos; changed = true; }
phrebejk@460
  3548
    return changed;
phrebejk@460
  3549
  }
phrebejk@460
  3550
phrebejk@460
  3551
  // Lightweight form of highlight -- proceed over this line and
phrebejk@460
  3552
  // update state, but don't save a style array.
phrebejk@460
  3553
  function processLine(cm, line, state) {
phrebejk@460
  3554
    var mode = cm.view.mode;
phrebejk@460
  3555
    var stream = new StringStream(line.text, cm.options.tabSize);
phrebejk@460
  3556
    if (line.text == "" && mode.blankLine) mode.blankLine(state);
phrebejk@460
  3557
    while (!stream.eol() && stream.pos <= 5000) {
phrebejk@460
  3558
      mode.token(stream, state);
phrebejk@460
  3559
      stream.start = stream.pos;
phrebejk@460
  3560
    }
phrebejk@460
  3561
  }
phrebejk@460
  3562
phrebejk@460
  3563
  var styleToClassCache = {};
phrebejk@460
  3564
  function styleToClass(style) {
phrebejk@460
  3565
    if (!style) return null;
phrebejk@460
  3566
    return styleToClassCache[style] ||
phrebejk@460
  3567
      (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-"));
phrebejk@460
  3568
  }
phrebejk@460
  3569
phrebejk@460
  3570
  function lineContent(cm, realLine, measure) {
phrebejk@460
  3571
    var merged, line = realLine, lineBefore, sawBefore, simple = true;
phrebejk@460
  3572
    while (merged = collapsedSpanAtStart(line)) {
phrebejk@460
  3573
      simple = false;
phrebejk@460
  3574
      line = getLine(cm.view.doc, merged.find().from.line);
phrebejk@460
  3575
      if (!lineBefore) lineBefore = line;
phrebejk@460
  3576
    }
phrebejk@460
  3577
phrebejk@460
  3578
    var builder = {pre: elt("pre"), col: 0, pos: 0, display: !measure,
phrebejk@460
  3579
                   measure: null, addedOne: false, cm: cm};
phrebejk@460
  3580
    if (line.textClass) builder.pre.className = line.textClass;
phrebejk@460
  3581
phrebejk@460
  3582
    do {
phrebejk@460
  3583
      if (!line.styles)
phrebejk@460
  3584
        highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
phrebejk@460
  3585
      builder.measure = line == realLine && measure;
phrebejk@460
  3586
      builder.pos = 0;
phrebejk@460
  3587
      builder.addToken = builder.measure ? buildTokenMeasure : buildToken;
phrebejk@460
  3588
      if (measure && sawBefore && line != realLine && !builder.addedOne) {
phrebejk@460
  3589
        measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure));
phrebejk@460
  3590
        builder.addedOne = true;
phrebejk@460
  3591
      }
phrebejk@460
  3592
      var next = insertLineContent(line, builder);
phrebejk@460
  3593
      sawBefore = line == lineBefore;
phrebejk@460
  3594
      if (next) {
phrebejk@460
  3595
        line = getLine(cm.view.doc, next.to.line);
phrebejk@460
  3596
        simple = false;
phrebejk@460
  3597
      }
phrebejk@460
  3598
    } while (next);
phrebejk@460
  3599
phrebejk@460
  3600
    if (measure && !builder.addedOne)
phrebejk@460
  3601
      measure[0] = builder.pre.appendChild(simple ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure));
phrebejk@460
  3602
    if (!builder.pre.firstChild && !lineIsHidden(realLine))
phrebejk@460
  3603
      builder.pre.appendChild(document.createTextNode("\u00a0"));
phrebejk@460
  3604
phrebejk@460
  3605
    return builder.pre;
phrebejk@460
  3606
  }
phrebejk@460
  3607
phrebejk@460
  3608
  var tokenSpecialChars = /[\t\u0000-\u0019\u200b\u2028\u2029\uFEFF]/g;
phrebejk@460
  3609
  function buildToken(builder, text, style, startStyle, endStyle) {
phrebejk@460
  3610
    if (!text) return;
phrebejk@460
  3611
    if (!tokenSpecialChars.test(text)) {
phrebejk@460
  3612
      builder.col += text.length;
phrebejk@460
  3613
      var content = document.createTextNode(text);
phrebejk@460
  3614
    } else {
phrebejk@460
  3615
      var content = document.createDocumentFragment(), pos = 0;
phrebejk@460
  3616
      while (true) {
phrebejk@460
  3617
        tokenSpecialChars.lastIndex = pos;
phrebejk@460
  3618
        var m = tokenSpecialChars.exec(text);
phrebejk@460
  3619
        var skipped = m ? m.index - pos : text.length - pos;
phrebejk@460
  3620
        if (skipped) {
phrebejk@460
  3621
          content.appendChild(document.createTextNode(text.slice(pos, pos + skipped)));
phrebejk@460
  3622
          builder.col += skipped;
phrebejk@460
  3623
        }
phrebejk@460
  3624
        if (!m) break;
phrebejk@460
  3625
        pos += skipped + 1;
phrebejk@460
  3626
        if (m[0] == "\t") {
phrebejk@460
  3627
          var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
phrebejk@460
  3628
          content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
phrebejk@460
  3629
          builder.col += tabWidth;
phrebejk@460
  3630
        } else {
phrebejk@460
  3631
          var token = elt("span", "\u2022", "cm-invalidchar");
phrebejk@460
  3632
          token.title = "\\u" + m[0].charCodeAt(0).toString(16);
phrebejk@460
  3633
          content.appendChild(token);
phrebejk@460
  3634
          builder.col += 1;
phrebejk@460
  3635
        }
phrebejk@460
  3636
      }
phrebejk@460
  3637
    }
phrebejk@460
  3638
    if (style || startStyle || endStyle || builder.measure) {
phrebejk@460
  3639
      var fullStyle = style || "";
phrebejk@460
  3640
      if (startStyle) fullStyle += startStyle;
phrebejk@460
  3641
      if (endStyle) fullStyle += endStyle;
phrebejk@460
  3642
      return builder.pre.appendChild(elt("span", [content], fullStyle));
phrebejk@460
  3643
    }
phrebejk@460
  3644
    builder.pre.appendChild(content);
phrebejk@460
  3645
  }
phrebejk@460
  3646
phrebejk@460
  3647
  function buildTokenMeasure(builder, text, style, startStyle, endStyle) {
phrebejk@460
  3648
    for (var i = 0; i < text.length; ++i) {
phrebejk@460
  3649
      if (i && i < text.length - 1 &&
phrebejk@460
  3650
          builder.cm.options.lineWrapping &&
phrebejk@460
  3651
          spanAffectsWrapping.test(text.slice(i - 1, i + 1)))
phrebejk@460
  3652
        builder.pre.appendChild(elt("wbr"));
phrebejk@460
  3653
      builder.measure[builder.pos++] =
phrebejk@460
  3654
        buildToken(builder, text.charAt(i), style,
phrebejk@460
  3655
                   i == 0 && startStyle, i == text.length - 1 && endStyle);
phrebejk@460
  3656
    }
phrebejk@460
  3657
    if (text.length) builder.addedOne = true;
phrebejk@460
  3658
  }
phrebejk@460
  3659
phrebejk@460
  3660
  function buildCollapsedSpan(builder, size, widget) {
phrebejk@460
  3661
    if (widget) {
phrebejk@460
  3662
      if (!builder.display) widget = widget.cloneNode(true);
phrebejk@460
  3663
      builder.pre.appendChild(widget);
phrebejk@460
  3664
      if (builder.measure && size) {
phrebejk@460
  3665
        builder.measure[builder.pos] = widget;
phrebejk@460
  3666
        builder.addedOne = true;
phrebejk@460
  3667
      }
phrebejk@460
  3668
    }
phrebejk@460
  3669
    builder.pos += size;
phrebejk@460
  3670
  }
phrebejk@460
  3671
phrebejk@460
  3672
  // Outputs a number of spans to make up a line, taking highlighting
phrebejk@460
  3673
  // and marked text into account.
phrebejk@460
  3674
  function insertLineContent(line, builder) {
phrebejk@460
  3675
    var st = line.styles, spans = line.markedSpans;
phrebejk@460
  3676
    if (!spans) {
phrebejk@460
  3677
      for (var i = 0; i < st.length; i+=2)
phrebejk@460
  3678
        builder.addToken(builder, st[i], styleToClass(st[i+1]));
phrebejk@460
  3679
      return;
phrebejk@460
  3680
    }
phrebejk@460
  3681
phrebejk@460
  3682
    var allText = line.text, len = allText.length;
phrebejk@460
  3683
    var pos = 0, i = 0, text = "", style;
phrebejk@460
  3684
    var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed;
phrebejk@460
  3685
    for (;;) {
phrebejk@460
  3686
      if (nextChange == pos) { // Update current marker set
phrebejk@460
  3687
        spanStyle = spanEndStyle = spanStartStyle = "";
phrebejk@460
  3688
        collapsed = null; nextChange = Infinity;
phrebejk@460
  3689
        var foundBookmark = null;
phrebejk@460
  3690
        for (var j = 0; j < spans.length; ++j) {
phrebejk@460
  3691
          var sp = spans[j], m = sp.marker;
phrebejk@460
  3692
          if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
phrebejk@460
  3693
            if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
phrebejk@460
  3694
            if (m.className) spanStyle += " " + m.className;
phrebejk@460
  3695
            if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
phrebejk@460
  3696
            if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
phrebejk@460
  3697
            if (m.collapsed && (!collapsed || collapsed.marker.width < m.width))
phrebejk@460
  3698
              collapsed = sp;
phrebejk@460
  3699
          } else if (sp.from > pos && nextChange > sp.from) {
phrebejk@460
  3700
            nextChange = sp.from;
phrebejk@460
  3701
          }
phrebejk@460
  3702
          if (m.type == "bookmark" && sp.from == pos && m.replacedWith)
phrebejk@460
  3703
            foundBookmark = m.replacedWith;
phrebejk@460
  3704
        }
phrebejk@460
  3705
        if (collapsed && (collapsed.from || 0) == pos) {
phrebejk@460
  3706
          buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos,
phrebejk@460
  3707
                             collapsed.from != null && collapsed.marker.replacedWith);
phrebejk@460
  3708
          if (collapsed.to == null) return collapsed.marker.find();
phrebejk@460
  3709
        }
phrebejk@460
  3710
        if (foundBookmark && !collapsed) buildCollapsedSpan(builder, 0, foundBookmark);
phrebejk@460
  3711
      }
phrebejk@460
  3712
      if (pos >= len) break;
phrebejk@460
  3713
phrebejk@460
  3714
      var upto = Math.min(len, nextChange);
phrebejk@460
  3715
      while (true) {
phrebejk@460
  3716
        if (text) {
phrebejk@460
  3717
          var end = pos + text.length;
phrebejk@460
  3718
          if (!collapsed) {
phrebejk@460
  3719
            var tokenText = end > upto ? text.slice(0, upto - pos) : text;
phrebejk@460
  3720
            builder.addToken(builder, tokenText, style + spanStyle,
phrebejk@460
  3721
                             spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "");
phrebejk@460
  3722
          }
phrebejk@460
  3723
          if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
phrebejk@460
  3724
          pos = end;
phrebejk@460
  3725
          spanStartStyle = "";
phrebejk@460
  3726
        }
phrebejk@460
  3727
        text = st[i++]; style = styleToClass(st[i++]);
phrebejk@460
  3728
      }
phrebejk@460
  3729
    }
phrebejk@460
  3730
  }
phrebejk@460
  3731
phrebejk@460
  3732
  // DOCUMENT DATA STRUCTURE
phrebejk@460
  3733
phrebejk@460
  3734
  function LeafChunk(lines) {
phrebejk@460
  3735
    this.lines = lines;
phrebejk@460
  3736
    this.parent = null;
phrebejk@460
  3737
    for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
phrebejk@460
  3738
      lines[i].parent = this;
phrebejk@460
  3739
      height += lines[i].height;
phrebejk@460
  3740
    }
phrebejk@460
  3741
    this.height = height;
phrebejk@460
  3742
  }
phrebejk@460
  3743
phrebejk@460
  3744
  LeafChunk.prototype = {
phrebejk@460
  3745
    chunkSize: function() { return this.lines.length; },
phrebejk@460
  3746
    remove: function(at, n, cm) {
phrebejk@460
  3747
      for (var i = at, e = at + n; i < e; ++i) {
phrebejk@460
  3748
        var line = this.lines[i];
phrebejk@460
  3749
        this.height -= line.height;
phrebejk@460
  3750
        cleanUpLine(line);
phrebejk@460
  3751
        signalLater(cm, line, "delete");
phrebejk@460
  3752
      }
phrebejk@460
  3753
      this.lines.splice(at, n);
phrebejk@460
  3754
    },
phrebejk@460
  3755
    collapse: function(lines) {
phrebejk@460
  3756
      lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
phrebejk@460
  3757
    },
phrebejk@460
  3758
    insertHeight: function(at, lines, height) {
phrebejk@460
  3759
      this.height += height;
phrebejk@460
  3760
      this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
phrebejk@460
  3761
      for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
phrebejk@460
  3762
    },
phrebejk@460
  3763
    iterN: function(at, n, op) {
phrebejk@460
  3764
      for (var e = at + n; at < e; ++at)
phrebejk@460
  3765
        if (op(this.lines[at])) return true;
phrebejk@460
  3766
    }
phrebejk@460
  3767
  };
phrebejk@460
  3768
phrebejk@460
  3769
  function BranchChunk(children) {
phrebejk@460
  3770
    this.children = children;
phrebejk@460
  3771
    var size = 0, height = 0;
phrebejk@460
  3772
    for (var i = 0, e = children.length; i < e; ++i) {
phrebejk@460
  3773
      var ch = children[i];
phrebejk@460
  3774
      size += ch.chunkSize(); height += ch.height;
phrebejk@460
  3775
      ch.parent = this;
phrebejk@460
  3776
    }
phrebejk@460
  3777
    this.size = size;
phrebejk@460
  3778
    this.height = height;
phrebejk@460
  3779
    this.parent = null;
phrebejk@460
  3780
  }
phrebejk@460
  3781
phrebejk@460
  3782
  BranchChunk.prototype = {
phrebejk@460
  3783
    chunkSize: function() { return this.size; },
phrebejk@460
  3784
    remove: function(at, n, callbacks) {
phrebejk@460
  3785
      this.size -= n;
phrebejk@460
  3786
      for (var i = 0; i < this.children.length; ++i) {
phrebejk@460
  3787
        var child = this.children[i], sz = child.chunkSize();
phrebejk@460
  3788
        if (at < sz) {
phrebejk@460
  3789
          var rm = Math.min(n, sz - at), oldHeight = child.height;
phrebejk@460
  3790
          child.remove(at, rm, callbacks);
phrebejk@460
  3791
          this.height -= oldHeight - child.height;
phrebejk@460
  3792
          if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
phrebejk@460
  3793
          if ((n -= rm) == 0) break;
phrebejk@460
  3794
          at = 0;
phrebejk@460
  3795
        } else at -= sz;
phrebejk@460
  3796
      }
phrebejk@460
  3797
      if (this.size - n < 25) {
phrebejk@460
  3798
        var lines = [];
phrebejk@460
  3799
        this.collapse(lines);
phrebejk@460
  3800
        this.children = [new LeafChunk(lines)];
phrebejk@460
  3801
        this.children[0].parent = this;
phrebejk@460
  3802
      }
phrebejk@460
  3803
    },
phrebejk@460
  3804
    collapse: function(lines) {
phrebejk@460
  3805
      for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
phrebejk@460
  3806
    },
phrebejk@460
  3807
    insert: function(at, lines) {
phrebejk@460
  3808
      var height = 0;
phrebejk@460
  3809
      for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
phrebejk@460
  3810
      this.insertHeight(at, lines, height);
phrebejk@460
  3811
    },
phrebejk@460
  3812
    insertHeight: function(at, lines, height) {
phrebejk@460
  3813
      this.size += lines.length;
phrebejk@460
  3814
      this.height += height;
phrebejk@460
  3815
      for (var i = 0, e = this.children.length; i < e; ++i) {
phrebejk@460
  3816
        var child = this.children[i], sz = child.chunkSize();
phrebejk@460
  3817
        if (at <= sz) {
phrebejk@460
  3818
          child.insertHeight(at, lines, height);
phrebejk@460
  3819
          if (child.lines && child.lines.length > 50) {
phrebejk@460
  3820
            while (child.lines.length > 50) {
phrebejk@460
  3821
              var spilled = child.lines.splice(child.lines.length - 25, 25);
phrebejk@460
  3822
              var newleaf = new LeafChunk(spilled);
phrebejk@460
  3823
              child.height -= newleaf.height;
phrebejk@460
  3824
              this.children.splice(i + 1, 0, newleaf);
phrebejk@460
  3825
              newleaf.parent = this;
phrebejk@460
  3826
            }
phrebejk@460
  3827
            this.maybeSpill();
phrebejk@460
  3828
          }
phrebejk@460
  3829
          break;
phrebejk@460
  3830
        }
phrebejk@460
  3831
        at -= sz;
phrebejk@460
  3832
      }
phrebejk@460
  3833
    },
phrebejk@460
  3834
    maybeSpill: function() {
phrebejk@460
  3835
      if (this.children.length <= 10) return;
phrebejk@460
  3836
      var me = this;
phrebejk@460
  3837
      do {
phrebejk@460
  3838
        var spilled = me.children.splice(me.children.length - 5, 5);
phrebejk@460
  3839
        var sibling = new BranchChunk(spilled);
phrebejk@460
  3840
        if (!me.parent) { // Become the parent node
phrebejk@460
  3841
          var copy = new BranchChunk(me.children);
phrebejk@460
  3842
          copy.parent = me;
phrebejk@460
  3843
          me.children = [copy, sibling];
phrebejk@460
  3844
          me = copy;
phrebejk@460
  3845
        } else {
phrebejk@460
  3846
          me.size -= sibling.size;
phrebejk@460
  3847
          me.height -= sibling.height;
phrebejk@460
  3848
          var myIndex = indexOf(me.parent.children, me);
phrebejk@460
  3849
          me.parent.children.splice(myIndex + 1, 0, sibling);
phrebejk@460
  3850
        }
phrebejk@460
  3851
        sibling.parent = me.parent;
phrebejk@460
  3852
      } while (me.children.length > 10);
phrebejk@460
  3853
      me.parent.maybeSpill();
phrebejk@460
  3854
    },
phrebejk@460
  3855
    iter: function(from, to, op) { this.iterN(from, to - from, op); },
phrebejk@460
  3856
    iterN: function(at, n, op) {
phrebejk@460
  3857
      for (var i = 0, e = this.children.length; i < e; ++i) {
phrebejk@460
  3858
        var child = this.children[i], sz = child.chunkSize();
phrebejk@460
  3859
        if (at < sz) {
phrebejk@460
  3860
          var used = Math.min(n, sz - at);
phrebejk@460
  3861
          if (child.iterN(at, used, op)) return true;
phrebejk@460
  3862
          if ((n -= used) == 0) break;
phrebejk@460
  3863
          at = 0;
phrebejk@460
  3864
        } else at -= sz;
phrebejk@460
  3865
      }
phrebejk@460
  3866
    }
phrebejk@460
  3867
  };
phrebejk@460
  3868
phrebejk@460
  3869
  // LINE UTILITIES
phrebejk@460
  3870
phrebejk@460
  3871
  function getLine(chunk, n) {
phrebejk@460
  3872
    while (!chunk.lines) {
phrebejk@460
  3873
      for (var i = 0;; ++i) {
phrebejk@460
  3874
        var child = chunk.children[i], sz = child.chunkSize();
phrebejk@460
  3875
        if (n < sz) { chunk = child; break; }
phrebejk@460
  3876
        n -= sz;
phrebejk@460
  3877
      }
phrebejk@460
  3878
    }
phrebejk@460
  3879
    return chunk.lines[n];
phrebejk@460
  3880
  }
phrebejk@460
  3881
phrebejk@460
  3882
  function updateLineHeight(line, height) {
phrebejk@460
  3883
    var diff = height - line.height;
phrebejk@460
  3884
    for (var n = line; n; n = n.parent) n.height += diff;
phrebejk@460
  3885
  }
phrebejk@460
  3886
phrebejk@460
  3887
  function lineNo(line) {
phrebejk@460
  3888
    if (line.parent == null) return null;
phrebejk@460
  3889
    var cur = line.parent, no = indexOf(cur.lines, line);
phrebejk@460
  3890
    for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
phrebejk@460
  3891
      for (var i = 0;; ++i) {
phrebejk@460
  3892
        if (chunk.children[i] == cur) break;
phrebejk@460
  3893
        no += chunk.children[i].chunkSize();
phrebejk@460
  3894
      }
phrebejk@460
  3895
    }
phrebejk@460
  3896
    return no;
phrebejk@460
  3897
  }
phrebejk@460
  3898
phrebejk@460
  3899
  function lineAtHeight(chunk, h) {
phrebejk@460
  3900
    var n = 0;
phrebejk@460
  3901
    outer: do {
phrebejk@460
  3902
      for (var i = 0, e = chunk.children.length; i < e; ++i) {
phrebejk@460
  3903
        var child = chunk.children[i], ch = child.height;
phrebejk@460
  3904
        if (h < ch) { chunk = child; continue outer; }
phrebejk@460
  3905
        h -= ch;
phrebejk@460
  3906
        n += child.chunkSize();
phrebejk@460
  3907
      }
phrebejk@460
  3908
      return n;
phrebejk@460
  3909
    } while (!chunk.lines);
phrebejk@460
  3910
    for (var i = 0, e = chunk.lines.length; i < e; ++i) {
phrebejk@460
  3911
      var line = chunk.lines[i], lh = line.height;
phrebejk@460
  3912
      if (h < lh) break;
phrebejk@460
  3913
      h -= lh;
phrebejk@460
  3914
    }
phrebejk@460
  3915
    return n + i;
phrebejk@460
  3916
  }
phrebejk@460
  3917
phrebejk@460
  3918
  function heightAtLine(cm, lineObj) {
phrebejk@460
  3919
    lineObj = visualLine(cm.view.doc, lineObj);
phrebejk@460
  3920
phrebejk@460
  3921
    var h = 0, chunk = lineObj.parent;
phrebejk@460
  3922
    for (var i = 0; i < chunk.lines.length; ++i) {
phrebejk@460
  3923
      var line = chunk.lines[i];
phrebejk@460
  3924
      if (line == lineObj) break;
phrebejk@460
  3925
      else h += line.height;
phrebejk@460
  3926
    }
phrebejk@460
  3927
    for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
phrebejk@460
  3928
      for (var i = 0; i < p.children.length; ++i) {
phrebejk@460
  3929
        var cur = p.children[i];
phrebejk@460
  3930
        if (cur == chunk) break;
phrebejk@460
  3931
        else h += cur.height;
phrebejk@460
  3932
      }
phrebejk@460
  3933
    }
phrebejk@460
  3934
    return h;
phrebejk@460
  3935
  }
phrebejk@460
  3936
phrebejk@460
  3937
  function getOrder(line) {
phrebejk@460
  3938
    var order = line.order;
phrebejk@460
  3939
    if (order == null) order = line.order = bidiOrdering(line.text);
phrebejk@460
  3940
    return order;
phrebejk@460
  3941
  }
phrebejk@460
  3942
phrebejk@460
  3943
  // HISTORY
phrebejk@460
  3944
phrebejk@460
  3945
  function makeHistory() {
phrebejk@460
  3946
    return {
phrebejk@460
  3947
      // Arrays of history events. Doing something adds an event to
phrebejk@460
  3948
      // done and clears undo. Undoing moves events from done to
phrebejk@460
  3949
      // undone, redoing moves them in the other direction.
phrebejk@460
  3950
      done: [], undone: [],
phrebejk@460
  3951
      // Used to track when changes can be merged into a single undo
phrebejk@460
  3952
      // event
phrebejk@460
  3953
      lastTime: 0, lastOp: null, lastOrigin: null,
phrebejk@460
  3954
      // Used by the isClean() method
phrebejk@460
  3955
      dirtyCounter: 0
phrebejk@460
  3956
    };
phrebejk@460
  3957
  }
phrebejk@460
  3958
phrebejk@460
  3959
  function addChange(cm, start, added, old, origin, fromBefore, toBefore, fromAfter, toAfter) {
phrebejk@460
  3960
    var history = cm.view.history;
phrebejk@460
  3961
    history.undone.length = 0;
phrebejk@460
  3962
    var time = +new Date, cur = lst(history.done);
phrebejk@460
  3963
    
phrebejk@460
  3964
    if (cur &&
phrebejk@460
  3965
        (history.lastOp == cm.curOp.id ||
phrebejk@460
  3966
         history.lastOrigin == origin && (origin == "input" || origin == "delete") &&
phrebejk@460
  3967
         history.lastTime > time - 600)) {
phrebejk@460
  3968
      // Merge this change into the last event
phrebejk@460
  3969
      var last = lst(cur.events);
phrebejk@460
  3970
      if (last.start > start + old.length || last.start + last.added < start) {
phrebejk@460
  3971
        // Doesn't intersect with last sub-event, add new sub-event
phrebejk@460
  3972
        cur.events.push({start: start, added: added, old: old});
phrebejk@460
  3973
      } else {
phrebejk@460
  3974
        // Patch up the last sub-event
phrebejk@460
  3975
        var startBefore = Math.max(0, last.start - start),
phrebejk@460
  3976
        endAfter = Math.max(0, (start + old.length) - (last.start + last.added));
phrebejk@460
  3977
        for (var i = startBefore; i > 0; --i) last.old.unshift(old[i - 1]);
phrebejk@460
  3978
        for (var i = endAfter; i > 0; --i) last.old.push(old[old.length - i]);
phrebejk@460
  3979
        if (startBefore) last.start = start;
phrebejk@460
  3980
        last.added += added - (old.length - startBefore - endAfter);
phrebejk@460
  3981
      }
phrebejk@460
  3982
      cur.fromAfter = fromAfter; cur.toAfter = toAfter;
phrebejk@460
  3983
    } else {
phrebejk@460
  3984
      // Can not be merged, start a new event.
phrebejk@460
  3985
      cur = {events: [{start: start, added: added, old: old}],
phrebejk@460
  3986
             fromBefore: fromBefore, toBefore: toBefore, fromAfter: fromAfter, toAfter: toAfter};
phrebejk@460
  3987
      history.done.push(cur);
phrebejk@460
  3988
      while (history.done.length > cm.options.undoDepth)
phrebejk@460
  3989
        history.done.shift();
phrebejk@460
  3990
      if (history.dirtyCounter < 0)
phrebejk@460
  3991
          // The user has made a change after undoing past the last clean state. 
phrebejk@460
  3992
          // We can never get back to a clean state now until markClean() is called.
phrebejk@460
  3993
          history.dirtyCounter = NaN;
phrebejk@460
  3994
      else
phrebejk@460
  3995
        history.dirtyCounter++;
phrebejk@460
  3996
    }
phrebejk@460
  3997
    history.lastTime = time;
phrebejk@460
  3998
    history.lastOp = cm.curOp.id;
phrebejk@460
  3999
    history.lastOrigin = origin;
phrebejk@460
  4000
  }
phrebejk@460
  4001
phrebejk@460
  4002
  // EVENT OPERATORS
phrebejk@460
  4003
phrebejk@460
  4004
  function stopMethod() {e_stop(this);}
phrebejk@460
  4005
  // Ensure an event has a stop method.
phrebejk@460
  4006
  function addStop(event) {
phrebejk@460
  4007
    if (!event.stop) event.stop = stopMethod;
phrebejk@460
  4008
    return event;
phrebejk@460
  4009
  }
phrebejk@460
  4010
phrebejk@460
  4011
  function e_preventDefault(e) {
phrebejk@460
  4012
    if (e.preventDefault) e.preventDefault();
phrebejk@460
  4013
    else e.returnValue = false;
phrebejk@460
  4014
  }
phrebejk@460
  4015
  function e_stopPropagation(e) {
phrebejk@460
  4016
    if (e.stopPropagation) e.stopPropagation();
phrebejk@460
  4017
    else e.cancelBubble = true;
phrebejk@460
  4018
  }
phrebejk@460
  4019
  function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
phrebejk@460
  4020
  CodeMirror.e_stop = e_stop;
phrebejk@460
  4021
  CodeMirror.e_preventDefault = e_preventDefault;
phrebejk@460
  4022
  CodeMirror.e_stopPropagation = e_stopPropagation;
phrebejk@460
  4023
phrebejk@460
  4024
  function e_target(e) {return e.target || e.srcElement;}
phrebejk@460
  4025
  function e_button(e) {
phrebejk@460
  4026
    var b = e.which;
phrebejk@460
  4027
    if (b == null) {
phrebejk@460
  4028
      if (e.button & 1) b = 1;
phrebejk@460
  4029
      else if (e.button & 2) b = 3;
phrebejk@460
  4030
      else if (e.button & 4) b = 2;
phrebejk@460
  4031
    }
phrebejk@460
  4032
    if (mac && e.ctrlKey && b == 1) b = 3;
phrebejk@460
  4033
    return b;
phrebejk@460
  4034
  }
phrebejk@460
  4035
phrebejk@460
  4036
  // Allow 3rd-party code to override event properties by adding an override
phrebejk@460
  4037
  // object to an event object.
phrebejk@460
  4038
  function e_prop(e, prop) {
phrebejk@460
  4039
    var overridden = e.override && e.override.hasOwnProperty(prop);
phrebejk@460
  4040
    return overridden ? e.override[prop] : e[prop];
phrebejk@460
  4041
  }
phrebejk@460
  4042
phrebejk@460
  4043
  // EVENT HANDLING
phrebejk@460
  4044
phrebejk@460
  4045
  function on(emitter, type, f) {
phrebejk@460
  4046
    if (emitter.addEventListener)
phrebejk@460
  4047
      emitter.addEventListener(type, f, false);
phrebejk@460
  4048
    else if (emitter.attachEvent)
phrebejk@460
  4049
      emitter.attachEvent("on" + type, f);
phrebejk@460
  4050
    else {
phrebejk@460
  4051
      var map = emitter._handlers || (emitter._handlers = {});
phrebejk@460
  4052
      var arr = map[type] || (map[type] = []);
phrebejk@460
  4053
      arr.push(f);
phrebejk@460
  4054
    }
phrebejk@460
  4055
  }
phrebejk@460
  4056
phrebejk@460
  4057
  function off(emitter, type, f) {
phrebejk@460
  4058
    if (emitter.removeEventListener)
phrebejk@460
  4059
      emitter.removeEventListener(type, f, false);
phrebejk@460
  4060
    else if (emitter.detachEvent)
phrebejk@460
  4061
      emitter.detachEvent("on" + type, f);
phrebejk@460
  4062
    else {
phrebejk@460
  4063
      var arr = emitter._handlers && emitter._handlers[type];
phrebejk@460
  4064
      if (!arr) return;
phrebejk@460
  4065
      for (var i = 0; i < arr.length; ++i)
phrebejk@460
  4066
        if (arr[i] == f) { arr.splice(i, 1); break; }
phrebejk@460
  4067
    }
phrebejk@460
  4068
  }
phrebejk@460
  4069
phrebejk@460
  4070
  function signal(emitter, type /*, values...*/) {
phrebejk@460
  4071
    var arr = emitter._handlers && emitter._handlers[type];
phrebejk@460
  4072
    if (!arr) return;
phrebejk@460
  4073
    var args = Array.prototype.slice.call(arguments, 2);
phrebejk@460
  4074
    for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
phrebejk@460
  4075
  }
phrebejk@460
  4076
phrebejk@460
  4077
  function signalLater(cm, emitter, type /*, values...*/) {
phrebejk@460
  4078
    var arr = emitter._handlers && emitter._handlers[type];
phrebejk@460
  4079
    if (!arr) return;
phrebejk@460
  4080
    var args = Array.prototype.slice.call(arguments, 3), flist = cm.curOp && cm.curOp.delayedCallbacks;
phrebejk@460
  4081
    function bnd(f) {return function(){f.apply(null, args);};};
phrebejk@460
  4082
    for (var i = 0; i < arr.length; ++i)
phrebejk@460
  4083
      if (flist) flist.push(bnd(arr[i]));
phrebejk@460
  4084
      else arr[i].apply(null, args);
phrebejk@460
  4085
  }
phrebejk@460
  4086
phrebejk@460
  4087
  function hasHandler(emitter, type) {
phrebejk@460
  4088
    var arr = emitter._handlers && emitter._handlers[type];
phrebejk@460
  4089
    return arr && arr.length > 0;
phrebejk@460
  4090
  }
phrebejk@460
  4091
phrebejk@460
  4092
  CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal;
phrebejk@460
  4093
phrebejk@460
  4094
  // MISC UTILITIES
phrebejk@460
  4095
phrebejk@460
  4096
  // Number of pixels added to scroller and sizer to hide scrollbar
phrebejk@460
  4097
  var scrollerCutOff = 30;
phrebejk@460
  4098
phrebejk@460
  4099
  // Returned or thrown by various protocols to signal 'I'm not
phrebejk@460
  4100
  // handling this'.
phrebejk@460
  4101
  var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
phrebejk@460
  4102
phrebejk@460
  4103
  function Delayed() {this.id = null;}
phrebejk@460
  4104
  Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
phrebejk@460
  4105
phrebejk@460
  4106
  // Counts the column offset in a string, taking tabs into account.
phrebejk@460
  4107
  // Used mostly to find indentation.
phrebejk@460
  4108
  function countColumn(string, end, tabSize) {
phrebejk@460
  4109
    if (end == null) {
phrebejk@460
  4110
      end = string.search(/[^\s\u00a0]/);
phrebejk@460
  4111
      if (end == -1) end = string.length;
phrebejk@460
  4112
    }
phrebejk@460
  4113
    for (var i = 0, n = 0; i < end; ++i) {
phrebejk@460
  4114
      if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
phrebejk@460
  4115
      else ++n;
phrebejk@460
  4116
    }
phrebejk@460
  4117
    return n;
phrebejk@460
  4118
  }
phrebejk@460
  4119
  CodeMirror.countColumn = countColumn;
phrebejk@460
  4120
phrebejk@460
  4121
  var spaceStrs = [""];
phrebejk@460
  4122
  function spaceStr(n) {
phrebejk@460
  4123
    while (spaceStrs.length <= n)
phrebejk@460
  4124
      spaceStrs.push(lst(spaceStrs) + " ");
phrebejk@460
  4125
    return spaceStrs[n];
phrebejk@460
  4126
  }
phrebejk@460
  4127
phrebejk@460
  4128
  function lst(arr) { return arr[arr.length-1]; }
phrebejk@460
  4129
phrebejk@460
  4130
  function selectInput(node) {
phrebejk@460
  4131
    if (ios) { // Mobile Safari apparently has a bug where select() is broken.
phrebejk@460
  4132
      node.selectionStart = 0;
phrebejk@460
  4133
      node.selectionEnd = node.value.length;
phrebejk@460
  4134
    } else node.select();
phrebejk@460
  4135
  }
phrebejk@460
  4136
phrebejk@460
  4137
  function indexOf(collection, elt) {
phrebejk@460
  4138
    if (collection.indexOf) return collection.indexOf(elt);
phrebejk@460
  4139
    for (var i = 0, e = collection.length; i < e; ++i)
phrebejk@460
  4140
      if (collection[i] == elt) return i;
phrebejk@460
  4141
    return -1;
phrebejk@460
  4142
  }
phrebejk@460
  4143
phrebejk@460
  4144
  function emptyArray(size) {
phrebejk@460
  4145
    for (var a = [], i = 0; i < size; ++i) a.push(undefined);
phrebejk@460
  4146
    return a;
phrebejk@460
  4147
  }
phrebejk@460
  4148
phrebejk@460
  4149
  function bind(f) {
phrebejk@460
  4150
    var args = Array.prototype.slice.call(arguments, 1);
phrebejk@460
  4151
    return function(){return f.apply(null, args);};
phrebejk@460
  4152
  }
phrebejk@460
  4153
phrebejk@460
  4154
  var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc]/;
phrebejk@460
  4155
  function isWordChar(ch) {
phrebejk@460
  4156
    return /\w/.test(ch) || ch > "\x80" &&
phrebejk@460
  4157
      (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
phrebejk@460
  4158
  }
phrebejk@460
  4159
phrebejk@460
  4160
  function isEmpty(obj) {
phrebejk@460
  4161
    var c = 0;
phrebejk@460
  4162
    for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) ++c;
phrebejk@460
  4163
    return !c;
phrebejk@460
  4164
  }
phrebejk@460
  4165
phrebejk@460
  4166
  var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F]/;
phrebejk@460
  4167
phrebejk@460
  4168
  // DOM UTILITIES
phrebejk@460
  4169
phrebejk@460
  4170
  function elt(tag, content, className, style) {
phrebejk@460
  4171
    var e = document.createElement(tag);
phrebejk@460
  4172
    if (className) e.className = className;
phrebejk@460
  4173
    if (style) e.style.cssText = style;
phrebejk@460
  4174
    if (typeof content == "string") setTextContent(e, content);
phrebejk@460
  4175
    else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
phrebejk@460
  4176
    return e;
phrebejk@460
  4177
  }
phrebejk@460
  4178
phrebejk@460
  4179
  function removeChildren(e) {
phrebejk@460
  4180
    e.innerHTML = "";
phrebejk@460
  4181
    return e;
phrebejk@460
  4182
  }
phrebejk@460
  4183
phrebejk@460
  4184
  function removeChildrenAndAdd(parent, e) {
phrebejk@460
  4185
    return removeChildren(parent).appendChild(e);
phrebejk@460
  4186
  }
phrebejk@460
  4187
phrebejk@460
  4188
  function setTextContent(e, str) {
phrebejk@460
  4189
    if (ie_lt9) {
phrebejk@460
  4190
      e.innerHTML = "";
phrebejk@460
  4191
      e.appendChild(document.createTextNode(str));
phrebejk@460
  4192
    } else e.textContent = str;
phrebejk@460
  4193
  }
phrebejk@460
  4194
phrebejk@460
  4195
  // FEATURE DETECTION
phrebejk@460
  4196
phrebejk@460
  4197
  // Detect drag-and-drop
phrebejk@460
  4198
  var dragAndDrop = function() {
phrebejk@460
  4199
    // There is *some* kind of drag-and-drop support in IE6-8, but I
phrebejk@460
  4200
    // couldn't get it to work yet.
phrebejk@460
  4201
    if (ie_lt9) return false;
phrebejk@460
  4202
    var div = elt('div');
phrebejk@460
  4203
    return "draggable" in div || "dragDrop" in div;
phrebejk@460
  4204
  }();
phrebejk@460
  4205
phrebejk@460
  4206
  // For a reason I have yet to figure out, some browsers disallow
phrebejk@460
  4207
  // word wrapping between certain characters *only* if a new inline
phrebejk@460
  4208
  // element is started between them. This makes it hard to reliably
phrebejk@460
  4209
  // measure the position of things, since that requires inserting an
phrebejk@460
  4210
  // extra span. This terribly fragile set of regexps matches the
phrebejk@460
  4211
  // character combinations that suffer from this phenomenon on the
phrebejk@460
  4212
  // various browsers.
phrebejk@460
  4213
  var spanAffectsWrapping = /^$/; // Won't match any two-character string
phrebejk@460
  4214
  if (gecko) spanAffectsWrapping = /$'/;
phrebejk@460
  4215
  else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/;
phrebejk@460
  4216
  else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/;
phrebejk@460
  4217
phrebejk@460
  4218
  var knownScrollbarWidth;
phrebejk@460
  4219
  function scrollbarWidth(measure) {
phrebejk@460
  4220
    if (knownScrollbarWidth != null) return knownScrollbarWidth;
phrebejk@460
  4221
    var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll");
phrebejk@460
  4222
    removeChildrenAndAdd(measure, test);
phrebejk@460
  4223
    if (test.offsetWidth)
phrebejk@460
  4224
      knownScrollbarWidth = test.offsetHeight - test.clientHeight;
phrebejk@460
  4225
    return knownScrollbarWidth || 0;
phrebejk@460
  4226
  }
phrebejk@460
  4227
phrebejk@460
  4228
  var zwspSupported;
phrebejk@460
  4229
  function zeroWidthElement(measure) {
phrebejk@460
  4230
    if (zwspSupported == null) {
phrebejk@460
  4231
      var test = elt("span", "\u200b");
phrebejk@460
  4232
      removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
phrebejk@460
  4233
      if (measure.firstChild.offsetHeight != 0)
phrebejk@460
  4234
        zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_lt8;
phrebejk@460
  4235
    }
phrebejk@460
  4236
    if (zwspSupported) return elt("span", "\u200b");
phrebejk@460
  4237
    else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
phrebejk@460
  4238
  }
phrebejk@460
  4239
phrebejk@460
  4240
  // See if "".split is the broken IE version, if so, provide an
phrebejk@460
  4241
  // alternative way to split lines.
phrebejk@460
  4242
  var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
phrebejk@460
  4243
    var pos = 0, result = [], l = string.length;
phrebejk@460
  4244
    while (pos <= l) {
phrebejk@460
  4245
      var nl = string.indexOf("\n", pos);
phrebejk@460
  4246
      if (nl == -1) nl = string.length;
phrebejk@460
  4247
      var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
phrebejk@460
  4248
      var rt = line.indexOf("\r");
phrebejk@460
  4249
      if (rt != -1) {
phrebejk@460
  4250
        result.push(line.slice(0, rt));
phrebejk@460
  4251
        pos += rt + 1;
phrebejk@460
  4252
      } else {
phrebejk@460
  4253
        result.push(line);
phrebejk@460
  4254
        pos = nl + 1;
phrebejk@460
  4255
      }
phrebejk@460
  4256
    }
phrebejk@460
  4257
    return result;
phrebejk@460
  4258
  } : function(string){return string.split(/\r\n?|\n/);};
phrebejk@460
  4259
  CodeMirror.splitLines = splitLines;
phrebejk@460
  4260
phrebejk@460
  4261
  var hasSelection = window.getSelection ? function(te) {
phrebejk@460
  4262
    try { return te.selectionStart != te.selectionEnd; }
phrebejk@460
  4263
    catch(e) { return false; }
phrebejk@460
  4264
  } : function(te) {
phrebejk@460
  4265
    try {var range = te.ownerDocument.selection.createRange();}
phrebejk@460
  4266
    catch(e) {}
phrebejk@460
  4267
    if (!range || range.parentElement() != te) return false;
phrebejk@460
  4268
    return range.compareEndPoints("StartToEnd", range) != 0;
phrebejk@460
  4269
  };
phrebejk@460
  4270
phrebejk@460
  4271
  var hasCopyEvent = (function() {
phrebejk@460
  4272
    var e = elt("div");
phrebejk@460
  4273
    if ("oncopy" in e) return true;
phrebejk@460
  4274
    e.setAttribute("oncopy", "return;");
phrebejk@460
  4275
    return typeof e.oncopy == 'function';
phrebejk@460
  4276
  })();
phrebejk@460
  4277
phrebejk@460
  4278
  // KEY NAMING
phrebejk@460
  4279
phrebejk@460
  4280
  var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
phrebejk@460
  4281
                  19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
phrebejk@460
  4282
                  36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
phrebejk@460
  4283
                  46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete",
phrebejk@460
  4284
                  186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
phrebejk@460
  4285
                  221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home",
phrebejk@460
  4286
                  63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"};
phrebejk@460
  4287
  CodeMirror.keyNames = keyNames;
phrebejk@460
  4288
  (function() {
phrebejk@460
  4289
    // Number keys
phrebejk@460
  4290
    for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
phrebejk@460
  4291
    // Alphabetic keys
phrebejk@460
  4292
    for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
phrebejk@460
  4293
    // Function keys
phrebejk@460
  4294
    for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
phrebejk@460
  4295
  })();
phrebejk@460
  4296
phrebejk@460
  4297
  // BIDI HELPERS
phrebejk@460
  4298
phrebejk@460
  4299
  function iterateBidiSections(order, from, to, f) {
phrebejk@460
  4300
    if (!order) return f(from, to, "ltr");
phrebejk@460
  4301
    for (var i = 0; i < order.length; ++i) {
phrebejk@460
  4302
      var part = order[i];
phrebejk@460
  4303
      if (part.from < to && part.to > from)
phrebejk@460
  4304
        f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
phrebejk@460
  4305
    }
phrebejk@460
  4306
  }
phrebejk@460
  4307
phrebejk@460
  4308
  function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
phrebejk@460
  4309
  function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
phrebejk@460
  4310
phrebejk@460
  4311
  function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
phrebejk@460
  4312
  function lineRight(line) {
phrebejk@460
  4313
    var order = getOrder(line);
phrebejk@460
  4314
    if (!order) return line.text.length;
phrebejk@460
  4315
    return bidiRight(lst(order));
phrebejk@460
  4316
  }
phrebejk@460
  4317
phrebejk@460
  4318
  function lineStart(cm, lineN) {
phrebejk@460
  4319
    var line = getLine(cm.view.doc, lineN);
phrebejk@460
  4320
    var visual = visualLine(cm.view.doc, line);
phrebejk@460
  4321
    if (visual != line) lineN = lineNo(visual);
phrebejk@460
  4322
    var order = getOrder(visual);
phrebejk@460
  4323
    var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
phrebejk@460
  4324
    return {line: lineN, ch: ch};
phrebejk@460
  4325
  }
phrebejk@460
  4326
  function lineEnd(cm, lineNo) {
phrebejk@460
  4327
    var merged, line;
phrebejk@460
  4328
    while (merged = collapsedSpanAtEnd(line = getLine(cm.view.doc, lineNo)))
phrebejk@460
  4329
      lineNo = merged.find().to.line;
phrebejk@460
  4330
    var order = getOrder(line);
phrebejk@460
  4331
    var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
phrebejk@460
  4332
    return {line: lineNo, ch: ch};
phrebejk@460
  4333
  }
phrebejk@460
  4334
phrebejk@460
  4335
  // This is somewhat involved. It is needed in order to move
phrebejk@460
  4336
  // 'visually' through bi-directional text -- i.e., pressing left
phrebejk@460
  4337
  // should make the cursor go left, even when in RTL text. The
phrebejk@460
  4338
  // tricky part is the 'jumps', where RTL and LTR text touch each
phrebejk@460
  4339
  // other. This often requires the cursor offset to move more than
phrebejk@460
  4340
  // one unit, in order to visually move one unit.
phrebejk@460
  4341
  function moveVisually(line, start, dir, byUnit) {
phrebejk@460
  4342
    var bidi = getOrder(line);
phrebejk@460
  4343
    if (!bidi) return moveLogically(line, start, dir, byUnit);
phrebejk@460
  4344
    var moveOneUnit = byUnit ? function(pos, dir) {
phrebejk@460
  4345
      do pos += dir;
phrebejk@460
  4346
      while (pos > 0 && isExtendingChar.test(line.text.charAt(pos)));
phrebejk@460
  4347
      return pos;
phrebejk@460
  4348
    } : function(pos, dir) { return pos + dir; };
phrebejk@460
  4349
    var linedir = bidi[0].level;
phrebejk@460
  4350
    for (var i = 0; i < bidi.length; ++i) {
phrebejk@460
  4351
      var part = bidi[i], sticky = part.level % 2 == linedir;
phrebejk@460
  4352
      if ((part.from < start && part.to > start) ||
phrebejk@460
  4353
          (sticky && (part.from == start || part.to == start))) break;
phrebejk@460
  4354
    }
phrebejk@460
  4355
    var target = moveOneUnit(start, part.level % 2 ? -dir : dir);
phrebejk@460
  4356
phrebejk@460
  4357
    while (target != null) {
phrebejk@460
  4358
      if (part.level % 2 == linedir) {
phrebejk@460
  4359
        if (target < part.from || target > part.to) {
phrebejk@460
  4360
          part = bidi[i += dir];
phrebejk@460
  4361
          target = part && (dir > 0 == part.level % 2 ? moveOneUnit(part.to, -1) : moveOneUnit(part.from, 1));
phrebejk@460
  4362
        } else break;
phrebejk@460
  4363
      } else {
phrebejk@460
  4364
        if (target == bidiLeft(part)) {
phrebejk@460
  4365
          part = bidi[--i];
phrebejk@460
  4366
          target = part && bidiRight(part);
phrebejk@460
  4367
        } else if (target == bidiRight(part)) {
phrebejk@460
  4368
          part = bidi[++i];
phrebejk@460
  4369
          target = part && bidiLeft(part);
phrebejk@460
  4370
        } else break;
phrebejk@460
  4371
      }
phrebejk@460
  4372
    }
phrebejk@460
  4373
phrebejk@460
  4374
    return target < 0 || target > line.text.length ? null : target;
phrebejk@460
  4375
  }
phrebejk@460
  4376
phrebejk@460
  4377
  function moveLogically(line, start, dir, byUnit) {
phrebejk@460
  4378
    var target = start + dir;
phrebejk@460
  4379
    if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir;
phrebejk@460
  4380
    return target < 0 || target > line.text.length ? null : target;
phrebejk@460
  4381
  }
phrebejk@460
  4382
phrebejk@460
  4383
  // Bidirectional ordering algorithm
phrebejk@460
  4384
  // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
phrebejk@460
  4385
  // that this (partially) implements.
phrebejk@460
  4386
phrebejk@460
  4387
  // One-char codes used for character types:
phrebejk@460
  4388
  // L (L):   Left-to-Right
phrebejk@460
  4389
  // R (R):   Right-to-Left
phrebejk@460
  4390
  // r (AL):  Right-to-Left Arabic
phrebejk@460
  4391
  // 1 (EN):  European Number
phrebejk@460
  4392
  // + (ES):  European Number Separator
phrebejk@460
  4393
  // % (ET):  European Number Terminator
phrebejk@460
  4394
  // n (AN):  Arabic Number
phrebejk@460
  4395
  // , (CS):  Common Number Separator
phrebejk@460
  4396
  // m (NSM): Non-Spacing Mark
phrebejk@460
  4397
  // b (BN):  Boundary Neutral
phrebejk@460
  4398
  // s (B):   Paragraph Separator
phrebejk@460
  4399
  // t (S):   Segment Separator
phrebejk@460
  4400
  // w (WS):  Whitespace
phrebejk@460
  4401
  // N (ON):  Other Neutrals
phrebejk@460
  4402
phrebejk@460
  4403
  // Returns null if characters are ordered as they appear
phrebejk@460
  4404
  // (left-to-right), or an array of sections ({from, to, level}
phrebejk@460
  4405
  // objects) in the order in which they occur visually.
phrebejk@460
  4406
  var bidiOrdering = (function() {
phrebejk@460
  4407
    // Character types for codepoints 0 to 0xff
phrebejk@460
  4408
    var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL";
phrebejk@460
  4409
    // Character types for codepoints 0x600 to 0x6ff
phrebejk@460
  4410
    var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr";
phrebejk@460
  4411
    function charType(code) {
phrebejk@460
  4412
      if (code <= 0xff) return lowTypes.charAt(code);
phrebejk@460
  4413
      else if (0x590 <= code && code <= 0x5f4) return "R";
phrebejk@460
  4414
      else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600);
phrebejk@460
  4415
      else if (0x700 <= code && code <= 0x8ac) return "r";
phrebejk@460
  4416
      else return "L";
phrebejk@460
  4417
    }
phrebejk@460
  4418
phrebejk@460
  4419
    var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
phrebejk@460
  4420
    var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
phrebejk@460
  4421
phrebejk@460
  4422
    return function charOrdering(str) {
phrebejk@460
  4423
      if (!bidiRE.test(str)) return false;
phrebejk@460
  4424
      var len = str.length, types = [], startType = null;
phrebejk@460
  4425
      for (var i = 0, type; i < len; ++i) {
phrebejk@460
  4426
        types.push(type = charType(str.charCodeAt(i)));
phrebejk@460
  4427
        if (startType == null) {
phrebejk@460
  4428
          if (type == "L") startType = "L";
phrebejk@460
  4429
          else if (type == "R" || type == "r") startType = "R";
phrebejk@460
  4430
        }
phrebejk@460
  4431
      }
phrebejk@460
  4432
      if (startType == null) startType = "L";
phrebejk@460
  4433
phrebejk@460
  4434
      // W1. Examine each non-spacing mark (NSM) in the level run, and
phrebejk@460
  4435
      // change the type of the NSM to the type of the previous
phrebejk@460
  4436
      // character. If the NSM is at the start of the level run, it will
phrebejk@460
  4437
      // get the type of sor.
phrebejk@460
  4438
      for (var i = 0, prev = startType; i < len; ++i) {
phrebejk@460
  4439
        var type = types[i];
phrebejk@460
  4440
        if (type == "m") types[i] = prev;
phrebejk@460
  4441
        else prev = type;
phrebejk@460
  4442
      }
phrebejk@460
  4443
phrebejk@460
  4444
      // W2. Search backwards from each instance of a European number
phrebejk@460
  4445
      // until the first strong type (R, L, AL, or sor) is found. If an
phrebejk@460
  4446
      // AL is found, change the type of the European number to Arabic
phrebejk@460
  4447
      // number.
phrebejk@460
  4448
      // W3. Change all ALs to R.
phrebejk@460
  4449
      for (var i = 0, cur = startType; i < len; ++i) {
phrebejk@460
  4450
        var type = types[i];
phrebejk@460
  4451
        if (type == "1" && cur == "r") types[i] = "n";
phrebejk@460
  4452
        else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
phrebejk@460
  4453
      }
phrebejk@460
  4454
phrebejk@460
  4455
      // W4. A single European separator between two European numbers
phrebejk@460
  4456
      // changes to a European number. A single common separator between
phrebejk@460
  4457
      // two numbers of the same type changes to that type.
phrebejk@460
  4458
      for (var i = 1, prev = types[0]; i < len - 1; ++i) {
phrebejk@460
  4459
        var type = types[i];
phrebejk@460
  4460
        if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
phrebejk@460
  4461
        else if (type == "," && prev == types[i+1] &&
phrebejk@460
  4462
                 (prev == "1" || prev == "n")) types[i] = prev;
phrebejk@460
  4463
        prev = type;
phrebejk@460
  4464
      }
phrebejk@460
  4465
phrebejk@460
  4466
      // W5. A sequence of European terminators adjacent to European
phrebejk@460
  4467
      // numbers changes to all European numbers.
phrebejk@460
  4468
      // W6. Otherwise, separators and terminators change to Other
phrebejk@460
  4469
      // Neutral.
phrebejk@460
  4470
      for (var i = 0; i < len; ++i) {
phrebejk@460
  4471
        var type = types[i];
phrebejk@460
  4472
        if (type == ",") types[i] = "N";
phrebejk@460
  4473
        else if (type == "%") {
phrebejk@460
  4474
          for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
phrebejk@460
  4475
          var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N";
phrebejk@460
  4476
          for (var j = i; j < end; ++j) types[j] = replace;
phrebejk@460
  4477
          i = end - 1;
phrebejk@460
  4478
        }
phrebejk@460
  4479
      }
phrebejk@460
  4480
phrebejk@460
  4481
      // W7. Search backwards from each instance of a European number
phrebejk@460
  4482
      // until the first strong type (R, L, or sor) is found. If an L is
phrebejk@460
  4483
      // found, then change the type of the European number to L.
phrebejk@460
  4484
      for (var i = 0, cur = startType; i < len; ++i) {
phrebejk@460
  4485
        var type = types[i];
phrebejk@460
  4486
        if (cur == "L" && type == "1") types[i] = "L";
phrebejk@460
  4487
        else if (isStrong.test(type)) cur = type;
phrebejk@460
  4488
      }
phrebejk@460
  4489
phrebejk@460
  4490
      // N1. A sequence of neutrals takes the direction of the
phrebejk@460
  4491
      // surrounding strong text if the text on both sides has the same
phrebejk@460
  4492
      // direction. European and Arabic numbers act as if they were R in
phrebejk@460
  4493
      // terms of their influence on neutrals. Start-of-level-run (sor)
phrebejk@460
  4494
      // and end-of-level-run (eor) are used at level run boundaries.
phrebejk@460
  4495
      // N2. Any remaining neutrals take the embedding direction.
phrebejk@460
  4496
      for (var i = 0; i < len; ++i) {
phrebejk@460
  4497
        if (isNeutral.test(types[i])) {
phrebejk@460
  4498
          for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
phrebejk@460
  4499
          var before = (i ? types[i-1] : startType) == "L";
phrebejk@460
  4500
          var after = (end < len - 1 ? types[end] : startType) == "L";
phrebejk@460
  4501
          var replace = before || after ? "L" : "R";
phrebejk@460
  4502
          for (var j = i; j < end; ++j) types[j] = replace;
phrebejk@460
  4503
          i = end - 1;
phrebejk@460
  4504
        }
phrebejk@460
  4505
      }
phrebejk@460
  4506
phrebejk@460
  4507
      // Here we depart from the documented algorithm, in order to avoid
phrebejk@460
  4508
      // building up an actual levels array. Since there are only three
phrebejk@460
  4509
      // levels (0, 1, 2) in an implementation that doesn't take
phrebejk@460
  4510
      // explicit embedding into account, we can build up the order on
phrebejk@460
  4511
      // the fly, without following the level-based algorithm.
phrebejk@460
  4512
      var order = [], m;
phrebejk@460
  4513
      for (var i = 0; i < len;) {
phrebejk@460
  4514
        if (countsAsLeft.test(types[i])) {
phrebejk@460
  4515
          var start = i;
phrebejk@460
  4516
          for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
phrebejk@460
  4517
          order.push({from: start, to: i, level: 0});
phrebejk@460
  4518
        } else {
phrebejk@460
  4519
          var pos = i, at = order.length;
phrebejk@460
  4520
          for (++i; i < len && types[i] != "L"; ++i) {}
phrebejk@460
  4521
          for (var j = pos; j < i;) {
phrebejk@460
  4522
            if (countsAsNum.test(types[j])) {
phrebejk@460
  4523
              if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1});
phrebejk@460
  4524
              var nstart = j;
phrebejk@460
  4525
              for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
phrebejk@460
  4526
              order.splice(at, 0, {from: nstart, to: j, level: 2});
phrebejk@460
  4527
              pos = j;
phrebejk@460
  4528
            } else ++j;
phrebejk@460
  4529
          }
phrebejk@460
  4530
          if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1});
phrebejk@460
  4531
        }
phrebejk@460
  4532
      }
phrebejk@460
  4533
      if (order[0].level == 1 && (m = str.match(/^\s+/))) {
phrebejk@460
  4534
        order[0].from = m[0].length;
phrebejk@460
  4535
        order.unshift({from: 0, to: m[0].length, level: 0});
phrebejk@460
  4536
      }
phrebejk@460
  4537
      if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
phrebejk@460
  4538
        lst(order).to -= m[0].length;
phrebejk@460
  4539
        order.push({from: len - m[0].length, to: len, level: 0});
phrebejk@460
  4540
      }
phrebejk@460
  4541
      if (order[0].level != lst(order).level)
phrebejk@460
  4542
        order.push({from: len, to: len, level: order[0].level});
phrebejk@460
  4543
phrebejk@460
  4544
      return order;
phrebejk@460
  4545
    };
phrebejk@460
  4546
  })();
phrebejk@460
  4547
phrebejk@460
  4548
  // THE END
phrebejk@460
  4549
phrebejk@460
  4550
  CodeMirror.version = "3.0";
phrebejk@460
  4551
phrebejk@460
  4552
  return CodeMirror;
phrebejk@460
  4553
})();