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