1// CodeMirror, copyright (c) by Marijn Haverbeke and others
2// Distributed under an MIT license: http://codemirror.net/LICENSE
3
4// This is CodeMirror (http://codemirror.net), a code editor
5// implemented in JavaScript on top of the browser's DOM.
6//
7// You can find some technical background for some of the code below
8// at http://marijnhaverbeke.nl/blog/#cm-internals .
9
10(function(mod) {
11  if (typeof exports == "object" && typeof module == "object") // CommonJS
12    module.exports = mod();
13  else if (typeof define == "function" && define.amd) // AMD
14    return define([], mod);
15  else // Plain browser env
16    this.CodeMirror = mod();
17})(function() {
18  "use strict";
19
20  // BROWSER SNIFFING
21
22  // Kludges for bugs and behavior differences that can't be feature
23  // detected are enabled based on userAgent etc sniffing.
24
25  var gecko = /gecko\/\d/i.test(navigator.userAgent);
26  // ie_uptoN means Internet Explorer version N or lower
27  var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
28  var ie_upto7 = ie_upto10 && (document.documentMode == null || document.documentMode < 8);
29  var ie_upto8 = ie_upto10 && (document.documentMode == null || document.documentMode < 9);
30  var ie_upto9 = ie_upto10 && (document.documentMode == null || document.documentMode < 10);
31  var ie_11up = /Trident\/([7-9]|\d{2,})\./.test(navigator.userAgent);
32  var ie = ie_upto10 || ie_11up;
33  var webkit = /WebKit\//.test(navigator.userAgent);
34  var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
35  var chrome = /Chrome\//.test(navigator.userAgent);
36  var presto = /Opera\//.test(navigator.userAgent);
37  var safari = /Apple Computer/.test(navigator.vendor);
38  var khtml = /KHTML\//.test(navigator.userAgent);
39  var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
40  var phantom = /PhantomJS/.test(navigator.userAgent);
41
42  var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
43  // This is woefully incomplete. Suggestions for alternative methods welcome.
44  var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
45  var mac = ios || /Mac/.test(navigator.platform);
46  var windows = /win/i.test(navigator.platform);
47
48  var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
49  if (presto_version) presto_version = Number(presto_version[1]);
50  if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
51  // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
52  var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
53  var captureRightClick = gecko || (ie && !ie_upto8);
54
55  // Optimize some code when these features are not used.
56  var sawReadOnlySpans = false, sawCollapsedSpans = false;
57
58  // EDITOR CONSTRUCTOR
59
60  // A CodeMirror instance represents an editor. This is the object
61  // that user code is usually dealing with.
62
63  function CodeMirror(place, options) {
64    if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
65
66    this.options = options = options || {};
67    // Determine effective options based on given values and defaults.
68    copyObj(defaults, options, false);
69    setGuttersForLineNumbers(options);
70
71    var doc = options.value;
72    if (typeof doc == "string") doc = new Doc(doc, options.mode);
73    this.doc = doc;
74
75    var display = this.display = new Display(place, doc);
76    display.wrapper.CodeMirror = this;
77    updateGutters(this);
78    themeChanged(this);
79    if (options.lineWrapping)
80      this.display.wrapper.className += " CodeMirror-wrap";
81    if (options.autofocus && !mobile) focusInput(this);
82
83    this.state = {
84      keyMaps: [],  // stores maps added by addKeyMap
85      overlays: [], // highlighting overlays, as added by addOverlay
86      modeGen: 0,   // bumped when mode/overlay changes, used to invalidate highlighting info
87      overwrite: false, focused: false,
88      suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
89      pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in readInput
90      draggingText: false,
91      highlight: new Delayed() // stores highlight worker timeout
92    };
93
94    // Override magic textarea content restore that IE sometimes does
95    // on our hidden textarea on reload
96    if (ie_upto10) setTimeout(bind(resetInput, this, true), 20);
97
98    registerEventHandlers(this);
99    ensureGlobalHandlers();
100
101    var cm = this;
102    runInOp(this, function() {
103      cm.curOp.forceUpdate = true;
104      attachDoc(cm, doc);
105
106      if ((options.autofocus && !mobile) || activeElt() == display.input)
107        setTimeout(bind(onFocus, cm), 20);
108      else
109        onBlur(cm);
110
111      for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
112        optionHandlers[opt](cm, options[opt], Init);
113      for (var i = 0; i < initHooks.length; ++i) initHooks[i](cm);
114    });
115  }
116
117  // DISPLAY CONSTRUCTOR
118
119  // The display handles the DOM integration, both for input reading
120  // and content drawing. It holds references to DOM nodes and
121  // display-related state.
122
123  function Display(place, doc) {
124    var d = this;
125
126    // The semihidden textarea that is focused when the editor is
127    // focused, and receives input.
128    var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
129    // The textarea is kept positioned near the cursor to prevent the
130    // fact that it'll be scrolled into view on input from scrolling
131    // our fake cursor out of view. On webkit, when wrap=off, paste is
132    // very slow. So make the area wide instead.
133    if (webkit) input.style.width = "1000px";
134    else input.setAttribute("wrap", "off");
135    // If border: 0; -- iOS fails to open keyboard (issue #1287)
136    if (ios) input.style.border = "1px solid black";
137    input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false");
138
139    // Wraps and hides input textarea
140    d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
141    // The fake scrollbar elements.
142    d.scrollbarH = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
143    d.scrollbarV = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
144    // Covers bottom-right square when both scrollbars are present.
145    d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
146    // Covers bottom of gutter when coverGutterNextToScrollbar is on
147    // and h scrollbar is present.
148    d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
149    // Will contain the actual code, positioned to cover the viewport.
150    d.lineDiv = elt("div", null, "CodeMirror-code");
151    // Elements are added to these to represent selection and cursors.
152    d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
153    d.cursorDiv = elt("div", null, "CodeMirror-cursors");
154    // A visibility: hidden element used to find the size of things.
155    d.measure = elt("div", null, "CodeMirror-measure");
156    // When lines outside of the viewport are measured, they are drawn in this.
157    d.lineMeasure = elt("div", null, "CodeMirror-measure");
158    // Wraps everything that needs to exist inside the vertically-padded coordinate system
159    d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
160                      null, "position: relative; outline: none");
161    // Moved around its parent to cover visible view.
162    d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
163    // Set to the height of the document, allowing scrolling.
164    d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
165    // Behavior of elts with overflow: auto and padding is
166    // inconsistent across browsers. This is used to ensure the
167    // scrollable area is big enough.
168    d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;");
169    // Will contain the gutters, if any.
170    d.gutters = elt("div", null, "CodeMirror-gutters");
171    d.lineGutter = null;
172    // Actual scrollable element.
173    d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
174    d.scroller.setAttribute("tabIndex", "-1");
175    // The element in which the editor lives.
176    d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV,
177                            d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
178
179    // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
180    if (ie_upto7) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
181    // Needed to hide big blue blinking cursor on Mobile Safari
182    if (ios) input.style.width = "0px";
183    if (!webkit) d.scroller.draggable = true;
184    // Needed to handle Tab key in KHTML
185    if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
186    // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
187    if (ie_upto7) d.scrollbarH.style.minHeight = d.scrollbarV.style.minWidth = "18px";
188
189    if (place.appendChild) place.appendChild(d.wrapper);
190    else place(d.wrapper);
191
192    // Current rendered range (may be bigger than the view window).
193    d.viewFrom = d.viewTo = doc.first;
194    // Information about the rendered lines.
195    d.view = [];
196    // Holds info about a single rendered line when it was rendered
197    // for measurement, while not in view.
198    d.externalMeasured = null;
199    // Empty space (in pixels) above the view
200    d.viewOffset = 0;
201    d.lastSizeC = 0;
202    d.updateLineNumbers = null;
203
204    // Used to only resize the line number gutter when necessary (when
205    // the amount of lines crosses a boundary that makes its width change)
206    d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
207    // See readInput and resetInput
208    d.prevInput = "";
209    // Set to true when a non-horizontal-scrolling line widget is
210    // added. As an optimization, line widget aligning is skipped when
211    // this is false.
212    d.alignWidgets = false;
213    // Flag that indicates whether we expect input to appear real soon
214    // now (after some event like 'keypress' or 'input') and are
215    // polling intensively.
216    d.pollingFast = false;
217    // Self-resetting timeout for the poller
218    d.poll = new Delayed();
219
220    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
221
222    // Tracks when resetInput has punted to just putting a short
223    // string into the textarea instead of the full selection.
224    d.inaccurateSelection = false;
225
226    // Tracks the maximum line length so that the horizontal scrollbar
227    // can be kept static when scrolling.
228    d.maxLine = null;
229    d.maxLineLength = 0;
230    d.maxLineChanged = false;
231
232    // Used for measuring wheel scrolling granularity
233    d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
234
235    // True when shift is held down.
236    d.shift = false;
237
238    // Used to track whether anything happened since the context menu
239    // was opened.
240    d.selForContextMenu = null;
241  }
242
243  // STATE UPDATES
244
245  // Used to get the editor into a consistent state again when options change.
246
247  function loadMode(cm) {
248    cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
249    resetModeState(cm);
250  }
251
252  function resetModeState(cm) {
253    cm.doc.iter(function(line) {
254      if (line.stateAfter) line.stateAfter = null;
255      if (line.styles) line.styles = null;
256    });
257    cm.doc.frontier = cm.doc.first;
258    startWorker(cm, 100);
259    cm.state.modeGen++;
260    if (cm.curOp) regChange(cm);
261  }
262
263  function wrappingChanged(cm) {
264    if (cm.options.lineWrapping) {
265      addClass(cm.display.wrapper, "CodeMirror-wrap");
266      cm.display.sizer.style.minWidth = "";
267    } else {
268      rmClass(cm.display.wrapper, "CodeMirror-wrap");
269      findMaxLine(cm);
270    }
271    estimateLineHeights(cm);
272    regChange(cm);
273    clearCaches(cm);
274    setTimeout(function(){updateScrollbars(cm);}, 100);
275  }
276
277  // Returns a function that estimates the height of a line, to use as
278  // first approximation until the line becomes visible (and is thus
279  // properly measurable).
280  function estimateHeight(cm) {
281    var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
282    var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
283    return function(line) {
284      if (lineIsHidden(cm.doc, line)) return 0;
285
286      var widgetsHeight = 0;
287      if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
288        if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
289      }
290
291      if (wrapping)
292        return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
293      else
294        return widgetsHeight + th;
295    };
296  }
297
298  function estimateLineHeights(cm) {
299    var doc = cm.doc, est = estimateHeight(cm);
300    doc.iter(function(line) {
301      var estHeight = est(line);
302      if (estHeight != line.height) updateLineHeight(line, estHeight);
303    });
304  }
305
306  function keyMapChanged(cm) {
307    var map = keyMap[cm.options.keyMap], style = map.style;
308    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
309      (style ? " cm-keymap-" + style : "");
310  }
311
312  function themeChanged(cm) {
313    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
314      cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
315    clearCaches(cm);
316  }
317
318  function guttersChanged(cm) {
319    updateGutters(cm);
320    regChange(cm);
321    setTimeout(function(){alignHorizontally(cm);}, 20);
322  }
323
324  // Rebuild the gutter elements, ensure the margin to the left of the
325  // code matches their width.
326  function updateGutters(cm) {
327    var gutters = cm.display.gutters, specs = cm.options.gutters;
328    removeChildren(gutters);
329    for (var i = 0; i < specs.length; ++i) {
330      var gutterClass = specs[i];
331      var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
332      if (gutterClass == "CodeMirror-linenumbers") {
333        cm.display.lineGutter = gElt;
334        gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
335      }
336    }
337    gutters.style.display = i ? "" : "none";
338    updateGutterSpace(cm);
339  }
340
341  function updateGutterSpace(cm) {
342    var width = cm.display.gutters.offsetWidth;
343    cm.display.sizer.style.marginLeft = width + "px";
344    cm.display.scrollbarH.style.left = cm.options.fixedGutter ? width + "px" : 0;
345  }
346
347  // Compute the character length of a line, taking into account
348  // collapsed ranges (see markText) that might hide parts, and join
349  // other lines onto it.
350  function lineLength(line) {
351    if (line.height == 0) return 0;
352    var len = line.text.length, merged, cur = line;
353    while (merged = collapsedSpanAtStart(cur)) {
354      var found = merged.find(0, true);
355      cur = found.from.line;
356      len += found.from.ch - found.to.ch;
357    }
358    cur = line;
359    while (merged = collapsedSpanAtEnd(cur)) {
360      var found = merged.find(0, true);
361      len -= cur.text.length - found.from.ch;
362      cur = found.to.line;
363      len += cur.text.length - found.to.ch;
364    }
365    return len;
366  }
367
368  // Find the longest line in the document.
369  function findMaxLine(cm) {
370    var d = cm.display, doc = cm.doc;
371    d.maxLine = getLine(doc, doc.first);
372    d.maxLineLength = lineLength(d.maxLine);
373    d.maxLineChanged = true;
374    doc.iter(function(line) {
375      var len = lineLength(line);
376      if (len > d.maxLineLength) {
377        d.maxLineLength = len;
378        d.maxLine = line;
379      }
380    });
381  }
382
383  // Make sure the gutters options contains the element
384  // "CodeMirror-linenumbers" when the lineNumbers option is true.
385  function setGuttersForLineNumbers(options) {
386    var found = indexOf(options.gutters, "CodeMirror-linenumbers");
387    if (found == -1 && options.lineNumbers) {
388      options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
389    } else if (found > -1 && !options.lineNumbers) {
390      options.gutters = options.gutters.slice(0);
391      options.gutters.splice(found, 1);
392    }
393  }
394
395  // SCROLLBARS
396
397  // Prepare DOM reads needed to update the scrollbars. Done in one
398  // shot to minimize update/measure roundtrips.
399  function measureForScrollbars(cm) {
400    var scroll = cm.display.scroller;
401    return {
402      clientHeight: scroll.clientHeight,
403      barHeight: cm.display.scrollbarV.clientHeight,
404      scrollWidth: scroll.scrollWidth, clientWidth: scroll.clientWidth,
405      barWidth: cm.display.scrollbarH.clientWidth,
406      docHeight: Math.round(cm.doc.height + paddingVert(cm.display))
407    };
408  }
409
410  // Re-synchronize the fake scrollbars with the actual size of the
411  // content.
412  function updateScrollbars(cm, measure) {
413    if (!measure) measure = measureForScrollbars(cm);
414    var d = cm.display;
415    var scrollHeight = measure.docHeight + scrollerCutOff;
416    var needsH = measure.scrollWidth > measure.clientWidth;
417    var needsV = scrollHeight > measure.clientHeight;
418    if (needsV) {
419      d.scrollbarV.style.display = "block";
420      d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
421      // A bug in IE8 can cause this value to be negative, so guard it.
422      d.scrollbarV.firstChild.style.height =
423        Math.max(0, scrollHeight - measure.clientHeight + (measure.barHeight || d.scrollbarV.clientHeight)) + "px";
424    } else {
425      d.scrollbarV.style.display = "";
426      d.scrollbarV.firstChild.style.height = "0";
427    }
428    if (needsH) {
429      d.scrollbarH.style.display = "block";
430      d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
431      d.scrollbarH.firstChild.style.width =
432        (measure.scrollWidth - measure.clientWidth + (measure.barWidth || d.scrollbarH.clientWidth)) + "px";
433    } else {
434      d.scrollbarH.style.display = "";
435      d.scrollbarH.firstChild.style.width = "0";
436    }
437    if (needsH && needsV) {
438      d.scrollbarFiller.style.display = "block";
439      d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
440    } else d.scrollbarFiller.style.display = "";
441    if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
442      d.gutterFiller.style.display = "block";
443      d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px";
444      d.gutterFiller.style.width = d.gutters.offsetWidth + "px";
445    } else d.gutterFiller.style.display = "";
446
447    if (!cm.state.checkedOverlayScrollbar && measure.clientHeight > 0) {
448      if (scrollbarWidth(d.measure) === 0) {
449        var w = mac && !mac_geMountainLion ? "12px" : "18px";
450        d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = w;
451        var barMouseDown = function(e) {
452          if (e_target(e) != d.scrollbarV && e_target(e) != d.scrollbarH)
453            operation(cm, onMouseDown)(e);
454        };
455        on(d.scrollbarV, "mousedown", barMouseDown);
456        on(d.scrollbarH, "mousedown", barMouseDown);
457      }
458      cm.state.checkedOverlayScrollbar = true;
459    }
460  }
461
462  // Compute the lines that are visible in a given viewport (defaults
463  // the the current scroll position). viewPort may contain top,
464  // height, and ensure (see op.scrollToPos) properties.
465  function visibleLines(display, doc, viewPort) {
466    var top = viewPort && viewPort.top != null ? Math.max(0, viewPort.top) : display.scroller.scrollTop;
467    top = Math.floor(top - paddingTop(display));
468    var bottom = viewPort && viewPort.bottom != null ? viewPort.bottom : top + display.wrapper.clientHeight;
469
470    var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
471    // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
472    // forces those lines into the viewport (if possible).
473    if (viewPort && viewPort.ensure) {
474      var ensureFrom = viewPort.ensure.from.line, ensureTo = viewPort.ensure.to.line;
475      if (ensureFrom < from)
476        return {from: ensureFrom,
477                to: lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)};
478      if (Math.min(ensureTo, doc.lastLine()) >= to)
479        return {from: lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight),
480                to: ensureTo};
481    }
482    return {from: from, to: Math.max(to, from + 1)};
483  }
484
485  // LINE NUMBERS
486
487  // Re-align line numbers and gutter marks to compensate for
488  // horizontal scrolling.
489  function alignHorizontally(cm) {
490    var display = cm.display, view = display.view;
491    if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
492    var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
493    var gutterW = display.gutters.offsetWidth, left = comp + "px";
494    for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
495      if (cm.options.fixedGutter && view[i].gutter)
496        view[i].gutter.style.left = left;
497      var align = view[i].alignable;
498      if (align) for (var j = 0; j < align.length; j++)
499        align[j].style.left = left;
500    }
501    if (cm.options.fixedGutter)
502      display.gutters.style.left = (comp + gutterW) + "px";
503  }
504
505  // Used to ensure that the line number gutter is still the right
506  // size for the current document size. Returns true when an update
507  // is needed.
508  function maybeUpdateLineNumberWidth(cm) {
509    if (!cm.options.lineNumbers) return false;
510    var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
511    if (last.length != display.lineNumChars) {
512      var test = display.measure.appendChild(elt("div", [elt("div", last)],
513                                                 "CodeMirror-linenumber CodeMirror-gutter-elt"));
514      var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
515      display.lineGutter.style.width = "";
516      display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
517      display.lineNumWidth = display.lineNumInnerWidth + padding;
518      display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
519      display.lineGutter.style.width = display.lineNumWidth + "px";
520      updateGutterSpace(cm);
521      return true;
522    }
523    return false;
524  }
525
526  function lineNumberFor(options, i) {
527    return String(options.lineNumberFormatter(i + options.firstLineNumber));
528  }
529
530  // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
531  // but using getBoundingClientRect to get a sub-pixel-accurate
532  // result.
533  function compensateForHScroll(display) {
534    return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
535  }
536
537  // DISPLAY DRAWING
538
539  // Updates the display, selection, and scrollbars, using the
540  // information in display.view to find out which nodes are no longer
541  // up-to-date. Tries to bail out early when no changes are needed,
542  // unless forced is true.
543  // Returns true if an actual update happened, false otherwise.
544  function updateDisplay(cm, viewPort, forced) {
545    var oldFrom = cm.display.viewFrom, oldTo = cm.display.viewTo, updated;
546    var visible = visibleLines(cm.display, cm.doc, viewPort);
547    for (var first = true;; first = false) {
548      var oldWidth = cm.display.scroller.clientWidth;
549      if (!updateDisplayInner(cm, visible, forced)) break;
550      updated = true;
551
552      // If the max line changed since it was last measured, measure it,
553      // and ensure the document's width matches it.
554      if (cm.display.maxLineChanged && !cm.options.lineWrapping)
555        adjustContentWidth(cm);
556
557      var barMeasure = measureForScrollbars(cm);
558      updateSelection(cm);
559      setDocumentHeight(cm, barMeasure);
560      updateScrollbars(cm, barMeasure);
561      if (webkit && cm.options.lineWrapping)
562        checkForWebkitWidthBug(cm, barMeasure); // (Issue #2420)
563      if (first && cm.options.lineWrapping && oldWidth != cm.display.scroller.clientWidth) {
564        forced = true;
565        continue;
566      }
567      forced = false;
568
569      // Clip forced viewport to actual scrollable area.
570      if (viewPort && viewPort.top != null)
571        viewPort = {top: Math.min(barMeasure.docHeight - scrollerCutOff - barMeasure.clientHeight, viewPort.top)};
572      // Updated line heights might result in the drawn area not
573      // actually covering the viewport. Keep looping until it does.
574      visible = visibleLines(cm.display, cm.doc, viewPort);
575      if (visible.from >= cm.display.viewFrom && visible.to <= cm.display.viewTo)
576        break;
577    }
578
579    cm.display.updateLineNumbers = null;
580    if (updated) {
581      signalLater(cm, "update", cm);
582      if (cm.display.viewFrom != oldFrom || cm.display.viewTo != oldTo)
583        signalLater(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
584    }
585    return updated;
586  }
587
588  // Does the actual updating of the line display. Bails out
589  // (returning false) when there is nothing to be done and forced is
590  // false.
591  function updateDisplayInner(cm, visible, forced) {
592    var display = cm.display, doc = cm.doc;
593    if (!display.wrapper.offsetWidth) {
594      resetView(cm);
595      return;
596    }
597
598    // Bail out if the visible area is already rendered and nothing changed.
599    if (!forced && visible.from >= display.viewFrom && visible.to <= display.viewTo &&
600        countDirtyView(cm) == 0)
601      return;
602
603    if (maybeUpdateLineNumberWidth(cm))
604      resetView(cm);
605    var dims = getDimensions(cm);
606
607    // Compute a suitable new viewport (from & to)
608    var end = doc.first + doc.size;
609    var from = Math.max(visible.from - cm.options.viewportMargin, doc.first);
610    var to = Math.min(end, visible.to + cm.options.viewportMargin);
611    if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
612    if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
613    if (sawCollapsedSpans) {
614      from = visualLineNo(cm.doc, from);
615      to = visualLineEndNo(cm.doc, to);
616    }
617
618    var different = from != display.viewFrom || to != display.viewTo ||
619      display.lastSizeC != display.wrapper.clientHeight;
620    adjustView(cm, from, to);
621
622    display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
623    // Position the mover div to align with the current scroll position
624    cm.display.mover.style.top = display.viewOffset + "px";
625
626    var toUpdate = countDirtyView(cm);
627    if (!different && toUpdate == 0 && !forced) return;
628
629    // For big changes, we hide the enclosing element during the
630    // update, since that speeds up the operations on most browsers.
631    var focused = activeElt();
632    if (toUpdate > 4) display.lineDiv.style.display = "none";
633    patchDisplay(cm, display.updateLineNumbers, dims);
634    if (toUpdate > 4) display.lineDiv.style.display = "";
635    // There might have been a widget with a focused element that got
636    // hidden or updated, if so re-focus it.
637    if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
638
639    // Prevent selection and cursors from interfering with the scroll
640    // width.
641    removeChildren(display.cursorDiv);
642    removeChildren(display.selectionDiv);
643
644    if (different) {
645      display.lastSizeC = display.wrapper.clientHeight;
646      startWorker(cm, 400);
647    }
648
649    updateHeightsInViewport(cm);
650
651    return true;
652  }
653
654  function adjustContentWidth(cm) {
655    var display = cm.display;
656    var width = measureChar(cm, display.maxLine, display.maxLine.text.length).left;
657    display.maxLineChanged = false;
658    var minWidth = Math.max(0, width + 3);
659    var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + minWidth + scrollerCutOff - display.scroller.clientWidth);
660    display.sizer.style.minWidth = minWidth + "px";
661    if (maxScrollLeft < cm.doc.scrollLeft)
662      setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true);
663  }
664
665  function setDocumentHeight(cm, measure) {
666    cm.display.sizer.style.minHeight = cm.display.heightForcer.style.top = measure.docHeight + "px";
667    cm.display.gutters.style.height = Math.max(measure.docHeight, measure.clientHeight - scrollerCutOff) + "px";
668  }
669
670  function checkForWebkitWidthBug(cm, measure) {
671    // Work around Webkit bug where it sometimes reserves space for a
672    // non-existing phantom scrollbar in the scroller (Issue #2420)
673    if (cm.display.sizer.offsetWidth + cm.display.gutters.offsetWidth < cm.display.scroller.clientWidth - 1) {
674      cm.display.sizer.style.minHeight = cm.display.heightForcer.style.top = "0px";
675      cm.display.gutters.style.height = measure.docHeight + "px";
676    }
677  }
678
679  // Read the actual heights of the rendered lines, and update their
680  // stored heights to match.
681  function updateHeightsInViewport(cm) {
682    var display = cm.display;
683    var prevBottom = display.lineDiv.offsetTop;
684    for (var i = 0; i < display.view.length; i++) {
685      var cur = display.view[i], height;
686      if (cur.hidden) continue;
687      if (ie_upto7) {
688        var bot = cur.node.offsetTop + cur.node.offsetHeight;
689        height = bot - prevBottom;
690        prevBottom = bot;
691      } else {
692        var box = cur.node.getBoundingClientRect();
693        height = box.bottom - box.top;
694      }
695      var diff = cur.line.height - height;
696      if (height < 2) height = textHeight(display);
697      if (diff > .001 || diff < -.001) {
698        updateLineHeight(cur.line, height);
699        updateWidgetHeight(cur.line);
700        if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
701          updateWidgetHeight(cur.rest[j]);
702      }
703    }
704  }
705
706  // Read and store the height of line widgets associated with the
707  // given line.
708  function updateWidgetHeight(line) {
709    if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
710      line.widgets[i].height = line.widgets[i].node.offsetHeight;
711  }
712
713  // Do a bulk-read of the DOM positions and sizes needed to draw the
714  // view, so that we don't interleave reading and writing to the DOM.
715  function getDimensions(cm) {
716    var d = cm.display, left = {}, width = {};
717    for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
718      left[cm.options.gutters[i]] = n.offsetLeft;
719      width[cm.options.gutters[i]] = n.offsetWidth;
720    }
721    return {fixedPos: compensateForHScroll(d),
722            gutterTotalWidth: d.gutters.offsetWidth,
723            gutterLeft: left,
724            gutterWidth: width,
725            wrapperWidth: d.wrapper.clientWidth};
726  }
727
728  // Sync the actual display DOM structure with display.view, removing
729  // nodes for lines that are no longer in view, and creating the ones
730  // that are not there yet, and updating the ones that are out of
731  // date.
732  function patchDisplay(cm, updateNumbersFrom, dims) {
733    var display = cm.display, lineNumbers = cm.options.lineNumbers;
734    var container = display.lineDiv, cur = container.firstChild;
735
736    function rm(node) {
737      var next = node.nextSibling;
738      // Works around a throw-scroll bug in OS X Webkit
739      if (webkit && mac && cm.display.currentWheelTarget == node)
740        node.style.display = "none";
741      else
742        node.parentNode.removeChild(node);
743      return next;
744    }
745
746    var view = display.view, lineN = display.viewFrom;
747    // Loop over the elements in the view, syncing cur (the DOM nodes
748    // in display.lineDiv) with the view as we go.
749    for (var i = 0; i < view.length; i++) {
750      var lineView = view[i];
751      if (lineView.hidden) {
752      } else if (!lineView.node) { // Not drawn yet
753        var node = buildLineElement(cm, lineView, lineN, dims);
754        container.insertBefore(node, cur);
755      } else { // Already drawn
756        while (cur != lineView.node) cur = rm(cur);
757        var updateNumber = lineNumbers && updateNumbersFrom != null &&
758          updateNumbersFrom <= lineN && lineView.lineNumber;
759        if (lineView.changes) {
760          if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
761          updateLineForChanges(cm, lineView, lineN, dims);
762        }
763        if (updateNumber) {
764          removeChildren(lineView.lineNumber);
765          lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
766        }
767        cur = lineView.node.nextSibling;
768      }
769      lineN += lineView.size;
770    }
771    while (cur) cur = rm(cur);
772  }
773
774  // When an aspect of a line changes, a string is added to
775  // lineView.changes. This updates the relevant part of the line's
776  // DOM structure.
777  function updateLineForChanges(cm, lineView, lineN, dims) {
778    for (var j = 0; j < lineView.changes.length; j++) {
779      var type = lineView.changes[j];
780      if (type == "text") updateLineText(cm, lineView);
781      else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
782      else if (type == "class") updateLineClasses(lineView);
783      else if (type == "widget") updateLineWidgets(lineView, dims);
784    }
785    lineView.changes = null;
786  }
787
788  // Lines with gutter elements, widgets or a background class need to
789  // be wrapped, and have the extra elements added to the wrapper div
790  function ensureLineWrapped(lineView) {
791    if (lineView.node == lineView.text) {
792      lineView.node = elt("div", null, null, "position: relative");
793      if (lineView.text.parentNode)
794        lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
795      lineView.node.appendChild(lineView.text);
796      if (ie_upto7) lineView.node.style.zIndex = 2;
797    }
798    return lineView.node;
799  }
800
801  function updateLineBackground(lineView) {
802    var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
803    if (cls) cls += " CodeMirror-linebackground";
804    if (lineView.background) {
805      if (cls) lineView.background.className = cls;
806      else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
807    } else if (cls) {
808      var wrap = ensureLineWrapped(lineView);
809      lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
810    }
811  }
812
813  // Wrapper around buildLineContent which will reuse the structure
814  // in display.externalMeasured when possible.
815  function getLineContent(cm, lineView) {
816    var ext = cm.display.externalMeasured;
817    if (ext && ext.line == lineView.line) {
818      cm.display.externalMeasured = null;
819      lineView.measure = ext.measure;
820      return ext.built;
821    }
822    return buildLineContent(cm, lineView);
823  }
824
825  // Redraw the line's text. Interacts with the background and text
826  // classes because the mode may output tokens that influence these
827  // classes.
828  function updateLineText(cm, lineView) {
829    var cls = lineView.text.className;
830    var built = getLineContent(cm, lineView);
831    if (lineView.text == lineView.node) lineView.node = built.pre;
832    lineView.text.parentNode.replaceChild(built.pre, lineView.text);
833    lineView.text = built.pre;
834    if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
835      lineView.bgClass = built.bgClass;
836      lineView.textClass = built.textClass;
837      updateLineClasses(lineView);
838    } else if (cls) {
839      lineView.text.className = cls;
840    }
841  }
842
843  function updateLineClasses(lineView) {
844    updateLineBackground(lineView);
845    if (lineView.line.wrapClass)
846      ensureLineWrapped(lineView).className = lineView.line.wrapClass;
847    else if (lineView.node != lineView.text)
848      lineView.node.className = "";
849    var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
850    lineView.text.className = textClass || "";
851  }
852
853  function updateLineGutter(cm, lineView, lineN, dims) {
854    if (lineView.gutter) {
855      lineView.node.removeChild(lineView.gutter);
856      lineView.gutter = null;
857    }
858    var markers = lineView.line.gutterMarkers;
859    if (cm.options.lineNumbers || markers) {
860      var wrap = ensureLineWrapped(lineView);
861      var gutterWrap = lineView.gutter =
862        wrap.insertBefore(elt("div", null, "CodeMirror-gutter-wrapper", "position: absolute; left: " +
863                              (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"),
864                          lineView.text);
865      if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
866        lineView.lineNumber = gutterWrap.appendChild(
867          elt("div", lineNumberFor(cm.options, lineN),
868              "CodeMirror-linenumber CodeMirror-gutter-elt",
869              "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
870              + cm.display.lineNumInnerWidth + "px"));
871      if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
872        var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
873        if (found)
874          gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
875                                     dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
876      }
877    }
878  }
879
880  function updateLineWidgets(lineView, dims) {
881    if (lineView.alignable) lineView.alignable = null;
882    for (var node = lineView.node.firstChild, next; node; node = next) {
883      var next = node.nextSibling;
884      if (node.className == "CodeMirror-linewidget")
885        lineView.node.removeChild(node);
886    }
887    insertLineWidgets(lineView, dims);
888  }
889
890  // Build a line's DOM representation from scratch
891  function buildLineElement(cm, lineView, lineN, dims) {
892    var built = getLineContent(cm, lineView);
893    lineView.text = lineView.node = built.pre;
894    if (built.bgClass) lineView.bgClass = built.bgClass;
895    if (built.textClass) lineView.textClass = built.textClass;
896
897    updateLineClasses(lineView);
898    updateLineGutter(cm, lineView, lineN, dims);
899    insertLineWidgets(lineView, dims);
900    return lineView.node;
901  }
902
903  // A lineView may contain multiple logical lines (when merged by
904  // collapsed spans). The widgets for all of them need to be drawn.
905  function insertLineWidgets(lineView, dims) {
906    insertLineWidgetsFor(lineView.line, lineView, dims, true);
907    if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
908      insertLineWidgetsFor(lineView.rest[i], lineView, dims, false);
909  }
910
911  function insertLineWidgetsFor(line, lineView, dims, allowAbove) {
912    if (!line.widgets) return;
913    var wrap = ensureLineWrapped(lineView);
914    for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
915      var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
916      if (!widget.handleMouseEvents) node.ignoreEvents = true;
917      positionLineWidget(widget, node, lineView, dims);
918      if (allowAbove && widget.above)
919        wrap.insertBefore(node, lineView.gutter || lineView.text);
920      else
921        wrap.appendChild(node);
922      signalLater(widget, "redraw");
923    }
924  }
925
926  function positionLineWidget(widget, node, lineView, dims) {
927    if (widget.noHScroll) {
928      (lineView.alignable || (lineView.alignable = [])).push(node);
929      var width = dims.wrapperWidth;
930      node.style.left = dims.fixedPos + "px";
931      if (!widget.coverGutter) {
932        width -= dims.gutterTotalWidth;
933        node.style.paddingLeft = dims.gutterTotalWidth + "px";
934      }
935      node.style.width = width + "px";
936    }
937    if (widget.coverGutter) {
938      node.style.zIndex = 5;
939      node.style.position = "relative";
940      if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
941    }
942  }
943
944  // POSITION OBJECT
945
946  // A Pos instance represents a position within the text.
947  var Pos = CodeMirror.Pos = function(line, ch) {
948    if (!(this instanceof Pos)) return new Pos(line, ch);
949    this.line = line; this.ch = ch;
950  };
951
952  // Compare two positions, return 0 if they are the same, a negative
953  // number when a is less, and a positive number otherwise.
954  var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
955
956  function copyPos(x) {return Pos(x.line, x.ch);}
957  function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
958  function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
959
960  // SELECTION / CURSOR
961
962  // Selection objects are immutable. A new one is created every time
963  // the selection changes. A selection is one or more non-overlapping
964  // (and non-touching) ranges, sorted, and an integer that indicates
965  // which one is the primary selection (the one that's scrolled into
966  // view, that getCursor returns, etc).
967  function Selection(ranges, primIndex) {
968    this.ranges = ranges;
969    this.primIndex = primIndex;
970  }
971
972  Selection.prototype = {
973    primary: function() { return this.ranges[this.primIndex]; },
974    equals: function(other) {
975      if (other == this) return true;
976      if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
977      for (var i = 0; i < this.ranges.length; i++) {
978        var here = this.ranges[i], there = other.ranges[i];
979        if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
980      }
981      return true;
982    },
983    deepCopy: function() {
984      for (var out = [], i = 0; i < this.ranges.length; i++)
985        out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
986      return new Selection(out, this.primIndex);
987    },
988    somethingSelected: function() {
989      for (var i = 0; i < this.ranges.length; i++)
990        if (!this.ranges[i].empty()) return true;
991      return false;
992    },
993    contains: function(pos, end) {
994      if (!end) end = pos;
995      for (var i = 0; i < this.ranges.length; i++) {
996        var range = this.ranges[i];
997        if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
998          return i;
999      }
1000      return -1;
1001    }
1002  };
1003
1004  function Range(anchor, head) {
1005    this.anchor = anchor; this.head = head;
1006  }
1007
1008  Range.prototype = {
1009    from: function() { return minPos(this.anchor, this.head); },
1010    to: function() { return maxPos(this.anchor, this.head); },
1011    empty: function() {
1012      return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
1013    }
1014  };
1015
1016  // Take an unsorted, potentially overlapping set of ranges, and
1017  // build a selection out of it. 'Consumes' ranges array (modifying
1018  // it).
1019  function normalizeSelection(ranges, primIndex) {
1020    var prim = ranges[primIndex];
1021    ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
1022    primIndex = indexOf(ranges, prim);
1023    for (var i = 1; i < ranges.length; i++) {
1024      var cur = ranges[i], prev = ranges[i - 1];
1025      if (cmp(prev.to(), cur.from()) >= 0) {
1026        var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
1027        var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
1028        if (i <= primIndex) --primIndex;
1029        ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
1030      }
1031    }
1032    return new Selection(ranges, primIndex);
1033  }
1034
1035  function simpleSelection(anchor, head) {
1036    return new Selection([new Range(anchor, head || anchor)], 0);
1037  }
1038
1039  // Most of the external API clips given positions to make sure they
1040  // actually exist within the document.
1041  function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
1042  function clipPos(doc, pos) {
1043    if (pos.line < doc.first) return Pos(doc.first, 0);
1044    var last = doc.first + doc.size - 1;
1045    if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
1046    return clipToLen(pos, getLine(doc, pos.line).text.length);
1047  }
1048  function clipToLen(pos, linelen) {
1049    var ch = pos.ch;
1050    if (ch == null || ch > linelen) return Pos(pos.line, linelen);
1051    else if (ch < 0) return Pos(pos.line, 0);
1052    else return pos;
1053  }
1054  function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
1055  function clipPosArray(doc, array) {
1056    for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
1057    return out;
1058  }
1059
1060  // SELECTION UPDATES
1061
1062  // The 'scroll' parameter given to many of these indicated whether
1063  // the new cursor position should be scrolled into view after
1064  // modifying the selection.
1065
1066  // If shift is held or the extend flag is set, extends a range to
1067  // include a given position (and optionally a second position).
1068  // Otherwise, simply returns the range between the given positions.
1069  // Used for cursor motion and such.
1070  function extendRange(doc, range, head, other) {
1071    if (doc.cm && doc.cm.display.shift || doc.extend) {
1072      var anchor = range.anchor;
1073      if (other) {
1074        var posBefore = cmp(head, anchor) < 0;
1075        if (posBefore != (cmp(other, anchor) < 0)) {
1076          anchor = head;
1077          head = other;
1078        } else if (posBefore != (cmp(head, other) < 0)) {
1079          head = other;
1080        }
1081      }
1082      return new Range(anchor, head);
1083    } else {
1084      return new Range(other || head, head);
1085    }
1086  }
1087
1088  // Extend the primary selection range, discard the rest.
1089  function extendSelection(doc, head, other, options) {
1090    setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
1091  }
1092
1093  // Extend all selections (pos is an array of selections with length
1094  // equal the number of selections)
1095  function extendSelections(doc, heads, options) {
1096    for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
1097      out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
1098    var newSel = normalizeSelection(out, doc.sel.primIndex);
1099    setSelection(doc, newSel, options);
1100  }
1101
1102  // Updates a single range in the selection.
1103  function replaceOneSelection(doc, i, range, options) {
1104    var ranges = doc.sel.ranges.slice(0);
1105    ranges[i] = range;
1106    setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
1107  }
1108
1109  // Reset the selection to a single range.
1110  function setSimpleSelection(doc, anchor, head, options) {
1111    setSelection(doc, simpleSelection(anchor, head), options);
1112  }
1113
1114  // Give beforeSelectionChange handlers a change to influence a
1115  // selection update.
1116  function filterSelectionChange(doc, sel) {
1117    var obj = {
1118      ranges: sel.ranges,
1119      update: function(ranges) {
1120        this.ranges = [];
1121        for (var i = 0; i < ranges.length; i++)
1122          this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
1123                                     clipPos(doc, ranges[i].head));
1124      }
1125    };
1126    signal(doc, "beforeSelectionChange", doc, obj);
1127    if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
1128    if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
1129    else return sel;
1130  }
1131
1132  function setSelectionReplaceHistory(doc, sel, options) {
1133    var done = doc.history.done, last = lst(done);
1134    if (last && last.ranges) {
1135      done[done.length - 1] = sel;
1136      setSelectionNoUndo(doc, sel, options);
1137    } else {
1138      setSelection(doc, sel, options);
1139    }
1140  }
1141
1142  // Set a new selection.
1143  function setSelection(doc, sel, options) {
1144    setSelectionNoUndo(doc, sel, options);
1145    addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
1146  }
1147
1148  function setSelectionNoUndo(doc, sel, options) {
1149    if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
1150      sel = filterSelectionChange(doc, sel);
1151
1152    var bias = options && options.bias ||
1153      (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
1154    setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
1155
1156    if (!(options && options.scroll === false) && doc.cm)
1157      ensureCursorVisible(doc.cm);
1158  }
1159
1160  function setSelectionInner(doc, sel) {
1161    if (sel.equals(doc.sel)) return;
1162
1163    doc.sel = sel;
1164
1165    if (doc.cm) {
1166      doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
1167      signalCursorActivity(doc.cm);
1168    }
1169    signalLater(doc, "cursorActivity", doc);
1170  }
1171
1172  // Verify that the selection does not partially select any atomic
1173  // marked ranges.
1174  function reCheckSelection(doc) {
1175    setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
1176  }
1177
1178  // Return a selection that does not partially select any atomic
1179  // ranges.
1180  function skipAtomicInSelection(doc, sel, bias, mayClear) {
1181    var out;
1182    for (var i = 0; i < sel.ranges.length; i++) {
1183      var range = sel.ranges[i];
1184      var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
1185      var newHead = skipAtomic(doc, range.head, bias, mayClear);
1186      if (out || newAnchor != range.anchor || newHead != range.head) {
1187        if (!out) out = sel.ranges.slice(0, i);
1188        out[i] = new Range(newAnchor, newHead);
1189      }
1190    }
1191    return out ? normalizeSelection(out, sel.primIndex) : sel;
1192  }
1193
1194  // Ensure a given position is not inside an atomic range.
1195  function skipAtomic(doc, pos, bias, mayClear) {
1196    var flipped = false, curPos = pos;
1197    var dir = bias || 1;
1198    doc.cantEdit = false;
1199    search: for (;;) {
1200      var line = getLine(doc, curPos.line);
1201      if (line.markedSpans) {
1202        for (var i = 0; i < line.markedSpans.length; ++i) {
1203          var sp = line.markedSpans[i], m = sp.marker;
1204          if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
1205              (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
1206            if (mayClear) {
1207              signal(m, "beforeCursorEnter");
1208              if (m.explicitlyCleared) {
1209                if (!line.markedSpans) break;
1210                else {--i; continue;}
1211              }
1212            }
1213            if (!m.atomic) continue;
1214            var newPos = m.find(dir < 0 ? -1 : 1);
1215            if (cmp(newPos, curPos) == 0) {
1216              newPos.ch += dir;
1217              if (newPos.ch < 0) {
1218                if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
1219                else newPos = null;
1220              } else if (newPos.ch > line.text.length) {
1221                if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
1222                else newPos = null;
1223              }
1224              if (!newPos) {
1225                if (flipped) {
1226                  // Driven in a corner -- no valid cursor position found at all
1227                  // -- try again *with* clearing, if we didn't already
1228                  if (!mayClear) return skipAtomic(doc, pos, bias, true);
1229                  // Otherwise, turn off editing until further notice, and return the start of the doc
1230                  doc.cantEdit = true;
1231                  return Pos(doc.first, 0);
1232                }
1233                flipped = true; newPos = pos; dir = -dir;
1234              }
1235            }
1236            curPos = newPos;
1237            continue search;
1238          }
1239        }
1240      }
1241      return curPos;
1242    }
1243  }
1244
1245  // SELECTION DRAWING
1246
1247  // Redraw the selection and/or cursor
1248  function updateSelection(cm) {
1249    var display = cm.display, doc = cm.doc;
1250    var curFragment = document.createDocumentFragment();
1251    var selFragment = document.createDocumentFragment();
1252
1253    for (var i = 0; i < doc.sel.ranges.length; i++) {
1254      var range = doc.sel.ranges[i];
1255      var collapsed = range.empty();
1256      if (collapsed || cm.options.showCursorWhenSelecting)
1257        drawSelectionCursor(cm, range, curFragment);
1258      if (!collapsed)
1259        drawSelectionRange(cm, range, selFragment);
1260    }
1261
1262    // Move the hidden textarea near the cursor to prevent scrolling artifacts
1263    if (cm.options.moveInputWithCursor) {
1264      var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
1265      var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
1266      var top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
1267                                     headPos.top + lineOff.top - wrapOff.top));
1268      var left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
1269                                      headPos.left + lineOff.left - wrapOff.left));
1270      display.inputDiv.style.top = top + "px";
1271      display.inputDiv.style.left = left + "px";
1272    }
1273
1274    removeChildrenAndAdd(display.cursorDiv, curFragment);
1275    removeChildrenAndAdd(display.selectionDiv, selFragment);
1276  }
1277
1278  // Draws a cursor for the given range
1279  function drawSelectionCursor(cm, range, output) {
1280    var pos = cursorCoords(cm, range.head, "div");
1281
1282    var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
1283    cursor.style.left = pos.left + "px";
1284    cursor.style.top = pos.top + "px";
1285    cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
1286
1287    if (pos.other) {
1288      // Secondary cursor, shown when on a 'jump' in bi-directional text
1289      var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
1290      otherCursor.style.display = "";
1291      otherCursor.style.left = pos.other.left + "px";
1292      otherCursor.style.top = pos.other.top + "px";
1293      otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
1294    }
1295  }
1296
1297  // Draws the given range as a highlighted selection
1298  function drawSelectionRange(cm, range, output) {
1299    var display = cm.display, doc = cm.doc;
1300    var fragment = document.createDocumentFragment();
1301    var padding = paddingH(cm.display), leftSide = padding.left, rightSide = display.lineSpace.offsetWidth - padding.right;
1302
1303    function add(left, top, width, bottom) {
1304      if (top < 0) top = 0;
1305      top = Math.round(top);
1306      bottom = Math.round(bottom);
1307      fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
1308                               "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
1309                               "px; height: " + (bottom - top) + "px"));
1310    }
1311
1312    function drawForLine(line, fromArg, toArg) {
1313      var lineObj = getLine(doc, line);
1314      var lineLen = lineObj.text.length;
1315      var start, end;
1316      function coords(ch, bias) {
1317        return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
1318      }
1319
1320      iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
1321        var leftPos = coords(from, "left"), rightPos, left, right;
1322        if (from == to) {
1323          rightPos = leftPos;
1324          left = right = leftPos.left;
1325        } else {
1326          rightPos = coords(to - 1, "right");
1327          if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
1328          left = leftPos.left;
1329          right = rightPos.right;
1330        }
1331        if (fromArg == null && from == 0) left = leftSide;
1332        if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
1333          add(left, leftPos.top, null, leftPos.bottom);
1334          left = leftSide;
1335          if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
1336        }
1337        if (toArg == null && to == lineLen) right = rightSide;
1338        if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
1339          start = leftPos;
1340        if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
1341          end = rightPos;
1342        if (left < leftSide + 1) left = leftSide;
1343        add(left, rightPos.top, right - left, rightPos.bottom);
1344      });
1345      return {start: start, end: end};
1346    }
1347
1348    var sFrom = range.from(), sTo = range.to();
1349    if (sFrom.line == sTo.line) {
1350      drawForLine(sFrom.line, sFrom.ch, sTo.ch);
1351    } else {
1352      var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
1353      var singleVLine = visualLine(fromLine) == visualLine(toLine);
1354      var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
1355      var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
1356      if (singleVLine) {
1357        if (leftEnd.top < rightStart.top - 2) {
1358          add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
1359          add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
1360        } else {
1361          add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
1362        }
1363      }
1364      if (leftEnd.bottom < rightStart.top)
1365        add(leftSide, leftEnd.bottom, null, rightStart.top);
1366    }
1367
1368    output.appendChild(fragment);
1369  }
1370
1371  // Cursor-blinking
1372  function restartBlink(cm) {
1373    if (!cm.state.focused) return;
1374    var display = cm.display;
1375    clearInterval(display.blinker);
1376    var on = true;
1377    display.cursorDiv.style.visibility = "";
1378    if (cm.options.cursorBlinkRate > 0)
1379      display.blinker = setInterval(function() {
1380        display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
1381      }, cm.options.cursorBlinkRate);
1382  }
1383
1384  // HIGHLIGHT WORKER
1385
1386  function startWorker(cm, time) {
1387    if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
1388      cm.state.highlight.set(time, bind(highlightWorker, cm));
1389  }
1390
1391  function highlightWorker(cm) {
1392    var doc = cm.doc;
1393    if (doc.frontier < doc.first) doc.frontier = doc.first;
1394    if (doc.frontier >= cm.display.viewTo) return;
1395    var end = +new Date + cm.options.workTime;
1396    var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
1397
1398    runInOp(cm, function() {
1399    doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
1400      if (doc.frontier >= cm.display.viewFrom) { // Visible
1401        var oldStyles = line.styles;
1402        var highlighted = highlightLine(cm, line, state, true);
1403        line.styles = highlighted.styles;
1404        if (highlighted.classes) line.styleClasses = highlighted.classes;
1405        else if (line.styleClasses) line.styleClasses = null;
1406        var ischange = !oldStyles || oldStyles.length != line.styles.length;
1407        for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
1408        if (ischange) regLineChange(cm, doc.frontier, "text");
1409        line.stateAfter = copyState(doc.mode, state);
1410      } else {
1411        processLine(cm, line.text, state);
1412        line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
1413      }
1414      ++doc.frontier;
1415      if (+new Date > end) {
1416        startWorker(cm, cm.options.workDelay);
1417        return true;
1418      }
1419    });
1420    });
1421  }
1422
1423  // Finds the line to start with when starting a parse. Tries to
1424  // find a line with a stateAfter, so that it can start with a
1425  // valid state. If that fails, it returns the line with the
1426  // smallest indentation, which tends to need the least context to
1427  // parse correctly.
1428  function findStartLine(cm, n, precise) {
1429    var minindent, minline, doc = cm.doc;
1430    var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
1431    for (var search = n; search > lim; --search) {
1432      if (search <= doc.first) return doc.first;
1433      var line = getLine(doc, search - 1);
1434      if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
1435      var indented = countColumn(line.text, null, cm.options.tabSize);
1436      if (minline == null || minindent > indented) {
1437        minline = search - 1;
1438        minindent = indented;
1439      }
1440    }
1441    return minline;
1442  }
1443
1444  function getStateBefore(cm, n, precise) {
1445    var doc = cm.doc, display = cm.display;
1446    if (!doc.mode.startState) return true;
1447    var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
1448    if (!state) state = startState(doc.mode);
1449    else state = copyState(doc.mode, state);
1450    doc.iter(pos, n, function(line) {
1451      processLine(cm, line.text, state);
1452      var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
1453      line.stateAfter = save ? copyState(doc.mode, state) : null;
1454      ++pos;
1455    });
1456    if (precise) doc.frontier = pos;
1457    return state;
1458  }
1459
1460  // POSITION MEASUREMENT
1461
1462  function paddingTop(display) {return display.lineSpace.offsetTop;}
1463  function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
1464  function paddingH(display) {
1465    if (display.cachedPaddingH) return display.cachedPaddingH;
1466    var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
1467    var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
1468    var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
1469    if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
1470    return data;
1471  }
1472
1473  // Ensure the lineView.wrapping.heights array is populated. This is
1474  // an array of bottom offsets for the lines that make up a drawn
1475  // line. When lineWrapping is on, there might be more than one
1476  // height.
1477  function ensureLineHeights(cm, lineView, rect) {
1478    var wrapping = cm.options.lineWrapping;
1479    var curWidth = wrapping && cm.display.scroller.clientWidth;
1480    if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
1481      var heights = lineView.measure.heights = [];
1482      if (wrapping) {
1483        lineView.measure.width = curWidth;
1484        var rects = lineView.text.firstChild.getClientRects();
1485        for (var i = 0; i < rects.length - 1; i++) {
1486          var cur = rects[i], next = rects[i + 1];
1487          if (Math.abs(cur.bottom - next.bottom) > 2)
1488            heights.push((cur.bottom + next.top) / 2 - rect.top);
1489        }
1490      }
1491      heights.push(rect.bottom - rect.top);
1492    }
1493  }
1494
1495  // Find a line map (mapping character offsets to text nodes) and a
1496  // measurement cache for the given line number. (A line view might
1497  // contain multiple lines when collapsed ranges are present.)
1498  function mapFromLineView(lineView, line, lineN) {
1499    if (lineView.line == line)
1500      return {map: lineView.measure.map, cache: lineView.measure.cache};
1501    for (var i = 0; i < lineView.rest.length; i++)
1502      if (lineView.rest[i] == line)
1503        return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
1504    for (var i = 0; i < lineView.rest.length; i++)
1505      if (lineNo(lineView.rest[i]) > lineN)
1506        return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
1507  }
1508
1509  // Render a line into the hidden node display.externalMeasured. Used
1510  // when measurement is needed for a line that's not in the viewport.
1511  function updateExternalMeasurement(cm, line) {
1512    line = visualLine(line);
1513    var lineN = lineNo(line);
1514    var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
1515    view.lineN = lineN;
1516    var built = view.built = buildLineContent(cm, view);
1517    view.text = built.pre;
1518    removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
1519    return view;
1520  }
1521
1522  // Get a {top, bottom, left, right} box (in line-local coordinates)
1523  // for a given character.
1524  function measureChar(cm, line, ch, bias) {
1525    return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
1526  }
1527
1528  // Find a line view that corresponds to the given line number.
1529  function findViewForLine(cm, lineN) {
1530    if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
1531      return cm.display.view[findViewIndex(cm, lineN)];
1532    var ext = cm.display.externalMeasured;
1533    if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
1534      return ext;
1535  }
1536
1537  // Measurement can be split in two steps, the set-up work that
1538  // applies to the whole line, and the measurement of the actual
1539  // character. Functions like coordsChar, that need to do a lot of
1540  // measurements in a row, can thus ensure that the set-up work is
1541  // only done once.
1542  function prepareMeasureForLine(cm, line) {
1543    var lineN = lineNo(line);
1544    var view = findViewForLine(cm, lineN);
1545    if (view && !view.text)
1546      view = null;
1547    else if (view && view.changes)
1548      updateLineForChanges(cm, view, lineN, getDimensions(cm));
1549    if (!view)
1550      view = updateExternalMeasurement(cm, line);
1551
1552    var info = mapFromLineView(view, line, lineN);
1553    return {
1554      line: line, view: view, rect: null,
1555      map: info.map, cache: info.cache, before: info.before,
1556      hasHeights: false
1557    };
1558  }
1559
1560  // Given a prepared measurement object, measures the position of an
1561  // actual character (or fetches it from the cache).
1562  function measureCharPrepared(cm, prepared, ch, bias) {
1563    if (prepared.before) ch = -1;
1564    var key = ch + (bias || ""), found;
1565    if (prepared.cache.hasOwnProperty(key)) {
1566      found = prepared.cache[key];
1567    } else {
1568      if (!prepared.rect)
1569        prepared.rect = prepared.view.text.getBoundingClientRect();
1570      if (!prepared.hasHeights) {
1571        ensureLineHeights(cm, prepared.view, prepared.rect);
1572        prepared.hasHeights = true;
1573      }
1574      found = measureCharInner(cm, prepared, ch, bias);
1575      if (!found.bogus) prepared.cache[key] = found;
1576    }
1577    return {left: found.left, right: found.right, top: found.top, bottom: found.bottom};
1578  }
1579
1580  var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
1581
1582  function measureCharInner(cm, prepared, ch, bias) {
1583    var map = prepared.map;
1584
1585    var node, start, end, collapse;
1586    // First, search the line map for the text node corresponding to,
1587    // or closest to, the target character.
1588    for (var i = 0; i < map.length; i += 3) {
1589      var mStart = map[i], mEnd = map[i + 1];
1590      if (ch < mStart) {
1591        start = 0; end = 1;
1592        collapse = "left";
1593      } else if (ch < mEnd) {
1594        start = ch - mStart;
1595        end = start + 1;
1596      } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
1597        end = mEnd - mStart;
1598        start = end - 1;
1599        if (ch >= mEnd) collapse = "right";
1600      }
1601      if (start != null) {
1602        node = map[i + 2];
1603        if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
1604          collapse = bias;
1605        if (bias == "left" && start == 0)
1606          while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
1607            node = map[(i -= 3) + 2];
1608            collapse = "left";
1609          }
1610        if (bias == "right" && start == mEnd - mStart)
1611          while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
1612            node = map[(i += 3) + 2];
1613            collapse = "right";
1614          }
1615        break;
1616      }
1617    }
1618
1619    var rect;
1620    if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
1621      while (start && isExtendingChar(prepared.line.text.charAt(mStart + start))) --start;
1622      while (mStart + end < mEnd && isExtendingChar(prepared.line.text.charAt(mStart + end))) ++end;
1623      if (ie_upto8 && start == 0 && end == mEnd - mStart) {
1624        rect = node.parentNode.getBoundingClientRect();
1625      } else if (ie && cm.options.lineWrapping) {
1626        var rects = range(node, start, end).getClientRects();
1627        if (rects.length)
1628          rect = rects[bias == "right" ? rects.length - 1 : 0];
1629        else
1630          rect = nullRect;
1631      } else {
1632        rect = range(node, start, end).getBoundingClientRect() || nullRect;
1633      }
1634    } else { // If it is a widget, simply get the box for the whole widget.
1635      if (start > 0) collapse = bias = "right";
1636      var rects;
1637      if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
1638        rect = rects[bias == "right" ? rects.length - 1 : 0];
1639      else
1640        rect = node.getBoundingClientRect();
1641    }
1642    if (ie_upto8 && !start && (!rect || !rect.left && !rect.right)) {
1643      var rSpan = node.parentNode.getClientRects()[0];
1644      if (rSpan)
1645        rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
1646      else
1647        rect = nullRect;
1648    }
1649
1650    var top, bot = (rect.bottom + rect.top) / 2 - prepared.rect.top;
1651    var heights = prepared.view.measure.heights;
1652    for (var i = 0; i < heights.length - 1; i++)
1653      if (bot < heights[i]) break;
1654    top = i ? heights[i - 1] : 0; bot = heights[i];
1655    var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
1656                  right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
1657                  top: top, bottom: bot};
1658    if (!rect.left && !rect.right) result.bogus = true;
1659    return result;
1660  }
1661
1662  function clearLineMeasurementCacheFor(lineView) {
1663    if (lineView.measure) {
1664      lineView.measure.cache = {};
1665      lineView.measure.heights = null;
1666      if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
1667        lineView.measure.caches[i] = {};
1668    }
1669  }
1670
1671  function clearLineMeasurementCache(cm) {
1672    cm.display.externalMeasure = null;
1673    removeChildren(cm.display.lineMeasure);
1674    for (var i = 0; i < cm.display.view.length; i++)
1675      clearLineMeasurementCacheFor(cm.display.view[i]);
1676  }
1677
1678  function clearCaches(cm) {
1679    clearLineMeasurementCache(cm);
1680    cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
1681    if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
1682    cm.display.lineNumChars = null;
1683  }
1684
1685  function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
1686  function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
1687
1688  // Converts a {top, bottom, left, right} box from line-local
1689  // coordinates into another coordinate system. Context may be one of
1690  // "line", "div" (display.lineDiv), "local"/null (editor), or "page".
1691  function intoCoordSystem(cm, lineObj, rect, context) {
1692    if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
1693      var size = widgetHeight(lineObj.widgets[i]);
1694      rect.top += size; rect.bottom += size;
1695    }
1696    if (context == "line") return rect;
1697    if (!context) context = "local";
1698    var yOff = heightAtLine(lineObj);
1699    if (context == "local") yOff += paddingTop(cm.display);
1700    else yOff -= cm.display.viewOffset;
1701    if (context == "page" || context == "window") {
1702      var lOff = cm.display.lineSpace.getBoundingClientRect();
1703      yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
1704      var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
1705      rect.left += xOff; rect.right += xOff;
1706    }
1707    rect.top += yOff; rect.bottom += yOff;
1708    return rect;
1709  }
1710
1711  // Coverts a box from "div" coords to another coordinate system.
1712  // Context may be "window", "page", "div", or "local"/null.
1713  function fromCoordSystem(cm, coords, context) {
1714    if (context == "div") return coords;
1715    var left = coords.left, top = coords.top;
1716    // First move into "page" coordinate system
1717    if (context == "page") {
1718      left -= pageScrollX();
1719      top -= pageScrollY();
1720    } else if (context == "local" || !context) {
1721      var localBox = cm.display.sizer.getBoundingClientRect();
1722      left += localBox.left;
1723      top += localBox.top;
1724    }
1725
1726    var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
1727    return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
1728  }
1729
1730  function charCoords(cm, pos, context, lineObj, bias) {
1731    if (!lineObj) lineObj = getLine(cm.doc, pos.line);
1732    return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
1733  }
1734
1735  // Returns a box for a given cursor position, which may have an
1736  // 'other' property containing the position of the secondary cursor
1737  // on a bidi boundary.
1738  function cursorCoords(cm, pos, context, lineObj, preparedMeasure) {
1739    lineObj = lineObj || getLine(cm.doc, pos.line);
1740    if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
1741    function get(ch, right) {
1742      var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left");
1743      if (right) m.left = m.right; else m.right = m.left;
1744      return intoCoordSystem(cm, lineObj, m, context);
1745    }
1746    function getBidi(ch, partPos) {
1747      var part = order[partPos], right = part.level % 2;
1748      if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
1749        part = order[--partPos];
1750        ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
1751        right = true;
1752      } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
1753        part = order[++partPos];
1754        ch = bidiLeft(part) - part.level % 2;
1755        right = false;
1756      }
1757      if (right && ch == part.to && ch > part.from) return get(ch - 1);
1758      return get(ch, right);
1759    }
1760    var order = getOrder(lineObj), ch = pos.ch;
1761    if (!order) return get(ch);
1762    var partPos = getBidiPartAt(order, ch);
1763    var val = getBidi(ch, partPos);
1764    if (bidiOther != null) val.other = getBidi(ch, bidiOther);
1765    return val;
1766  }
1767
1768  // Used to cheaply estimate the coordinates for a position. Used for
1769  // intermediate scroll updates.
1770  function estimateCoords(cm, pos) {
1771    var left = 0, pos = clipPos(cm.doc, pos);
1772    if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
1773    var lineObj = getLine(cm.doc, pos.line);
1774    var top = heightAtLine(lineObj) + paddingTop(cm.display);
1775    return {left: left, right: left, top: top, bottom: top + lineObj.height};
1776  }
1777
1778  // Positions returned by coordsChar contain some extra information.
1779  // xRel is the relative x position of the input coordinates compared
1780  // to the found position (so xRel > 0 means the coordinates are to
1781  // the right of the character position, for example). When outside
1782  // is true, that means the coordinates lie outside the line's
1783  // vertical range.
1784  function PosWithInfo(line, ch, outside, xRel) {
1785    var pos = Pos(line, ch);
1786    pos.xRel = xRel;
1787    if (outside) pos.outside = true;
1788    return pos;
1789  }
1790
1791  // Compute the character position closest to the given coordinates.
1792  // Input must be lineSpace-local ("div" coordinate system).
1793  function coordsChar(cm, x, y) {
1794    var doc = cm.doc;
1795    y += cm.display.viewOffset;
1796    if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
1797    var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
1798    if (lineN > last)
1799      return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
1800    if (x < 0) x = 0;
1801
1802    var lineObj = getLine(doc, lineN);
1803    for (;;) {
1804      var found = coordsCharInner(cm, lineObj, lineN, x, y);
1805      var merged = collapsedSpanAtEnd(lineObj);
1806      var mergedPos = merged && merged.find(0, true);
1807      if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
1808        lineN = lineNo(lineObj = mergedPos.to.line);
1809      else
1810        return found;
1811    }
1812  }
1813
1814  function coordsCharInner(cm, lineObj, lineNo, x, y) {
1815    var innerOff = y - heightAtLine(lineObj);
1816    var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
1817    var preparedMeasure = prepareMeasureForLine(cm, lineObj);
1818
1819    function getX(ch) {
1820      var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
1821      wrongLine = true;
1822      if (innerOff > sp.bottom) return sp.left - adjust;
1823      else if (innerOff < sp.top) return sp.left + adjust;
1824      else wrongLine = false;
1825      return sp.left;
1826    }
1827
1828    var bidi = getOrder(lineObj), dist = lineObj.text.length;
1829    var from = lineLeft(lineObj), to = lineRight(lineObj);
1830    var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
1831
1832    if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
1833    // Do a binary search between these bounds.
1834    for (;;) {
1835      if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
1836        var ch = x < fromX || x - fromX <= toX - x ? from : to;
1837        var xDiff = x - (ch == from ? fromX : toX);
1838        while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
1839        var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
1840                              xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
1841        return pos;
1842      }
1843      var step = Math.ceil(dist / 2), middle = from + step;
1844      if (bidi) {
1845        middle = from;
1846        for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
1847      }
1848      var middleX = getX(middle);
1849      if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
1850      else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
1851    }
1852  }
1853
1854  var measureText;
1855  // Compute the default text height.
1856  function textHeight(display) {
1857    if (display.cachedTextHeight != null) return display.cachedTextHeight;
1858    if (measureText == null) {
1859      measureText = elt("pre");
1860      // Measure a bunch of lines, for browsers that compute
1861      // fractional heights.
1862      for (var i = 0; i < 49; ++i) {
1863        measureText.appendChild(document.createTextNode("x"));
1864        measureText.appendChild(elt("br"));
1865      }
1866      measureText.appendChild(document.createTextNode("x"));
1867    }
1868    removeChildrenAndAdd(display.measure, measureText);
1869    var height = measureText.offsetHeight / 50;
1870    if (height > 3) display.cachedTextHeight = height;
1871    removeChildren(display.measure);
1872    return height || 1;
1873  }
1874
1875  // Compute the default character width.
1876  function charWidth(display) {
1877    if (display.cachedCharWidth != null) return display.cachedCharWidth;
1878    var anchor = elt("span", "xxxxxxxxxx");
1879    var pre = elt("pre", [anchor]);
1880    removeChildrenAndAdd(display.measure, pre);
1881    var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
1882    if (width > 2) display.cachedCharWidth = width;
1883    return width || 10;
1884  }
1885
1886  // OPERATIONS
1887
1888  // Operations are used to wrap a series of changes to the editor
1889  // state in such a way that each change won't have to update the
1890  // cursor and display (which would be awkward, slow, and
1891  // error-prone). Instead, display updates are batched and then all
1892  // combined and executed at once.
1893
1894  var nextOpId = 0;
1895  // Start a new operation.
1896  function startOperation(cm) {
1897    cm.curOp = {
1898      viewChanged: false,      // Flag that indicates that lines might need to be redrawn
1899      startHeight: cm.doc.height, // Used to detect need to update scrollbar
1900      forceUpdate: false,      // Used to force a redraw
1901      updateInput: null,       // Whether to reset the input textarea
1902      typing: false,           // Whether this reset should be careful to leave existing text (for compositing)
1903      changeObjs: null,        // Accumulated changes, for firing change events
1904      cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
1905      selectionChanged: false, // Whether the selection needs to be redrawn
1906      updateMaxLine: false,    // Set when the widest line needs to be determined anew
1907      scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
1908      scrollToPos: null,       // Used to scroll to a specific position
1909      id: ++nextOpId           // Unique ID
1910    };
1911    if (!delayedCallbackDepth++) delayedCallbacks = [];
1912  }
1913
1914  // Finish an operation, updating the display and signalling delayed events
1915  function endOperation(cm) {
1916    var op = cm.curOp, doc = cm.doc, display = cm.display;
1917    cm.curOp = null;
1918
1919    if (op.updateMaxLine) findMaxLine(cm);
1920
1921    // If it looks like an update might be needed, call updateDisplay
1922    if (op.viewChanged || op.forceUpdate || op.scrollTop != null ||
1923        op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
1924                           op.scrollToPos.to.line >= display.viewTo) ||
1925        display.maxLineChanged && cm.options.lineWrapping) {
1926      var updated = updateDisplay(cm, {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
1927      if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop;
1928    }
1929    // If no update was run, but the selection changed, redraw that.
1930    if (!updated && op.selectionChanged) updateSelection(cm);
1931    if (!updated && op.startHeight != cm.doc.height) updateScrollbars(cm);
1932
1933    // Abort mouse wheel delta measurement, when scrolling explicitly
1934    if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
1935      display.wheelStartX = display.wheelStartY = null;
1936
1937    // Propagate the scroll position to the actual DOM scroller
1938    if (op.scrollTop != null && display.scroller.scrollTop != op.scrollTop) {
1939      var top = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
1940      display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = top;
1941    }
1942    if (op.scrollLeft != null && display.scroller.scrollLeft != op.scrollLeft) {
1943      var left = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
1944      display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = left;
1945      alignHorizontally(cm);
1946    }
1947    // If we need to scroll a specific position into view, do so.
1948    if (op.scrollToPos) {
1949      var coords = scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos.from),
1950                                     clipPos(cm.doc, op.scrollToPos.to), op.scrollToPos.margin);
1951      if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
1952    }
1953
1954    if (op.selectionChanged) restartBlink(cm);
1955
1956    if (cm.state.focused && op.updateInput)
1957      resetInput(cm, op.typing);
1958
1959    // Fire events for markers that are hidden/unidden by editing or
1960    // undoing
1961    var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
1962    if (hidden) for (var i = 0; i < hidden.length; ++i)
1963      if (!hidden[i].lines.length) signal(hidden[i], "hide");
1964    if (unhidden) for (var i = 0; i < unhidden.length; ++i)
1965      if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
1966
1967    var delayed;
1968    if (!--delayedCallbackDepth) {
1969      delayed = delayedCallbacks;
1970      delayedCallbacks = null;
1971    }
1972    // Fire change events, and delayed event handlers
1973    if (op.changeObjs)
1974      signal(cm, "changes", cm, op.changeObjs);
1975    if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i]();
1976    if (op.cursorActivityHandlers)
1977      for (var i = 0; i < op.cursorActivityHandlers.length; i++)
1978        op.cursorActivityHandlers[i](cm);
1979  }
1980
1981  // Run the given function in an operation
1982  function runInOp(cm, f) {
1983    if (cm.curOp) return f();
1984    startOperation(cm);
1985    try { return f(); }
1986    finally { endOperation(cm); }
1987  }
1988  // Wraps a function in an operation. Returns the wrapped function.
1989  function operation(cm, f) {
1990    return function() {
1991      if (cm.curOp) return f.apply(cm, arguments);
1992      startOperation(cm);
1993      try { return f.apply(cm, arguments); }
1994      finally { endOperation(cm); }
1995    };
1996  }
1997  // Used to add methods to editor and doc instances, wrapping them in
1998  // operations.
1999  function methodOp(f) {
2000    return function() {
2001      if (this.curOp) return f.apply(this, arguments);
2002      startOperation(this);
2003      try { return f.apply(this, arguments); }
2004      finally { endOperation(this); }
2005    };
2006  }
2007  function docMethodOp(f) {
2008    return function() {
2009      var cm = this.cm;
2010      if (!cm || cm.curOp) return f.apply(this, arguments);
2011      startOperation(cm);
2012      try { return f.apply(this, arguments); }
2013      finally { endOperation(cm); }
2014    };
2015  }
2016
2017  // VIEW TRACKING
2018
2019  // These objects are used to represent the visible (currently drawn)
2020  // part of the document. A LineView may correspond to multiple
2021  // logical lines, if those are connected by collapsed ranges.
2022  function LineView(doc, line, lineN) {
2023    // The starting line
2024    this.line = line;
2025    // Continuing lines, if any
2026    this.rest = visualLineContinued(line);
2027    // Number of logical lines in this visual line
2028    this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
2029    this.node = this.text = null;
2030    this.hidden = lineIsHidden(doc, line);
2031  }
2032
2033  // Create a range of LineView objects for the given lines.
2034  function buildViewArray(cm, from, to) {
2035    var array = [], nextPos;
2036    for (var pos = from; pos < to; pos = nextPos) {
2037      var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
2038      nextPos = pos + view.size;
2039      array.push(view);
2040    }
2041    return array;
2042  }
2043
2044  // Updates the display.view data structure for a given change to the
2045  // document. From and to are in pre-change coordinates. Lendiff is
2046  // the amount of lines added or subtracted by the change. This is
2047  // used for changes that span multiple lines, or change the way
2048  // lines are divided into visual lines. regLineChange (below)
2049  // registers single-line changes.
2050  function regChange(cm, from, to, lendiff) {
2051    if (from == null) from = cm.doc.first;
2052    if (to == null) to = cm.doc.first + cm.doc.size;
2053    if (!lendiff) lendiff = 0;
2054
2055    var display = cm.display;
2056    if (lendiff && to < display.viewTo &&
2057        (display.updateLineNumbers == null || display.updateLineNumbers > from))
2058      display.updateLineNumbers = from;
2059
2060    cm.curOp.viewChanged = true;
2061
2062    if (from >= display.viewTo) { // Change after
2063      if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
2064        resetView(cm);
2065    } else if (to <= display.viewFrom) { // Change before
2066      if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
2067        resetView(cm);
2068      } else {
2069        display.viewFrom += lendiff;
2070        display.viewTo += lendiff;
2071      }
2072    } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
2073      resetView(cm);
2074    } else if (from <= display.viewFrom) { // Top overlap
2075      var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
2076      if (cut) {
2077        display.view = display.view.slice(cut.index);
2078        display.viewFrom = cut.lineN;
2079        display.viewTo += lendiff;
2080      } else {
2081        resetView(cm);
2082      }
2083    } else if (to >= display.viewTo) { // Bottom overlap
2084      var cut = viewCuttingPoint(cm, from, from, -1);
2085      if (cut) {
2086        display.view = display.view.slice(0, cut.index);
2087        display.viewTo = cut.lineN;
2088      } else {
2089        resetView(cm);
2090      }
2091    } else { // Gap in the middle
2092      var cutTop = viewCuttingPoint(cm, from, from, -1);
2093      var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
2094      if (cutTop && cutBot) {
2095        display.view = display.view.slice(0, cutTop.index)
2096          .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
2097          .concat(display.view.slice(cutBot.index));
2098        display.viewTo += lendiff;
2099      } else {
2100        resetView(cm);
2101      }
2102    }
2103
2104    var ext = display.externalMeasured;
2105    if (ext) {
2106      if (to < ext.lineN)
2107        ext.lineN += lendiff;
2108      else if (from < ext.lineN + ext.size)
2109        display.externalMeasured = null;
2110    }
2111  }
2112
2113  // Register a change to a single line. Type must be one of "text",
2114  // "gutter", "class", "widget"
2115  function regLineChange(cm, line, type) {
2116    cm.curOp.viewChanged = true;
2117    var display = cm.display, ext = cm.display.externalMeasured;
2118    if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
2119      display.externalMeasured = null;
2120
2121    if (line < display.viewFrom || line >= display.viewTo) return;
2122    var lineView = display.view[findViewIndex(cm, line)];
2123    if (lineView.node == null) return;
2124    var arr = lineView.changes || (lineView.changes = []);
2125    if (indexOf(arr, type) == -1) arr.push(type);
2126  }
2127
2128  // Clear the view.
2129  function resetView(cm) {
2130    cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
2131    cm.display.view = [];
2132    cm.display.viewOffset = 0;
2133  }
2134
2135  // Find the view element corresponding to a given line. Return null
2136  // when the line isn't visible.
2137  function findViewIndex(cm, n) {
2138    if (n >= cm.display.viewTo) return null;
2139    n -= cm.display.viewFrom;
2140    if (n < 0) return null;
2141    var view = cm.display.view;
2142    for (var i = 0; i < view.length; i++) {
2143      n -= view[i].size;
2144      if (n < 0) return i;
2145    }
2146  }
2147
2148  function viewCuttingPoint(cm, oldN, newN, dir) {
2149    var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
2150    if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
2151      return {index: index, lineN: newN};
2152    for (var i = 0, n = cm.display.viewFrom; i < index; i++)
2153      n += view[i].size;
2154    if (n != oldN) {
2155      if (dir > 0) {
2156        if (index == view.length - 1) return null;
2157        diff = (n + view[index].size) - oldN;
2158        index++;
2159      } else {
2160        diff = n - oldN;
2161      }
2162      oldN += diff; newN += diff;
2163    }
2164    while (visualLineNo(cm.doc, newN) != newN) {
2165      if (index == (dir < 0 ? 0 : view.length - 1)) return null;
2166      newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
2167      index += dir;
2168    }
2169    return {index: index, lineN: newN};
2170  }
2171
2172  // Force the view to cover a given range, adding empty view element
2173  // or clipping off existing ones as needed.
2174  function adjustView(cm, from, to) {
2175    var display = cm.display, view = display.view;
2176    if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
2177      display.view = buildViewArray(cm, from, to);
2178      display.viewFrom = from;
2179    } else {
2180      if (display.viewFrom > from)
2181        display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
2182      else if (display.viewFrom < from)
2183        display.view = display.view.slice(findViewIndex(cm, from));
2184      display.viewFrom = from;
2185      if (display.viewTo < to)
2186        display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
2187      else if (display.viewTo > to)
2188        display.view = display.view.slice(0, findViewIndex(cm, to));
2189    }
2190    display.viewTo = to;
2191  }
2192
2193  // Count the number of lines in the view whose DOM representation is
2194  // out of date (or nonexistent).
2195  function countDirtyView(cm) {
2196    var view = cm.display.view, dirty = 0;
2197    for (var i = 0; i < view.length; i++) {
2198      var lineView = view[i];
2199      if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
2200    }
2201    return dirty;
2202  }
2203
2204  // INPUT HANDLING
2205
2206  // Poll for input changes, using the normal rate of polling. This
2207  // runs as long as the editor is focused.
2208  function slowPoll(cm) {
2209    if (cm.display.pollingFast) return;
2210    cm.display.poll.set(cm.options.pollInterval, function() {
2211      readInput(cm);
2212      if (cm.state.focused) slowPoll(cm);
2213    });
2214  }
2215
2216  // When an event has just come in that is likely to add or change
2217  // something in the input textarea, we poll faster, to ensure that
2218  // the change appears on the screen quickly.
2219  function fastPoll(cm) {
2220    var missed = false;
2221    cm.display.pollingFast = true;
2222    function p() {
2223      var changed = readInput(cm);
2224      if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
2225      else {cm.display.pollingFast = false; slowPoll(cm);}
2226    }
2227    cm.display.poll.set(20, p);
2228  }
2229
2230  // Read input from the textarea, and update the document to match.
2231  // When something is selected, it is present in the textarea, and
2232  // selected (unless it is huge, in which case a placeholder is
2233  // used). When nothing is selected, the cursor sits after previously
2234  // seen text (can be empty), which is stored in prevInput (we must
2235  // not reset the textarea when typing, because that breaks IME).
2236  function readInput(cm) {
2237    var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc;
2238    // Since this is called a *lot*, try to bail out as cheaply as
2239    // possible when it is clear that nothing happened. hasSelection
2240    // will be the case when there is a lot of text in the textarea,
2241    // in which case reading its value would be expensive.
2242    if (!cm.state.focused || (hasSelection(input) && !prevInput) || isReadOnly(cm) || cm.options.disableInput)
2243      return false;
2244    // See paste handler for more on the fakedLastChar kludge
2245    if (cm.state.pasteIncoming && cm.state.fakedLastChar) {
2246      input.value = input.value.substring(0, input.value.length - 1);
2247      cm.state.fakedLastChar = false;
2248    }
2249    var text = input.value;
2250    // If nothing changed, bail.
2251    if (text == prevInput && !cm.somethingSelected()) return false;
2252    // Work around nonsensical selection resetting in IE9/10
2253    if (ie && !ie_upto8 && cm.display.inputHasSelection === text) {
2254      resetInput(cm);
2255      return false;
2256    }
2257
2258    var withOp = !cm.curOp;
2259    if (withOp) startOperation(cm);
2260    cm.display.shift = false;
2261
2262    if (text.charCodeAt(0) == 0x200b && doc.sel == cm.display.selForContextMenu && !prevInput)
2263      prevInput = "\u200b";
2264    // Find the part of the input that is actually new
2265    var same = 0, l = Math.min(prevInput.length, text.length);
2266    while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
2267    var inserted = text.slice(same), textLines = splitLines(inserted);
2268
2269    // When pasing N lines into N selections, insert one line per selection
2270    var multiPaste = cm.state.pasteIncoming && textLines.length > 1 && doc.sel.ranges.length == textLines.length;
2271
2272    // Normal behavior is to insert the new text into every selection
2273    for (var i = doc.sel.ranges.length - 1; i >= 0; i--) {
2274      var range = doc.sel.ranges[i];
2275      var from = range.from(), to = range.to();
2276      // Handle deletion
2277      if (same < prevInput.length)
2278        from = Pos(from.line, from.ch - (prevInput.length - same));
2279      // Handle overwrite
2280      else if (cm.state.overwrite && range.empty() && !cm.state.pasteIncoming)
2281        to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
2282      var updateInput = cm.curOp.updateInput;
2283      var changeEvent = {from: from, to: to, text: multiPaste ? [textLines[i]] : textLines,
2284                         origin: cm.state.pasteIncoming ? "paste" : cm.state.cutIncoming ? "cut" : "+input"};
2285      makeChange(cm.doc, changeEvent);
2286      signalLater(cm, "inputRead", cm, changeEvent);
2287      // When an 'electric' character is inserted, immediately trigger a reindent
2288      if (inserted && !cm.state.pasteIncoming && cm.options.electricChars &&
2289          cm.options.smartIndent && range.head.ch < 100 &&
2290          (!i || doc.sel.ranges[i - 1].head.line != range.head.line)) {
2291        var mode = cm.getModeAt(range.head);
2292        if (mode.electricChars) {
2293          for (var j = 0; j < mode.electricChars.length; j++)
2294            if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
2295              indentLine(cm, range.head.line, "smart");
2296              break;
2297            }
2298        } else if (mode.electricInput) {
2299          var end = changeEnd(changeEvent);
2300          if (mode.electricInput.test(getLine(doc, end.line).text.slice(0, end.ch)))
2301            indentLine(cm, range.head.line, "smart");
2302        }
2303      }
2304    }
2305    ensureCursorVisible(cm);
2306    cm.curOp.updateInput = updateInput;
2307    cm.curOp.typing = true;
2308
2309    // Don't leave long text in the textarea, since it makes further polling slow
2310    if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = "";
2311    else cm.display.prevInput = text;
2312    if (withOp) endOperation(cm);
2313    cm.state.pasteIncoming = cm.state.cutIncoming = false;
2314    return true;
2315  }
2316
2317  // Reset the input to correspond to the selection (or to be empty,
2318  // when not typing and nothing is selected)
2319  function resetInput(cm, typing) {
2320    var minimal, selected, doc = cm.doc;
2321    if (cm.somethingSelected()) {
2322      cm.display.prevInput = "";
2323      var range = doc.sel.primary();
2324      minimal = hasCopyEvent &&
2325        (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
2326      var content = minimal ? "-" : selected || cm.getSelection();
2327      cm.display.input.value = content;
2328      if (cm.state.focused) selectInput(cm.display.input);
2329      if (ie && !ie_upto8) cm.display.inputHasSelection = content;
2330    } else if (!typing) {
2331      cm.display.prevInput = cm.display.input.value = "";
2332      if (ie && !ie_upto8) cm.display.inputHasSelection = null;
2333    }
2334    cm.display.inaccurateSelection = minimal;
2335  }
2336
2337  function focusInput(cm) {
2338    if (cm.options.readOnly != "nocursor" && (!mobile || activeElt() != cm.display.input))
2339      cm.display.input.focus();
2340  }
2341
2342  function ensureFocus(cm) {
2343    if (!cm.state.focused) { focusInput(cm); onFocus(cm); }
2344  }
2345
2346  function isReadOnly(cm) {
2347    return cm.options.readOnly || cm.doc.cantEdit;
2348  }
2349
2350  // EVENT HANDLERS
2351
2352  // Attach the necessary event handlers when initializing the editor
2353  function registerEventHandlers(cm) {
2354    var d = cm.display;
2355    on(d.scroller, "mousedown", operation(cm, onMouseDown));
2356    // Older IE's will not fire a second mousedown for a double click
2357    if (ie_upto10)
2358      on(d.scroller, "dblclick", operation(cm, function(e) {
2359        if (signalDOMEvent(cm, e)) return;
2360        var pos = posFromMouse(cm, e);
2361        if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
2362        e_preventDefault(e);
2363        var word = findWordAt(cm, pos);
2364        extendSelection(cm.doc, word.anchor, word.head);
2365      }));
2366    else
2367      on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
2368    // Prevent normal selection in the editor (we handle our own)
2369    on(d.lineSpace, "selectstart", function(e) {
2370      if (!eventInWidget(d, e)) e_preventDefault(e);
2371    });
2372    // Some browsers fire contextmenu *after* opening the menu, at
2373    // which point we can't mess with it anymore. Context menu is
2374    // handled in onMouseDown for these browsers.
2375    if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
2376
2377    // Sync scrolling between fake scrollbars and real scrollable
2378    // area, ensure viewport is updated when scrolling.
2379    on(d.scroller, "scroll", function() {
2380      if (d.scroller.clientHeight) {
2381        setScrollTop(cm, d.scroller.scrollTop);
2382        setScrollLeft(cm, d.scroller.scrollLeft, true);
2383        signal(cm, "scroll", cm);
2384      }
2385    });
2386    on(d.scrollbarV, "scroll", function() {
2387      if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop);
2388    });
2389    on(d.scrollbarH, "scroll", function() {
2390      if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft);
2391    });
2392
2393    // Listen to wheel events in order to try and update the viewport on time.
2394    on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
2395    on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
2396
2397    // Prevent clicks in the scrollbars from killing focus
2398    function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); }
2399    on(d.scrollbarH, "mousedown", reFocus);
2400    on(d.scrollbarV, "mousedown", reFocus);
2401    // Prevent wrapper from ever scrolling
2402    on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
2403
2404    on(d.input, "keyup", operation(cm, onKeyUp));
2405    on(d.input, "input", function() {
2406      if (ie && !ie_upto8 && cm.display.inputHasSelection) cm.display.inputHasSelection = null;
2407      fastPoll(cm);
2408    });
2409    on(d.input, "keydown", operation(cm, onKeyDown));
2410    on(d.input, "keypress", operation(cm, onKeyPress));
2411    on(d.input, "focus", bind(onFocus, cm));
2412    on(d.input, "blur", bind(onBlur, cm));
2413
2414    function drag_(e) {
2415      if (!signalDOMEvent(cm, e)) e_stop(e);
2416    }
2417    if (cm.options.dragDrop) {
2418      on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
2419      on(d.scroller, "dragenter", drag_);
2420      on(d.scroller, "dragover", drag_);
2421      on(d.scroller, "drop", operation(cm, onDrop));
2422    }
2423    on(d.scroller, "paste", function(e) {
2424      if (eventInWidget(d, e)) return;
2425      cm.state.pasteIncoming = true;
2426      focusInput(cm);
2427      fastPoll(cm);
2428    });
2429    on(d.input, "paste", function() {
2430      // Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206
2431      // Add a char to the end of textarea before paste occur so that
2432      // selection doesn't span to the end of textarea.
2433      if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) {
2434        var start = d.input.selectionStart, end = d.input.selectionEnd;
2435        d.input.value += "$";
2436        d.input.selectionStart = start;
2437        d.input.selectionEnd = end;
2438        cm.state.fakedLastChar = true;
2439      }
2440      cm.state.pasteIncoming = true;
2441      fastPoll(cm);
2442    });
2443
2444    function prepareCopyCut(e) {
2445      if (cm.somethingSelected()) {
2446        if (d.inaccurateSelection) {
2447          d.prevInput = "";
2448          d.inaccurateSelection = false;
2449          d.input.value = cm.getSelection();
2450          selectInput(d.input);
2451        }
2452      } else {
2453        var text = "", ranges = [];
2454        for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
2455          var line = cm.doc.sel.ranges[i].head.line;
2456          var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
2457          ranges.push(lineRange);
2458          text += cm.getRange(lineRange.anchor, lineRange.head);
2459        }
2460        if (e.type == "cut") {
2461          cm.setSelections(ranges, null, sel_dontScroll);
2462        } else {
2463          d.prevInput = "";
2464          d.input.value = text;
2465          selectInput(d.input);
2466        }
2467      }
2468      if (e.type == "cut") cm.state.cutIncoming = true;
2469    }
2470    on(d.input, "cut", prepareCopyCut);
2471    on(d.input, "copy", prepareCopyCut);
2472
2473    // Needed to handle Tab key in KHTML
2474    if (khtml) on(d.sizer, "mouseup", function() {
2475      if (activeElt() == d.input) d.input.blur();
2476      focusInput(cm);
2477    });
2478  }
2479
2480  // Called when the window resizes
2481  function onResize(cm) {
2482    // Might be a text scaling operation, clear size caches.
2483    var d = cm.display;
2484    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
2485    cm.setSize();
2486  }
2487
2488  // MOUSE EVENTS
2489
2490  // Return true when the given mouse event happened in a widget
2491  function eventInWidget(display, e) {
2492    for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
2493      if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true;
2494    }
2495  }
2496
2497  // Given a mouse event, find the corresponding position. If liberal
2498  // is false, it checks whether a gutter or scrollbar was clicked,
2499  // and returns null if it was. forRect is used by rectangular
2500  // selections, and tries to estimate a character position even for
2501  // coordinates beyond the right of the text.
2502  function posFromMouse(cm, e, liberal, forRect) {
2503    var display = cm.display;
2504    if (!liberal) {
2505      var target = e_target(e);
2506      if (target == display.scrollbarH || target == display.scrollbarV ||
2507          target == display.scrollbarFiller || target == display.gutterFiller) return null;
2508    }
2509    var x, y, space = display.lineSpace.getBoundingClientRect();
2510    // Fails unpredictably on IE[67] when mouse is dragged around quickly.
2511    try { x = e.clientX - space.left; y = e.clientY - space.top; }
2512    catch (e) { return null; }
2513    var coords = coordsChar(cm, x, y), line;
2514    if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
2515      var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
2516      coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
2517    }
2518    return coords;
2519  }
2520
2521  // A mouse down can be a single click, double click, triple click,
2522  // start of selection drag, start of text drag, new cursor
2523  // (ctrl-click), rectangle drag (alt-drag), or xwin
2524  // middle-click-paste. Or it might be a click on something we should
2525  // not interfere with, such as a scrollbar or widget.
2526  function onMouseDown(e) {
2527    if (signalDOMEvent(this, e)) return;
2528    var cm = this, display = cm.display;
2529    display.shift = e.shiftKey;
2530
2531    if (eventInWidget(display, e)) {
2532      if (!webkit) {
2533        // Briefly turn off draggability, to allow widgets to do
2534        // normal dragging things.
2535        display.scroller.draggable = false;
2536        setTimeout(function(){display.scroller.draggable = true;}, 100);
2537      }
2538      return;
2539    }
2540    if (clickInGutter(cm, e)) return;
2541    var start = posFromMouse(cm, e);
2542    window.focus();
2543
2544    switch (e_button(e)) {
2545    case 1:
2546      if (start)
2547        leftButtonDown(cm, e, start);
2548      else if (e_target(e) == display.scroller)
2549        e_preventDefault(e);
2550      break;
2551    case 2:
2552      if (webkit) cm.state.lastMiddleDown = +new Date;
2553      if (start) extendSelection(cm.doc, start);
2554      setTimeout(bind(focusInput, cm), 20);
2555      e_preventDefault(e);
2556      break;
2557    case 3:
2558      if (captureRightClick) onContextMenu(cm, e);
2559      break;
2560    }
2561  }
2562
2563  var lastClick, lastDoubleClick;
2564  function leftButtonDown(cm, e, start) {
2565    setTimeout(bind(ensureFocus, cm), 0);
2566
2567    var now = +new Date, type;
2568    if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
2569      type = "triple";
2570    } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
2571      type = "double";
2572      lastDoubleClick = {time: now, pos: start};
2573    } else {
2574      type = "single";
2575      lastClick = {time: now, pos: start};
2576    }
2577
2578    var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey;
2579    if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) &&
2580        type == "single" && sel.contains(start) > -1 && sel.somethingSelected())
2581      leftButtonStartDrag(cm, e, start, modifier);
2582    else
2583      leftButtonSelect(cm, e, start, type, modifier);
2584  }
2585
2586  // Start a text drag. When it ends, see if any dragging actually
2587  // happen, and treat as a click if it didn't.
2588  function leftButtonStartDrag(cm, e, start, modifier) {
2589    var display = cm.display;
2590    var dragEnd = operation(cm, function(e2) {
2591      if (webkit) display.scroller.draggable = false;
2592      cm.state.draggingText = false;
2593      off(document, "mouseup", dragEnd);
2594      off(display.scroller, "drop", dragEnd);
2595      if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
2596        e_preventDefault(e2);
2597        if (!modifier)
2598          extendSelection(cm.doc, start);
2599        focusInput(cm);
2600        // Work around unexplainable focus problem in IE9 (#2127)
2601        if (ie_upto10 && !ie_upto8)
2602          setTimeout(function() {document.body.focus(); focusInput(cm);}, 20);
2603      }
2604    });
2605    // Let the drag handler handle this.
2606    if (webkit) display.scroller.draggable = true;
2607    cm.state.draggingText = dragEnd;
2608    // IE's approach to draggable
2609    if (display.scroller.dragDrop) display.scroller.dragDrop();
2610    on(document, "mouseup", dragEnd);
2611    on(display.scroller, "drop", dragEnd);
2612  }
2613
2614  // Normal selection, as opposed to text dragging.
2615  function leftButtonSelect(cm, e, start, type, addNew) {
2616    var display = cm.display, doc = cm.doc;
2617    e_preventDefault(e);
2618
2619    var ourRange, ourIndex, startSel = doc.sel;
2620    if (addNew && !e.shiftKey) {
2621      ourIndex = doc.sel.contains(start);
2622      if (ourIndex > -1)
2623        ourRange = doc.sel.ranges[ourIndex];
2624      else
2625        ourRange = new Range(start, start);
2626    } else {
2627      ourRange = doc.sel.primary();
2628    }
2629
2630    if (e.altKey) {
2631      type = "rect";
2632      if (!addNew) ourRange = new Range(start, start);
2633      start = posFromMouse(cm, e, true, true);
2634      ourIndex = -1;
2635    } else if (type == "double") {
2636      var word = findWordAt(cm, start);
2637      if (cm.display.shift || doc.extend)
2638        ourRange = extendRange(doc, ourRange, word.anchor, word.head);
2639      else
2640        ourRange = word;
2641    } else if (type == "triple") {
2642      var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
2643      if (cm.display.shift || doc.extend)
2644        ourRange = extendRange(doc, ourRange, line.anchor, line.head);
2645      else
2646        ourRange = line;
2647    } else {
2648      ourRange = extendRange(doc, ourRange, start);
2649    }
2650
2651    if (!addNew) {
2652      ourIndex = 0;
2653      setSelection(doc, new Selection([ourRange], 0), sel_mouse);
2654      startSel = doc.sel;
2655    } else if (ourIndex > -1) {
2656      replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
2657    } else {
2658      ourIndex = doc.sel.ranges.length;
2659      setSelection(doc, normalizeSelection(doc.sel.ranges.concat([ourRange]), ourIndex),
2660                   {scroll: false, origin: "*mouse"});
2661    }
2662
2663    var lastPos = start;
2664    function extendTo(pos) {
2665      if (cmp(lastPos, pos) == 0) return;
2666      lastPos = pos;
2667
2668      if (type == "rect") {
2669        var ranges = [], tabSize = cm.options.tabSize;
2670        var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
2671        var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
2672        var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
2673        for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
2674             line <= end; line++) {
2675          var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
2676          if (left == right)
2677            ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
2678          else if (text.length > leftPos)
2679            ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
2680        }
2681        if (!ranges.length) ranges.push(new Range(start, start));
2682        setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
2683                     {origin: "*mouse", scroll: false});
2684        cm.scrollIntoView(pos);
2685      } else {
2686        var oldRange = ourRange;
2687        var anchor = oldRange.anchor, head = pos;
2688        if (type != "single") {
2689          if (type == "double")
2690            var range = findWordAt(cm, pos);
2691          else
2692            var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
2693          if (cmp(range.anchor, anchor) > 0) {
2694            head = range.head;
2695            anchor = minPos(oldRange.from(), range.anchor);
2696          } else {
2697            head = range.anchor;
2698            anchor = maxPos(oldRange.to(), range.head);
2699          }
2700        }
2701        var ranges = startSel.ranges.slice(0);
2702        ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
2703        setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
2704      }
2705    }
2706
2707    var editorSize = display.wrapper.getBoundingClientRect();
2708    // Used to ensure timeout re-tries don't fire when another extend
2709    // happened in the meantime (clearTimeout isn't reliable -- at
2710    // least on Chrome, the timeouts still happen even when cleared,
2711    // if the clear happens after their scheduled firing time).
2712    var counter = 0;
2713
2714    function extend(e) {
2715      var curCount = ++counter;
2716      var cur = posFromMouse(cm, e, true, type == "rect");
2717      if (!cur) return;
2718      if (cmp(cur, lastPos) != 0) {
2719        ensureFocus(cm);
2720        extendTo(cur);
2721        var visible = visibleLines(display, doc);
2722        if (cur.line >= visible.to || cur.line < visible.from)
2723          setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
2724      } else {
2725        var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
2726        if (outside) setTimeout(operation(cm, function() {
2727          if (counter != curCount) return;
2728          display.scroller.scrollTop += outside;
2729          extend(e);
2730        }), 50);
2731      }
2732    }
2733
2734    function done(e) {
2735      counter = Infinity;
2736      e_preventDefault(e);
2737      focusInput(cm);
2738      off(document, "mousemove", move);
2739      off(document, "mouseup", up);
2740      doc.history.lastSelOrigin = null;
2741    }
2742
2743    var move = operation(cm, function(e) {
2744      if ((ie && !ie_upto9) ?  !e.buttons : !e_button(e)) done(e);
2745      else extend(e);
2746    });
2747    var up = operation(cm, done);
2748    on(document, "mousemove", move);
2749    on(document, "mouseup", up);
2750  }
2751
2752  // Determines whether an event happened in the gutter, and fires the
2753  // handlers for the corresponding event.
2754  function gutterEvent(cm, e, type, prevent, signalfn) {
2755    try { var mX = e.clientX, mY = e.clientY; }
2756    catch(e) { return false; }
2757    if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
2758    if (prevent) e_preventDefault(e);
2759
2760    var display = cm.display;
2761    var lineBox = display.lineDiv.getBoundingClientRect();
2762
2763    if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
2764    mY -= lineBox.top - display.viewOffset;
2765
2766    for (var i = 0; i < cm.options.gutters.length; ++i) {
2767      var g = display.gutters.childNodes[i];
2768      if (g && g.getBoundingClientRect().right >= mX) {
2769        var line = lineAtHeight(cm.doc, mY);
2770        var gutter = cm.options.gutters[i];
2771        signalfn(cm, type, cm, line, gutter, e);
2772        return e_defaultPrevented(e);
2773      }
2774    }
2775  }
2776
2777  function clickInGutter(cm, e) {
2778    return gutterEvent(cm, e, "gutterClick", true, signalLater);
2779  }
2780
2781  // Kludge to work around strange IE behavior where it'll sometimes
2782  // re-fire a series of drag-related events right after the drop (#1551)
2783  var lastDrop = 0;
2784
2785  function onDrop(e) {
2786    var cm = this;
2787    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
2788      return;
2789    e_preventDefault(e);
2790    if (ie) lastDrop = +new Date;
2791    var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
2792    if (!pos || isReadOnly(cm)) return;
2793    // Might be a file drop, in which case we simply extract the text
2794    // and insert it.
2795    if (files && files.length && window.FileReader && window.File) {
2796      var n = files.length, text = Array(n), read = 0;
2797      var loadFile = function(file, i) {
2798        var reader = new FileReader;
2799        reader.onload = operation(cm, function() {
2800          text[i] = reader.result;
2801          if (++read == n) {
2802            pos = clipPos(cm.doc, pos);
2803            var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"};
2804            makeChange(cm.doc, change);
2805            setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
2806          }
2807        });
2808        reader.readAsText(file);
2809      };
2810      for (var i = 0; i < n; ++i) loadFile(files[i], i);
2811    } else { // Normal drop
2812      // Don't do a replace if the drop happened inside of the selected text.
2813      if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
2814        cm.state.draggingText(e);
2815        // Ensure the editor is re-focused
2816        setTimeout(bind(focusInput, cm), 20);
2817        return;
2818      }
2819      try {
2820        var text = e.dataTransfer.getData("Text");
2821        if (text) {
2822          if (cm.state.draggingText && !(mac ? e.metaKey : e.ctrlKey))
2823            var selected = cm.listSelections();
2824          setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
2825          if (selected) for (var i = 0; i < selected.length; ++i)
2826            replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
2827          cm.replaceSelection(text, "around", "paste");
2828          focusInput(cm);
2829        }
2830      }
2831      catch(e){}
2832    }
2833  }
2834
2835  function onDragStart(cm, e) {
2836    if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
2837    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
2838
2839    e.dataTransfer.setData("Text", cm.getSelection());
2840
2841    // Use dummy image instead of default browsers image.
2842    // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
2843    if (e.dataTransfer.setDragImage && !safari) {
2844      var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
2845      img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
2846      if (presto) {
2847        img.width = img.height = 1;
2848        cm.display.wrapper.appendChild(img);
2849        // Force a relayout, or Opera won't use our image for some obscure reason
2850        img._top = img.offsetTop;
2851      }
2852      e.dataTransfer.setDragImage(img, 0, 0);
2853      if (presto) img.parentNode.removeChild(img);
2854    }
2855  }
2856
2857  // SCROLL EVENTS
2858
2859  // Sync the scrollable area and scrollbars, ensure the viewport
2860  // covers the visible area.
2861  function setScrollTop(cm, val) {
2862    if (Math.abs(cm.doc.scrollTop - val) < 2) return;
2863    cm.doc.scrollTop = val;
2864    if (!gecko) updateDisplay(cm, {top: val});
2865    if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
2866    if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
2867    if (gecko) updateDisplay(cm);
2868    startWorker(cm, 100);
2869  }
2870  // Sync scroller and scrollbar, ensure the gutter elements are
2871  // aligned.
2872  function setScrollLeft(cm, val, isScroller) {
2873    if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
2874    val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
2875    cm.doc.scrollLeft = val;
2876    alignHorizontally(cm);
2877    if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
2878    if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
2879  }
2880
2881  // Since the delta values reported on mouse wheel events are
2882  // unstandardized between browsers and even browser versions, and
2883  // generally horribly unpredictable, this code starts by measuring
2884  // the scroll effect that the first few mouse wheel events have,
2885  // and, from that, detects the way it can convert deltas to pixel
2886  // offsets afterwards.
2887  //
2888  // The reason we want to know the amount a wheel event will scroll
2889  // is that it gives us a chance to update the display before the
2890  // actual scrolling happens, reducing flickering.
2891
2892  var wheelSamples = 0, wheelPixelsPerUnit = null;
2893  // Fill in a browser-detected starting value on browsers where we
2894  // know one. These don't have to be accurate -- the result of them
2895  // being wrong would just be a slight flicker on the first wheel
2896  // scroll (if it is large enough).
2897  if (ie) wheelPixelsPerUnit = -.53;
2898  else if (gecko) wheelPixelsPerUnit = 15;
2899  else if (chrome) wheelPixelsPerUnit = -.7;
2900  else if (safari) wheelPixelsPerUnit = -1/3;
2901
2902  function onScrollWheel(cm, e) {
2903    var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
2904    if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
2905    if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
2906    else if (dy == null) dy = e.wheelDelta;
2907
2908    var display = cm.display, scroll = display.scroller;
2909    // Quit if there's nothing to scroll here
2910    if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
2911          dy && scroll.scrollHeight > scroll.clientHeight)) return;
2912
2913    // Webkit browsers on OS X abort momentum scrolls when the target
2914    // of the scroll event is removed from the scrollable element.
2915    // This hack (see related code in patchDisplay) makes sure the
2916    // element is kept around.
2917    if (dy && mac && webkit) {
2918      outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
2919        for (var i = 0; i < view.length; i++) {
2920          if (view[i].node == cur) {
2921            cm.display.currentWheelTarget = cur;
2922            break outer;
2923          }
2924        }
2925      }
2926    }
2927
2928    // On some browsers, horizontal scrolling will cause redraws to
2929    // happen before the gutter has been realigned, causing it to
2930    // wriggle around in a most unseemly way. When we have an
2931    // estimated pixels/delta value, we just handle horizontal
2932    // scrolling entirely here. It'll be slightly off from native, but
2933    // better than glitching out.
2934    if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
2935      if (dy)
2936        setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
2937      setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
2938      e_preventDefault(e);
2939      display.wheelStartX = null; // Abort measurement, if in progress
2940      return;
2941    }
2942
2943    // 'Project' the visible viewport to cover the area that is being
2944    // scrolled into view (if we know enough to estimate it).
2945    if (dy && wheelPixelsPerUnit != null) {
2946      var pixels = dy * wheelPixelsPerUnit;
2947      var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
2948      if (pixels < 0) top = Math.max(0, top + pixels - 50);
2949      else bot = Math.min(cm.doc.height, bot + pixels + 50);
2950      updateDisplay(cm, {top: top, bottom: bot});
2951    }
2952
2953    if (wheelSamples < 20) {
2954      if (display.wheelStartX == null) {
2955        display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
2956        display.wheelDX = dx; display.wheelDY = dy;
2957        setTimeout(function() {
2958          if (display.wheelStartX == null) return;
2959          var movedX = scroll.scrollLeft - display.wheelStartX;
2960          var movedY = scroll.scrollTop - display.wheelStartY;
2961          var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
2962            (movedX && display.wheelDX && movedX / display.wheelDX);
2963          display.wheelStartX = display.wheelStartY = null;
2964          if (!sample) return;
2965          wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
2966          ++wheelSamples;
2967        }, 200);
2968      } else {
2969        display.wheelDX += dx; display.wheelDY += dy;
2970      }
2971    }
2972  }
2973
2974  // KEY EVENTS
2975
2976  // Run a handler that was bound to a key.
2977  function doHandleBinding(cm, bound, dropShift) {
2978    if (typeof bound == "string") {
2979      bound = commands[bound];
2980      if (!bound) return false;
2981    }
2982    // Ensure previous input has been read, so that the handler sees a
2983    // consistent view of the document
2984    if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
2985    var prevShift = cm.display.shift, done = false;
2986    try {
2987      if (isReadOnly(cm)) cm.state.suppressEdits = true;
2988      if (dropShift) cm.display.shift = false;
2989      done = bound(cm) != Pass;
2990    } finally {
2991      cm.display.shift = prevShift;
2992      cm.state.suppressEdits = false;
2993    }
2994    return done;
2995  }
2996
2997  // Collect the currently active keymaps.
2998  function allKeyMaps(cm) {
2999    var maps = cm.state.keyMaps.slice(0);
3000    if (cm.options.extraKeys) maps.push(cm.options.extraKeys);
3001    maps.push(cm.options.keyMap);
3002    return maps;
3003  }
3004
3005  var maybeTransition;
3006  // Handle a key from the keydown event.
3007  function handleKeyBinding(cm, e) {
3008    // Handle automatic keymap transitions
3009    var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
3010    clearTimeout(maybeTransition);
3011    if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
3012      if (getKeyMap(cm.options.keyMap) == startMap) {
3013        cm.options.keyMap = (next.call ? next.call(null, cm) : next);
3014        keyMapChanged(cm);
3015      }
3016    }, 50);
3017
3018    var name = keyName(e, true), handled = false;
3019    if (!name) return false;
3020    var keymaps = allKeyMaps(cm);
3021
3022    if (e.shiftKey) {
3023      // First try to resolve full name (including 'Shift-'). Failing
3024      // that, see if there is a cursor-motion command (starting with
3025      // 'go') bound to the keyname without 'Shift-'.
3026      handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);})
3027             || lookupKey(name, keymaps, function(b) {
3028                  if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
3029                    return doHandleBinding(cm, b);
3030                });
3031    } else {
3032      handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); });
3033    }
3034
3035    if (handled) {
3036      e_preventDefault(e);
3037      restartBlink(cm);
3038      signalLater(cm, "keyHandled", cm, name, e);
3039    }
3040    return handled;
3041  }
3042
3043  // Handle a key from the keypress event
3044  function handleCharBinding(cm, e, ch) {
3045    var handled = lookupKey("'" + ch + "'", allKeyMaps(cm),
3046                            function(b) { return doHandleBinding(cm, b, true); });
3047    if (handled) {
3048      e_preventDefault(e);
3049      restartBlink(cm);
3050      signalLater(cm, "keyHandled", cm, "'" + ch + "'", e);
3051    }
3052    return handled;
3053  }
3054
3055  var lastStoppedKey = null;
3056  function onKeyDown(e) {
3057    var cm = this;
3058    ensureFocus(cm);
3059    if (signalDOMEvent(cm, e)) return;
3060    // IE does strange things with escape.
3061    if (ie_upto10 && e.keyCode == 27) e.returnValue = false;
3062    var code = e.keyCode;
3063    cm.display.shift = code == 16 || e.shiftKey;
3064    var handled = handleKeyBinding(cm, e);
3065    if (presto) {
3066      lastStoppedKey = handled ? code : null;
3067      // Opera has no cut event... we try to at least catch the key combo
3068      if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
3069        cm.replaceSelection("", null, "cut");
3070    }
3071
3072    // Turn mouse into crosshair when Alt is held on Mac.
3073    if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
3074      showCrossHair(cm);
3075  }
3076
3077  function showCrossHair(cm) {
3078    var lineDiv = cm.display.lineDiv;
3079    addClass(lineDiv, "CodeMirror-crosshair");
3080
3081    function up(e) {
3082      if (e.keyCode == 18 || !e.altKey) {
3083        rmClass(lineDiv, "CodeMirror-crosshair");
3084        off(document, "keyup", up);
3085        off(document, "mouseover", up);
3086      }
3087    }
3088    on(document, "keyup", up);
3089    on(document, "mouseover", up);
3090  }
3091
3092  function onKeyUp(e) {
3093    if (signalDOMEvent(this, e)) return;
3094    if (e.keyCode == 16) this.doc.sel.shift = false;
3095  }
3096
3097  function onKeyPress(e) {
3098    var cm = this;
3099    if (signalDOMEvent(cm, e)) return;
3100    var keyCode = e.keyCode, charCode = e.charCode;
3101    if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
3102    if (((presto && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
3103    var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
3104    if (handleCharBinding(cm, e, ch)) return;
3105    if (ie && !ie_upto8) cm.display.inputHasSelection = null;
3106    fastPoll(cm);
3107  }
3108
3109  // FOCUS/BLUR EVENTS
3110
3111  function onFocus(cm) {
3112    if (cm.options.readOnly == "nocursor") return;
3113    if (!cm.state.focused) {
3114      signal(cm, "focus", cm);
3115      cm.state.focused = true;
3116      addClass(cm.display.wrapper, "CodeMirror-focused");
3117      // The prevInput test prevents this from firing when a context
3118      // menu is closed (since the resetInput would kill the
3119      // select-all detection hack)
3120      if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
3121        resetInput(cm);
3122        if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #1730
3123      }
3124    }
3125    slowPoll(cm);
3126    restartBlink(cm);
3127  }
3128  function onBlur(cm) {
3129    if (cm.state.focused) {
3130      signal(cm, "blur", cm);
3131      cm.state.focused = false;
3132      rmClass(cm.display.wrapper, "CodeMirror-focused");
3133    }
3134    clearInterval(cm.display.blinker);
3135    setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
3136  }
3137
3138  // CONTEXT MENU HANDLING
3139
3140  // To make the context menu work, we need to briefly unhide the
3141  // textarea (making it as unobtrusive as possible) to let the
3142  // right-click take effect on it.
3143  function onContextMenu(cm, e) {
3144    if (signalDOMEvent(cm, e, "contextmenu")) return;
3145    var display = cm.display;
3146    if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return;
3147
3148    var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
3149    if (!pos || presto) return; // Opera is difficult.
3150
3151    // Reset the current text selection only if the click is done outside of the selection
3152    // and 'resetSelectionOnContextMenu' option is true.
3153    var reset = cm.options.resetSelectionOnContextMenu;
3154    if (reset && cm.doc.sel.contains(pos) == -1)
3155      operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
3156
3157    var oldCSS = display.input.style.cssText;
3158    display.inputDiv.style.position = "absolute";
3159    display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
3160      "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
3161      (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
3162      "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
3163    focusInput(cm);
3164    resetInput(cm);
3165    // Adds "Select all" to context menu in FF
3166    if (!cm.somethingSelected()) display.input.value = display.prevInput = " ";
3167    display.selForContextMenu = cm.doc.sel;
3168    clearTimeout(display.detectingSelectAll);
3169
3170    // Select-all will be greyed out if there's nothing to select, so
3171    // this adds a zero-width space so that we can later check whether
3172    // it got selected.
3173    function prepareSelectAllHack() {
3174      if (display.input.selectionStart != null) {
3175        var selected = cm.somethingSelected();
3176        var extval = display.input.value = "\u200b" + (selected ? display.input.value : "");
3177        display.prevInput = selected ? "" : "\u200b";
3178        display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
3179        // Re-set this, in case some other handler touched the
3180        // selection in the meantime.
3181        display.selForContextMenu = cm.doc.sel;
3182      }
3183    }
3184    function rehide() {
3185      display.inputDiv.style.position = "relative";
3186      display.input.style.cssText = oldCSS;
3187      if (ie_upto8) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
3188      slowPoll(cm);
3189
3190      // Try to detect the user choosing select-all
3191      if (display.input.selectionStart != null) {
3192        if (!ie || ie_upto8) prepareSelectAllHack();
3193        var i = 0, poll = function() {
3194          if (display.selForContextMenu == cm.doc.sel && display.input.selectionStart == 0)
3195            operation(cm, commands.selectAll)(cm);
3196          else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
3197          else resetInput(cm);
3198        };
3199        display.detectingSelectAll = setTimeout(poll, 200);
3200      }
3201    }
3202
3203    if (ie && !ie_upto8) prepareSelectAllHack();
3204    if (captureRightClick) {
3205      e_stop(e);
3206      var mouseup = function() {
3207        off(window, "mouseup", mouseup);
3208        setTimeout(rehide, 20);
3209      };
3210      on(window, "mouseup", mouseup);
3211    } else {
3212      setTimeout(rehide, 50);
3213    }
3214  }
3215
3216  function contextMenuInGutter(cm, e) {
3217    if (!hasHandler(cm, "gutterContextMenu")) return false;
3218    return gutterEvent(cm, e, "gutterContextMenu", false, signal);
3219  }
3220
3221  // UPDATING
3222
3223  // Compute the position of the end of a change (its 'to' property
3224  // refers to the pre-change end).
3225  var changeEnd = CodeMirror.changeEnd = function(change) {
3226    if (!change.text) return change.to;
3227    return Pos(change.from.line + change.text.length - 1,
3228               lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
3229  };
3230
3231  // Adjust a position to refer to the post-change position of the
3232  // same text, or the end of the change if the change covers it.
3233  function adjustForChange(pos, change) {
3234    if (cmp(pos, change.from) < 0) return pos;
3235    if (cmp(pos, change.to) <= 0) return changeEnd(change);
3236
3237    var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
3238    if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
3239    return Pos(line, ch);
3240  }
3241
3242  function computeSelAfterChange(doc, change) {
3243    var out = [];
3244    for (var i = 0; i < doc.sel.ranges.length; i++) {
3245      var range = doc.sel.ranges[i];
3246      out.push(new Range(adjustForChange(range.anchor, change),
3247                         adjustForChange(range.head, change)));
3248    }
3249    return normalizeSelection(out, doc.sel.primIndex);
3250  }
3251
3252  function offsetPos(pos, old, nw) {
3253    if (pos.line == old.line)
3254      return Pos(nw.line, pos.ch - old.ch + nw.ch);
3255    else
3256      return Pos(nw.line + (pos.line - old.line), pos.ch);
3257  }
3258
3259  // Used by replaceSelections to allow moving the selection to the
3260  // start or around the replaced test. Hint may be "start" or "around".
3261  function computeReplacedSel(doc, changes, hint) {
3262    var out = [];
3263    var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
3264    for (var i = 0; i < changes.length; i++) {
3265      var change = changes[i];
3266      var from = offsetPos(change.from, oldPrev, newPrev);
3267      var to = offsetPos(changeEnd(change), oldPrev, newPrev);
3268      oldPrev = change.to;
3269      newPrev = to;
3270      if (hint == "around") {
3271        var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
3272        out[i] = new Range(inv ? to : from, inv ? from : to);
3273      } else {
3274        out[i] = new Range(from, from);
3275      }
3276    }
3277    return new Selection(out, doc.sel.primIndex);
3278  }
3279
3280  // Allow "beforeChange" event handlers to influence a change
3281  function filterChange(doc, change, update) {
3282    var obj = {
3283      canceled: false,
3284      from: change.from,
3285      to: change.to,
3286      text: change.text,
3287      origin: change.origin,
3288      cancel: function() { this.canceled = true; }
3289    };
3290    if (update) obj.update = function(from, to, text, origin) {
3291      if (from) this.from = clipPos(doc, from);
3292      if (to) this.to = clipPos(doc, to);
3293      if (text) this.text = text;
3294      if (origin !== undefined) this.origin = origin;
3295    };
3296    signal(doc, "beforeChange", doc, obj);
3297    if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
3298
3299    if (obj.canceled) return null;
3300    return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
3301  }
3302
3303  // Apply a change to a document, and add it to the document's
3304  // history, and propagating it to all linked documents.
3305  function makeChange(doc, change, ignoreReadOnly) {
3306    if (doc.cm) {
3307      if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
3308      if (doc.cm.state.suppressEdits) return;
3309    }
3310
3311    if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
3312      change = filterChange(doc, change, true);
3313      if (!change) return;
3314    }
3315
3316    // Possibly split or suppress the update based on the presence
3317    // of read-only spans in its range.
3318    var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
3319    if (split) {
3320      for (var i = split.length - 1; i >= 0; --i)
3321        makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
3322    } else {
3323      makeChangeInner(doc, change);
3324    }
3325  }
3326
3327  function makeChangeInner(doc, change) {
3328    if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
3329    var selAfter = computeSelAfterChange(doc, change);
3330    addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
3331
3332    makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
3333    var rebased = [];
3334
3335    linkedDocs(doc, function(doc, sharedHist) {
3336      if (!sharedHist && indexOf(rebased, doc.history) == -1) {
3337        rebaseHist(doc.history, change);
3338        rebased.push(doc.history);
3339      }
3340      makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
3341    });
3342  }
3343
3344  // Revert a change stored in a document's history.
3345  function makeChangeFromHistory(doc, type, allowSelectionOnly) {
3346    if (doc.cm && doc.cm.state.suppressEdits) return;
3347
3348    var hist = doc.history, event, selAfter = doc.sel;
3349    var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
3350
3351    // Verify that there is a useable event (so that ctrl-z won't
3352    // needlessly clear selection events)
3353    for (var i = 0; i < source.length; i++) {
3354      event = source[i];
3355      if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
3356        break;
3357    }
3358    if (i == source.length) return;
3359    hist.lastOrigin = hist.lastSelOrigin = null;
3360
3361    for (;;) {
3362      event = source.pop();
3363      if (event.ranges) {
3364        pushSelectionToHistory(event, dest);
3365        if (allowSelectionOnly && !event.equals(doc.sel)) {
3366          setSelection(doc, event, {clearRedo: false});
3367          return;
3368        }
3369        selAfter = event;
3370      }
3371      else break;
3372    }
3373
3374    // Build up a reverse change object to add to the opposite history
3375    // stack (redo when undoing, and vice versa).
3376    var antiChanges = [];
3377    pushSelectionToHistory(selAfter, dest);
3378    dest.push({changes: antiChanges, generation: hist.generation});
3379    hist.generation = event.generation || ++hist.maxGeneration;
3380
3381    var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
3382
3383    for (var i = event.changes.length - 1; i >= 0; --i) {
3384      var change = event.changes[i];
3385      change.origin = type;
3386      if (filter && !filterChange(doc, change, false)) {
3387        source.length = 0;
3388        return;
3389      }
3390
3391      antiChanges.push(historyChangeFromChange(doc, change));
3392
3393      var after = i ? computeSelAfterChange(doc, change, null) : lst(source);
3394      makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
3395      if (!i && doc.cm) doc.cm.scrollIntoView(change);
3396      var rebased = [];
3397
3398      // Propagate to the linked documents
3399      linkedDocs(doc, function(doc, sharedHist) {
3400        if (!sharedHist && indexOf(rebased, doc.history) == -1) {
3401          rebaseHist(doc.history, change);
3402          rebased.push(doc.history);
3403        }
3404        makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
3405      });
3406    }
3407  }
3408
3409  // Sub-views need their line numbers shifted when text is added
3410  // above or below them in the parent document.
3411  function shiftDoc(doc, distance) {
3412    if (distance == 0) return;
3413    doc.first += distance;
3414    doc.sel = new Selection(map(doc.sel.ranges, function(range) {
3415      return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
3416                       Pos(range.head.line + distance, range.head.ch));
3417    }), doc.sel.primIndex);
3418    if (doc.cm) {
3419      regChange(doc.cm, doc.first, doc.first - distance, distance);
3420      for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
3421        regLineChange(doc.cm, l, "gutter");
3422    }
3423  }
3424
3425  // More lower-level change function, handling only a single document
3426  // (not linked ones).
3427  function makeChangeSingleDoc(doc, change, selAfter, spans) {
3428    if (doc.cm && !doc.cm.curOp)
3429      return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
3430
3431    if (change.to.line < doc.first) {
3432      shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
3433      return;
3434    }
3435    if (change.from.line > doc.lastLine()) return;
3436
3437    // Clip the change to the size of this doc
3438    if (change.from.line < doc.first) {
3439      var shift = change.text.length - 1 - (doc.first - change.from.line);
3440      shiftDoc(doc, shift);
3441      change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
3442                text: [lst(change.text)], origin: change.origin};
3443    }
3444    var last = doc.lastLine();
3445    if (change.to.line > last) {
3446      change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
3447                text: [change.text[0]], origin: change.origin};
3448    }
3449
3450    change.removed = getBetween(doc, change.from, change.to);
3451
3452    if (!selAfter) selAfter = computeSelAfterChange(doc, change, null);
3453    if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
3454    else updateDoc(doc, change, spans);
3455    setSelectionNoUndo(doc, selAfter, sel_dontScroll);
3456  }
3457
3458  // Handle the interaction of a change to a document with the editor
3459  // that this document is part of.
3460  function makeChangeSingleDocInEditor(cm, change, spans) {
3461    var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
3462
3463    var recomputeMaxLength = false, checkWidthStart = from.line;
3464    if (!cm.options.lineWrapping) {
3465      checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
3466      doc.iter(checkWidthStart, to.line + 1, function(line) {
3467        if (line == display.maxLine) {
3468          recomputeMaxLength = true;
3469          return true;
3470        }
3471      });
3472    }
3473
3474    if (doc.sel.contains(change.from, change.to) > -1)
3475      signalCursorActivity(cm);
3476
3477    updateDoc(doc, change, spans, estimateHeight(cm));
3478
3479    if (!cm.options.lineWrapping) {
3480      doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
3481        var len = lineLength(line);
3482        if (len > display.maxLineLength) {
3483          display.maxLine = line;
3484          display.maxLineLength = len;
3485          display.maxLineChanged = true;
3486          recomputeMaxLength = false;
3487        }
3488      });
3489      if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
3490    }
3491
3492    // Adjust frontier, schedule worker
3493    doc.frontier = Math.min(doc.frontier, from.line);
3494    startWorker(cm, 400);
3495
3496    var lendiff = change.text.length - (to.line - from.line) - 1;
3497    // Remember that these lines changed, for updating the display
3498    if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
3499      regLineChange(cm, from.line, "text");
3500    else
3501      regChange(cm, from.line, to.line + 1, lendiff);
3502
3503    var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
3504    if (changeHandler || changesHandler) {
3505      var obj = {
3506        from: from, to: to,
3507        text: change.text,
3508        removed: change.removed,
3509        origin: change.origin
3510      };
3511      if (changeHandler) signalLater(cm, "change", cm, obj);
3512      if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
3513    }
3514    cm.display.selForContextMenu = null;
3515  }
3516
3517  function replaceRange(doc, code, from, to, origin) {
3518    if (!to) to = from;
3519    if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
3520    if (typeof code == "string") code = splitLines(code);
3521    makeChange(doc, {from: from, to: to, text: code, origin: origin});
3522  }
3523
3524  // SCROLLING THINGS INTO VIEW
3525
3526  // If an editor sits on the top or bottom of the window, partially
3527  // scrolled out of view, this ensures that the cursor is visible.
3528  function maybeScrollWindow(cm, coords) {
3529    var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
3530    if (coords.top + box.top < 0) doScroll = true;
3531    else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
3532    if (doScroll != null && !phantom) {
3533      var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
3534                           (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
3535                           (coords.bottom - coords.top + scrollerCutOff) + "px; left: " +
3536                           coords.left + "px; width: 2px;");
3537      cm.display.lineSpace.appendChild(scrollNode);
3538      scrollNode.scrollIntoView(doScroll);
3539      cm.display.lineSpace.removeChild(scrollNode);
3540    }
3541  }
3542
3543  // Scroll a given position into view (immediately), verifying that
3544  // it actually became visible (as line heights are accurately
3545  // measured, the position of something may 'drift' during drawing).
3546  function scrollPosIntoView(cm, pos, end, margin) {
3547    if (margin == null) margin = 0;
3548    for (;;) {
3549      var changed = false, coords = cursorCoords(cm, pos);
3550      var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
3551      var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
3552                                         Math.min(coords.top, endCoords.top) - margin,
3553                                         Math.max(coords.left, endCoords.left),
3554                                         Math.max(coords.bottom, endCoords.bottom) + margin);
3555      var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
3556      if (scrollPos.scrollTop != null) {
3557        setScrollTop(cm, scrollPos.scrollTop);
3558        if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
3559      }
3560      if (scrollPos.scrollLeft != null) {
3561        setScrollLeft(cm, scrollPos.scrollLeft);
3562        if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
3563      }
3564      if (!changed) return coords;
3565    }
3566  }
3567
3568  // Scroll a given set of coordinates into view (immediately).
3569  function scrollIntoView(cm, x1, y1, x2, y2) {
3570    var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
3571    if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
3572    if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
3573  }
3574
3575  // Calculate a new scroll position needed to scroll the given
3576  // rectangle into view. Returns an object with scrollTop and
3577  // scrollLeft properties. When these are undefined, the
3578  // vertical/horizontal position does not need to be adjusted.
3579  function calculateScrollPos(cm, x1, y1, x2, y2) {
3580    var display = cm.display, snapMargin = textHeight(cm.display);
3581    if (y1 < 0) y1 = 0;
3582    var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
3583    var screen = display.scroller.clientHeight - scrollerCutOff, result = {};
3584    var docBottom = cm.doc.height + paddingVert(display);
3585    var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
3586    if (y1 < screentop) {
3587      result.scrollTop = atTop ? 0 : y1;
3588    } else if (y2 > screentop + screen) {
3589      var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
3590      if (newTop != screentop) result.scrollTop = newTop;
3591    }
3592
3593    var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
3594    var screenw = display.scroller.clientWidth - scrollerCutOff;
3595    x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
3596    var gutterw = display.gutters.offsetWidth;
3597    var atLeft = x1 < gutterw + 10;
3598    if (x1 < screenleft + gutterw || atLeft) {
3599      if (atLeft) x1 = 0;
3600      result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
3601    } else if (x2 > screenw + screenleft - 3) {
3602      result.scrollLeft = x2 + 10 - screenw;
3603    }
3604    return result;
3605  }
3606
3607  // Store a relative adjustment to the scroll position in the current
3608  // operation (to be applied when the operation finishes).
3609  function addToScrollPos(cm, left, top) {
3610    if (left != null || top != null) resolveScrollToPos(cm);
3611    if (left != null)
3612      cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
3613    if (top != null)
3614      cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
3615  }
3616
3617  // Make sure that at the end of the operation the current cursor is
3618  // shown.
3619  function ensureCursorVisible(cm) {
3620    resolveScrollToPos(cm);
3621    var cur = cm.getCursor(), from = cur, to = cur;
3622    if (!cm.options.lineWrapping) {
3623      from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
3624      to = Pos(cur.line, cur.ch + 1);
3625    }
3626    cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
3627  }
3628
3629  // When an operation has its scrollToPos property set, and another
3630  // scroll action is applied before the end of the operation, this
3631  // 'simulates' scrolling that position into view in a cheap way, so
3632  // that the effect of intermediate scroll commands is not ignored.
3633  function resolveScrollToPos(cm) {
3634    var range = cm.curOp.scrollToPos;
3635    if (range) {
3636      cm.curOp.scrollToPos = null;
3637      var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
3638      var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
3639                                    Math.min(from.top, to.top) - range.margin,
3640                                    Math.max(from.right, to.right),
3641                                    Math.max(from.bottom, to.bottom) + range.margin);
3642      cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
3643    }
3644  }
3645
3646  // API UTILITIES
3647
3648  // Indent the given line. The how parameter can be "smart",
3649  // "add"/null, "subtract", or "prev". When aggressive is false
3650  // (typically set to true for forced single-line indents), empty
3651  // lines are not indented, and places where the mode returns Pass
3652  // are left alone.
3653  function indentLine(cm, n, how, aggressive) {
3654    var doc = cm.doc, state;
3655    if (how == null) how = "add";
3656    if (how == "smart") {
3657      // Fall back to "prev" when the mode doesn't have an indentation
3658      // method.
3659      if (!cm.doc.mode.indent) how = "prev";
3660      else state = getStateBefore(cm, n);
3661    }
3662
3663    var tabSize = cm.options.tabSize;
3664    var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
3665    if (line.stateAfter) line.stateAfter = null;
3666    var curSpaceString = line.text.match(/^\s*/)[0], indentation;
3667    if (!aggressive && !/\S/.test(line.text)) {
3668      indentation = 0;
3669      how = "not";
3670    } else if (how == "smart") {
3671      indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
3672      if (indentation == Pass) {
3673        if (!aggressive) return;
3674        how = "prev";
3675      }
3676    }
3677    if (how == "prev") {
3678      if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
3679      else indentation = 0;
3680    } else if (how == "add") {
3681      indentation = curSpace + cm.options.indentUnit;
3682    } else if (how == "subtract") {
3683      indentation = curSpace - cm.options.indentUnit;
3684    } else if (typeof how == "number") {
3685      indentation = curSpace + how;
3686    }
3687    indentation = Math.max(0, indentation);
3688
3689    var indentString = "", pos = 0;
3690    if (cm.options.indentWithTabs)
3691      for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
3692    if (pos < indentation) indentString += spaceStr(indentation - pos);
3693
3694    if (indentString != curSpaceString) {
3695      replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
3696    } else {
3697      // Ensure that, if the cursor was in the whitespace at the start
3698      // of the line, it is moved to the end of that space.
3699      for (var i = 0; i < doc.sel.ranges.length; i++) {
3700        var range = doc.sel.ranges[i];
3701        if (range.head.line == n && range.head.ch < curSpaceString.length) {
3702          var pos = Pos(n, curSpaceString.length);
3703          replaceOneSelection(doc, i, new Range(pos, pos));
3704          break;
3705        }
3706      }
3707    }
3708    line.stateAfter = null;
3709  }
3710
3711  // Utility for applying a change to a line by handle or number,
3712  // returning the number and optionally registering the line as
3713  // changed.
3714  function changeLine(cm, handle, changeType, op) {
3715    var no = handle, line = handle, doc = cm.doc;
3716    if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
3717    else no = lineNo(handle);
3718    if (no == null) return null;
3719    if (op(line, no)) regLineChange(cm, no, changeType);
3720    return line;
3721  }
3722
3723  // Helper for deleting text near the selection(s), used to implement
3724  // backspace, delete, and similar functionality.
3725  function deleteNearSelection(cm, compute) {
3726    var ranges = cm.doc.sel.ranges, kill = [];
3727    // Build up a set of ranges to kill first, merging overlapping
3728    // ranges.
3729    for (var i = 0; i < ranges.length; i++) {
3730      var toKill = compute(ranges[i]);
3731      while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
3732        var replaced = kill.pop();
3733        if (cmp(replaced.from, toKill.from) < 0) {
3734          toKill.from = replaced.from;
3735          break;
3736        }
3737      }
3738      kill.push(toKill);
3739    }
3740    // Next, remove those actual ranges.
3741    runInOp(cm, function() {
3742      for (var i = kill.length - 1; i >= 0; i--)
3743        replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
3744      ensureCursorVisible(cm);
3745    });
3746  }
3747
3748  // Used for horizontal relative motion. Dir is -1 or 1 (left or
3749  // right), unit can be "char", "column" (like char, but doesn't
3750  // cross line boundaries), "word" (across next word), or "group" (to
3751  // the start of next group of word or non-word-non-whitespace
3752  // chars). The visually param controls whether, in right-to-left
3753  // text, direction 1 means to move towards the next index in the
3754  // string, or towards the character to the right of the current
3755  // position. The resulting position will have a hitSide=true
3756  // property if it reached the end of the document.
3757  function findPosH(doc, pos, dir, unit, visually) {
3758    var line = pos.line, ch = pos.ch, origDir = dir;
3759    var lineObj = getLine(doc, line);
3760    var possible = true;
3761    function findNextLine() {
3762      var l = line + dir;
3763      if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
3764      line = l;
3765      return lineObj = getLine(doc, l);
3766    }
3767    function moveOnce(boundToLine) {
3768      var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
3769      if (next == null) {
3770        if (!boundToLine && findNextLine()) {
3771          if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
3772          else ch = dir < 0 ? lineObj.text.length : 0;
3773        } else return (possible = false);
3774      } else ch = next;
3775      return true;
3776    }
3777
3778    if (unit == "char") moveOnce();
3779    else if (unit == "column") moveOnce(true);
3780    else if (unit == "word" || unit == "group") {
3781      var sawType = null, group = unit == "group";
3782      var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
3783      for (var first = true;; first = false) {
3784        if (dir < 0 && !moveOnce(!first)) break;
3785        var cur = lineObj.text.charAt(ch) || "\n";
3786        var type = isWordChar(cur, helper) ? "w"
3787          : group && cur == "\n" ? "n"
3788          : !group || /\s/.test(cur) ? null
3789          : "p";
3790        if (group && !first && !type) type = "s";
3791        if (sawType && sawType != type) {
3792          if (dir < 0) {dir = 1; moveOnce();}
3793          break;
3794        }
3795
3796        if (type) sawType = type;
3797        if (dir > 0 && !moveOnce(!first)) break;
3798      }
3799    }
3800    var result = skipAtomic(doc, Pos(line, ch), origDir, true);
3801    if (!possible) result.hitSide = true;
3802    return result;
3803  }
3804
3805  // For relative vertical movement. Dir may be -1 or 1. Unit can be
3806  // "page" or "line". The resulting position will have a hitSide=true
3807  // property if it reached the end of the document.
3808  function findPosV(cm, pos, dir, unit) {
3809    var doc = cm.doc, x = pos.left, y;
3810    if (unit == "page") {
3811      var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
3812      y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
3813    } else if (unit == "line") {
3814      y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
3815    }
3816    for (;;) {
3817      var target = coordsChar(cm, x, y);
3818      if (!target.outside) break;
3819      if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
3820      y += dir * 5;
3821    }
3822    return target;
3823  }
3824
3825  // Find the word at the given position (as returned by coordsChar).
3826  function findWordAt(cm, pos) {
3827    var doc = cm.doc, line = getLine(doc, pos.line).text;
3828    var start = pos.ch, end = pos.ch;
3829    if (line) {
3830      var helper = cm.getHelper(pos, "wordChars");
3831      if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
3832      var startChar = line.charAt(start);
3833      var check = isWordChar(startChar, helper)
3834        ? function(ch) { return isWordChar(ch, helper); }
3835        : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
3836        : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
3837      while (start > 0 && check(line.charAt(start - 1))) --start;
3838      while (end < line.length && check(line.charAt(end))) ++end;
3839    }
3840    return new Range(Pos(pos.line, start), Pos(pos.line, end));
3841  }
3842
3843  // EDITOR METHODS
3844
3845  // The publicly visible API. Note that methodOp(f) means
3846  // 'wrap f in an operation, performed on its `this` parameter'.
3847
3848  // This is not the complete set of editor methods. Most of the
3849  // methods defined on the Doc type are also injected into
3850  // CodeMirror.prototype, for backwards compatibility and
3851  // convenience.
3852
3853  CodeMirror.prototype = {
3854    constructor: CodeMirror,
3855    focus: function(){window.focus(); focusInput(this); fastPoll(this);},
3856
3857    setOption: function(option, value) {
3858      var options = this.options, old = options[option];
3859      if (options[option] == value && option != "mode") return;
3860      options[option] = value;
3861      if (optionHandlers.hasOwnProperty(option))
3862        operation(this, optionHandlers[option])(this, value, old);
3863    },
3864
3865    getOption: function(option) {return this.options[option];},
3866    getDoc: function() {return this.doc;},
3867
3868    addKeyMap: function(map, bottom) {
3869      this.state.keyMaps[bottom ? "push" : "unshift"](map);
3870    },
3871    removeKeyMap: function(map) {
3872      var maps = this.state.keyMaps;
3873      for (var i = 0; i < maps.length; ++i)
3874        if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map)) {
3875          maps.splice(i, 1);
3876          return true;
3877        }
3878    },
3879
3880    addOverlay: methodOp(function(spec, options) {
3881      var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
3882      if (mode.startState) throw new Error("Overlays may not be stateful.");
3883      this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
3884      this.state.modeGen++;
3885      regChange(this);
3886    }),
3887    removeOverlay: methodOp(function(spec) {
3888      var overlays = this.state.overlays;
3889      for (var i = 0; i < overlays.length; ++i) {
3890        var cur = overlays[i].modeSpec;
3891        if (cur == spec || typeof spec == "string" && cur.name == spec) {
3892          overlays.splice(i, 1);
3893          this.state.modeGen++;
3894          regChange(this);
3895          return;
3896        }
3897      }
3898    }),
3899
3900    indentLine: methodOp(function(n, dir, aggressive) {
3901      if (typeof dir != "string" && typeof dir != "number") {
3902        if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
3903        else dir = dir ? "add" : "subtract";
3904      }
3905      if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
3906    }),
3907    indentSelection: methodOp(function(how) {
3908      var ranges = this.doc.sel.ranges, end = -1;
3909      for (var i = 0; i < ranges.length; i++) {
3910        var range = ranges[i];
3911        if (!range.empty()) {
3912          var start = Math.max(end, range.from().line);
3913          var to = range.to();
3914          end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
3915          for (var j = start; j < end; ++j)
3916            indentLine(this, j, how);
3917        } else if (range.head.line > end) {
3918          indentLine(this, range.head.line, how, true);
3919          end = range.head.line;
3920          if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
3921        }
3922      }
3923    }),
3924
3925    // Fetch the parser token for a given character. Useful for hacks
3926    // that want to inspect the mode state (say, for completion).
3927    getTokenAt: function(pos, precise) {
3928      var doc = this.doc;
3929      pos = clipPos(doc, pos);
3930      var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode;
3931      var line = getLine(doc, pos.line);
3932      var stream = new StringStream(line.text, this.options.tabSize);
3933      while (stream.pos < pos.ch && !stream.eol()) {
3934        stream.start = stream.pos;
3935        var style = readToken(mode, stream, state);
3936      }
3937      return {start: stream.start,
3938              end: stream.pos,
3939              string: stream.current(),
3940              type: style || null,
3941              state: state};
3942    },
3943
3944    getTokenTypeAt: function(pos) {
3945      pos = clipPos(this.doc, pos);
3946      var styles = getLineStyles(this, getLine(this.doc, pos.line));
3947      var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
3948      var type;
3949      if (ch == 0) type = styles[2];
3950      else for (;;) {
3951        var mid = (before + after) >> 1;
3952        if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
3953        else if (styles[mid * 2 + 1] < ch) before = mid + 1;
3954        else { type = styles[mid * 2 + 2]; break; }
3955      }
3956      var cut = type ? type.indexOf("cm-overlay ") : -1;
3957      return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
3958    },
3959
3960    getModeAt: function(pos) {
3961      var mode = this.doc.mode;
3962      if (!mode.innerMode) return mode;
3963      return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
3964    },
3965
3966    getHelper: function(pos, type) {
3967      return this.getHelpers(pos, type)[0];
3968    },
3969
3970    getHelpers: function(pos, type) {
3971      var found = [];
3972      if (!helpers.hasOwnProperty(type)) return helpers;
3973      var help = helpers[type], mode = this.getModeAt(pos);
3974      if (typeof mode[type] == "string") {
3975        if (help[mode[type]]) found.push(help[mode[type]]);
3976      } else if (mode[type]) {
3977        for (var i = 0; i < mode[type].length; i++) {
3978          var val = help[mode[type][i]];
3979          if (val) found.push(val);
3980        }
3981      } else if (mode.helperType && help[mode.helperType]) {
3982        found.push(help[mode.helperType]);
3983      } else if (help[mode.name]) {
3984        found.push(help[mode.name]);
3985      }
3986      for (var i = 0; i < help._global.length; i++) {
3987        var cur = help._global[i];
3988        if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
3989          found.push(cur.val);
3990      }
3991      return found;
3992    },
3993
3994    getStateAfter: function(line, precise) {
3995      var doc = this.doc;
3996      line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
3997      return getStateBefore(this, line + 1, precise);
3998    },
3999
4000    cursorCoords: function(start, mode) {
4001      var pos, range = this.doc.sel.primary();
4002      if (start == null) pos = range.head;
4003      else if (typeof start == "object") pos = clipPos(this.doc, start);
4004      else pos = start ? range.from() : range.to();
4005      return cursorCoords(this, pos, mode || "page");
4006    },
4007
4008    charCoords: function(pos, mode) {
4009      return charCoords(this, clipPos(this.doc, pos), mode || "page");
4010    },
4011
4012    coordsChar: function(coords, mode) {
4013      coords = fromCoordSystem(this, coords, mode || "page");
4014      return coordsChar(this, coords.left, coords.top);
4015    },
4016
4017    lineAtHeight: function(height, mode) {
4018      height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
4019      return lineAtHeight(this.doc, height + this.display.viewOffset);
4020    },
4021    heightAtLine: function(line, mode) {
4022      var end = false, last = this.doc.first + this.doc.size - 1;
4023      if (line < this.doc.first) line = this.doc.first;
4024      else if (line > last) { line = last; end = true; }
4025      var lineObj = getLine(this.doc, line);
4026      return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
4027        (end ? this.doc.height - heightAtLine(lineObj) : 0);
4028    },
4029
4030    defaultTextHeight: function() { return textHeight(this.display); },
4031    defaultCharWidth: function() { return charWidth(this.display); },
4032
4033    setGutterMarker: methodOp(function(line, gutterID, value) {
4034      return changeLine(this, line, "gutter", function(line) {
4035        var markers = line.gutterMarkers || (line.gutterMarkers = {});
4036        markers[gutterID] = value;
4037        if (!value && isEmpty(markers)) line.gutterMarkers = null;
4038        return true;
4039      });
4040    }),
4041
4042    clearGutter: methodOp(function(gutterID) {
4043      var cm = this, doc = cm.doc, i = doc.first;
4044      doc.iter(function(line) {
4045        if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
4046          line.gutterMarkers[gutterID] = null;
4047          regLineChange(cm, i, "gutter");
4048          if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
4049        }
4050        ++i;
4051      });
4052    }),
4053
4054    addLineClass: methodOp(function(handle, where, cls) {
4055      return changeLine(this, handle, "class", function(line) {
4056        var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
4057        if (!line[prop]) line[prop] = cls;
4058        else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false;
4059        else line[prop] += " " + cls;
4060        return true;
4061      });
4062    }),
4063
4064    removeLineClass: methodOp(function(handle, where, cls) {
4065      return changeLine(this, handle, "class", function(line) {
4066        var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
4067        var cur = line[prop];
4068        if (!cur) return false;
4069        else if (cls == null) line[prop] = null;
4070        else {
4071          var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)"));
4072          if (!found) return false;
4073          var end = found.index + found[0].length;
4074          line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
4075        }
4076        return true;
4077      });
4078    }),
4079
4080    addLineWidget: methodOp(function(handle, node, options) {
4081      return addLineWidget(this, handle, node, options);
4082    }),
4083
4084    removeLineWidget: function(widget) { widget.clear(); },
4085
4086    lineInfo: function(line) {
4087      if (typeof line == "number") {
4088        if (!isLine(this.doc, line)) return null;
4089        var n = line;
4090        line = getLine(this.doc, line);
4091        if (!line) return null;
4092      } else {
4093        var n = lineNo(line);
4094        if (n == null) return null;
4095      }
4096      return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
4097              textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
4098              widgets: line.widgets};
4099    },
4100
4101    getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
4102
4103    addWidget: function(pos, node, scroll, vert, horiz) {
4104      var display = this.display;
4105      pos = cursorCoords(this, clipPos(this.doc, pos));
4106      var top = pos.bottom, left = pos.left;
4107      node.style.position = "absolute";
4108      display.sizer.appendChild(node);
4109      if (vert == "over") {
4110        top = pos.top;
4111      } else if (vert == "above" || vert == "near") {
4112        var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
4113        hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
4114        // Default to positioning above (if specified and possible); otherwise default to positioning below
4115        if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
4116          top = pos.top - node.offsetHeight;
4117        else if (pos.bottom + node.offsetHeight <= vspace)
4118          top = pos.bottom;
4119        if (left + node.offsetWidth > hspace)
4120          left = hspace - node.offsetWidth;
4121      }
4122      node.style.top = top + "px";
4123      node.style.left = node.style.right = "";
4124      if (horiz == "right") {
4125        left = display.sizer.clientWidth - node.offsetWidth;
4126        node.style.right = "0px";
4127      } else {
4128        if (horiz == "left") left = 0;
4129        else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
4130        node.style.left = left + "px";
4131      }
4132      if (scroll)
4133        scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
4134    },
4135
4136    triggerOnKeyDown: methodOp(onKeyDown),
4137    triggerOnKeyPress: methodOp(onKeyPress),
4138    triggerOnKeyUp: methodOp(onKeyUp),
4139
4140    execCommand: function(cmd) {
4141      if (commands.hasOwnProperty(cmd))
4142        return commands[cmd](this);
4143    },
4144
4145    findPosH: function(from, amount, unit, visually) {
4146      var dir = 1;
4147      if (amount < 0) { dir = -1; amount = -amount; }
4148      for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
4149        cur = findPosH(this.doc, cur, dir, unit, visually);
4150        if (cur.hitSide) break;
4151      }
4152      return cur;
4153    },
4154
4155    moveH: methodOp(function(dir, unit) {
4156      var cm = this;
4157      cm.extendSelectionsBy(function(range) {
4158        if (cm.display.shift || cm.doc.extend || range.empty())
4159          return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
4160        else
4161          return dir < 0 ? range.from() : range.to();
4162      }, sel_move);
4163    }),
4164
4165    deleteH: methodOp(function(dir, unit) {
4166      var sel = this.doc.sel, doc = this.doc;
4167      if (sel.somethingSelected())
4168        doc.replaceSelection("", null, "+delete");
4169      else
4170        deleteNearSelection(this, function(range) {
4171          var other = findPosH(doc, range.head, dir, unit, false);
4172          return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
4173        });
4174    }),
4175
4176    findPosV: function(from, amount, unit, goalColumn) {
4177      var dir = 1, x = goalColumn;
4178      if (amount < 0) { dir = -1; amount = -amount; }
4179      for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
4180        var coords = cursorCoords(this, cur, "div");
4181        if (x == null) x = coords.left;
4182        else coords.left = x;
4183        cur = findPosV(this, coords, dir, unit);
4184        if (cur.hitSide) break;
4185      }
4186      return cur;
4187    },
4188
4189    moveV: methodOp(function(dir, unit) {
4190      var cm = this, doc = this.doc, goals = [];
4191      var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
4192      doc.extendSelectionsBy(function(range) {
4193        if (collapse)
4194          return dir < 0 ? range.from() : range.to();
4195        var headPos = cursorCoords(cm, range.head, "div");
4196        if (range.goalColumn != null) headPos.left = range.goalColumn;
4197        goals.push(headPos.left);
4198        var pos = findPosV(cm, headPos, dir, unit);
4199        if (unit == "page" && range == doc.sel.primary())
4200          addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
4201        return pos;
4202      }, sel_move);
4203      if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
4204        doc.sel.ranges[i].goalColumn = goals[i];
4205    }),
4206
4207    toggleOverwrite: function(value) {
4208      if (value != null && value == this.state.overwrite) return;
4209      if (this.state.overwrite = !this.state.overwrite)
4210        addClass(this.display.cursorDiv, "CodeMirror-overwrite");
4211      else
4212        rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
4213
4214      signal(this, "overwriteToggle", this, this.state.overwrite);
4215    },
4216    hasFocus: function() { return activeElt() == this.display.input; },
4217
4218    scrollTo: methodOp(function(x, y) {
4219      if (x != null || y != null) resolveScrollToPos(this);
4220      if (x != null) this.curOp.scrollLeft = x;
4221      if (y != null) this.curOp.scrollTop = y;
4222    }),
4223    getScrollInfo: function() {
4224      var scroller = this.display.scroller, co = scrollerCutOff;
4225      return {left: scroller.scrollLeft, top: scroller.scrollTop,
4226              height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,
4227              clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};
4228    },
4229
4230    scrollIntoView: methodOp(function(range, margin) {
4231      if (range == null) {
4232        range = {from: this.doc.sel.primary().head, to: null};
4233        if (margin == null) margin = this.options.cursorScrollMargin;
4234      } else if (typeof range == "number") {
4235        range = {from: Pos(range, 0), to: null};
4236      } else if (range.from == null) {
4237        range = {from: range, to: null};
4238      }
4239      if (!range.to) range.to = range.from;
4240      range.margin = margin || 0;
4241
4242      if (range.from.line != null) {
4243        resolveScrollToPos(this);
4244        this.curOp.scrollToPos = range;
4245      } else {
4246        var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
4247                                      Math.min(range.from.top, range.to.top) - range.margin,
4248                                      Math.max(range.from.right, range.to.right),
4249                                      Math.max(range.from.bottom, range.to.bottom) + range.margin);
4250        this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
4251      }
4252    }),
4253
4254    setSize: methodOp(function(width, height) {
4255      function interpret(val) {
4256        return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
4257      }
4258      if (width != null) this.display.wrapper.style.width = interpret(width);
4259      if (height != null) this.display.wrapper.style.height = interpret(height);
4260      if (this.options.lineWrapping) clearLineMeasurementCache(this);
4261      this.curOp.forceUpdate = true;
4262      signal(this, "refresh", this);
4263    }),
4264
4265    operation: function(f){return runInOp(this, f);},
4266
4267    refresh: methodOp(function() {
4268      var oldHeight = this.display.cachedTextHeight;
4269      regChange(this);
4270      this.curOp.forceUpdate = true;
4271      clearCaches(this);
4272      this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
4273      updateGutterSpace(this);
4274      if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
4275        estimateLineHeights(this);
4276      signal(this, "refresh", this);
4277    }),
4278
4279    swapDoc: methodOp(function(doc) {
4280      var old = this.doc;
4281      old.cm = null;
4282      attachDoc(this, doc);
4283      clearCaches(this);
4284      resetInput(this);
4285      this.scrollTo(doc.scrollLeft, doc.scrollTop);
4286      signalLater(this, "swapDoc", this, old);
4287      return old;
4288    }),
4289
4290    getInputField: function(){return this.display.input;},
4291    getWrapperElement: function(){return this.display.wrapper;},
4292    getScrollerElement: function(){return this.display.scroller;},
4293    getGutterElement: function(){return this.display.gutters;}
4294  };
4295  eventMixin(CodeMirror);
4296
4297  // OPTION DEFAULTS
4298
4299  // The default configuration options.
4300  var defaults = CodeMirror.defaults = {};
4301  // Functions to run when options are changed.
4302  var optionHandlers = CodeMirror.optionHandlers = {};
4303
4304  function option(name, deflt, handle, notOnInit) {
4305    CodeMirror.defaults[name] = deflt;
4306    if (handle) optionHandlers[name] =
4307      notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
4308  }
4309
4310  // Passed to option handlers when there is no old value.
4311  var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
4312
4313  // These two are, on init, called from the constructor because they
4314  // have to be initialized before the editor can start at all.
4315  option("value", "", function(cm, val) {
4316    cm.setValue(val);
4317  }, true);
4318  option("mode", null, function(cm, val) {
4319    cm.doc.modeOption = val;
4320    loadMode(cm);
4321  }, true);
4322
4323  option("indentUnit", 2, loadMode, true);
4324  option("indentWithTabs", false);
4325  option("smartIndent", true);
4326  option("tabSize", 4, function(cm) {
4327    resetModeState(cm);
4328    clearCaches(cm);
4329    regChange(cm);
4330  }, true);
4331  option("specialChars", /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\ufeff]/g, function(cm, val) {
4332    cm.options.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
4333    cm.refresh();
4334  }, true);
4335  option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
4336  option("electricChars", true);
4337  option("rtlMoveVisually", !windows);
4338  option("wholeLineUpdateBefore", true);
4339
4340  option("theme", "default", function(cm) {
4341    themeChanged(cm);
4342    guttersChanged(cm);
4343  }, true);
4344  option("keyMap", "default", keyMapChanged);
4345  option("extraKeys", null);
4346
4347  option("lineWrapping", false, wrappingChanged, true);
4348  option("gutters", [], function(cm) {
4349    setGuttersForLineNumbers(cm.options);
4350    guttersChanged(cm);
4351  }, true);
4352  option("fixedGutter", true, function(cm, val) {
4353    cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
4354    cm.refresh();
4355  }, true);
4356  option("coverGutterNextToScrollbar", false, updateScrollbars, true);
4357  option("lineNumbers", false, function(cm) {
4358    setGuttersForLineNumbers(cm.options);
4359    guttersChanged(cm);
4360  }, true);
4361  option("firstLineNumber", 1, guttersChanged, true);
4362  option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
4363  option("showCursorWhenSelecting", false, updateSelection, true);
4364
4365  option("resetSelectionOnContextMenu", true);
4366
4367  option("readOnly", false, function(cm, val) {
4368    if (val == "nocursor") {
4369      onBlur(cm);
4370      cm.display.input.blur();
4371      cm.display.disabled = true;
4372    } else {
4373      cm.display.disabled = false;
4374      if (!val) resetInput(cm);
4375    }
4376  });
4377  option("disableInput", false, function(cm, val) {if (!val) resetInput(cm);}, true);
4378  option("dragDrop", true);
4379
4380  option("cursorBlinkRate", 530);
4381  option("cursorScrollMargin", 0);
4382  option("cursorHeight", 1);
4383  option("workTime", 100);
4384  option("workDelay", 100);
4385  option("flattenSpans", true, resetModeState, true);
4386  option("addModeClass", false, resetModeState, true);
4387  option("pollInterval", 100);
4388  option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
4389  option("historyEventDelay", 1250);
4390  option("viewportMargin", 10, function(cm){cm.refresh();}, true);
4391  option("maxHighlightLength", 10000, resetModeState, true);
4392  option("moveInputWithCursor", true, function(cm, val) {
4393    if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0;
4394  });
4395
4396  option("tabindex", null, function(cm, val) {
4397    cm.display.input.tabIndex = val || "";
4398  });
4399  option("autofocus", null);
4400
4401  // MODE DEFINITION AND QUERYING
4402
4403  // Known modes, by name and by MIME
4404  var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
4405
4406  // Extra arguments are stored as the mode's dependencies, which is
4407  // used by (legacy) mechanisms like loadmode.js to automatically
4408  // load a mode. (Preferred mechanism is the require/define calls.)
4409  CodeMirror.defineMode = function(name, mode) {
4410    if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
4411    if (arguments.length > 2) {
4412      mode.dependencies = [];
4413      for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
4414    }
4415    modes[name] = mode;
4416  };
4417
4418  CodeMirror.defineMIME = function(mime, spec) {
4419    mimeModes[mime] = spec;
4420  };
4421
4422  // Given a MIME type, a {name, ...options} config object, or a name
4423  // string, return a mode config object.
4424  CodeMirror.resolveMode = function(spec) {
4425    if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
4426      spec = mimeModes[spec];
4427    } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
4428      var found = mimeModes[spec.name];
4429      if (typeof found == "string") found = {name: found};
4430      spec = createObj(found, spec);
4431      spec.name = found.name;
4432    } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
4433      return CodeMirror.resolveMode("application/xml");
4434    }
4435    if (typeof spec == "string") return {name: spec};
4436    else return spec || {name: "null"};
4437  };
4438
4439  // Given a mode spec (anything that resolveMode accepts), find and
4440  // initialize an actual mode object.
4441  CodeMirror.getMode = function(options, spec) {
4442    var spec = CodeMirror.resolveMode(spec);
4443    var mfactory = modes[spec.name];
4444    if (!mfactory) return CodeMirror.getMode(options, "text/plain");
4445    var modeObj = mfactory(options, spec);
4446    if (modeExtensions.hasOwnProperty(spec.name)) {
4447      var exts = modeExtensions[spec.name];
4448      for (var prop in exts) {
4449        if (!exts.hasOwnProperty(prop)) continue;
4450        if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
4451        modeObj[prop] = exts[prop];
4452      }
4453    }
4454    modeObj.name = spec.name;
4455    if (spec.helperType) modeObj.helperType = spec.helperType;
4456    if (spec.modeProps) for (var prop in spec.modeProps)
4457      modeObj[prop] = spec.modeProps[prop];
4458
4459    return modeObj;
4460  };
4461
4462  // Minimal default mode.
4463  CodeMirror.defineMode("null", function() {
4464    return {token: function(stream) {stream.skipToEnd();}};
4465  });
4466  CodeMirror.defineMIME("text/plain", "null");
4467
4468  // This can be used to attach properties to mode objects from
4469  // outside the actual mode definition.
4470  var modeExtensions = CodeMirror.modeExtensions = {};
4471  CodeMirror.extendMode = function(mode, properties) {
4472    var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
4473    copyObj(properties, exts);
4474  };
4475
4476  // EXTENSIONS
4477
4478  CodeMirror.defineExtension = function(name, func) {
4479    CodeMirror.prototype[name] = func;
4480  };
4481  CodeMirror.defineDocExtension = function(name, func) {
4482    Doc.prototype[name] = func;
4483  };
4484  CodeMirror.defineOption = option;
4485
4486  var initHooks = [];
4487  CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
4488
4489  var helpers = CodeMirror.helpers = {};
4490  CodeMirror.registerHelper = function(type, name, value) {
4491    if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
4492    helpers[type][name] = value;
4493  };
4494  CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
4495    CodeMirror.registerHelper(type, name, value);
4496    helpers[type]._global.push({pred: predicate, val: value});
4497  };
4498
4499  // MODE STATE HANDLING
4500
4501  // Utility functions for working with state. Exported because nested
4502  // modes need to do this for their inner modes.
4503
4504  var copyState = CodeMirror.copyState = function(mode, state) {
4505    if (state === true) return state;
4506    if (mode.copyState) return mode.copyState(state);
4507    var nstate = {};
4508    for (var n in state) {
4509      var val = state[n];
4510      if (val instanceof Array) val = val.concat([]);
4511      nstate[n] = val;
4512    }
4513    return nstate;
4514  };
4515
4516  var startState = CodeMirror.startState = function(mode, a1, a2) {
4517    return mode.startState ? mode.startState(a1, a2) : true;
4518  };
4519
4520  // Given a mode and a state (for that mode), find the inner mode and
4521  // state at the position that the state refers to.
4522  CodeMirror.innerMode = function(mode, state) {
4523    while (mode.innerMode) {
4524      var info = mode.innerMode(state);
4525      if (!info || info.mode == mode) break;
4526      state = info.state;
4527      mode = info.mode;
4528    }
4529    return info || {mode: mode, state: state};
4530  };
4531
4532  // STANDARD COMMANDS
4533
4534  // Commands are parameter-less actions that can be performed on an
4535  // editor, mostly used for keybindings.
4536  var commands = CodeMirror.commands = {
4537    selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
4538    singleSelection: function(cm) {
4539      cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
4540    },
4541    killLine: function(cm) {
4542      deleteNearSelection(cm, function(range) {
4543        if (range.empty()) {
4544          var len = getLine(cm.doc, range.head.line).text.length;
4545          if (range.head.ch == len && range.head.line < cm.lastLine())
4546            return {from: range.head, to: Pos(range.head.line + 1, 0)};
4547          else
4548            return {from: range.head, to: Pos(range.head.line, len)};
4549        } else {
4550          return {from: range.from(), to: range.to()};
4551        }
4552      });
4553    },
4554    deleteLine: function(cm) {
4555      deleteNearSelection(cm, function(range) {
4556        return {from: Pos(range.from().line, 0),
4557                to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
4558      });
4559    },
4560    delLineLeft: function(cm) {
4561      deleteNearSelection(cm, function(range) {
4562        return {from: Pos(range.from().line, 0), to: range.from()};
4563      });
4564    },
4565    undo: function(cm) {cm.undo();},
4566    redo: function(cm) {cm.redo();},
4567    undoSelection: function(cm) {cm.undoSelection();},
4568    redoSelection: function(cm) {cm.redoSelection();},
4569    goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
4570    goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
4571    goLineStart: function(cm) {
4572      cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); }, sel_move);
4573    },
4574    goLineStartSmart: function(cm) {
4575      cm.extendSelectionsBy(function(range) {
4576        var start = lineStart(cm, range.head.line);
4577        var line = cm.getLineHandle(start.line);
4578        var order = getOrder(line);
4579        if (!order || order[0].level == 0) {
4580          var firstNonWS = Math.max(0, line.text.search(/\S/));
4581          var inWS = range.head.line == start.line && range.head.ch <= firstNonWS && range.head.ch;
4582          return Pos(start.line, inWS ? 0 : firstNonWS);
4583        }
4584        return start;
4585      }, sel_move);
4586    },
4587    goLineEnd: function(cm) {
4588      cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); }, sel_move);
4589    },
4590    goLineRight: function(cm) {
4591      cm.extendSelectionsBy(function(range) {
4592        var top = cm.charCoords(range.head, "div").top + 5;
4593        return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
4594      }, sel_move);
4595    },
4596    goLineLeft: function(cm) {
4597      cm.extendSelectionsBy(function(range) {
4598        var top = cm.charCoords(range.head, "div").top + 5;
4599        return cm.coordsChar({left: 0, top: top}, "div");
4600      }, sel_move);
4601    },
4602    goLineUp: function(cm) {cm.moveV(-1, "line");},
4603    goLineDown: function(cm) {cm.moveV(1, "line");},
4604    goPageUp: function(cm) {cm.moveV(-1, "page");},
4605    goPageDown: function(cm) {cm.moveV(1, "page");},
4606    goCharLeft: function(cm) {cm.moveH(-1, "char");},
4607    goCharRight: function(cm) {cm.moveH(1, "char");},
4608    goColumnLeft: function(cm) {cm.moveH(-1, "column");},
4609    goColumnRight: function(cm) {cm.moveH(1, "column");},
4610    goWordLeft: function(cm) {cm.moveH(-1, "word");},
4611    goGroupRight: function(cm) {cm.moveH(1, "group");},
4612    goGroupLeft: function(cm) {cm.moveH(-1, "group");},
4613    goWordRight: function(cm) {cm.moveH(1, "word");},
4614    delCharBefore: function(cm) {cm.deleteH(-1, "char");},
4615    delCharAfter: function(cm) {cm.deleteH(1, "char");},
4616    delWordBefore: function(cm) {cm.deleteH(-1, "word");},
4617    delWordAfter: function(cm) {cm.deleteH(1, "word");},
4618    delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
4619    delGroupAfter: function(cm) {cm.deleteH(1, "group");},
4620    indentAuto: function(cm) {cm.indentSelection("smart");},
4621    indentMore: function(cm) {cm.indentSelection("add");},
4622    indentLess: function(cm) {cm.indentSelection("subtract");},
4623    insertTab: function(cm) {cm.replaceSelection("\t");},
4624    insertSoftTab: function(cm) {
4625      var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
4626      for (var i = 0; i < ranges.length; i++) {
4627        var pos = ranges[i].from();
4628        var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
4629        spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
4630      }
4631      cm.replaceSelections(spaces);
4632    },
4633    defaultTab: function(cm) {
4634      if (cm.somethingSelected()) cm.indentSelection("add");
4635      else cm.execCommand("insertTab");
4636    },
4637    transposeChars: function(cm) {
4638      runInOp(cm, function() {
4639        var ranges = cm.listSelections(), newSel = [];
4640        for (var i = 0; i < ranges.length; i++) {
4641          var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
4642          if (line) {
4643            if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
4644            if (cur.ch > 0) {
4645              cur = new Pos(cur.line, cur.ch + 1);
4646              cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
4647                              Pos(cur.line, cur.ch - 2), cur, "+transpose");
4648            } else if (cur.line > cm.doc.first) {
4649              var prev = getLine(cm.doc, cur.line - 1).text;
4650              if (prev)
4651                cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1),
4652                                Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
4653            }
4654          }
4655          newSel.push(new Range(cur, cur));
4656        }
4657        cm.setSelections(newSel);
4658      });
4659    },
4660    newlineAndIndent: function(cm) {
4661      runInOp(cm, function() {
4662        var len = cm.listSelections().length;
4663        for (var i = 0; i < len; i++) {
4664          var range = cm.listSelections()[i];
4665          cm.replaceRange("\n", range.anchor, range.head, "+input");
4666          cm.indentLine(range.from().line + 1, null, true);
4667          ensureCursorVisible(cm);
4668        }
4669      });
4670    },
4671    toggleOverwrite: function(cm) {cm.toggleOverwrite();}
4672  };
4673
4674  // STANDARD KEYMAPS
4675
4676  var keyMap = CodeMirror.keyMap = {};
4677  keyMap.basic = {
4678    "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
4679    "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
4680    "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
4681    "Tab": "defaultTab", "Shift-Tab": "indentAuto",
4682    "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
4683    "Esc": "singleSelection"
4684  };
4685  // Note that the save and find-related commands aren't defined by
4686  // default. User code or addons can define them. Unknown commands
4687  // are simply ignored.
4688  keyMap.pcDefault = {
4689    "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
4690    "Ctrl-Home": "goDocStart", "Ctrl-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
4691    "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
4692    "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
4693    "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
4694    "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
4695    "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
4696    fallthrough: "basic"
4697  };
4698  keyMap.macDefault = {
4699    "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
4700    "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
4701    "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delGroupBefore",
4702    "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
4703    "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
4704    "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft",
4705    "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection",
4706    fallthrough: ["basic", "emacsy"]
4707  };
4708  // Very basic readline/emacs-style bindings, which are standard on Mac.
4709  keyMap.emacsy = {
4710    "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
4711    "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
4712    "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
4713    "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
4714  };
4715  keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
4716
4717  // KEYMAP DISPATCH
4718
4719  function getKeyMap(val) {
4720    if (typeof val == "string") return keyMap[val];
4721    else return val;
4722  }
4723
4724  // Given an array of keymaps and a key name, call handle on any
4725  // bindings found, until that returns a truthy value, at which point
4726  // we consider the key handled. Implements things like binding a key
4727  // to false stopping further handling and keymap fallthrough.
4728  var lookupKey = CodeMirror.lookupKey = function(name, maps, handle) {
4729    function lookup(map) {
4730      map = getKeyMap(map);
4731      var found = map[name];
4732      if (found === false) return "stop";
4733      if (found != null && handle(found)) return true;
4734      if (map.nofallthrough) return "stop";
4735
4736      var fallthrough = map.fallthrough;
4737      if (fallthrough == null) return false;
4738      if (Object.prototype.toString.call(fallthrough) != "[object Array]")
4739        return lookup(fallthrough);
4740      for (var i = 0; i < fallthrough.length; ++i) {
4741        var done = lookup(fallthrough[i]);
4742        if (done) return done;
4743      }
4744      return false;
4745    }
4746
4747    for (var i = 0; i < maps.length; ++i) {
4748      var done = lookup(maps[i]);
4749      if (done) return done != "stop";
4750    }
4751  };
4752
4753  // Modifier key presses don't count as 'real' key presses for the
4754  // purpose of keymap fallthrough.
4755  var isModifierKey = CodeMirror.isModifierKey = function(event) {
4756    var name = keyNames[event.keyCode];
4757    return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
4758  };
4759
4760  // Look up the name of a key as indicated by an event object.
4761  var keyName = CodeMirror.keyName = function(event, noShift) {
4762    if (presto && event.keyCode == 34 && event["char"]) return false;
4763    var name = keyNames[event.keyCode];
4764    if (name == null || event.altGraphKey) return false;
4765    if (event.altKey) name = "Alt-" + name;
4766    if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name;
4767    if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name;
4768    if (!noShift && event.shiftKey) name = "Shift-" + name;
4769    return name;
4770  };
4771
4772  // FROMTEXTAREA
4773
4774  CodeMirror.fromTextArea = function(textarea, options) {
4775    if (!options) options = {};
4776    options.value = textarea.value;
4777    if (!options.tabindex && textarea.tabindex)
4778      options.tabindex = textarea.tabindex;
4779    if (!options.placeholder && textarea.placeholder)
4780      options.placeholder = textarea.placeholder;
4781    // Set autofocus to true if this textarea is focused, or if it has
4782    // autofocus and no other element is focused.
4783    if (options.autofocus == null) {
4784      var hasFocus = activeElt();
4785      options.autofocus = hasFocus == textarea ||
4786        textarea.getAttribute("autofocus") != null && hasFocus == document.body;
4787    }
4788
4789    function save() {textarea.value = cm.getValue();}
4790    if (textarea.form) {
4791      on(textarea.form, "submit", save);
4792      // Deplorable hack to make the submit method do the right thing.
4793      if (!options.leaveSubmitMethodAlone) {
4794        var form = textarea.form, realSubmit = form.submit;
4795        try {
4796          var wrappedSubmit = form.submit = function() {
4797            save();
4798            form.submit = realSubmit;
4799            form.submit();
4800            form.submit = wrappedSubmit;
4801          };
4802        } catch(e) {}
4803      }
4804    }
4805
4806    textarea.style.display = "none";
4807    var cm = CodeMirror(function(node) {
4808      textarea.parentNode.insertBefore(node, textarea.nextSibling);
4809    }, options);
4810    cm.save = save;
4811    cm.getTextArea = function() { return textarea; };
4812    cm.toTextArea = function() {
4813      save();
4814      textarea.parentNode.removeChild(cm.getWrapperElement());
4815      textarea.style.display = "";
4816      if (textarea.form) {
4817        off(textarea.form, "submit", save);
4818        if (typeof textarea.form.submit == "function")
4819          textarea.form.submit = realSubmit;
4820      }
4821    };
4822    return cm;
4823  };
4824
4825  // STRING STREAM
4826
4827  // Fed to the mode parsers, provides helper functions to make
4828  // parsers more succinct.
4829
4830  var StringStream = CodeMirror.StringStream = function(string, tabSize) {
4831    this.pos = this.start = 0;
4832    this.string = string;
4833    this.tabSize = tabSize || 8;
4834    this.lastColumnPos = this.lastColumnValue = 0;
4835    this.lineStart = 0;
4836  };
4837
4838  StringStream.prototype = {
4839    eol: function() {return this.pos >= this.string.length;},
4840    sol: function() {return this.pos == this.lineStart;},
4841    peek: function() {return this.string.charAt(this.pos) || undefined;},
4842    next: function() {
4843      if (this.pos < this.string.length)
4844        return this.string.charAt(this.pos++);
4845    },
4846    eat: function(match) {
4847      var ch = this.string.charAt(this.pos);
4848      if (typeof match == "string") var ok = ch == match;
4849      else var ok = ch && (match.test ? match.test(ch) : match(ch));
4850      if (ok) {++this.pos; return ch;}
4851    },
4852    eatWhile: function(match) {
4853      var start = this.pos;
4854      while (this.eat(match)){}
4855      return this.pos > start;
4856    },
4857    eatSpace: function() {
4858      var start = this.pos;
4859      while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
4860      return this.pos > start;
4861    },
4862    skipToEnd: function() {this.pos = this.string.length;},
4863    skipTo: function(ch) {
4864      var found = this.string.indexOf(ch, this.pos);
4865      if (found > -1) {this.pos = found; return true;}
4866    },
4867    backUp: function(n) {this.pos -= n;},
4868    column: function() {
4869      if (this.lastColumnPos < this.start) {
4870        this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
4871        this.lastColumnPos = this.start;
4872      }
4873      return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
4874    },
4875    indentation: function() {
4876      return countColumn(this.string, null, this.tabSize) -
4877        (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
4878    },
4879    match: function(pattern, consume, caseInsensitive) {
4880      if (typeof pattern == "string") {
4881        var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
4882        var substr = this.string.substr(this.pos, pattern.length);
4883        if (cased(substr) == cased(pattern)) {
4884          if (consume !== false) this.pos += pattern.length;
4885          return true;
4886        }
4887      } else {
4888        var match = this.string.slice(this.pos).match(pattern);
4889        if (match && match.index > 0) return null;
4890        if (match && consume !== false) this.pos += match[0].length;
4891        return match;
4892      }
4893    },
4894    current: function(){return this.string.slice(this.start, this.pos);},
4895    hideFirstChars: function(n, inner) {
4896      this.lineStart += n;
4897      try { return inner(); }
4898      finally { this.lineStart -= n; }
4899    }
4900  };
4901
4902  // TEXTMARKERS
4903
4904  // Created with markText and setBookmark methods. A TextMarker is a
4905  // handle that can be used to clear or find a marked position in the
4906  // document. Line objects hold arrays (markedSpans) containing
4907  // {from, to, marker} object pointing to such marker objects, and
4908  // indicating that such a marker is present on that line. Multiple
4909  // lines may point to the same marker when it spans across lines.
4910  // The spans will have null for their from/to properties when the
4911  // marker continues beyond the start/end of the line. Markers have
4912  // links back to the lines they currently touch.
4913
4914  var TextMarker = CodeMirror.TextMarker = function(doc, type) {
4915    this.lines = [];
4916    this.type = type;
4917    this.doc = doc;
4918  };
4919  eventMixin(TextMarker);
4920
4921  // Clear the marker.
4922  TextMarker.prototype.clear = function() {
4923    if (this.explicitlyCleared) return;
4924    var cm = this.doc.cm, withOp = cm && !cm.curOp;
4925    if (withOp) startOperation(cm);
4926    if (hasHandler(this, "clear")) {
4927      var found = this.find();
4928      if (found) signalLater(this, "clear", found.from, found.to);
4929    }
4930    var min = null, max = null;
4931    for (var i = 0; i < this.lines.length; ++i) {
4932      var line = this.lines[i];
4933      var span = getMarkedSpanFor(line.markedSpans, this);
4934      if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
4935      else if (cm) {
4936        if (span.to != null) max = lineNo(line);
4937        if (span.from != null) min = lineNo(line);
4938      }
4939      line.markedSpans = removeMarkedSpan(line.markedSpans, span);
4940      if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
4941        updateLineHeight(line, textHeight(cm.display));
4942    }
4943    if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
4944      var visual = visualLine(this.lines[i]), len = lineLength(visual);
4945      if (len > cm.display.maxLineLength) {
4946        cm.display.maxLine = visual;
4947        cm.display.maxLineLength = len;
4948        cm.display.maxLineChanged = true;
4949      }
4950    }
4951
4952    if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
4953    this.lines.length = 0;
4954    this.explicitlyCleared = true;
4955    if (this.atomic && this.doc.cantEdit) {
4956      this.doc.cantEdit = false;
4957      if (cm) reCheckSelection(cm.doc);
4958    }
4959    if (cm) signalLater(cm, "markerCleared", cm, this);
4960    if (withOp) endOperation(cm);
4961    if (this.parent) this.parent.clear();
4962  };
4963
4964  // Find the position of the marker in the document. Returns a {from,
4965  // to} object by default. Side can be passed to get a specific side
4966  // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
4967  // Pos objects returned contain a line object, rather than a line
4968  // number (used to prevent looking up the same line twice).
4969  TextMarker.prototype.find = function(side, lineObj) {
4970    if (side == null && this.type == "bookmark") side = 1;
4971    var from, to;
4972    for (var i = 0; i < this.lines.length; ++i) {
4973      var line = this.lines[i];
4974      var span = getMarkedSpanFor(line.markedSpans, this);
4975      if (span.from != null) {
4976        from = Pos(lineObj ? line : lineNo(line), span.from);
4977        if (side == -1) return from;
4978      }
4979      if (span.to != null) {
4980        to = Pos(lineObj ? line : lineNo(line), span.to);
4981        if (side == 1) return to;
4982      }
4983    }
4984    return from && {from: from, to: to};
4985  };
4986
4987  // Signals that the marker's widget changed, and surrounding layout
4988  // should be recomputed.
4989  TextMarker.prototype.changed = function() {
4990    var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
4991    if (!pos || !cm) return;
4992    runInOp(cm, function() {
4993      var line = pos.line, lineN = lineNo(pos.line);
4994      var view = findViewForLine(cm, lineN);
4995      if (view) {
4996        clearLineMeasurementCacheFor(view);
4997        cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
4998      }
4999      cm.curOp.updateMaxLine = true;
5000      if (!lineIsHidden(widget.doc, line) && widget.height != null) {
5001        var oldHeight = widget.height;
5002        widget.height = null;
5003        var dHeight = widgetHeight(widget) - oldHeight;
5004        if (dHeight)
5005          updateLineHeight(line, line.height + dHeight);
5006      }
5007    });
5008  };
5009
5010  TextMarker.prototype.attachLine = function(line) {
5011    if (!this.lines.length && this.doc.cm) {
5012      var op = this.doc.cm.curOp;
5013      if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
5014        (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
5015    }
5016    this.lines.push(line);
5017  };
5018  TextMarker.prototype.detachLine = function(line) {
5019    this.lines.splice(indexOf(this.lines, line), 1);
5020    if (!this.lines.length && this.doc.cm) {
5021      var op = this.doc.cm.curOp;
5022      (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
5023    }
5024  };
5025
5026  // Collapsed markers have unique ids, in order to be able to order
5027  // them, which is needed for uniquely determining an outer marker
5028  // when they overlap (they may nest, but not partially overlap).
5029  var nextMarkerId = 0;
5030
5031  // Create a marker, wire it up to the right lines, and
5032  function markText(doc, from, to, options, type) {
5033    // Shared markers (across linked documents) are handled separately
5034    // (markTextShared will call out to this again, once per
5035    // document).
5036    if (options && options.shared) return markTextShared(doc, from, to, options, type);
5037    // Ensure we are in an operation.
5038    if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
5039
5040    var marker = new TextMarker(doc, type), diff = cmp(from, to);
5041    if (options) copyObj(options, marker, false);
5042    // Don't connect empty markers unless clearWhenEmpty is false
5043    if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
5044      return marker;
5045    if (marker.replacedWith) {
5046      // Showing up as a widget implies collapsed (widget replaces text)
5047      marker.collapsed = true;
5048      marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
5049      if (!options.handleMouseEvents) marker.widgetNode.ignoreEvents = true;
5050      if (options.insertLeft) marker.widgetNode.insertLeft = true;
5051    }
5052    if (marker.collapsed) {
5053      if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
5054          from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
5055        throw new Error("Inserting collapsed marker partially overlapping an existing one");
5056      sawCollapsedSpans = true;
5057    }
5058
5059    if (marker.addToHistory)
5060      addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
5061
5062    var curLine = from.line, cm = doc.cm, updateMaxLine;
5063    doc.iter(curLine, to.line + 1, function(line) {
5064      if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
5065        updateMaxLine = true;
5066      if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
5067      addMarkedSpan(line, new MarkedSpan(marker,
5068                                         curLine == from.line ? from.ch : null,
5069                                         curLine == to.line ? to.ch : null));
5070      ++curLine;
5071    });
5072    // lineIsHidden depends on the presence of the spans, so needs a second pass
5073    if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
5074      if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
5075    });
5076
5077    if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
5078
5079    if (marker.readOnly) {
5080      sawReadOnlySpans = true;
5081      if (doc.history.done.length || doc.history.undone.length)
5082        doc.clearHistory();
5083    }
5084    if (marker.collapsed) {
5085      marker.id = ++nextMarkerId;
5086      marker.atomic = true;
5087    }
5088    if (cm) {
5089      // Sync editor state
5090      if (updateMaxLine) cm.curOp.updateMaxLine = true;
5091      if (marker.collapsed)
5092        regChange(cm, from.line, to.line + 1);
5093      else if (marker.className || marker.title || marker.startStyle || marker.endStyle)
5094        for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
5095      if (marker.atomic) reCheckSelection(cm.doc);
5096      signalLater(cm, "markerAdded", cm, marker);
5097    }
5098    return marker;
5099  }
5100
5101  // SHARED TEXTMARKERS
5102
5103  // A shared marker spans multiple linked documents. It is
5104  // implemented as a meta-marker-object controlling multiple normal
5105  // markers.
5106  var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
5107    this.markers = markers;
5108    this.primary = primary;
5109    for (var i = 0; i < markers.length; ++i)
5110      markers[i].parent = this;
5111  };
5112  eventMixin(SharedTextMarker);
5113
5114  SharedTextMarker.prototype.clear = function() {
5115    if (this.explicitlyCleared) return;
5116    this.explicitlyCleared = true;
5117    for (var i = 0; i < this.markers.length; ++i)
5118      this.markers[i].clear();
5119    signalLater(this, "clear");
5120  };
5121  SharedTextMarker.prototype.find = function(side, lineObj) {
5122    return this.primary.find(side, lineObj);
5123  };
5124
5125  function markTextShared(doc, from, to, options, type) {
5126    options = copyObj(options);
5127    options.shared = false;
5128    var markers = [markText(doc, from, to, options, type)], primary = markers[0];
5129    var widget = options.widgetNode;
5130    linkedDocs(doc, function(doc) {
5131      if (widget) options.widgetNode = widget.cloneNode(true);
5132      markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
5133      for (var i = 0; i < doc.linked.length; ++i)
5134        if (doc.linked[i].isParent) return;
5135      primary = lst(markers);
5136    });
5137    return new SharedTextMarker(markers, primary);
5138  }
5139
5140  function findSharedMarkers(doc) {
5141    return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
5142                         function(m) { return m.parent; });
5143  }
5144
5145  function copySharedMarkers(doc, markers) {
5146    for (var i = 0; i < markers.length; i++) {
5147      var marker = markers[i], pos = marker.find();
5148      var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
5149      if (cmp(mFrom, mTo)) {
5150        var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
5151        marker.markers.push(subMark);
5152        subMark.parent = marker;
5153      }
5154    }
5155  }
5156
5157  function detachSharedMarkers(markers) {
5158    for (var i = 0; i < markers.length; i++) {
5159      var marker = markers[i], linked = [marker.primary.doc];;
5160      linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
5161      for (var j = 0; j < marker.markers.length; j++) {
5162        var subMarker = marker.markers[j];
5163        if (indexOf(linked, subMarker.doc) == -1) {
5164          subMarker.parent = null;
5165          marker.markers.splice(j--, 1);
5166        }
5167      }
5168    }
5169  }
5170
5171  // TEXTMARKER SPANS
5172
5173  function MarkedSpan(marker, from, to) {
5174    this.marker = marker;
5175    this.from = from; this.to = to;
5176  }
5177
5178  // Search an array of spans for a span matching the given marker.
5179  function getMarkedSpanFor(spans, marker) {
5180    if (spans) for (var i = 0; i < spans.length; ++i) {
5181      var span = spans[i];
5182      if (span.marker == marker) return span;
5183    }
5184  }
5185  // Remove a span from an array, returning undefined if no spans are
5186  // left (we don't store arrays for lines without spans).
5187  function removeMarkedSpan(spans, span) {
5188    for (var r, i = 0; i < spans.length; ++i)
5189      if (spans[i] != span) (r || (r = [])).push(spans[i]);
5190    return r;
5191  }
5192  // Add a span to a line.
5193  function addMarkedSpan(line, span) {
5194    line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
5195    span.marker.attachLine(line);
5196  }
5197
5198  // Used for the algorithm that adjusts markers for a change in the
5199  // document. These functions cut an array of spans at a given
5200  // character position, returning an array of remaining chunks (or
5201  // undefined if nothing remains).
5202  function markedSpansBefore(old, startCh, isInsert) {
5203    if (old) for (var i = 0, nw; i < old.length; ++i) {
5204      var span = old[i], marker = span.marker;
5205      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
5206      if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
5207        var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
5208        (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
5209      }
5210    }
5211    return nw;
5212  }
5213  function markedSpansAfter(old, endCh, isInsert) {
5214    if (old) for (var i = 0, nw; i < old.length; ++i) {
5215      var span = old[i], marker = span.marker;
5216      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
5217      if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
5218        var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
5219        (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
5220                                              span.to == null ? null : span.to - endCh));
5221      }
5222    }
5223    return nw;
5224  }
5225
5226  // Given a change object, compute the new set of marker spans that
5227  // cover the line in which the change took place. Removes spans
5228  // entirely within the change, reconnects spans belonging to the
5229  // same marker that appear on both sides of the change, and cuts off
5230  // spans partially within the change. Returns an array of span
5231  // arrays with one element for each line in (after) the change.
5232  function stretchSpansOverChange(doc, change) {
5233    var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
5234    var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
5235    if (!oldFirst && !oldLast) return null;
5236
5237    var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
5238    // Get the spans that 'stick out' on both sides
5239    var first = markedSpansBefore(oldFirst, startCh, isInsert);
5240    var last = markedSpansAfter(oldLast, endCh, isInsert);
5241
5242    // Next, merge those two ends
5243    var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
5244    if (first) {
5245      // Fix up .to properties of first
5246      for (var i = 0; i < first.length; ++i) {
5247        var span = first[i];
5248        if (span.to == null) {
5249          var found = getMarkedSpanFor(last, span.marker);
5250          if (!found) span.to = startCh;
5251          else if (sameLine) span.to = found.to == null ? null : found.to + offset;
5252        }
5253      }
5254    }
5255    if (last) {
5256      // Fix up .from in last (or move them into first in case of sameLine)
5257      for (var i = 0; i < last.length; ++i) {
5258        var span = last[i];
5259        if (span.to != null) span.to += offset;
5260        if (span.from == null) {
5261          var found = getMarkedSpanFor(first, span.marker);
5262          if (!found) {
5263            span.from = offset;
5264            if (sameLine) (first || (first = [])).push(span);
5265          }
5266        } else {
5267          span.from += offset;
5268          if (sameLine) (first || (first = [])).push(span);
5269        }
5270      }
5271    }
5272    // Make sure we didn't create any zero-length spans
5273    if (first) first = clearEmptySpans(first);
5274    if (last && last != first) last = clearEmptySpans(last);
5275
5276    var newMarkers = [first];
5277    if (!sameLine) {
5278      // Fill gap with whole-line-spans
5279      var gap = change.text.length - 2, gapMarkers;
5280      if (gap > 0 && first)
5281        for (var i = 0; i < first.length; ++i)
5282          if (first[i].to == null)
5283            (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
5284      for (var i = 0; i < gap; ++i)
5285        newMarkers.push(gapMarkers);
5286      newMarkers.push(last);
5287    }
5288    return newMarkers;
5289  }
5290
5291  // Remove spans that are empty and don't have a clearWhenEmpty
5292  // option of false.
5293  function clearEmptySpans(spans) {
5294    for (var i = 0; i < spans.length; ++i) {
5295      var span = spans[i];
5296      if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
5297        spans.splice(i--, 1);
5298    }
5299    if (!spans.length) return null;
5300    return spans;
5301  }
5302
5303  // Used for un/re-doing changes from the history. Combines the
5304  // result of computing the existing spans with the set of spans that
5305  // existed in the history (so that deleting around a span and then
5306  // undoing brings back the span).
5307  function mergeOldSpans(doc, change) {
5308    var old = getOldSpans(doc, change);
5309    var stretched = stretchSpansOverChange(doc, change);
5310    if (!old) return stretched;
5311    if (!stretched) return old;
5312
5313    for (var i = 0; i < old.length; ++i) {
5314      var oldCur = old[i], stretchCur = stretched[i];
5315      if (oldCur && stretchCur) {
5316        spans: for (var j = 0; j < stretchCur.length; ++j) {
5317          var span = stretchCur[j];
5318          for (var k = 0; k < oldCur.length; ++k)
5319            if (oldCur[k].marker == span.marker) continue spans;
5320          oldCur.push(span);
5321        }
5322      } else if (stretchCur) {
5323        old[i] = stretchCur;
5324      }
5325    }
5326    return old;
5327  }
5328
5329  // Used to 'clip' out readOnly ranges when making a change.
5330  function removeReadOnlyRanges(doc, from, to) {
5331    var markers = null;
5332    doc.iter(from.line, to.line + 1, function(line) {
5333      if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
5334        var mark = line.markedSpans[i].marker;
5335        if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
5336          (markers || (markers = [])).push(mark);
5337      }
5338    });
5339    if (!markers) return null;
5340    var parts = [{from: from, to: to}];
5341    for (var i = 0; i < markers.length; ++i) {
5342      var mk = markers[i], m = mk.find(0);
5343      for (var j = 0; j < parts.length; ++j) {
5344        var p = parts[j];
5345        if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
5346        var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
5347        if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
5348          newParts.push({from: p.from, to: m.from});
5349        if (dto > 0 || !mk.inclusiveRight && !dto)
5350          newParts.push({from: m.to, to: p.to});
5351        parts.splice.apply(parts, newParts);
5352        j += newParts.length - 1;
5353      }
5354    }
5355    return parts;
5356  }
5357
5358  // Connect or disconnect spans from a line.
5359  function detachMarkedSpans(line) {
5360    var spans = line.markedSpans;
5361    if (!spans) return;
5362    for (var i = 0; i < spans.length; ++i)
5363      spans[i].marker.detachLine(line);
5364    line.markedSpans = null;
5365  }
5366  function attachMarkedSpans(line, spans) {
5367    if (!spans) return;
5368    for (var i = 0; i < spans.length; ++i)
5369      spans[i].marker.attachLine(line);
5370    line.markedSpans = spans;
5371  }
5372
5373  // Helpers used when computing which overlapping collapsed span
5374  // counts as the larger one.
5375  function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
5376  function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
5377
5378  // Returns a number indicating which of two overlapping collapsed
5379  // spans is larger (and thus includes the other). Falls back to
5380  // comparing ids when the spans cover exactly the same range.
5381  function compareCollapsedMarkers(a, b) {
5382    var lenDiff = a.lines.length - b.lines.length;
5383    if (lenDiff != 0) return lenDiff;
5384    var aPos = a.find(), bPos = b.find();
5385    var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
5386    if (fromCmp) return -fromCmp;
5387    var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
5388    if (toCmp) return toCmp;
5389    return b.id - a.id;
5390  }
5391
5392  // Find out whether a line ends or starts in a collapsed span. If
5393  // so, return the marker for that span.
5394  function collapsedSpanAtSide(line, start) {
5395    var sps = sawCollapsedSpans && line.markedSpans, found;
5396    if (sps) for (var sp, i = 0; i < sps.length; ++i) {
5397      sp = sps[i];
5398      if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
5399          (!found || compareCollapsedMarkers(found, sp.marker) < 0))
5400        found = sp.marker;
5401    }
5402    return found;
5403  }
5404  function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
5405  function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
5406
5407  // Test whether there exists a collapsed span that partially
5408  // overlaps (covers the start or end, but not both) of a new span.
5409  // Such overlap is not allowed.
5410  function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
5411    var line = getLine(doc, lineNo);
5412    var sps = sawCollapsedSpans && line.markedSpans;
5413    if (sps) for (var i = 0; i < sps.length; ++i) {
5414      var sp = sps[i];
5415      if (!sp.marker.collapsed) continue;
5416      var found = sp.marker.find(0);
5417      var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
5418      var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
5419      if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
5420      if (fromCmp <= 0 && (cmp(found.to, from) || extraRight(sp.marker) - extraLeft(marker)) > 0 ||
5421          fromCmp >= 0 && (cmp(found.from, to) || extraLeft(sp.marker) - extraRight(marker)) < 0)
5422        return true;
5423    }
5424  }
5425
5426  // A visual line is a line as drawn on the screen. Folding, for
5427  // example, can cause multiple logical lines to appear on the same
5428  // visual line. This finds the start of the visual line that the
5429  // given line is part of (usually that is the line itself).
5430  function visualLine(line) {
5431    var merged;
5432    while (merged = collapsedSpanAtStart(line))
5433      line = merged.find(-1, true).line;
5434    return line;
5435  }
5436
5437  // Returns an array of logical lines that continue the visual line
5438  // started by the argument, or undefined if there are no such lines.
5439  function visualLineContinued(line) {
5440    var merged, lines;
5441    while (merged = collapsedSpanAtEnd(line)) {
5442      line = merged.find(1, true).line;
5443      (lines || (lines = [])).push(line);
5444    }
5445    return lines;
5446  }
5447
5448  // Get the line number of the start of the visual line that the
5449  // given line number is part of.
5450  function visualLineNo(doc, lineN) {
5451    var line = getLine(doc, lineN), vis = visualLine(line);
5452    if (line == vis) return lineN;
5453    return lineNo(vis);
5454  }
5455  // Get the line number of the start of the next visual line after
5456  // the given line.
5457  function visualLineEndNo(doc, lineN) {
5458    if (lineN > doc.lastLine()) return lineN;
5459    var line = getLine(doc, lineN), merged;
5460    if (!lineIsHidden(doc, line)) return lineN;
5461    while (merged = collapsedSpanAtEnd(line))
5462      line = merged.find(1, true).line;
5463    return lineNo(line) + 1;
5464  }
5465
5466  // Compute whether a line is hidden. Lines count as hidden when they
5467  // are part of a visual line that starts with another line, or when
5468  // they are entirely covered by collapsed, non-widget span.
5469  function lineIsHidden(doc, line) {
5470    var sps = sawCollapsedSpans && line.markedSpans;
5471    if (sps) for (var sp, i = 0; i < sps.length; ++i) {
5472      sp = sps[i];
5473      if (!sp.marker.collapsed) continue;
5474      if (sp.from == null) return true;
5475      if (sp.marker.widgetNode) continue;
5476      if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
5477        return true;
5478    }
5479  }
5480  function lineIsHiddenInner(doc, line, span) {
5481    if (span.to == null) {
5482      var end = span.marker.find(1, true);
5483      return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
5484    }
5485    if (span.marker.inclusiveRight && span.to == line.text.length)
5486      return true;
5487    for (var sp, i = 0; i < line.markedSpans.length; ++i) {
5488      sp = line.markedSpans[i];
5489      if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
5490          (sp.to == null || sp.to != span.from) &&
5491          (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
5492          lineIsHiddenInner(doc, line, sp)) return true;
5493    }
5494  }
5495
5496  // LINE WIDGETS
5497
5498  // Line widgets are block elements displayed above or below a line.
5499
5500  var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {
5501    if (options) for (var opt in options) if (options.hasOwnProperty(opt))
5502      this[opt] = options[opt];
5503    this.cm = cm;
5504    this.node = node;
5505  };
5506  eventMixin(LineWidget);
5507
5508  function adjustScrollWhenAboveVisible(cm, line, diff) {
5509    if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
5510      addToScrollPos(cm, null, diff);
5511  }
5512
5513  LineWidget.prototype.clear = function() {
5514    var cm = this.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
5515    if (no == null || !ws) return;
5516    for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
5517    if (!ws.length) line.widgets = null;
5518    var height = widgetHeight(this);
5519    runInOp(cm, function() {
5520      adjustScrollWhenAboveVisible(cm, line, -height);
5521      regLineChange(cm, no, "widget");
5522      updateLineHeight(line, Math.max(0, line.height - height));
5523    });
5524  };
5525  LineWidget.prototype.changed = function() {
5526    var oldH = this.height, cm = this.cm, line = this.line;
5527    this.height = null;
5528    var diff = widgetHeight(this) - oldH;
5529    if (!diff) return;
5530    runInOp(cm, function() {
5531      cm.curOp.forceUpdate = true;
5532      adjustScrollWhenAboveVisible(cm, line, diff);
5533      updateLineHeight(line, line.height + diff);
5534    });
5535  };
5536
5537  function widgetHeight(widget) {
5538    if (widget.height != null) return widget.height;
5539    if (!contains(document.body, widget.node))
5540      removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative"));
5541    return widget.height = widget.node.offsetHeight;
5542  }
5543
5544  function addLineWidget(cm, handle, node, options) {
5545    var widget = new LineWidget(cm, node, options);
5546    if (widget.noHScroll) cm.display.alignWidgets = true;
5547    changeLine(cm, handle, "widget", function(line) {
5548      var widgets = line.widgets || (line.widgets = []);
5549      if (widget.insertAt == null) widgets.push(widget);
5550      else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
5551      widget.line = line;
5552      if (!lineIsHidden(cm.doc, line)) {
5553        var aboveVisible = heightAtLine(line) < cm.doc.scrollTop;
5554        updateLineHeight(line, line.height + widgetHeight(widget));
5555        if (aboveVisible) addToScrollPos(cm, null, widget.height);
5556        cm.curOp.forceUpdate = true;
5557      }
5558      return true;
5559    });
5560    return widget;
5561  }
5562
5563  // LINE DATA STRUCTURE
5564
5565  // Line objects. These hold state related to a line, including
5566  // highlighting info (the styles array).
5567  var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
5568    this.text = text;
5569    attachMarkedSpans(this, markedSpans);
5570    this.height = estimateHeight ? estimateHeight(this) : 1;
5571  };
5572  eventMixin(Line);
5573  Line.prototype.lineNo = function() { return lineNo(this); };
5574
5575  // Change the content (text, markers) of a line. Automatically
5576  // invalidates cached information and tries to re-estimate the
5577  // line's height.
5578  function updateLine(line, text, markedSpans, estimateHeight) {
5579    line.text = text;
5580    if (line.stateAfter) line.stateAfter = null;
5581    if (line.styles) line.styles = null;
5582    if (line.order != null) line.order = null;
5583    detachMarkedSpans(line);
5584    attachMarkedSpans(line, markedSpans);
5585    var estHeight = estimateHeight ? estimateHeight(line) : 1;
5586    if (estHeight != line.height) updateLineHeight(line, estHeight);
5587  }
5588
5589  // Detach a line from the document tree and its markers.
5590  function cleanUpLine(line) {
5591    line.parent = null;
5592    detachMarkedSpans(line);
5593  }
5594
5595  function extractLineClasses(type, output) {
5596    if (type) for (;;) {
5597      var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
5598      if (!lineClass) break;
5599      type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
5600      var prop = lineClass[1] ? "bgClass" : "textClass";
5601      if (output[prop] == null)
5602        output[prop] = lineClass[2];
5603      else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
5604        output[prop] += " " + lineClass[2];
5605    }
5606    return type;
5607  }
5608
5609  function callBlankLine(mode, state) {
5610    if (mode.blankLine) return mode.blankLine(state);
5611    if (!mode.innerMode) return;
5612    var inner = CodeMirror.innerMode(mode, state);
5613    if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
5614  }
5615
5616  function readToken(mode, stream, state) {
5617    for (var i = 0; i < 10; i++) {
5618      var style = mode.token(stream, state);
5619      if (stream.pos > stream.start) return style;
5620    }
5621    throw new Error("Mode " + mode.name + " failed to advance stream.");
5622  }
5623
5624  // Run the given mode's parser over a line, calling f for each token.
5625  function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
5626    var flattenSpans = mode.flattenSpans;
5627    if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
5628    var curStart = 0, curStyle = null;
5629    var stream = new StringStream(text, cm.options.tabSize), style;
5630    if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
5631    while (!stream.eol()) {
5632      if (stream.pos > cm.options.maxHighlightLength) {
5633        flattenSpans = false;
5634        if (forceToEnd) processLine(cm, text, state, stream.pos);
5635        stream.pos = text.length;
5636        style = null;
5637      } else {
5638        style = extractLineClasses(readToken(mode, stream, state), lineClasses);
5639      }
5640      if (cm.options.addModeClass) {
5641        var mName = CodeMirror.innerMode(mode, state).mode.name;
5642        if (mName) style = "m-" + (style ? mName + " " + style : mName);
5643      }
5644      if (!flattenSpans || curStyle != style) {
5645        if (curStart < stream.start) f(stream.start, curStyle);
5646        curStart = stream.start; curStyle = style;
5647      }
5648      stream.start = stream.pos;
5649    }
5650    while (curStart < stream.pos) {
5651      // Webkit seems to refuse to render text nodes longer than 57444 characters
5652      var pos = Math.min(stream.pos, curStart + 50000);
5653      f(pos, curStyle);
5654      curStart = pos;
5655    }
5656  }
5657
5658  // Compute a style array (an array starting with a mode generation
5659  // -- for invalidation -- followed by pairs of end positions and
5660  // style strings), which is used to highlight the tokens on the
5661  // line.
5662  function highlightLine(cm, line, state, forceToEnd) {
5663    // A styles array always starts with a number identifying the
5664    // mode/overlays that it is based on (for easy invalidation).
5665    var st = [cm.state.modeGen], lineClasses = {};
5666    // Compute the base array of styles
5667    runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
5668      st.push(end, style);
5669    }, lineClasses, forceToEnd);
5670
5671    // Run overlays, adjust style array.
5672    for (var o = 0; o < cm.state.overlays.length; ++o) {
5673      var overlay = cm.state.overlays[o], i = 1, at = 0;
5674      runMode(cm, line.text, overlay.mode, true, function(end, style) {
5675        var start = i;
5676        // Ensure there's a token end at the current position, and that i points at it
5677        while (at < end) {
5678          var i_end = st[i];
5679          if (i_end > end)
5680            st.splice(i, 1, end, st[i+1], i_end);
5681          i += 2;
5682          at = Math.min(end, i_end);
5683        }
5684        if (!style) return;
5685        if (overlay.opaque) {
5686          st.splice(start, i - start, end, "cm-overlay " + style);
5687          i = start + 2;
5688        } else {
5689          for (; start < i; start += 2) {
5690            var cur = st[start+1];
5691            st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
5692          }
5693        }
5694      }, lineClasses);
5695    }
5696
5697    return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
5698  }
5699
5700  function getLineStyles(cm, line) {
5701    if (!line.styles || line.styles[0] != cm.state.modeGen) {
5702      var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
5703      line.styles = result.styles;
5704      if (result.classes) line.styleClasses = result.classes;
5705      else if (line.styleClasses) line.styleClasses = null;
5706    }
5707    return line.styles;
5708  }
5709
5710  // Lightweight form of highlight -- proceed over this line and
5711  // update state, but don't save a style array. Used for lines that
5712  // aren't currently visible.
5713  function processLine(cm, text, state, startAt) {
5714    var mode = cm.doc.mode;
5715    var stream = new StringStream(text, cm.options.tabSize);
5716    stream.start = stream.pos = startAt || 0;
5717    if (text == "") callBlankLine(mode, state);
5718    while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
5719      readToken(mode, stream, state);
5720      stream.start = stream.pos;
5721    }
5722  }
5723
5724  // Convert a style as returned by a mode (either null, or a string
5725  // containing one or more styles) to a CSS style. This is cached,
5726  // and also looks for line-wide styles.
5727  var styleToClassCache = {}, styleToClassCacheWithMode = {};
5728  function interpretTokenStyle(style, options) {
5729    if (!style || /^\s*$/.test(style)) return null;
5730    var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
5731    return cache[style] ||
5732      (cache[style] = style.replace(/\S+/g, "cm-$&"));
5733  }
5734
5735  // Render the DOM representation of the text of a line. Also builds
5736  // up a 'line map', which points at the DOM nodes that represent
5737  // specific stretches of text, and is used by the measuring code.
5738  // The returned object contains the DOM node, this map, and
5739  // information about line-wide styles that were set by the mode.
5740  function buildLineContent(cm, lineView) {
5741    // The padding-right forces the element to have a 'border', which
5742    // is needed on Webkit to be able to get line-level bounding
5743    // rectangles for it (in measureChar).
5744    var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
5745    var builder = {pre: elt("pre", [content]), content: content, col: 0, pos: 0, cm: cm};
5746    lineView.measure = {};
5747
5748    // Iterate over the logical lines that make up this visual line.
5749    for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
5750      var line = i ? lineView.rest[i - 1] : lineView.line, order;
5751      builder.pos = 0;
5752      builder.addToken = buildToken;
5753      // Optionally wire in some hacks into the token-rendering
5754      // algorithm, to deal with browser quirks.
5755      if ((ie || webkit) && cm.getOption("lineWrapping"))
5756        builder.addToken = buildTokenSplitSpaces(builder.addToken);
5757      if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
5758        builder.addToken = buildTokenBadBidi(builder.addToken, order);
5759      builder.map = [];
5760      insertLineContent(line, builder, getLineStyles(cm, line));
5761      if (line.styleClasses) {
5762        if (line.styleClasses.bgClass)
5763          builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
5764        if (line.styleClasses.textClass)
5765          builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
5766      }
5767
5768      // Ensure at least a single node is present, for measuring.
5769      if (builder.map.length == 0)
5770        builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
5771
5772      // Store the map and a cache object for the current logical line
5773      if (i == 0) {
5774        lineView.measure.map = builder.map;
5775        lineView.measure.cache = {};
5776      } else {
5777        (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
5778        (lineView.measure.caches || (lineView.measure.caches = [])).push({});
5779      }
5780    }
5781
5782    signal(cm, "renderLine", cm, lineView.line, builder.pre);
5783    if (builder.pre.className)
5784      builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
5785    return builder;
5786  }
5787
5788  function defaultSpecialCharPlaceholder(ch) {
5789    var token = elt("span", "\u2022", "cm-invalidchar");
5790    token.title = "\\u" + ch.charCodeAt(0).toString(16);
5791    return token;
5792  }
5793
5794  // Build up the DOM representation for a single token, and add it to
5795  // the line map. Takes care to render special characters separately.
5796  function buildToken(builder, text, style, startStyle, endStyle, title) {
5797    if (!text) return;
5798    var special = builder.cm.options.specialChars, mustWrap = false;
5799    if (!special.test(text)) {
5800      builder.col += text.length;
5801      var content = document.createTextNode(text);
5802      builder.map.push(builder.pos, builder.pos + text.length, content);
5803      if (ie_upto8) mustWrap = true;
5804      builder.pos += text.length;
5805    } else {
5806      var content = document.createDocumentFragment(), pos = 0;
5807      while (true) {
5808        special.lastIndex = pos;
5809        var m = special.exec(text);
5810        var skipped = m ? m.index - pos : text.length - pos;
5811        if (skipped) {
5812          var txt = document.createTextNode(text.slice(pos, pos + skipped));
5813          if (ie_upto8) content.appendChild(elt("span", [txt]));
5814          else content.appendChild(txt);
5815          builder.map.push(builder.pos, builder.pos + skipped, txt);
5816          builder.col += skipped;
5817          builder.pos += skipped;
5818        }
5819        if (!m) break;
5820        pos += skipped + 1;
5821        if (m[0] == "\t") {
5822          var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
5823          var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
5824          builder.col += tabWidth;
5825        } else {
5826          var txt = builder.cm.options.specialCharPlaceholder(m[0]);
5827          if (ie_upto8) content.appendChild(elt("span", [txt]));
5828          else content.appendChild(txt);
5829          builder.col += 1;
5830        }
5831        builder.map.push(builder.pos, builder.pos + 1, txt);
5832        builder.pos++;
5833      }
5834    }
5835    if (style || startStyle || endStyle || mustWrap) {
5836      var fullStyle = style || "";
5837      if (startStyle) fullStyle += startStyle;
5838      if (endStyle) fullStyle += endStyle;
5839      var token = elt("span", [content], fullStyle);
5840      if (title) token.title = title;
5841      return builder.content.appendChild(token);
5842    }
5843    builder.content.appendChild(content);
5844  }
5845
5846  function buildTokenSplitSpaces(inner) {
5847    function split(old) {
5848      var out = " ";
5849      for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
5850      out += " ";
5851      return out;
5852    }
5853    return function(builder, text, style, startStyle, endStyle, title) {
5854      inner(builder, text.replace(/ {3,}/g, split), style, startStyle, endStyle, title);
5855    };
5856  }
5857
5858  // Work around nonsense dimensions being reported for stretches of
5859  // right-to-left text.
5860  function buildTokenBadBidi(inner, order) {
5861    return function(builder, text, style, startStyle, endStyle, title) {
5862      style = style ? style + " cm-force-border" : "cm-force-border";
5863      var start = builder.pos, end = start + text.length;
5864      for (;;) {
5865        // Find the part that overlaps with the start of this text
5866        for (var i = 0; i < order.length; i++) {
5867          var part = order[i];
5868          if (part.to > start && part.from <= start) break;
5869        }
5870        if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title);
5871        inner(builder, text.slice(0, part.to - start), style, startStyle, null, title);
5872        startStyle = null;
5873        text = text.slice(part.to - start);
5874        start = part.to;
5875      }
5876    };
5877  }
5878
5879  function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
5880    var widget = !ignoreWidget && marker.widgetNode;
5881    if (widget) {
5882      builder.map.push(builder.pos, builder.pos + size, widget);
5883      builder.content.appendChild(widget);
5884    }
5885    builder.pos += size;
5886  }
5887
5888  // Outputs a number of spans to make up a line, taking highlighting
5889  // and marked text into account.
5890  function insertLineContent(line, builder, styles) {
5891    var spans = line.markedSpans, allText = line.text, at = 0;
5892    if (!spans) {
5893      for (var i = 1; i < styles.length; i+=2)
5894        builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
5895      return;
5896    }
5897
5898    var len = allText.length, pos = 0, i = 1, text = "", style;
5899    var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
5900    for (;;) {
5901      if (nextChange == pos) { // Update current marker set
5902        spanStyle = spanEndStyle = spanStartStyle = title = "";
5903        collapsed = null; nextChange = Infinity;
5904        var foundBookmarks = [];
5905        for (var j = 0; j < spans.length; ++j) {
5906          var sp = spans[j], m = sp.marker;
5907          if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
5908            if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
5909            if (m.className) spanStyle += " " + m.className;
5910            if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
5911            if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
5912            if (m.title && !title) title = m.title;
5913            if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
5914              collapsed = sp;
5915          } else if (sp.from > pos && nextChange > sp.from) {
5916            nextChange = sp.from;
5917          }
5918          if (m.type == "bookmark" && sp.from == pos && m.widgetNode) foundBookmarks.push(m);
5919        }
5920        if (collapsed && (collapsed.from || 0) == pos) {
5921          buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
5922                             collapsed.marker, collapsed.from == null);
5923          if (collapsed.to == null) return;
5924        }
5925        if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
5926          buildCollapsedSpan(builder, 0, foundBookmarks[j]);
5927      }
5928      if (pos >= len) break;
5929
5930      var upto = Math.min(len, nextChange);
5931      while (true) {
5932        if (text) {
5933          var end = pos + text.length;
5934          if (!collapsed) {
5935            var tokenText = end > upto ? text.slice(0, upto - pos) : text;
5936            builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
5937                             spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title);
5938          }
5939          if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
5940          pos = end;
5941          spanStartStyle = "";
5942        }
5943        text = allText.slice(at, at = styles[i++]);
5944        style = interpretTokenStyle(styles[i++], builder.cm.options);
5945      }
5946    }
5947  }
5948
5949  // DOCUMENT DATA STRUCTURE
5950
5951  // By default, updates that start and end at the beginning of a line
5952  // are treated specially, in order to make the association of line
5953  // widgets and marker elements with the text behave more intuitive.
5954  function isWholeLineUpdate(doc, change) {
5955    return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
5956      (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
5957  }
5958
5959  // Perform a change on the document data structure.
5960  function updateDoc(doc, change, markedSpans, estimateHeight) {
5961    function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
5962    function update(line, text, spans) {
5963      updateLine(line, text, spans, estimateHeight);
5964      signalLater(line, "change", line, change);
5965    }
5966
5967    var from = change.from, to = change.to, text = change.text;
5968    var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
5969    var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
5970
5971    // Adjust the line structure
5972    if (isWholeLineUpdate(doc, change)) {
5973      // This is a whole-line replace. Treated specially to make
5974      // sure line objects move the way they are supposed to.
5975      for (var i = 0, added = []; i < text.length - 1; ++i)
5976        added.push(new Line(text[i], spansFor(i), estimateHeight));
5977      update(lastLine, lastLine.text, lastSpans);
5978      if (nlines) doc.remove(from.line, nlines);
5979      if (added.length) doc.insert(from.line, added);
5980    } else if (firstLine == lastLine) {
5981      if (text.length == 1) {
5982        update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
5983      } else {
5984        for (var added = [], i = 1; i < text.length - 1; ++i)
5985          added.push(new Line(text[i], spansFor(i), estimateHeight));
5986        added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
5987        update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
5988        doc.insert(from.line + 1, added);
5989      }
5990    } else if (text.length == 1) {
5991      update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
5992      doc.remove(from.line + 1, nlines);
5993    } else {
5994      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
5995      update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
5996      for (var i = 1, added = []; i < text.length - 1; ++i)
5997        added.push(new Line(text[i], spansFor(i), estimateHeight));
5998      if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
5999      doc.insert(from.line + 1, added);
6000    }
6001
6002    signalLater(doc, "change", doc, change);
6003  }
6004
6005  // The document is represented as a BTree consisting of leaves, with
6006  // chunk of lines in them, and branches, with up to ten leaves or
6007  // other branch nodes below them. The top node is always a branch
6008  // node, and is the document object itself (meaning it has
6009  // additional methods and properties).
6010  //
6011  // All nodes have parent links. The tree is used both to go from
6012  // line numbers to line objects, and to go from objects to numbers.
6013  // It also indexes by height, and is used to convert between height
6014  // and line object, and to find the total height of the document.
6015  //
6016  // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
6017
6018  function LeafChunk(lines) {
6019    this.lines = lines;
6020    this.parent = null;
6021    for (var i = 0, height = 0; i < lines.length; ++i) {
6022      lines[i].parent = this;
6023      height += lines[i].height;
6024    }
6025    this.height = height;
6026  }
6027
6028  LeafChunk.prototype = {
6029    chunkSize: function() { return this.lines.length; },
6030    // Remove the n lines at offset 'at'.
6031    removeInner: function(at, n) {
6032      for (var i = at, e = at + n; i < e; ++i) {
6033        var line = this.lines[i];
6034        this.height -= line.height;
6035        cleanUpLine(line);
6036        signalLater(line, "delete");
6037      }
6038      this.lines.splice(at, n);
6039    },
6040    // Helper used to collapse a small branch into a single leaf.
6041    collapse: function(lines) {
6042      lines.push.apply(lines, this.lines);
6043    },
6044    // Insert the given array of lines at offset 'at', count them as
6045    // having the given height.
6046    insertInner: function(at, lines, height) {
6047      this.height += height;
6048      this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
6049      for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
6050    },
6051    // Used to iterate over a part of the tree.
6052    iterN: function(at, n, op) {
6053      for (var e = at + n; at < e; ++at)
6054        if (op(this.lines[at])) return true;
6055    }
6056  };
6057
6058  function BranchChunk(children) {
6059    this.children = children;
6060    var size = 0, height = 0;
6061    for (var i = 0; i < children.length; ++i) {
6062      var ch = children[i];
6063      size += ch.chunkSize(); height += ch.height;
6064      ch.parent = this;
6065    }
6066    this.size = size;
6067    this.height = height;
6068    this.parent = null;
6069  }
6070
6071  BranchChunk.prototype = {
6072    chunkSize: function() { return this.size; },
6073    removeInner: function(at, n) {
6074      this.size -= n;
6075      for (var i = 0; i < this.children.length; ++i) {
6076        var child = this.children[i], sz = child.chunkSize();
6077        if (at < sz) {
6078          var rm = Math.min(n, sz - at), oldHeight = child.height;
6079          child.removeInner(at, rm);
6080          this.height -= oldHeight - child.height;
6081          if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
6082          if ((n -= rm) == 0) break;
6083          at = 0;
6084        } else at -= sz;
6085      }
6086      // If the result is smaller than 25 lines, ensure that it is a
6087      // single leaf node.
6088      if (this.size - n < 25 &&
6089          (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
6090        var lines = [];
6091        this.collapse(lines);
6092        this.children = [new LeafChunk(lines)];
6093        this.children[0].parent = this;
6094      }
6095    },
6096    collapse: function(lines) {
6097      for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
6098    },
6099    insertInner: function(at, lines, height) {
6100      this.size += lines.length;
6101      this.height += height;
6102      for (var i = 0; i < this.children.length; ++i) {
6103        var child = this.children[i], sz = child.chunkSize();
6104        if (at <= sz) {
6105          child.insertInner(at, lines, height);
6106          if (child.lines && child.lines.length > 50) {
6107            while (child.lines.length > 50) {
6108              var spilled = child.lines.splice(child.lines.length - 25, 25);
6109              var newleaf = new LeafChunk(spilled);
6110              child.height -= newleaf.height;
6111              this.children.splice(i + 1, 0, newleaf);
6112              newleaf.parent = this;
6113            }
6114            this.maybeSpill();
6115          }
6116          break;
6117        }
6118        at -= sz;
6119      }
6120    },
6121    // When a node has grown, check whether it should be split.
6122    maybeSpill: function() {
6123      if (this.children.length <= 10) return;
6124      var me = this;
6125      do {
6126        var spilled = me.children.splice(me.children.length - 5, 5);
6127        var sibling = new BranchChunk(spilled);
6128        if (!me.parent) { // Become the parent node
6129          var copy = new BranchChunk(me.children);
6130          copy.parent = me;
6131          me.children = [copy, sibling];
6132          me = copy;
6133        } else {
6134          me.size -= sibling.size;
6135          me.height -= sibling.height;
6136          var myIndex = indexOf(me.parent.children, me);
6137          me.parent.children.splice(myIndex + 1, 0, sibling);
6138        }
6139        sibling.parent = me.parent;
6140      } while (me.children.length > 10);
6141      me.parent.maybeSpill();
6142    },
6143    iterN: function(at, n, op) {
6144      for (var i = 0; i < this.children.length; ++i) {
6145        var child = this.children[i], sz = child.chunkSize();
6146        if (at < sz) {
6147          var used = Math.min(n, sz - at);
6148          if (child.iterN(at, used, op)) return true;
6149          if ((n -= used) == 0) break;
6150          at = 0;
6151        } else at -= sz;
6152      }
6153    }
6154  };
6155
6156  var nextDocId = 0;
6157  var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
6158    if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
6159    if (firstLine == null) firstLine = 0;
6160
6161    BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
6162    this.first = firstLine;
6163    this.scrollTop = this.scrollLeft = 0;
6164    this.cantEdit = false;
6165    this.cleanGeneration = 1;
6166    this.frontier = firstLine;
6167    var start = Pos(firstLine, 0);
6168    this.sel = simpleSelection(start);
6169    this.history = new History(null);
6170    this.id = ++nextDocId;
6171    this.modeOption = mode;
6172
6173    if (typeof text == "string") text = splitLines(text);
6174    updateDoc(this, {from: start, to: start, text: text});
6175    setSelection(this, simpleSelection(start), sel_dontScroll);
6176  };
6177
6178  Doc.prototype = createObj(BranchChunk.prototype, {
6179    constructor: Doc,
6180    // Iterate over the document. Supports two forms -- with only one
6181    // argument, it calls that for each line in the document. With
6182    // three, it iterates over the range given by the first two (with
6183    // the second being non-inclusive).
6184    iter: function(from, to, op) {
6185      if (op) this.iterN(from - this.first, to - from, op);
6186      else this.iterN(this.first, this.first + this.size, from);
6187    },
6188
6189    // Non-public interface for adding and removing lines.
6190    insert: function(at, lines) {
6191      var height = 0;
6192      for (var i = 0; i < lines.length; ++i) height += lines[i].height;
6193      this.insertInner(at - this.first, lines, height);
6194    },
6195    remove: function(at, n) { this.removeInner(at - this.first, n); },
6196
6197    // From here, the methods are part of the public interface. Most
6198    // are also available from CodeMirror (editor) instances.
6199
6200    getValue: function(lineSep) {
6201      var lines = getLines(this, this.first, this.first + this.size);
6202      if (lineSep === false) return lines;
6203      return lines.join(lineSep || "\n");
6204    },
6205    setValue: docMethodOp(function(code) {
6206      var top = Pos(this.first, 0), last = this.first + this.size - 1;
6207      makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
6208                        text: splitLines(code), origin: "setValue"}, true);
6209      setSelection(this, simpleSelection(top));
6210    }),
6211    replaceRange: function(code, from, to, origin) {
6212      from = clipPos(this, from);
6213      to = to ? clipPos(this, to) : from;
6214      replaceRange(this, code, from, to, origin);
6215    },
6216    getRange: function(from, to, lineSep) {
6217      var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
6218      if (lineSep === false) return lines;
6219      return lines.join(lineSep || "\n");
6220    },
6221
6222    getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
6223
6224    getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
6225    getLineNumber: function(line) {return lineNo(line);},
6226
6227    getLineHandleVisualStart: function(line) {
6228      if (typeof line == "number") line = getLine(this, line);
6229      return visualLine(line);
6230    },
6231
6232    lineCount: function() {return this.size;},
6233    firstLine: function() {return this.first;},
6234    lastLine: function() {return this.first + this.size - 1;},
6235
6236    clipPos: function(pos) {return clipPos(this, pos);},
6237
6238    getCursor: function(start) {
6239      var range = this.sel.primary(), pos;
6240      if (start == null || start == "head") pos = range.head;
6241      else if (start == "anchor") pos = range.anchor;
6242      else if (start == "end" || start == "to" || start === false) pos = range.to();
6243      else pos = range.from();
6244      return pos;
6245    },
6246    listSelections: function() { return this.sel.ranges; },
6247    somethingSelected: function() {return this.sel.somethingSelected();},
6248
6249    setCursor: docMethodOp(function(line, ch, options) {
6250      setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
6251    }),
6252    setSelection: docMethodOp(function(anchor, head, options) {
6253      setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
6254    }),
6255    extendSelection: docMethodOp(function(head, other, options) {
6256      extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
6257    }),
6258    extendSelections: docMethodOp(function(heads, options) {
6259      extendSelections(this, clipPosArray(this, heads, options));
6260    }),
6261    extendSelectionsBy: docMethodOp(function(f, options) {
6262      extendSelections(this, map(this.sel.ranges, f), options);
6263    }),
6264    setSelections: docMethodOp(function(ranges, primary, options) {
6265      if (!ranges.length) return;
6266      for (var i = 0, out = []; i < ranges.length; i++)
6267        out[i] = new Range(clipPos(this, ranges[i].anchor),
6268                           clipPos(this, ranges[i].head));
6269      if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
6270      setSelection(this, normalizeSelection(out, primary), options);
6271    }),
6272    addSelection: docMethodOp(function(anchor, head, options) {
6273      var ranges = this.sel.ranges.slice(0);
6274      ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
6275      setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
6276    }),
6277
6278    getSelection: function(lineSep) {
6279      var ranges = this.sel.ranges, lines;
6280      for (var i = 0; i < ranges.length; i++) {
6281        var sel = getBetween(this, ranges[i].from(), ranges[i].to());
6282        lines = lines ? lines.concat(sel) : sel;
6283      }
6284      if (lineSep === false) return lines;
6285      else return lines.join(lineSep || "\n");
6286    },
6287    getSelections: function(lineSep) {
6288      var parts = [], ranges = this.sel.ranges;
6289      for (var i = 0; i < ranges.length; i++) {
6290        var sel = getBetween(this, ranges[i].from(), ranges[i].to());
6291        if (lineSep !== false) sel = sel.join(lineSep || "\n");
6292        parts[i] = sel;
6293      }
6294      return parts;
6295    },
6296    replaceSelection: function(code, collapse, origin) {
6297      var dup = [];
6298      for (var i = 0; i < this.sel.ranges.length; i++)
6299        dup[i] = code;
6300      this.replaceSelections(dup, collapse, origin || "+input");
6301    },
6302    replaceSelections: docMethodOp(function(code, collapse, origin) {
6303      var changes = [], sel = this.sel;
6304      for (var i = 0; i < sel.ranges.length; i++) {
6305        var range = sel.ranges[i];
6306        changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin};
6307      }
6308      var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
6309      for (var i = changes.length - 1; i >= 0; i--)
6310        makeChange(this, changes[i]);
6311      if (newSel) setSelectionReplaceHistory(this, newSel);
6312      else if (this.cm) ensureCursorVisible(this.cm);
6313    }),
6314    undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
6315    redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
6316    undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
6317    redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
6318
6319    setExtending: function(val) {this.extend = val;},
6320    getExtending: function() {return this.extend;},
6321
6322    historySize: function() {
6323      var hist = this.history, done = 0, undone = 0;
6324      for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
6325      for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
6326      return {undo: done, redo: undone};
6327    },
6328    clearHistory: function() {this.history = new History(this.history.maxGeneration);},
6329
6330    markClean: function() {
6331      this.cleanGeneration = this.changeGeneration(true);
6332    },
6333    changeGeneration: function(forceSplit) {
6334      if (forceSplit)
6335        this.history.lastOp = this.history.lastOrigin = null;
6336      return this.history.generation;
6337    },
6338    isClean: function (gen) {
6339      return this.history.generation == (gen || this.cleanGeneration);
6340    },
6341
6342    getHistory: function() {
6343      return {done: copyHistoryArray(this.history.done),
6344              undone: copyHistoryArray(this.history.undone)};
6345    },
6346    setHistory: function(histData) {
6347      var hist = this.history = new History(this.history.maxGeneration);
6348      hist.done = copyHistoryArray(histData.done.slice(0), null, true);
6349      hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
6350    },
6351
6352    markText: function(from, to, options) {
6353      return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
6354    },
6355    setBookmark: function(pos, options) {
6356      var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
6357                      insertLeft: options && options.insertLeft,
6358                      clearWhenEmpty: false, shared: options && options.shared};
6359      pos = clipPos(this, pos);
6360      return markText(this, pos, pos, realOpts, "bookmark");
6361    },
6362    findMarksAt: function(pos) {
6363      pos = clipPos(this, pos);
6364      var markers = [], spans = getLine(this, pos.line).markedSpans;
6365      if (spans) for (var i = 0; i < spans.length; ++i) {
6366        var span = spans[i];
6367        if ((span.from == null || span.from <= pos.ch) &&
6368            (span.to == null || span.to >= pos.ch))
6369          markers.push(span.marker.parent || span.marker);
6370      }
6371      return markers;
6372    },
6373    findMarks: function(from, to, filter) {
6374      from = clipPos(this, from); to = clipPos(this, to);
6375      var found = [], lineNo = from.line;
6376      this.iter(from.line, to.line + 1, function(line) {
6377        var spans = line.markedSpans;
6378        if (spans) for (var i = 0; i < spans.length; i++) {
6379          var span = spans[i];
6380          if (!(lineNo == from.line && from.ch > span.to ||
6381                span.from == null && lineNo != from.line||
6382                lineNo == to.line && span.from > to.ch) &&
6383              (!filter || filter(span.marker)))
6384            found.push(span.marker.parent || span.marker);
6385        }
6386        ++lineNo;
6387      });
6388      return found;
6389    },
6390    getAllMarks: function() {
6391      var markers = [];
6392      this.iter(function(line) {
6393        var sps = line.markedSpans;
6394        if (sps) for (var i = 0; i < sps.length; ++i)
6395          if (sps[i].from != null) markers.push(sps[i].marker);
6396      });
6397      return markers;
6398    },
6399
6400    posFromIndex: function(off) {
6401      var ch, lineNo = this.first;
6402      this.iter(function(line) {
6403        var sz = line.text.length + 1;
6404        if (sz > off) { ch = off; return true; }
6405        off -= sz;
6406        ++lineNo;
6407      });
6408      return clipPos(this, Pos(lineNo, ch));
6409    },
6410    indexFromPos: function (coords) {
6411      coords = clipPos(this, coords);
6412      var index = coords.ch;
6413      if (coords.line < this.first || coords.ch < 0) return 0;
6414      this.iter(this.first, coords.line, function (line) {
6415        index += line.text.length + 1;
6416      });
6417      return index;
6418    },
6419
6420    copy: function(copyHistory) {
6421      var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
6422      doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
6423      doc.sel = this.sel;
6424      doc.extend = false;
6425      if (copyHistory) {
6426        doc.history.undoDepth = this.history.undoDepth;
6427        doc.setHistory(this.getHistory());
6428      }
6429      return doc;
6430    },
6431
6432    linkedDoc: function(options) {
6433      if (!options) options = {};
6434      var from = this.first, to = this.first + this.size;
6435      if (options.from != null && options.from > from) from = options.from;
6436      if (options.to != null && options.to < to) to = options.to;
6437      var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
6438      if (options.sharedHist) copy.history = this.history;
6439      (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
6440      copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
6441      copySharedMarkers(copy, findSharedMarkers(this));
6442      return copy;
6443    },
6444    unlinkDoc: function(other) {
6445      if (other instanceof CodeMirror) other = other.doc;
6446      if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
6447        var link = this.linked[i];
6448        if (link.doc != other) continue;
6449        this.linked.splice(i, 1);
6450        other.unlinkDoc(this);
6451        detachSharedMarkers(findSharedMarkers(this));
6452        break;
6453      }
6454      // If the histories were shared, split them again
6455      if (other.history == this.history) {
6456        var splitIds = [other.id];
6457        linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
6458        other.history = new History(null);
6459        other.history.done = copyHistoryArray(this.history.done, splitIds);
6460        other.history.undone = copyHistoryArray(this.history.undone, splitIds);
6461      }
6462    },
6463    iterLinkedDocs: function(f) {linkedDocs(this, f);},
6464
6465    getMode: function() {return this.mode;},
6466    getEditor: function() {return this.cm;}
6467  });
6468
6469  // Public alias.
6470  Doc.prototype.eachLine = Doc.prototype.iter;
6471
6472  // Set up methods on CodeMirror's prototype to redirect to the editor's document.
6473  var dontDelegate = "iter insert remove copy getEditor".split(" ");
6474  for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
6475    CodeMirror.prototype[prop] = (function(method) {
6476      return function() {return method.apply(this.doc, arguments);};
6477    })(Doc.prototype[prop]);
6478
6479  eventMixin(Doc);
6480
6481  // Call f for all linked documents.
6482  function linkedDocs(doc, f, sharedHistOnly) {
6483    function propagate(doc, skip, sharedHist) {
6484      if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
6485        var rel = doc.linked[i];
6486        if (rel.doc == skip) continue;
6487        var shared = sharedHist && rel.sharedHist;
6488        if (sharedHistOnly && !shared) continue;
6489        f(rel.doc, shared);
6490        propagate(rel.doc, doc, shared);
6491      }
6492    }
6493    propagate(doc, null, true);
6494  }
6495
6496  // Attach a document to an editor.
6497  function attachDoc(cm, doc) {
6498    if (doc.cm) throw new Error("This document is already in use.");
6499    cm.doc = doc;
6500    doc.cm = cm;
6501    estimateLineHeights(cm);
6502    loadMode(cm);
6503    if (!cm.options.lineWrapping) findMaxLine(cm);
6504    cm.options.mode = doc.modeOption;
6505    regChange(cm);
6506  }
6507
6508  // LINE UTILITIES
6509
6510  // Find the line object corresponding to the given line number.
6511  function getLine(doc, n) {
6512    n -= doc.first;
6513    if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
6514    for (var chunk = doc; !chunk.lines;) {
6515      for (var i = 0;; ++i) {
6516        var child = chunk.children[i], sz = child.chunkSize();
6517        if (n < sz) { chunk = child; break; }
6518        n -= sz;
6519      }
6520    }
6521    return chunk.lines[n];
6522  }
6523
6524  // Get the part of a document between two positions, as an array of
6525  // strings.
6526  function getBetween(doc, start, end) {
6527    var out = [], n = start.line;
6528    doc.iter(start.line, end.line + 1, function(line) {
6529      var text = line.text;
6530      if (n == end.line) text = text.slice(0, end.ch);
6531      if (n == start.line) text = text.slice(start.ch);
6532      out.push(text);
6533      ++n;
6534    });
6535    return out;
6536  }
6537  // Get the lines between from and to, as array of strings.
6538  function getLines(doc, from, to) {
6539    var out = [];
6540    doc.iter(from, to, function(line) { out.push(line.text); });
6541    return out;
6542  }
6543
6544  // Update the height of a line, propagating the height change
6545  // upwards to parent nodes.
6546  function updateLineHeight(line, height) {
6547    var diff = height - line.height;
6548    if (diff) for (var n = line; n; n = n.parent) n.height += diff;
6549  }
6550
6551  // Given a line object, find its line number by walking up through
6552  // its parent links.
6553  function lineNo(line) {
6554    if (line.parent == null) return null;
6555    var cur = line.parent, no = indexOf(cur.lines, line);
6556    for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
6557      for (var i = 0;; ++i) {
6558        if (chunk.children[i] == cur) break;
6559        no += chunk.children[i].chunkSize();
6560      }
6561    }
6562    return no + cur.first;
6563  }
6564
6565  // Find the line at the given vertical position, using the height
6566  // information in the document tree.
6567  function lineAtHeight(chunk, h) {
6568    var n = chunk.first;
6569    outer: do {
6570      for (var i = 0; i < chunk.children.length; ++i) {
6571        var child = chunk.children[i], ch = child.height;
6572        if (h < ch) { chunk = child; continue outer; }
6573        h -= ch;
6574        n += child.chunkSize();
6575      }
6576      return n;
6577    } while (!chunk.lines);
6578    for (var i = 0; i < chunk.lines.length; ++i) {
6579      var line = chunk.lines[i], lh = line.height;
6580      if (h < lh) break;
6581      h -= lh;
6582    }
6583    return n + i;
6584  }
6585
6586
6587  // Find the height above the given line.
6588  function heightAtLine(lineObj) {
6589    lineObj = visualLine(lineObj);
6590
6591    var h = 0, chunk = lineObj.parent;
6592    for (var i = 0; i < chunk.lines.length; ++i) {
6593      var line = chunk.lines[i];
6594      if (line == lineObj) break;
6595      else h += line.height;
6596    }
6597    for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
6598      for (var i = 0; i < p.children.length; ++i) {
6599        var cur = p.children[i];
6600        if (cur == chunk) break;
6601        else h += cur.height;
6602      }
6603    }
6604    return h;
6605  }
6606
6607  // Get the bidi ordering for the given line (and cache it). Returns
6608  // false for lines that are fully left-to-right, and an array of
6609  // BidiSpan objects otherwise.
6610  function getOrder(line) {
6611    var order = line.order;
6612    if (order == null) order = line.order = bidiOrdering(line.text);
6613    return order;
6614  }
6615
6616  // HISTORY
6617
6618  function History(startGen) {
6619    // Arrays of change events and selections. Doing something adds an
6620    // event to done and clears undo. Undoing moves events from done
6621    // to undone, redoing moves them in the other direction.
6622    this.done = []; this.undone = [];
6623    this.undoDepth = Infinity;
6624    // Used to track when changes can be merged into a single undo
6625    // event
6626    this.lastModTime = this.lastSelTime = 0;
6627    this.lastOp = null;
6628    this.lastOrigin = this.lastSelOrigin = null;
6629    // Used by the isClean() method
6630    this.generation = this.maxGeneration = startGen || 1;
6631  }
6632
6633  // Create a history change event from an updateDoc-style change
6634  // object.
6635  function historyChangeFromChange(doc, change) {
6636    var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
6637    attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
6638    linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
6639    return histChange;
6640  }
6641
6642  // Pop all selection events off the end of a history array. Stop at
6643  // a change event.
6644  function clearSelectionEvents(array) {
6645    while (array.length) {
6646      var last = lst(array);
6647      if (last.ranges) array.pop();
6648      else break;
6649    }
6650  }
6651
6652  // Find the top change event in the history. Pop off selection
6653  // events that are in the way.
6654  function lastChangeEvent(hist, force) {
6655    if (force) {
6656      clearSelectionEvents(hist.done);
6657      return lst(hist.done);
6658    } else if (hist.done.length && !lst(hist.done).ranges) {
6659      return lst(hist.done);
6660    } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
6661      hist.done.pop();
6662      return lst(hist.done);
6663    }
6664  }
6665
6666  // Register a change in the history. Merges changes that are within
6667  // a single operation, ore are close together with an origin that
6668  // allows merging (starting with "+") into a single event.
6669  function addChangeToHistory(doc, change, selAfter, opId) {
6670    var hist = doc.history;
6671    hist.undone.length = 0;
6672    var time = +new Date, cur;
6673
6674    if ((hist.lastOp == opId ||
6675         hist.lastOrigin == change.origin && change.origin &&
6676         ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
6677          change.origin.charAt(0) == "*")) &&
6678        (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
6679      // Merge this change into the last event
6680      var last = lst(cur.changes);
6681      if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
6682        // Optimized case for simple insertion -- don't want to add
6683        // new changesets for every character typed
6684        last.to = changeEnd(change);
6685      } else {
6686        // Add new sub-event
6687        cur.changes.push(historyChangeFromChange(doc, change));
6688      }
6689    } else {
6690      // Can not be merged, start a new event.
6691      var before = lst(hist.done);
6692      if (!before || !before.ranges)
6693        pushSelectionToHistory(doc.sel, hist.done);
6694      cur = {changes: [historyChangeFromChange(doc, change)],
6695             generation: hist.generation};
6696      hist.done.push(cur);
6697      while (hist.done.length > hist.undoDepth) {
6698        hist.done.shift();
6699        if (!hist.done[0].ranges) hist.done.shift();
6700      }
6701    }
6702    hist.done.push(selAfter);
6703    hist.generation = ++hist.maxGeneration;
6704    hist.lastModTime = hist.lastSelTime = time;
6705    hist.lastOp = opId;
6706    hist.lastOrigin = hist.lastSelOrigin = change.origin;
6707
6708    if (!last) signal(doc, "historyAdded");
6709  }
6710
6711  function selectionEventCanBeMerged(doc, origin, prev, sel) {
6712    var ch = origin.charAt(0);
6713    return ch == "*" ||
6714      ch == "+" &&
6715      prev.ranges.length == sel.ranges.length &&
6716      prev.somethingSelected() == sel.somethingSelected() &&
6717      new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
6718  }
6719
6720  // Called whenever the selection changes, sets the new selection as
6721  // the pending selection in the history, and pushes the old pending
6722  // selection into the 'done' array when it was significantly
6723  // different (in number of selected ranges, emptiness, or time).
6724  function addSelectionToHistory(doc, sel, opId, options) {
6725    var hist = doc.history, origin = options && options.origin;
6726
6727    // A new event is started when the previous origin does not match
6728    // the current, or the origins don't allow matching. Origins
6729    // starting with * are always merged, those starting with + are
6730    // merged when similar and close together in time.
6731    if (opId == hist.lastOp ||
6732        (origin && hist.lastSelOrigin == origin &&
6733         (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
6734          selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
6735      hist.done[hist.done.length - 1] = sel;
6736    else
6737      pushSelectionToHistory(sel, hist.done);
6738
6739    hist.lastSelTime = +new Date;
6740    hist.lastSelOrigin = origin;
6741    hist.lastOp = opId;
6742    if (options && options.clearRedo !== false)
6743      clearSelectionEvents(hist.undone);
6744  }
6745
6746  function pushSelectionToHistory(sel, dest) {
6747    var top = lst(dest);
6748    if (!(top && top.ranges && top.equals(sel)))
6749      dest.push(sel);
6750  }
6751
6752  // Used to store marked span information in the history.
6753  function attachLocalSpans(doc, change, from, to) {
6754    var existing = change["spans_" + doc.id], n = 0;
6755    doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
6756      if (line.markedSpans)
6757        (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
6758      ++n;
6759    });
6760  }
6761
6762  // When un/re-doing restores text containing marked spans, those
6763  // that have been explicitly cleared should not be restored.
6764  function removeClearedSpans(spans) {
6765    if (!spans) return null;
6766    for (var i = 0, out; i < spans.length; ++i) {
6767      if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
6768      else if (out) out.push(spans[i]);
6769    }
6770    return !out ? spans : out.length ? out : null;
6771  }
6772
6773  // Retrieve and filter the old marked spans stored in a change event.
6774  function getOldSpans(doc, change) {
6775    var found = change["spans_" + doc.id];
6776    if (!found) return null;
6777    for (var i = 0, nw = []; i < change.text.length; ++i)
6778      nw.push(removeClearedSpans(found[i]));
6779    return nw;
6780  }
6781
6782  // Used both to provide a JSON-safe object in .getHistory, and, when
6783  // detaching a document, to split the history in two
6784  function copyHistoryArray(events, newGroup, instantiateSel) {
6785    for (var i = 0, copy = []; i < events.length; ++i) {
6786      var event = events[i];
6787      if (event.ranges) {
6788        copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
6789        continue;
6790      }
6791      var changes = event.changes, newChanges = [];
6792      copy.push({changes: newChanges});
6793      for (var j = 0; j < changes.length; ++j) {
6794        var change = changes[j], m;
6795        newChanges.push({from: change.from, to: change.to, text: change.text});
6796        if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
6797          if (indexOf(newGroup, Number(m[1])) > -1) {
6798            lst(newChanges)[prop] = change[prop];
6799            delete change[prop];
6800          }
6801        }
6802      }
6803    }
6804    return copy;
6805  }
6806
6807  // Rebasing/resetting history to deal with externally-sourced changes
6808
6809  function rebaseHistSelSingle(pos, from, to, diff) {
6810    if (to < pos.line) {
6811      pos.line += diff;
6812    } else if (from < pos.line) {
6813      pos.line = from;
6814      pos.ch = 0;
6815    }
6816  }
6817
6818  // Tries to rebase an array of history events given a change in the
6819  // document. If the change touches the same lines as the event, the
6820  // event, and everything 'behind' it, is discarded. If the change is
6821  // before the event, the event's positions are updated. Uses a
6822  // copy-on-write scheme for the positions, to avoid having to
6823  // reallocate them all on every rebase, but also avoid problems with
6824  // shared position objects being unsafely updated.
6825  function rebaseHistArray(array, from, to, diff) {
6826    for (var i = 0; i < array.length; ++i) {
6827      var sub = array[i], ok = true;
6828      if (sub.ranges) {
6829        if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
6830        for (var j = 0; j < sub.ranges.length; j++) {
6831          rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
6832          rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
6833        }
6834        continue;
6835      }
6836      for (var j = 0; j < sub.changes.length; ++j) {
6837        var cur = sub.changes[j];
6838        if (to < cur.from.line) {
6839          cur.from = Pos(cur.from.line + diff, cur.from.ch);
6840          cur.to = Pos(cur.to.line + diff, cur.to.ch);
6841        } else if (from <= cur.to.line) {
6842          ok = false;
6843          break;
6844        }
6845      }
6846      if (!ok) {
6847        array.splice(0, i + 1);
6848        i = 0;
6849      }
6850    }
6851  }
6852
6853  function rebaseHist(hist, change) {
6854    var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
6855    rebaseHistArray(hist.done, from, to, diff);
6856    rebaseHistArray(hist.undone, from, to, diff);
6857  }
6858
6859  // EVENT UTILITIES
6860
6861  // Due to the fact that we still support jurassic IE versions, some
6862  // compatibility wrappers are needed.
6863
6864  var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
6865    if (e.preventDefault) e.preventDefault();
6866    else e.returnValue = false;
6867  };
6868  var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
6869    if (e.stopPropagation) e.stopPropagation();
6870    else e.cancelBubble = true;
6871  };
6872  function e_defaultPrevented(e) {
6873    return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
6874  }
6875  var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
6876
6877  function e_target(e) {return e.target || e.srcElement;}
6878  function e_button(e) {
6879    var b = e.which;
6880    if (b == null) {
6881      if (e.button & 1) b = 1;
6882      else if (e.button & 2) b = 3;
6883      else if (e.button & 4) b = 2;
6884    }
6885    if (mac && e.ctrlKey && b == 1) b = 3;
6886    return b;
6887  }
6888
6889  // EVENT HANDLING
6890
6891  // Lightweight event framework. on/off also work on DOM nodes,
6892  // registering native DOM handlers.
6893
6894  var on = CodeMirror.on = function(emitter, type, f) {
6895    if (emitter.addEventListener)
6896      emitter.addEventListener(type, f, false);
6897    else if (emitter.attachEvent)
6898      emitter.attachEvent("on" + type, f);
6899    else {
6900      var map = emitter._handlers || (emitter._handlers = {});
6901      var arr = map[type] || (map[type] = []);
6902      arr.push(f);
6903    }
6904  };
6905
6906  var off = CodeMirror.off = function(emitter, type, f) {
6907    if (emitter.removeEventListener)
6908      emitter.removeEventListener(type, f, false);
6909    else if (emitter.detachEvent)
6910      emitter.detachEvent("on" + type, f);
6911    else {
6912      var arr = emitter._handlers && emitter._handlers[type];
6913      if (!arr) return;
6914      for (var i = 0; i < arr.length; ++i)
6915        if (arr[i] == f) { arr.splice(i, 1); break; }
6916    }
6917  };
6918
6919  var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
6920    var arr = emitter._handlers && emitter._handlers[type];
6921    if (!arr) return;
6922    var args = Array.prototype.slice.call(arguments, 2);
6923    for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
6924  };
6925
6926  // Often, we want to signal events at a point where we are in the
6927  // middle of some work, but don't want the handler to start calling
6928  // other methods on the editor, which might be in an inconsistent
6929  // state or simply not expect any other events to happen.
6930  // signalLater looks whether there are any handlers, and schedules
6931  // them to be executed when the last operation ends, or, if no
6932  // operation is active, when a timeout fires.
6933  var delayedCallbacks, delayedCallbackDepth = 0;
6934  function signalLater(emitter, type /*, values...*/) {
6935    var arr = emitter._handlers && emitter._handlers[type];
6936    if (!arr) return;
6937    var args = Array.prototype.slice.call(arguments, 2);
6938    if (!delayedCallbacks) {
6939      ++delayedCallbackDepth;
6940      delayedCallbacks = [];
6941      setTimeout(fireDelayed, 0);
6942    }
6943    function bnd(f) {return function(){f.apply(null, args);};};
6944    for (var i = 0; i < arr.length; ++i)
6945      delayedCallbacks.push(bnd(arr[i]));
6946  }
6947
6948  function fireDelayed() {
6949    --delayedCallbackDepth;
6950    var delayed = delayedCallbacks;
6951    delayedCallbacks = null;
6952    for (var i = 0; i < delayed.length; ++i) delayed[i]();
6953  }
6954
6955  // The DOM events that CodeMirror handles can be overridden by
6956  // registering a (non-DOM) handler on the editor for the event name,
6957  // and preventDefault-ing the event in that handler.
6958  function signalDOMEvent(cm, e, override) {
6959    signal(cm, override || e.type, cm, e);
6960    return e_defaultPrevented(e) || e.codemirrorIgnore;
6961  }
6962
6963  function signalCursorActivity(cm) {
6964    var arr = cm._handlers && cm._handlers.cursorActivity;
6965    if (!arr) return;
6966    var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
6967    for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
6968      set.push(arr[i]);
6969  }
6970
6971  function hasHandler(emitter, type) {
6972    var arr = emitter._handlers && emitter._handlers[type];
6973    return arr && arr.length > 0;
6974  }
6975
6976  // Add on and off methods to a constructor's prototype, to make
6977  // registering events on such objects more convenient.
6978  function eventMixin(ctor) {
6979    ctor.prototype.on = function(type, f) {on(this, type, f);};
6980    ctor.prototype.off = function(type, f) {off(this, type, f);};
6981  }
6982
6983  // MISC UTILITIES
6984
6985  // Number of pixels added to scroller and sizer to hide scrollbar
6986  var scrollerCutOff = 30;
6987
6988  // Returned or thrown by various protocols to signal 'I'm not
6989  // handling this'.
6990  var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
6991
6992  // Reused option objects for setSelection & friends
6993  var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
6994
6995  function Delayed() {this.id = null;}
6996  Delayed.prototype.set = function(ms, f) {
6997    clearTimeout(this.id);
6998    this.id = setTimeout(f, ms);
6999  };
7000
7001  // Counts the column offset in a string, taking tabs into account.
7002  // Used mostly to find indentation.
7003  var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
7004    if (end == null) {
7005      end = string.search(/[^\s\u00a0]/);
7006      if (end == -1) end = string.length;
7007    }
7008    for (var i = startIndex || 0, n = startValue || 0;;) {
7009      var nextTab = string.indexOf("\t", i);
7010      if (nextTab < 0 || nextTab >= end)
7011        return n + (end - i);
7012      n += nextTab - i;
7013      n += tabSize - (n % tabSize);
7014      i = nextTab + 1;
7015    }
7016  };
7017
7018  // The inverse of countColumn -- find the offset that corresponds to
7019  // a particular column.
7020  function findColumn(string, goal, tabSize) {
7021    for (var pos = 0, col = 0;;) {
7022      var nextTab = string.indexOf("\t", pos);
7023      if (nextTab == -1) nextTab = string.length;
7024      var skipped = nextTab - pos;
7025      if (nextTab == string.length || col + skipped >= goal)
7026        return pos + Math.min(skipped, goal - col);
7027      col += nextTab - pos;
7028      col += tabSize - (col % tabSize);
7029      pos = nextTab + 1;
7030      if (col >= goal) return pos;
7031    }
7032  }
7033
7034  var spaceStrs = [""];
7035  function spaceStr(n) {
7036    while (spaceStrs.length <= n)
7037      spaceStrs.push(lst(spaceStrs) + " ");
7038    return spaceStrs[n];
7039  }
7040
7041  function lst(arr) { return arr[arr.length-1]; }
7042
7043  var selectInput = function(node) { node.select(); };
7044  if (ios) // Mobile Safari apparently has a bug where select() is broken.
7045    selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
7046  else if (ie) // Suppress mysterious IE10 errors
7047    selectInput = function(node) { try { node.select(); } catch(_e) {} };
7048
7049  function indexOf(array, elt) {
7050    for (var i = 0; i < array.length; ++i)
7051      if (array[i] == elt) return i;
7052    return -1;
7053  }
7054  if ([].indexOf) indexOf = function(array, elt) { return array.indexOf(elt); };
7055  function map(array, f) {
7056    var out = [];
7057    for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
7058    return out;
7059  }
7060  if ([].map) map = function(array, f) { return array.map(f); };
7061
7062  function createObj(base, props) {
7063    var inst;
7064    if (Object.create) {
7065      inst = Object.create(base);
7066    } else {
7067      var ctor = function() {};
7068      ctor.prototype = base;
7069      inst = new ctor();
7070    }
7071    if (props) copyObj(props, inst);
7072    return inst;
7073  };
7074
7075  function copyObj(obj, target, overwrite) {
7076    if (!target) target = {};
7077    for (var prop in obj)
7078      if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
7079        target[prop] = obj[prop];
7080    return target;
7081  }
7082
7083  function bind(f) {
7084    var args = Array.prototype.slice.call(arguments, 1);
7085    return function(){return f.apply(null, args);};
7086  }
7087
7088  var nonASCIISingleCaseWordChar = /[\u00df\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
7089  var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
7090    return /\w/.test(ch) || ch > "\x80" &&
7091      (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
7092  };
7093  function isWordChar(ch, helper) {
7094    if (!helper) return isWordCharBasic(ch);
7095    if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
7096    return helper.test(ch);
7097  }
7098
7099  function isEmpty(obj) {
7100    for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
7101    return true;
7102  }
7103
7104  // Extending unicode characters. A series of a non-extending char +
7105  // any number of extending chars is treated as a single unit as far
7106  // as editing and measuring is concerned. This is not fully correct,
7107  // since some scripts/fonts/browsers also treat other configurations
7108  // of code points as a group.
7109  var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
7110  function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
7111
7112  // DOM UTILITIES
7113
7114  function elt(tag, content, className, style) {
7115    var e = document.createElement(tag);
7116    if (className) e.className = className;
7117    if (style) e.style.cssText = style;
7118    if (typeof content == "string") e.appendChild(document.createTextNode(content));
7119    else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
7120    return e;
7121  }
7122
7123  var range;
7124  if (document.createRange) range = function(node, start, end) {
7125    var r = document.createRange();
7126    r.setEnd(node, end);
7127    r.setStart(node, start);
7128    return r;
7129  };
7130  else range = function(node, start, end) {
7131    var r = document.body.createTextRange();
7132    r.moveToElementText(node.parentNode);
7133    r.collapse(true);
7134    r.moveEnd("character", end);
7135    r.moveStart("character", start);
7136    return r;
7137  };
7138
7139  function removeChildren(e) {
7140    for (var count = e.childNodes.length; count > 0; --count)
7141      e.removeChild(e.firstChild);
7142    return e;
7143  }
7144
7145  function removeChildrenAndAdd(parent, e) {
7146    return removeChildren(parent).appendChild(e);
7147  }
7148
7149  function contains(parent, child) {
7150    if (parent.contains)
7151      return parent.contains(child);
7152    while (child = child.parentNode)
7153      if (child == parent) return true;
7154  }
7155
7156  function activeElt() { return document.activeElement; }
7157  // Older versions of IE throws unspecified error when touching
7158  // document.activeElement in some cases (during loading, in iframe)
7159  if (ie_upto10) activeElt = function() {
7160    try { return document.activeElement; }
7161    catch(e) { return document.body; }
7162  };
7163
7164  function classTest(cls) { return new RegExp("\\b" + cls + "\\b\\s*"); }
7165  function rmClass(node, cls) {
7166    var test = classTest(cls);
7167    if (test.test(node.className)) node.className = node.className.replace(test, "");
7168  }
7169  function addClass(node, cls) {
7170    if (!classTest(cls).test(node.className)) node.className += " " + cls;
7171  }
7172  function joinClasses(a, b) {
7173    var as = a.split(" ");
7174    for (var i = 0; i < as.length; i++)
7175      if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
7176    return b;
7177  }
7178
7179  // WINDOW-WIDE EVENTS
7180
7181  // These must be handled carefully, because naively registering a
7182  // handler for each editor will cause the editors to never be
7183  // garbage collected.
7184
7185  function forEachCodeMirror(f) {
7186    if (!document.body.getElementsByClassName) return;
7187    var byClass = document.body.getElementsByClassName("CodeMirror");
7188    for (var i = 0; i < byClass.length; i++) {
7189      var cm = byClass[i].CodeMirror;
7190      if (cm) f(cm);
7191    }
7192  }
7193
7194  var globalsRegistered = false;
7195  function ensureGlobalHandlers() {
7196    if (globalsRegistered) return;
7197    registerGlobalHandlers();
7198    globalsRegistered = true;
7199  }
7200  function registerGlobalHandlers() {
7201    // When the window resizes, we need to refresh active editors.
7202    var resizeTimer;
7203    on(window, "resize", function() {
7204      if (resizeTimer == null) resizeTimer = setTimeout(function() {
7205        resizeTimer = null;
7206        knownScrollbarWidth = null;
7207        forEachCodeMirror(onResize);
7208      }, 100);
7209    });
7210    // When the window loses focus, we want to show the editor as blurred
7211    on(window, "blur", function() {
7212      forEachCodeMirror(onBlur);
7213    });
7214  }
7215
7216  // FEATURE DETECTION
7217
7218  // Detect drag-and-drop
7219  var dragAndDrop = function() {
7220    // There is *some* kind of drag-and-drop support in IE6-8, but I
7221    // couldn't get it to work yet.
7222    if (ie_upto8) return false;
7223    var div = elt('div');
7224    return "draggable" in div || "dragDrop" in div;
7225  }();
7226
7227  var knownScrollbarWidth;
7228  function scrollbarWidth(measure) {
7229    if (knownScrollbarWidth != null) return knownScrollbarWidth;
7230    var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll");
7231    removeChildrenAndAdd(measure, test);
7232    if (test.offsetWidth)
7233      knownScrollbarWidth = test.offsetHeight - test.clientHeight;
7234    return knownScrollbarWidth || 0;
7235  }
7236
7237  var zwspSupported;
7238  function zeroWidthElement(measure) {
7239    if (zwspSupported == null) {
7240      var test = elt("span", "\u200b");
7241      removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
7242      if (measure.firstChild.offsetHeight != 0)
7243        zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_upto7;
7244    }
7245    if (zwspSupported) return elt("span", "\u200b");
7246    else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
7247  }
7248
7249  // Feature-detect IE's crummy client rect reporting for bidi text
7250  var badBidiRects;
7251  function hasBadBidiRects(measure) {
7252    if (badBidiRects != null) return badBidiRects;
7253    var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
7254    var r0 = range(txt, 0, 1).getBoundingClientRect();
7255    if (r0.left == r0.right) return false;
7256    var r1 = range(txt, 1, 2).getBoundingClientRect();
7257    return badBidiRects = (r1.right - r0.right < 3);
7258  }
7259
7260  // See if "".split is the broken IE version, if so, provide an
7261  // alternative way to split lines.
7262  var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
7263    var pos = 0, result = [], l = string.length;
7264    while (pos <= l) {
7265      var nl = string.indexOf("\n", pos);
7266      if (nl == -1) nl = string.length;
7267      var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
7268      var rt = line.indexOf("\r");
7269      if (rt != -1) {
7270        result.push(line.slice(0, rt));
7271        pos += rt + 1;
7272      } else {
7273        result.push(line);
7274        pos = nl + 1;
7275      }
7276    }
7277    return result;
7278  } : function(string){return string.split(/\r\n?|\n/);};
7279
7280  var hasSelection = window.getSelection ? function(te) {
7281    try { return te.selectionStart != te.selectionEnd; }
7282    catch(e) { return false; }
7283  } : function(te) {
7284    try {var range = te.ownerDocument.selection.createRange();}
7285    catch(e) {}
7286    if (!range || range.parentElement() != te) return false;
7287    return range.compareEndPoints("StartToEnd", range) != 0;
7288  };
7289
7290  var hasCopyEvent = (function() {
7291    var e = elt("div");
7292    if ("oncopy" in e) return true;
7293    e.setAttribute("oncopy", "return;");
7294    return typeof e.oncopy == "function";
7295  })();
7296
7297  // KEY NAMES
7298
7299  var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
7300                  19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
7301                  36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
7302                  46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete",
7303                  173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
7304                  221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
7305                  63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"};
7306  CodeMirror.keyNames = keyNames;
7307  (function() {
7308    // Number keys
7309    for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
7310    // Alphabetic keys
7311    for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
7312    // Function keys
7313    for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
7314  })();
7315
7316  // BIDI HELPERS
7317
7318  function iterateBidiSections(order, from, to, f) {
7319    if (!order) return f(from, to, "ltr");
7320    var found = false;
7321    for (var i = 0; i < order.length; ++i) {
7322      var part = order[i];
7323      if (part.from < to && part.to > from || from == to && part.to == from) {
7324        f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
7325        found = true;
7326      }
7327    }
7328    if (!found) f(from, to, "ltr");
7329  }
7330
7331  function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
7332  function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
7333
7334  function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
7335  function lineRight(line) {
7336    var order = getOrder(line);
7337    if (!order) return line.text.length;
7338    return bidiRight(lst(order));
7339  }
7340
7341  function lineStart(cm, lineN) {
7342    var line = getLine(cm.doc, lineN);
7343    var visual = visualLine(line);
7344    if (visual != line) lineN = lineNo(visual);
7345    var order = getOrder(visual);
7346    var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
7347    return Pos(lineN, ch);
7348  }
7349  function lineEnd(cm, lineN) {
7350    var merged, line = getLine(cm.doc, lineN);
7351    while (merged = collapsedSpanAtEnd(line)) {
7352      line = merged.find(1, true).line;
7353      lineN = null;
7354    }
7355    var order = getOrder(line);
7356    var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
7357    return Pos(lineN == null ? lineNo(line) : lineN, ch);
7358  }
7359
7360  function compareBidiLevel(order, a, b) {
7361    var linedir = order[0].level;
7362    if (a == linedir) return true;
7363    if (b == linedir) return false;
7364    return a < b;
7365  }
7366  var bidiOther;
7367  function getBidiPartAt(order, pos) {
7368    bidiOther = null;
7369    for (var i = 0, found; i < order.length; ++i) {
7370      var cur = order[i];
7371      if (cur.from < pos && cur.to > pos) return i;
7372      if ((cur.from == pos || cur.to == pos)) {
7373        if (found == null) {
7374          found = i;
7375        } else if (compareBidiLevel(order, cur.level, order[found].level)) {
7376          if (cur.from != cur.to) bidiOther = found;
7377          return i;
7378        } else {
7379          if (cur.from != cur.to) bidiOther = i;
7380          return found;
7381        }
7382      }
7383    }
7384    return found;
7385  }
7386
7387  function moveInLine(line, pos, dir, byUnit) {
7388    if (!byUnit) return pos + dir;
7389    do pos += dir;
7390    while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
7391    return pos;
7392  }
7393
7394  // This is needed in order to move 'visually' through bi-directional
7395  // text -- i.e., pressing left should make the cursor go left, even
7396  // when in RTL text. The tricky part is the 'jumps', where RTL and
7397  // LTR text touch each other. This often requires the cursor offset
7398  // to move more than one unit, in order to visually move one unit.
7399  function moveVisually(line, start, dir, byUnit) {
7400    var bidi = getOrder(line);
7401    if (!bidi) return moveLogically(line, start, dir, byUnit);
7402    var pos = getBidiPartAt(bidi, start), part = bidi[pos];
7403    var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
7404
7405    for (;;) {
7406      if (target > part.from && target < part.to) return target;
7407      if (target == part.from || target == part.to) {
7408        if (getBidiPartAt(bidi, target) == pos) return target;
7409        part = bidi[pos += dir];
7410        return (dir > 0) == part.level % 2 ? part.to : part.from;
7411      } else {
7412        part = bidi[pos += dir];
7413        if (!part) return null;
7414        if ((dir > 0) == part.level % 2)
7415          target = moveInLine(line, part.to, -1, byUnit);
7416        else
7417          target = moveInLine(line, part.from, 1, byUnit);
7418      }
7419    }
7420  }
7421
7422  function moveLogically(line, start, dir, byUnit) {
7423    var target = start + dir;
7424    if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
7425    return target < 0 || target > line.text.length ? null : target;
7426  }
7427
7428  // Bidirectional ordering algorithm
7429  // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
7430  // that this (partially) implements.
7431
7432  // One-char codes used for character types:
7433  // L (L):   Left-to-Right
7434  // R (R):   Right-to-Left
7435  // r (AL):  Right-to-Left Arabic
7436  // 1 (EN):  European Number
7437  // + (ES):  European Number Separator
7438  // % (ET):  European Number Terminator
7439  // n (AN):  Arabic Number
7440  // , (CS):  Common Number Separator
7441  // m (NSM): Non-Spacing Mark
7442  // b (BN):  Boundary Neutral
7443  // s (B):   Paragraph Separator
7444  // t (S):   Segment Separator
7445  // w (WS):  Whitespace
7446  // N (ON):  Other Neutrals
7447
7448  // Returns null if characters are ordered as they appear
7449  // (left-to-right), or an array of sections ({from, to, level}
7450  // objects) in the order in which they occur visually.
7451  var bidiOrdering = (function() {
7452    // Character types for codepoints 0 to 0xff
7453    var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
7454    // Character types for codepoints 0x600 to 0x6ff
7455    var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
7456    function charType(code) {
7457      if (code <= 0xf7) return lowTypes.charAt(code);
7458      else if (0x590 <= code && code <= 0x5f4) return "R";
7459      else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
7460      else if (0x6ee <= code && code <= 0x8ac) return "r";
7461      else if (0x2000 <= code && code <= 0x200b) return "w";
7462      else if (code == 0x200c) return "b";
7463      else return "L";
7464    }
7465
7466    var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
7467    var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
7468    // Browsers seem to always treat the boundaries of block elements as being L.
7469    var outerType = "L";
7470
7471    function BidiSpan(level, from, to) {
7472      this.level = level;
7473      this.from = from; this.to = to;
7474    }
7475
7476    return function(str) {
7477      if (!bidiRE.test(str)) return false;
7478      var len = str.length, types = [];
7479      for (var i = 0, type; i < len; ++i)
7480        types.push(type = charType(str.charCodeAt(i)));
7481
7482      // W1. Examine each non-spacing mark (NSM) in the level run, and
7483      // change the type of the NSM to the type of the previous
7484      // character. If the NSM is at the start of the level run, it will
7485      // get the type of sor.
7486      for (var i = 0, prev = outerType; i < len; ++i) {
7487        var type = types[i];
7488        if (type == "m") types[i] = prev;
7489        else prev = type;
7490      }
7491
7492      // W2. Search backwards from each instance of a European number
7493      // until the first strong type (R, L, AL, or sor) is found. If an
7494      // AL is found, change the type of the European number to Arabic
7495      // number.
7496      // W3. Change all ALs to R.
7497      for (var i = 0, cur = outerType; i < len; ++i) {
7498        var type = types[i];
7499        if (type == "1" && cur == "r") types[i] = "n";
7500        else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
7501      }
7502
7503      // W4. A single European separator between two European numbers
7504      // changes to a European number. A single common separator between
7505      // two numbers of the same type changes to that type.
7506      for (var i = 1, prev = types[0]; i < len - 1; ++i) {
7507        var type = types[i];
7508        if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
7509        else if (type == "," && prev == types[i+1] &&
7510                 (prev == "1" || prev == "n")) types[i] = prev;
7511        prev = type;
7512      }
7513
7514      // W5. A sequence of European terminators adjacent to European
7515      // numbers changes to all European numbers.
7516      // W6. Otherwise, separators and terminators change to Other
7517      // Neutral.
7518      for (var i = 0; i < len; ++i) {
7519        var type = types[i];
7520        if (type == ",") types[i] = "N";
7521        else if (type == "%") {
7522          for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
7523          var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
7524          for (var j = i; j < end; ++j) types[j] = replace;
7525          i = end - 1;
7526        }
7527      }
7528
7529      // W7. Search backwards from each instance of a European number
7530      // until the first strong type (R, L, or sor) is found. If an L is
7531      // found, then change the type of the European number to L.
7532      for (var i = 0, cur = outerType; i < len; ++i) {
7533        var type = types[i];
7534        if (cur == "L" && type == "1") types[i] = "L";
7535        else if (isStrong.test(type)) cur = type;
7536      }
7537
7538      // N1. A sequence of neutrals takes the direction of the
7539      // surrounding strong text if the text on both sides has the same
7540      // direction. European and Arabic numbers act as if they were R in
7541      // terms of their influence on neutrals. Start-of-level-run (sor)
7542      // and end-of-level-run (eor) are used at level run boundaries.
7543      // N2. Any remaining neutrals take the embedding direction.
7544      for (var i = 0; i < len; ++i) {
7545        if (isNeutral.test(types[i])) {
7546          for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
7547          var before = (i ? types[i-1] : outerType) == "L";
7548          var after = (end < len ? types[end] : outerType) == "L";
7549          var replace = before || after ? "L" : "R";
7550          for (var j = i; j < end; ++j) types[j] = replace;
7551          i = end - 1;
7552        }
7553      }
7554
7555      // Here we depart from the documented algorithm, in order to avoid
7556      // building up an actual levels array. Since there are only three
7557      // levels (0, 1, 2) in an implementation that doesn't take
7558      // explicit embedding into account, we can build up the order on
7559      // the fly, without following the level-based algorithm.
7560      var order = [], m;
7561      for (var i = 0; i < len;) {
7562        if (countsAsLeft.test(types[i])) {
7563          var start = i;
7564          for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
7565          order.push(new BidiSpan(0, start, i));
7566        } else {
7567          var pos = i, at = order.length;
7568          for (++i; i < len && types[i] != "L"; ++i) {}
7569          for (var j = pos; j < i;) {
7570            if (countsAsNum.test(types[j])) {
7571              if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
7572              var nstart = j;
7573              for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
7574              order.splice(at, 0, new BidiSpan(2, nstart, j));
7575              pos = j;
7576            } else ++j;
7577          }
7578          if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
7579        }
7580      }
7581      if (order[0].level == 1 && (m = str.match(/^\s+/))) {
7582        order[0].from = m[0].length;
7583        order.unshift(new BidiSpan(0, 0, m[0].length));
7584      }
7585      if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
7586        lst(order).to -= m[0].length;
7587        order.push(new BidiSpan(0, len - m[0].length, len));
7588      }
7589      if (order[0].level != lst(order).level)
7590        order.push(new BidiSpan(order[0].level, len, len));
7591
7592      return order;
7593    };
7594  })();
7595
7596  // THE END
7597
7598  CodeMirror.version = "4.2.0";
7599
7600  return CodeMirror;
7601});
7602