Kartom

codemirror.js from Trampermonkey beta(dec 2014)

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