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