Subversion Repositories wimsdev

Rev

Rev 14283 | Rev 15332 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/LICENSE
  3.  
  4. // This is CodeMirror (https://codemirror.net), a code editor
  5. // implemented in JavaScript on top of the browser's DOM.
  6. //
  7. // You can find some technical background for some of the code below
  8. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  9.  
  10. (function (global, factory) {
  11.   typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  12.   typeof define === 'function' && define.amd ? define(factory) :
  13.   (global = global || self, global.CodeMirror = factory());
  14. }(this, (function () { 'use strict';
  15.  
  16.   // Kludges for bugs and behavior differences that can't be feature
  17.   // detected are enabled based on userAgent etc sniffing.
  18.   var userAgent = navigator.userAgent;
  19.   var platform = navigator.platform;
  20.  
  21.   var gecko = /gecko\/\d/i.test(userAgent);
  22.   var ie_upto10 = /MSIE \d/.test(userAgent);
  23.   var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  24.   var edge = /Edge\/(\d+)/.exec(userAgent);
  25.   var ie = ie_upto10 || ie_11up || edge;
  26.   var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
  27.   var webkit = !edge && /WebKit\//.test(userAgent);
  28.   var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  29.   var chrome = !edge && /Chrome\//.test(userAgent);
  30.   var presto = /Opera\//.test(userAgent);
  31.   var safari = /Apple Computer/.test(navigator.vendor);
  32.   var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  33.   var phantom = /PhantomJS/.test(userAgent);
  34.  
  35.   var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
  36.   var android = /Android/.test(userAgent);
  37.   // This is woefully incomplete. Suggestions for alternative methods welcome.
  38.   var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  39.   var mac = ios || /Mac/.test(platform);
  40.   var chromeOS = /\bCrOS\b/.test(userAgent);
  41.   var windows = /win/i.test(platform);
  42.  
  43.   var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  44.   if (presto_version) { presto_version = Number(presto_version[1]); }
  45.   if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  46.   // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  47.   var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  48.   var captureRightClick = gecko || (ie && ie_version >= 9);
  49.  
  50.   function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  51.  
  52.   var rmClass = function(node, cls) {
  53.     var current = node.className;
  54.     var match = classTest(cls).exec(current);
  55.     if (match) {
  56.       var after = current.slice(match.index + match[0].length);
  57.       node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  58.     }
  59.   };
  60.  
  61.   function removeChildren(e) {
  62.     for (var count = e.childNodes.length; count > 0; --count)
  63.       { e.removeChild(e.firstChild); }
  64.     return e
  65.   }
  66.  
  67.   function removeChildrenAndAdd(parent, e) {
  68.     return removeChildren(parent).appendChild(e)
  69.   }
  70.  
  71.   function elt(tag, content, className, style) {
  72.     var e = document.createElement(tag);
  73.     if (className) { e.className = className; }
  74.     if (style) { e.style.cssText = style; }
  75.     if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
  76.     else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
  77.     return e
  78.   }
  79.   // wrapper for elt, which removes the elt from the accessibility tree
  80.   function eltP(tag, content, className, style) {
  81.     var e = elt(tag, content, className, style);
  82.     e.setAttribute("role", "presentation");
  83.     return e
  84.   }
  85.  
  86.   var range;
  87.   if (document.createRange) { range = function(node, start, end, endNode) {
  88.     var r = document.createRange();
  89.     r.setEnd(endNode || node, end);
  90.     r.setStart(node, start);
  91.     return r
  92.   }; }
  93.   else { range = function(node, start, end) {
  94.     var r = document.body.createTextRange();
  95.     try { r.moveToElementText(node.parentNode); }
  96.     catch(e) { return r }
  97.     r.collapse(true);
  98.     r.moveEnd("character", end);
  99.     r.moveStart("character", start);
  100.     return r
  101.   }; }
  102.  
  103.   function contains(parent, child) {
  104.     if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  105.       { child = child.parentNode; }
  106.     if (parent.contains)
  107.       { return parent.contains(child) }
  108.     do {
  109.       if (child.nodeType == 11) { child = child.host; }
  110.       if (child == parent) { return true }
  111.     } while (child = child.parentNode)
  112.   }
  113.  
  114.   function activeElt() {
  115.     // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  116.     // IE < 10 will throw when accessed while the page is loading or in an iframe.
  117.     // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  118.     var activeElement;
  119.     try {
  120.       activeElement = document.activeElement;
  121.     } catch(e) {
  122.       activeElement = document.body || null;
  123.     }
  124.     while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  125.       { activeElement = activeElement.shadowRoot.activeElement; }
  126.     return activeElement
  127.   }
  128.  
  129.   function addClass(node, cls) {
  130.     var current = node.className;
  131.     if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
  132.   }
  133.   function joinClasses(a, b) {
  134.     var as = a.split(" ");
  135.     for (var i = 0; i < as.length; i++)
  136.       { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
  137.     return b
  138.   }
  139.  
  140.   var selectInput = function(node) { node.select(); };
  141.   if (ios) // Mobile Safari apparently has a bug where select() is broken.
  142.     { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
  143.   else if (ie) // Suppress mysterious IE10 errors
  144.     { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
  145.  
  146.   function bind(f) {
  147.     var args = Array.prototype.slice.call(arguments, 1);
  148.     return function(){return f.apply(null, args)}
  149.   }
  150.  
  151.   function copyObj(obj, target, overwrite) {
  152.     if (!target) { target = {}; }
  153.     for (var prop in obj)
  154.       { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  155.         { target[prop] = obj[prop]; } }
  156.     return target
  157.   }
  158.  
  159.   // Counts the column offset in a string, taking tabs into account.
  160.   // Used mostly to find indentation.
  161.   function countColumn(string, end, tabSize, startIndex, startValue) {
  162.     if (end == null) {
  163.       end = string.search(/[^\s\u00a0]/);
  164.       if (end == -1) { end = string.length; }
  165.     }
  166.     for (var i = startIndex || 0, n = startValue || 0;;) {
  167.       var nextTab = string.indexOf("\t", i);
  168.       if (nextTab < 0 || nextTab >= end)
  169.         { return n + (end - i) }
  170.       n += nextTab - i;
  171.       n += tabSize - (n % tabSize);
  172.       i = nextTab + 1;
  173.     }
  174.   }
  175.  
  176.   var Delayed = function() {
  177.     this.id = null;
  178.     this.f = null;
  179.     this.time = 0;
  180.     this.handler = bind(this.onTimeout, this);
  181.   };
  182.   Delayed.prototype.onTimeout = function (self) {
  183.     self.id = 0;
  184.     if (self.time <= +new Date) {
  185.       self.f();
  186.     } else {
  187.       setTimeout(self.handler, self.time - +new Date);
  188.     }
  189.   };
  190.   Delayed.prototype.set = function (ms, f) {
  191.     this.f = f;
  192.     var time = +new Date + ms;
  193.     if (!this.id || time < this.time) {
  194.       clearTimeout(this.id);
  195.       this.id = setTimeout(this.handler, ms);
  196.       this.time = time;
  197.     }
  198.   };
  199.  
  200.   function indexOf(array, elt) {
  201.     for (var i = 0; i < array.length; ++i)
  202.       { if (array[i] == elt) { return i } }
  203.     return -1
  204.   }
  205.  
  206.   // Number of pixels added to scroller and sizer to hide scrollbar
  207.   var scrollerGap = 50;
  208.  
  209.   // Returned or thrown by various protocols to signal 'I'm not
  210.   // handling this'.
  211.   var Pass = {toString: function(){return "CodeMirror.Pass"}};
  212.  
  213.   // Reused option objects for setSelection & friends
  214.   var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  215.  
  216.   // The inverse of countColumn -- find the offset that corresponds to
  217.   // a particular column.
  218.   function findColumn(string, goal, tabSize) {
  219.     for (var pos = 0, col = 0;;) {
  220.       var nextTab = string.indexOf("\t", pos);
  221.       if (nextTab == -1) { nextTab = string.length; }
  222.       var skipped = nextTab - pos;
  223.       if (nextTab == string.length || col + skipped >= goal)
  224.         { return pos + Math.min(skipped, goal - col) }
  225.       col += nextTab - pos;
  226.       col += tabSize - (col % tabSize);
  227.       pos = nextTab + 1;
  228.       if (col >= goal) { return pos }
  229.     }
  230.   }
  231.  
  232.   var spaceStrs = [""];
  233.   function spaceStr(n) {
  234.     while (spaceStrs.length <= n)
  235.       { spaceStrs.push(lst(spaceStrs) + " "); }
  236.     return spaceStrs[n]
  237.   }
  238.  
  239.   function lst(arr) { return arr[arr.length-1] }
  240.  
  241.   function map(array, f) {
  242.     var out = [];
  243.     for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  244.     return out
  245.   }
  246.  
  247.   function insertSorted(array, value, score) {
  248.     var pos = 0, priority = score(value);
  249.     while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  250.     array.splice(pos, 0, value);
  251.   }
  252.  
  253.   function nothing() {}
  254.  
  255.   function createObj(base, props) {
  256.     var inst;
  257.     if (Object.create) {
  258.       inst = Object.create(base);
  259.     } else {
  260.       nothing.prototype = base;
  261.       inst = new nothing();
  262.     }
  263.     if (props) { copyObj(props, inst); }
  264.     return inst
  265.   }
  266.  
  267.   var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  268.   function isWordCharBasic(ch) {
  269.     return /\w/.test(ch) || ch > "\x80" &&
  270.       (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  271.   }
  272.   function isWordChar(ch, helper) {
  273.     if (!helper) { return isWordCharBasic(ch) }
  274.     if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  275.     return helper.test(ch)
  276.   }
  277.  
  278.   function isEmpty(obj) {
  279.     for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  280.     return true
  281.   }
  282.  
  283.   // Extending unicode characters. A series of a non-extending char +
  284.   // any number of extending chars is treated as a single unit as far
  285.   // as editing and measuring is concerned. This is not fully correct,
  286.   // since some scripts/fonts/browsers also treat other configurations
  287.   // of code points as a group.
  288.   var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
  289.   function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  290.  
  291.   // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  292.   function skipExtendingChars(str, pos, dir) {
  293.     while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  294.     return pos
  295.   }
  296.  
  297.   // Returns the value from the range [`from`; `to`] that satisfies
  298.   // `pred` and is closest to `from`. Assumes that at least `to`
  299.   // satisfies `pred`. Supports `from` being greater than `to`.
  300.   function findFirst(pred, from, to) {
  301.     // At any point we are certain `to` satisfies `pred`, don't know
  302.     // whether `from` does.
  303.     var dir = from > to ? -1 : 1;
  304.     for (;;) {
  305.       if (from == to) { return from }
  306.       var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  307.       if (mid == from) { return pred(mid) ? from : to }
  308.       if (pred(mid)) { to = mid; }
  309.       else { from = mid + dir; }
  310.     }
  311.   }
  312.  
  313.   // BIDI HELPERS
  314.  
  315.   function iterateBidiSections(order, from, to, f) {
  316.     if (!order) { return f(from, to, "ltr", 0) }
  317.     var found = false;
  318.     for (var i = 0; i < order.length; ++i) {
  319.       var part = order[i];
  320.       if (part.from < to && part.to > from || from == to && part.to == from) {
  321.         f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  322.         found = true;
  323.       }
  324.     }
  325.     if (!found) { f(from, to, "ltr"); }
  326.   }
  327.  
  328.   var bidiOther = null;
  329.   function getBidiPartAt(order, ch, sticky) {
  330.     var found;
  331.     bidiOther = null;
  332.     for (var i = 0; i < order.length; ++i) {
  333.       var cur = order[i];
  334.       if (cur.from < ch && cur.to > ch) { return i }
  335.       if (cur.to == ch) {
  336.         if (cur.from != cur.to && sticky == "before") { found = i; }
  337.         else { bidiOther = i; }
  338.       }
  339.       if (cur.from == ch) {
  340.         if (cur.from != cur.to && sticky != "before") { found = i; }
  341.         else { bidiOther = i; }
  342.       }
  343.     }
  344.     return found != null ? found : bidiOther
  345.   }
  346.  
  347.   // Bidirectional ordering algorithm
  348.   // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  349.   // that this (partially) implements.
  350.  
  351.   // One-char codes used for character types:
  352.   // L (L):   Left-to-Right
  353.   // R (R):   Right-to-Left
  354.   // r (AL):  Right-to-Left Arabic
  355.   // 1 (EN):  European Number
  356.   // + (ES):  European Number Separator
  357.   // % (ET):  European Number Terminator
  358.   // n (AN):  Arabic Number
  359.   // , (CS):  Common Number Separator
  360.   // m (NSM): Non-Spacing Mark
  361.   // b (BN):  Boundary Neutral
  362.   // s (B):   Paragraph Separator
  363.   // t (S):   Segment Separator
  364.   // w (WS):  Whitespace
  365.   // N (ON):  Other Neutrals
  366.  
  367.   // Returns null if characters are ordered as they appear
  368.   // (left-to-right), or an array of sections ({from, to, level}
  369.   // objects) in the order in which they occur visually.
  370.   var bidiOrdering = (function() {
  371.     // Character types for codepoints 0 to 0xff
  372.     var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  373.     // Character types for codepoints 0x600 to 0x6f9
  374.     var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  375.     function charType(code) {
  376.       if (code <= 0xf7) { return lowTypes.charAt(code) }
  377.       else if (0x590 <= code && code <= 0x5f4) { return "R" }
  378.       else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  379.       else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  380.       else if (0x2000 <= code && code <= 0x200b) { return "w" }
  381.       else if (code == 0x200c) { return "b" }
  382.       else { return "L" }
  383.     }
  384.  
  385.     var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  386.     var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  387.  
  388.     function BidiSpan(level, from, to) {
  389.       this.level = level;
  390.       this.from = from; this.to = to;
  391.     }
  392.  
  393.     return function(str, direction) {
  394.       var outerType = direction == "ltr" ? "L" : "R";
  395.  
  396.       if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  397.       var len = str.length, types = [];
  398.       for (var i = 0; i < len; ++i)
  399.         { types.push(charType(str.charCodeAt(i))); }
  400.  
  401.       // W1. Examine each non-spacing mark (NSM) in the level run, and
  402.       // change the type of the NSM to the type of the previous
  403.       // character. If the NSM is at the start of the level run, it will
  404.       // get the type of sor.
  405.       for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  406.         var type = types[i$1];
  407.         if (type == "m") { types[i$1] = prev; }
  408.         else { prev = type; }
  409.       }
  410.  
  411.       // W2. Search backwards from each instance of a European number
  412.       // until the first strong type (R, L, AL, or sor) is found. If an
  413.       // AL is found, change the type of the European number to Arabic
  414.       // number.
  415.       // W3. Change all ALs to R.
  416.       for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  417.         var type$1 = types[i$2];
  418.         if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  419.         else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  420.       }
  421.  
  422.       // W4. A single European separator between two European numbers
  423.       // changes to a European number. A single common separator between
  424.       // two numbers of the same type changes to that type.
  425.       for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  426.         var type$2 = types[i$3];
  427.         if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  428.         else if (type$2 == "," && prev$1 == types[i$3+1] &&
  429.                  (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  430.         prev$1 = type$2;
  431.       }
  432.  
  433.       // W5. A sequence of European terminators adjacent to European
  434.       // numbers changes to all European numbers.
  435.       // W6. Otherwise, separators and terminators change to Other
  436.       // Neutral.
  437.       for (var i$4 = 0; i$4 < len; ++i$4) {
  438.         var type$3 = types[i$4];
  439.         if (type$3 == ",") { types[i$4] = "N"; }
  440.         else if (type$3 == "%") {
  441.           var end = (void 0);
  442.           for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  443.           var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  444.           for (var j = i$4; j < end; ++j) { types[j] = replace; }
  445.           i$4 = end - 1;
  446.         }
  447.       }
  448.  
  449.       // W7. Search backwards from each instance of a European number
  450.       // until the first strong type (R, L, or sor) is found. If an L is
  451.       // found, then change the type of the European number to L.
  452.       for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  453.         var type$4 = types[i$5];
  454.         if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  455.         else if (isStrong.test(type$4)) { cur$1 = type$4; }
  456.       }
  457.  
  458.       // N1. A sequence of neutrals takes the direction of the
  459.       // surrounding strong text if the text on both sides has the same
  460.       // direction. European and Arabic numbers act as if they were R in
  461.       // terms of their influence on neutrals. Start-of-level-run (sor)
  462.       // and end-of-level-run (eor) are used at level run boundaries.
  463.       // N2. Any remaining neutrals take the embedding direction.
  464.       for (var i$6 = 0; i$6 < len; ++i$6) {
  465.         if (isNeutral.test(types[i$6])) {
  466.           var end$1 = (void 0);
  467.           for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  468.           var before = (i$6 ? types[i$6-1] : outerType) == "L";
  469.           var after = (end$1 < len ? types[end$1] : outerType) == "L";
  470.           var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  471.           for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  472.           i$6 = end$1 - 1;
  473.         }
  474.       }
  475.  
  476.       // Here we depart from the documented algorithm, in order to avoid
  477.       // building up an actual levels array. Since there are only three
  478.       // levels (0, 1, 2) in an implementation that doesn't take
  479.       // explicit embedding into account, we can build up the order on
  480.       // the fly, without following the level-based algorithm.
  481.       var order = [], m;
  482.       for (var i$7 = 0; i$7 < len;) {
  483.         if (countsAsLeft.test(types[i$7])) {
  484.           var start = i$7;
  485.           for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  486.           order.push(new BidiSpan(0, start, i$7));
  487.         } else {
  488.           var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
  489.           for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  490.           for (var j$2 = pos; j$2 < i$7;) {
  491.             if (countsAsNum.test(types[j$2])) {
  492.               if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
  493.               var nstart = j$2;
  494.               for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  495.               order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  496.               at += isRTL;
  497.               pos = j$2;
  498.             } else { ++j$2; }
  499.           }
  500.           if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  501.         }
  502.       }
  503.       if (direction == "ltr") {
  504.         if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  505.           order[0].from = m[0].length;
  506.           order.unshift(new BidiSpan(0, 0, m[0].length));
  507.         }
  508.         if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  509.           lst(order).to -= m[0].length;
  510.           order.push(new BidiSpan(0, len - m[0].length, len));
  511.         }
  512.       }
  513.  
  514.       return direction == "rtl" ? order.reverse() : order
  515.     }
  516.   })();
  517.  
  518.   // Get the bidi ordering for the given line (and cache it). Returns
  519.   // false for lines that are fully left-to-right, and an array of
  520.   // BidiSpan objects otherwise.
  521.   function getOrder(line, direction) {
  522.     var order = line.order;
  523.     if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  524.     return order
  525.   }
  526.  
  527.   // EVENT HANDLING
  528.  
  529.   // Lightweight event framework. on/off also work on DOM nodes,
  530.   // registering native DOM handlers.
  531.  
  532.   var noHandlers = [];
  533.  
  534.   var on = function(emitter, type, f) {
  535.     if (emitter.addEventListener) {
  536.       emitter.addEventListener(type, f, false);
  537.     } else if (emitter.attachEvent) {
  538.       emitter.attachEvent("on" + type, f);
  539.     } else {
  540.       var map = emitter._handlers || (emitter._handlers = {});
  541.       map[type] = (map[type] || noHandlers).concat(f);
  542.     }
  543.   };
  544.  
  545.   function getHandlers(emitter, type) {
  546.     return emitter._handlers && emitter._handlers[type] || noHandlers
  547.   }
  548.  
  549.   function off(emitter, type, f) {
  550.     if (emitter.removeEventListener) {
  551.       emitter.removeEventListener(type, f, false);
  552.     } else if (emitter.detachEvent) {
  553.       emitter.detachEvent("on" + type, f);
  554.     } else {
  555.       var map = emitter._handlers, arr = map && map[type];
  556.       if (arr) {
  557.         var index = indexOf(arr, f);
  558.         if (index > -1)
  559.           { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  560.       }
  561.     }
  562.   }
  563.  
  564.   function signal(emitter, type /*, values...*/) {
  565.     var handlers = getHandlers(emitter, type);
  566.     if (!handlers.length) { return }
  567.     var args = Array.prototype.slice.call(arguments, 2);
  568.     for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  569.   }
  570.  
  571.   // The DOM events that CodeMirror handles can be overridden by
  572.   // registering a (non-DOM) handler on the editor for the event name,
  573.   // and preventDefault-ing the event in that handler.
  574.   function signalDOMEvent(cm, e, override) {
  575.     if (typeof e == "string")
  576.       { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  577.     signal(cm, override || e.type, cm, e);
  578.     return e_defaultPrevented(e) || e.codemirrorIgnore
  579.   }
  580.  
  581.   function signalCursorActivity(cm) {
  582.     var arr = cm._handlers && cm._handlers.cursorActivity;
  583.     if (!arr) { return }
  584.     var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  585.     for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  586.       { set.push(arr[i]); } }
  587.   }
  588.  
  589.   function hasHandler(emitter, type) {
  590.     return getHandlers(emitter, type).length > 0
  591.   }
  592.  
  593.   // Add on and off methods to a constructor's prototype, to make
  594.   // registering events on such objects more convenient.
  595.   function eventMixin(ctor) {
  596.     ctor.prototype.on = function(type, f) {on(this, type, f);};
  597.     ctor.prototype.off = function(type, f) {off(this, type, f);};
  598.   }
  599.  
  600.   // Due to the fact that we still support jurassic IE versions, some
  601.   // compatibility wrappers are needed.
  602.  
  603.   function e_preventDefault(e) {
  604.     if (e.preventDefault) { e.preventDefault(); }
  605.     else { e.returnValue = false; }
  606.   }
  607.   function e_stopPropagation(e) {
  608.     if (e.stopPropagation) { e.stopPropagation(); }
  609.     else { e.cancelBubble = true; }
  610.   }
  611.   function e_defaultPrevented(e) {
  612.     return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  613.   }
  614.   function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  615.  
  616.   function e_target(e) {return e.target || e.srcElement}
  617.   function e_button(e) {
  618.     var b = e.which;
  619.     if (b == null) {
  620.       if (e.button & 1) { b = 1; }
  621.       else if (e.button & 2) { b = 3; }
  622.       else if (e.button & 4) { b = 2; }
  623.     }
  624.     if (mac && e.ctrlKey && b == 1) { b = 3; }
  625.     return b
  626.   }
  627.  
  628.   // Detect drag-and-drop
  629.   var dragAndDrop = function() {
  630.     // There is *some* kind of drag-and-drop support in IE6-8, but I
  631.     // couldn't get it to work yet.
  632.     if (ie && ie_version < 9) { return false }
  633.     var div = elt('div');
  634.     return "draggable" in div || "dragDrop" in div
  635.   }();
  636.  
  637.   var zwspSupported;
  638.   function zeroWidthElement(measure) {
  639.     if (zwspSupported == null) {
  640.       var test = elt("span", "\u200b");
  641.       removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  642.       if (measure.firstChild.offsetHeight != 0)
  643.         { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  644.     }
  645.     var node = zwspSupported ? elt("span", "\u200b") :
  646.       elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  647.     node.setAttribute("cm-text", "");
  648.     return node
  649.   }
  650.  
  651.   // Feature-detect IE's crummy client rect reporting for bidi text
  652.   var badBidiRects;
  653.   function hasBadBidiRects(measure) {
  654.     if (badBidiRects != null) { return badBidiRects }
  655.     var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  656.     var r0 = range(txt, 0, 1).getBoundingClientRect();
  657.     var r1 = range(txt, 1, 2).getBoundingClientRect();
  658.     removeChildren(measure);
  659.     if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  660.     return badBidiRects = (r1.right - r0.right < 3)
  661.   }
  662.  
  663.   // See if "".split is the broken IE version, if so, provide an
  664.   // alternative way to split lines.
  665.   var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  666.     var pos = 0, result = [], l = string.length;
  667.     while (pos <= l) {
  668.       var nl = string.indexOf("\n", pos);
  669.       if (nl == -1) { nl = string.length; }
  670.       var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  671.       var rt = line.indexOf("\r");
  672.       if (rt != -1) {
  673.         result.push(line.slice(0, rt));
  674.         pos += rt + 1;
  675.       } else {
  676.         result.push(line);
  677.         pos = nl + 1;
  678.       }
  679.     }
  680.     return result
  681.   } : function (string) { return string.split(/\r\n?|\n/); };
  682.  
  683.   var hasSelection = window.getSelection ? function (te) {
  684.     try { return te.selectionStart != te.selectionEnd }
  685.     catch(e) { return false }
  686.   } : function (te) {
  687.     var range;
  688.     try {range = te.ownerDocument.selection.createRange();}
  689.     catch(e) {}
  690.     if (!range || range.parentElement() != te) { return false }
  691.     return range.compareEndPoints("StartToEnd", range) != 0
  692.   };
  693.  
  694.   var hasCopyEvent = (function () {
  695.     var e = elt("div");
  696.     if ("oncopy" in e) { return true }
  697.     e.setAttribute("oncopy", "return;");
  698.     return typeof e.oncopy == "function"
  699.   })();
  700.  
  701.   var badZoomedRects = null;
  702.   function hasBadZoomedRects(measure) {
  703.     if (badZoomedRects != null) { return badZoomedRects }
  704.     var node = removeChildrenAndAdd(measure, elt("span", "x"));
  705.     var normal = node.getBoundingClientRect();
  706.     var fromRange = range(node, 0, 1).getBoundingClientRect();
  707.     return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  708.   }
  709.  
  710.   // Known modes, by name and by MIME
  711.   var modes = {}, mimeModes = {};
  712.  
  713.   // Extra arguments are stored as the mode's dependencies, which is
  714.   // used by (legacy) mechanisms like loadmode.js to automatically
  715.   // load a mode. (Preferred mechanism is the require/define calls.)
  716.   function defineMode(name, mode) {
  717.     if (arguments.length > 2)
  718.       { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  719.     modes[name] = mode;
  720.   }
  721.  
  722.   function defineMIME(mime, spec) {
  723.     mimeModes[mime] = spec;
  724.   }
  725.  
  726.   // Given a MIME type, a {name, ...options} config object, or a name
  727.   // string, return a mode config object.
  728.   function resolveMode(spec) {
  729.     if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  730.       spec = mimeModes[spec];
  731.     } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  732.       var found = mimeModes[spec.name];
  733.       if (typeof found == "string") { found = {name: found}; }
  734.       spec = createObj(found, spec);
  735.       spec.name = found.name;
  736.     } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  737.       return resolveMode("application/xml")
  738.     } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  739.       return resolveMode("application/json")
  740.     }
  741.     if (typeof spec == "string") { return {name: spec} }
  742.     else { return spec || {name: "null"} }
  743.   }
  744.  
  745.   // Given a mode spec (anything that resolveMode accepts), find and
  746.   // initialize an actual mode object.
  747.   function getMode(options, spec) {
  748.     spec = resolveMode(spec);
  749.     var mfactory = modes[spec.name];
  750.     if (!mfactory) { return getMode(options, "text/plain") }
  751.     var modeObj = mfactory(options, spec);
  752.     if (modeExtensions.hasOwnProperty(spec.name)) {
  753.       var exts = modeExtensions[spec.name];
  754.       for (var prop in exts) {
  755.         if (!exts.hasOwnProperty(prop)) { continue }
  756.         if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  757.         modeObj[prop] = exts[prop];
  758.       }
  759.     }
  760.     modeObj.name = spec.name;
  761.     if (spec.helperType) { modeObj.helperType = spec.helperType; }
  762.     if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  763.       { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  764.  
  765.     return modeObj
  766.   }
  767.  
  768.   // This can be used to attach properties to mode objects from
  769.   // outside the actual mode definition.
  770.   var modeExtensions = {};
  771.   function extendMode(mode, properties) {
  772.     var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  773.     copyObj(properties, exts);
  774.   }
  775.  
  776.   function copyState(mode, state) {
  777.     if (state === true) { return state }
  778.     if (mode.copyState) { return mode.copyState(state) }
  779.     var nstate = {};
  780.     for (var n in state) {
  781.       var val = state[n];
  782.       if (val instanceof Array) { val = val.concat([]); }
  783.       nstate[n] = val;
  784.     }
  785.     return nstate
  786.   }
  787.  
  788.   // Given a mode and a state (for that mode), find the inner mode and
  789.   // state at the position that the state refers to.
  790.   function innerMode(mode, state) {
  791.     var info;
  792.     while (mode.innerMode) {
  793.       info = mode.innerMode(state);
  794.       if (!info || info.mode == mode) { break }
  795.       state = info.state;
  796.       mode = info.mode;
  797.     }
  798.     return info || {mode: mode, state: state}
  799.   }
  800.  
  801.   function startState(mode, a1, a2) {
  802.     return mode.startState ? mode.startState(a1, a2) : true
  803.   }
  804.  
  805.   // STRING STREAM
  806.  
  807.   // Fed to the mode parsers, provides helper functions to make
  808.   // parsers more succinct.
  809.  
  810.   var StringStream = function(string, tabSize, lineOracle) {
  811.     this.pos = this.start = 0;
  812.     this.string = string;
  813.     this.tabSize = tabSize || 8;
  814.     this.lastColumnPos = this.lastColumnValue = 0;
  815.     this.lineStart = 0;
  816.     this.lineOracle = lineOracle;
  817.   };
  818.  
  819.   StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  820.   StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  821.   StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  822.   StringStream.prototype.next = function () {
  823.     if (this.pos < this.string.length)
  824.       { return this.string.charAt(this.pos++) }
  825.   };
  826.   StringStream.prototype.eat = function (match) {
  827.     var ch = this.string.charAt(this.pos);
  828.     var ok;
  829.     if (typeof match == "string") { ok = ch == match; }
  830.     else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  831.     if (ok) {++this.pos; return ch}
  832.   };
  833.   StringStream.prototype.eatWhile = function (match) {
  834.     var start = this.pos;
  835.     while (this.eat(match)){}
  836.     return this.pos > start
  837.   };
  838.   StringStream.prototype.eatSpace = function () {
  839.     var start = this.pos;
  840.     while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
  841.     return this.pos > start
  842.   };
  843.   StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  844.   StringStream.prototype.skipTo = function (ch) {
  845.     var found = this.string.indexOf(ch, this.pos);
  846.     if (found > -1) {this.pos = found; return true}
  847.   };
  848.   StringStream.prototype.backUp = function (n) {this.pos -= n;};
  849.   StringStream.prototype.column = function () {
  850.     if (this.lastColumnPos < this.start) {
  851.       this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  852.       this.lastColumnPos = this.start;
  853.     }
  854.     return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  855.   };
  856.   StringStream.prototype.indentation = function () {
  857.     return countColumn(this.string, null, this.tabSize) -
  858.       (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  859.   };
  860.   StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  861.     if (typeof pattern == "string") {
  862.       var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  863.       var substr = this.string.substr(this.pos, pattern.length);
  864.       if (cased(substr) == cased(pattern)) {
  865.         if (consume !== false) { this.pos += pattern.length; }
  866.         return true
  867.       }
  868.     } else {
  869.       var match = this.string.slice(this.pos).match(pattern);
  870.       if (match && match.index > 0) { return null }
  871.       if (match && consume !== false) { this.pos += match[0].length; }
  872.       return match
  873.     }
  874.   };
  875.   StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  876.   StringStream.prototype.hideFirstChars = function (n, inner) {
  877.     this.lineStart += n;
  878.     try { return inner() }
  879.     finally { this.lineStart -= n; }
  880.   };
  881.   StringStream.prototype.lookAhead = function (n) {
  882.     var oracle = this.lineOracle;
  883.     return oracle && oracle.lookAhead(n)
  884.   };
  885.   StringStream.prototype.baseToken = function () {
  886.     var oracle = this.lineOracle;
  887.     return oracle && oracle.baseToken(this.pos)
  888.   };
  889.  
  890.   // Find the line object corresponding to the given line number.
  891.   function getLine(doc, n) {
  892.     n -= doc.first;
  893.     if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  894.     var chunk = doc;
  895.     while (!chunk.lines) {
  896.       for (var i = 0;; ++i) {
  897.         var child = chunk.children[i], sz = child.chunkSize();
  898.         if (n < sz) { chunk = child; break }
  899.         n -= sz;
  900.       }
  901.     }
  902.     return chunk.lines[n]
  903.   }
  904.  
  905.   // Get the part of a document between two positions, as an array of
  906.   // strings.
  907.   function getBetween(doc, start, end) {
  908.     var out = [], n = start.line;
  909.     doc.iter(start.line, end.line + 1, function (line) {
  910.       var text = line.text;
  911.       if (n == end.line) { text = text.slice(0, end.ch); }
  912.       if (n == start.line) { text = text.slice(start.ch); }
  913.       out.push(text);
  914.       ++n;
  915.     });
  916.     return out
  917.   }
  918.   // Get the lines between from and to, as array of strings.
  919.   function getLines(doc, from, to) {
  920.     var out = [];
  921.     doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  922.     return out
  923.   }
  924.  
  925.   // Update the height of a line, propagating the height change
  926.   // upwards to parent nodes.
  927.   function updateLineHeight(line, height) {
  928.     var diff = height - line.height;
  929.     if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  930.   }
  931.  
  932.   // Given a line object, find its line number by walking up through
  933.   // its parent links.
  934.   function lineNo(line) {
  935.     if (line.parent == null) { return null }
  936.     var cur = line.parent, no = indexOf(cur.lines, line);
  937.     for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  938.       for (var i = 0;; ++i) {
  939.         if (chunk.children[i] == cur) { break }
  940.         no += chunk.children[i].chunkSize();
  941.       }
  942.     }
  943.     return no + cur.first
  944.   }
  945.  
  946.   // Find the line at the given vertical position, using the height
  947.   // information in the document tree.
  948.   function lineAtHeight(chunk, h) {
  949.     var n = chunk.first;
  950.     outer: do {
  951.       for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  952.         var child = chunk.children[i$1], ch = child.height;
  953.         if (h < ch) { chunk = child; continue outer }
  954.         h -= ch;
  955.         n += child.chunkSize();
  956.       }
  957.       return n
  958.     } while (!chunk.lines)
  959.     var i = 0;
  960.     for (; i < chunk.lines.length; ++i) {
  961.       var line = chunk.lines[i], lh = line.height;
  962.       if (h < lh) { break }
  963.       h -= lh;
  964.     }
  965.     return n + i
  966.   }
  967.  
  968.   function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  969.  
  970.   function lineNumberFor(options, i) {
  971.     return String(options.lineNumberFormatter(i + options.firstLineNumber))
  972.   }
  973.  
  974.   // A Pos instance represents a position within the text.
  975.   function Pos(line, ch, sticky) {
  976.     if ( sticky === void 0 ) sticky = null;
  977.  
  978.     if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  979.     this.line = line;
  980.     this.ch = ch;
  981.     this.sticky = sticky;
  982.   }
  983.  
  984.   // Compare two positions, return 0 if they are the same, a negative
  985.   // number when a is less, and a positive number otherwise.
  986.   function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  987.  
  988.   function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  989.  
  990.   function copyPos(x) {return Pos(x.line, x.ch)}
  991.   function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  992.   function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  993.  
  994.   // Most of the external API clips given positions to make sure they
  995.   // actually exist within the document.
  996.   function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  997.   function clipPos(doc, pos) {
  998.     if (pos.line < doc.first) { return Pos(doc.first, 0) }
  999.     var last = doc.first + doc.size - 1;
  1000.     if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  1001.     return clipToLen(pos, getLine(doc, pos.line).text.length)
  1002.   }
  1003.   function clipToLen(pos, linelen) {
  1004.     var ch = pos.ch;
  1005.     if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  1006.     else if (ch < 0) { return Pos(pos.line, 0) }
  1007.     else { return pos }
  1008.   }
  1009.   function clipPosArray(doc, array) {
  1010.     var out = [];
  1011.     for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  1012.     return out
  1013.   }
  1014.  
  1015.   var SavedContext = function(state, lookAhead) {
  1016.     this.state = state;
  1017.     this.lookAhead = lookAhead;
  1018.   };
  1019.  
  1020.   var Context = function(doc, state, line, lookAhead) {
  1021.     this.state = state;
  1022.     this.doc = doc;
  1023.     this.line = line;
  1024.     this.maxLookAhead = lookAhead || 0;
  1025.     this.baseTokens = null;
  1026.     this.baseTokenPos = 1;
  1027.   };
  1028.  
  1029.   Context.prototype.lookAhead = function (n) {
  1030.     var line = this.doc.getLine(this.line + n);
  1031.     if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  1032.     return line
  1033.   };
  1034.  
  1035.   Context.prototype.baseToken = function (n) {
  1036.     if (!this.baseTokens) { return null }
  1037.     while (this.baseTokens[this.baseTokenPos] <= n)
  1038.       { this.baseTokenPos += 2; }
  1039.     var type = this.baseTokens[this.baseTokenPos + 1];
  1040.     return {type: type && type.replace(/( |^)overlay .*/, ""),
  1041.             size: this.baseTokens[this.baseTokenPos] - n}
  1042.   };
  1043.  
  1044.   Context.prototype.nextLine = function () {
  1045.     this.line++;
  1046.     if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  1047.   };
  1048.  
  1049.   Context.fromSaved = function (doc, saved, line) {
  1050.     if (saved instanceof SavedContext)
  1051.       { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  1052.     else
  1053.       { return new Context(doc, copyState(doc.mode, saved), line) }
  1054.   };
  1055.  
  1056.   Context.prototype.save = function (copy) {
  1057.     var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  1058.     return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  1059.   };
  1060.  
  1061.  
  1062.   // Compute a style array (an array starting with a mode generation
  1063.   // -- for invalidation -- followed by pairs of end positions and
  1064.   // style strings), which is used to highlight the tokens on the
  1065.   // line.
  1066.   function highlightLine(cm, line, context, forceToEnd) {
  1067.     // A styles array always starts with a number identifying the
  1068.     // mode/overlays that it is based on (for easy invalidation).
  1069.     var st = [cm.state.modeGen], lineClasses = {};
  1070.     // Compute the base array of styles
  1071.     runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  1072.             lineClasses, forceToEnd);
  1073.     var state = context.state;
  1074.  
  1075.     // Run overlays, adjust style array.
  1076.     var loop = function ( o ) {
  1077.       context.baseTokens = st;
  1078.       var overlay = cm.state.overlays[o], i = 1, at = 0;
  1079.       context.state = true;
  1080.       runMode(cm, line.text, overlay.mode, context, function (end, style) {
  1081.         var start = i;
  1082.         // Ensure there's a token end at the current position, and that i points at it
  1083.         while (at < end) {
  1084.           var i_end = st[i];
  1085.           if (i_end > end)
  1086.             { st.splice(i, 1, end, st[i+1], i_end); }
  1087.           i += 2;
  1088.           at = Math.min(end, i_end);
  1089.         }
  1090.         if (!style) { return }
  1091.         if (overlay.opaque) {
  1092.           st.splice(start, i - start, end, "overlay " + style);
  1093.           i = start + 2;
  1094.         } else {
  1095.           for (; start < i; start += 2) {
  1096.             var cur = st[start+1];
  1097.             st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  1098.           }
  1099.         }
  1100.       }, lineClasses);
  1101.       context.state = state;
  1102.       context.baseTokens = null;
  1103.       context.baseTokenPos = 1;
  1104.     };
  1105.  
  1106.     for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  1107.  
  1108.     return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  1109.   }
  1110.  
  1111.   function getLineStyles(cm, line, updateFrontier) {
  1112.     if (!line.styles || line.styles[0] != cm.state.modeGen) {
  1113.       var context = getContextBefore(cm, lineNo(line));
  1114.       var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  1115.       var result = highlightLine(cm, line, context);
  1116.       if (resetState) { context.state = resetState; }
  1117.       line.stateAfter = context.save(!resetState);
  1118.       line.styles = result.styles;
  1119.       if (result.classes) { line.styleClasses = result.classes; }
  1120.       else if (line.styleClasses) { line.styleClasses = null; }
  1121.       if (updateFrontier === cm.doc.highlightFrontier)
  1122.         { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  1123.     }
  1124.     return line.styles
  1125.   }
  1126.  
  1127.   function getContextBefore(cm, n, precise) {
  1128.     var doc = cm.doc, display = cm.display;
  1129.     if (!doc.mode.startState) { return new Context(doc, true, n) }
  1130.     var start = findStartLine(cm, n, precise);
  1131.     var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  1132.     var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  1133.  
  1134.     doc.iter(start, n, function (line) {
  1135.       processLine(cm, line.text, context);
  1136.       var pos = context.line;
  1137.       line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  1138.       context.nextLine();
  1139.     });
  1140.     if (precise) { doc.modeFrontier = context.line; }
  1141.     return context
  1142.   }
  1143.  
  1144.   // Lightweight form of highlight -- proceed over this line and
  1145.   // update state, but don't save a style array. Used for lines that
  1146.   // aren't currently visible.
  1147.   function processLine(cm, text, context, startAt) {
  1148.     var mode = cm.doc.mode;
  1149.     var stream = new StringStream(text, cm.options.tabSize, context);
  1150.     stream.start = stream.pos = startAt || 0;
  1151.     if (text == "") { callBlankLine(mode, context.state); }
  1152.     while (!stream.eol()) {
  1153.       readToken(mode, stream, context.state);
  1154.       stream.start = stream.pos;
  1155.     }
  1156.   }
  1157.  
  1158.   function callBlankLine(mode, state) {
  1159.     if (mode.blankLine) { return mode.blankLine(state) }
  1160.     if (!mode.innerMode) { return }
  1161.     var inner = innerMode(mode, state);
  1162.     if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1163.   }
  1164.  
  1165.   function readToken(mode, stream, state, inner) {
  1166.     for (var i = 0; i < 10; i++) {
  1167.       if (inner) { inner[0] = innerMode(mode, state).mode; }
  1168.       var style = mode.token(stream, state);
  1169.       if (stream.pos > stream.start) { return style }
  1170.     }
  1171.     throw new Error("Mode " + mode.name + " failed to advance stream.")
  1172.   }
  1173.  
  1174.   var Token = function(stream, type, state) {
  1175.     this.start = stream.start; this.end = stream.pos;
  1176.     this.string = stream.current();
  1177.     this.type = type || null;
  1178.     this.state = state;
  1179.   };
  1180.  
  1181.   // Utility for getTokenAt and getLineTokens
  1182.   function takeToken(cm, pos, precise, asArray) {
  1183.     var doc = cm.doc, mode = doc.mode, style;
  1184.     pos = clipPos(doc, pos);
  1185.     var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  1186.     var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  1187.     if (asArray) { tokens = []; }
  1188.     while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1189.       stream.start = stream.pos;
  1190.       style = readToken(mode, stream, context.state);
  1191.       if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  1192.     }
  1193.     return asArray ? tokens : new Token(stream, style, context.state)
  1194.   }
  1195.  
  1196.   function extractLineClasses(type, output) {
  1197.     if (type) { for (;;) {
  1198.       var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  1199.       if (!lineClass) { break }
  1200.       type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  1201.       var prop = lineClass[1] ? "bgClass" : "textClass";
  1202.       if (output[prop] == null)
  1203.         { output[prop] = lineClass[2]; }
  1204.       else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
  1205.         { output[prop] += " " + lineClass[2]; }
  1206.     } }
  1207.     return type
  1208.   }
  1209.  
  1210.   // Run the given mode's parser over a line, calling f for each token.
  1211.   function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1212.     var flattenSpans = mode.flattenSpans;
  1213.     if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  1214.     var curStart = 0, curStyle = null;
  1215.     var stream = new StringStream(text, cm.options.tabSize, context), style;
  1216.     var inner = cm.options.addModeClass && [null];
  1217.     if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  1218.     while (!stream.eol()) {
  1219.       if (stream.pos > cm.options.maxHighlightLength) {
  1220.         flattenSpans = false;
  1221.         if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  1222.         stream.pos = text.length;
  1223.         style = null;
  1224.       } else {
  1225.         style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  1226.       }
  1227.       if (inner) {
  1228.         var mName = inner[0].name;
  1229.         if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  1230.       }
  1231.       if (!flattenSpans || curStyle != style) {
  1232.         while (curStart < stream.start) {
  1233.           curStart = Math.min(stream.start, curStart + 5000);
  1234.           f(curStart, curStyle);
  1235.         }
  1236.         curStyle = style;
  1237.       }
  1238.       stream.start = stream.pos;
  1239.     }
  1240.     while (curStart < stream.pos) {
  1241.       // Webkit seems to refuse to render text nodes longer than 57444
  1242.       // characters, and returns inaccurate measurements in nodes
  1243.       // starting around 5000 chars.
  1244.       var pos = Math.min(stream.pos, curStart + 5000);
  1245.       f(pos, curStyle);
  1246.       curStart = pos;
  1247.     }
  1248.   }
  1249.  
  1250.   // Finds the line to start with when starting a parse. Tries to
  1251.   // find a line with a stateAfter, so that it can start with a
  1252.   // valid state. If that fails, it returns the line with the
  1253.   // smallest indentation, which tends to need the least context to
  1254.   // parse correctly.
  1255.   function findStartLine(cm, n, precise) {
  1256.     var minindent, minline, doc = cm.doc;
  1257.     var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  1258.     for (var search = n; search > lim; --search) {
  1259.       if (search <= doc.first) { return doc.first }
  1260.       var line = getLine(doc, search - 1), after = line.stateAfter;
  1261.       if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  1262.         { return search }
  1263.       var indented = countColumn(line.text, null, cm.options.tabSize);
  1264.       if (minline == null || minindent > indented) {
  1265.         minline = search - 1;
  1266.         minindent = indented;
  1267.       }
  1268.     }
  1269.     return minline
  1270.   }
  1271.  
  1272.   function retreatFrontier(doc, n) {
  1273.     doc.modeFrontier = Math.min(doc.modeFrontier, n);
  1274.     if (doc.highlightFrontier < n - 10) { return }
  1275.     var start = doc.first;
  1276.     for (var line = n - 1; line > start; line--) {
  1277.       var saved = getLine(doc, line).stateAfter;
  1278.       // change is on 3
  1279.       // state on line 1 looked ahead 2 -- so saw 3
  1280.       // test 1 + 2 < 3 should cover this
  1281.       if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1282.         start = line + 1;
  1283.         break
  1284.       }
  1285.     }
  1286.     doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  1287.   }
  1288.  
  1289.   // Optimize some code when these features are not used.
  1290.   var sawReadOnlySpans = false, sawCollapsedSpans = false;
  1291.  
  1292.   function seeReadOnlySpans() {
  1293.     sawReadOnlySpans = true;
  1294.   }
  1295.  
  1296.   function seeCollapsedSpans() {
  1297.     sawCollapsedSpans = true;
  1298.   }
  1299.  
  1300.   // TEXTMARKER SPANS
  1301.  
  1302.   function MarkedSpan(marker, from, to) {
  1303.     this.marker = marker;
  1304.     this.from = from; this.to = to;
  1305.   }
  1306.  
  1307.   // Search an array of spans for a span matching the given marker.
  1308.   function getMarkedSpanFor(spans, marker) {
  1309.     if (spans) { for (var i = 0; i < spans.length; ++i) {
  1310.       var span = spans[i];
  1311.       if (span.marker == marker) { return span }
  1312.     } }
  1313.   }
  1314.   // Remove a span from an array, returning undefined if no spans are
  1315.   // left (we don't store arrays for lines without spans).
  1316.   function removeMarkedSpan(spans, span) {
  1317.     var r;
  1318.     for (var i = 0; i < spans.length; ++i)
  1319.       { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  1320.     return r
  1321.   }
  1322.   // Add a span to a line.
  1323.   function addMarkedSpan(line, span) {
  1324.     line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  1325.     span.marker.attachLine(line);
  1326.   }
  1327.  
  1328.   // Used for the algorithm that adjusts markers for a change in the
  1329.   // document. These functions cut an array of spans at a given
  1330.   // character position, returning an array of remaining chunks (or
  1331.   // undefined if nothing remains).
  1332.   function markedSpansBefore(old, startCh, isInsert) {
  1333.     var nw;
  1334.     if (old) { for (var i = 0; i < old.length; ++i) {
  1335.       var span = old[i], marker = span.marker;
  1336.       var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  1337.       if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  1338.         var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  1339.         ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  1340.       }
  1341.     } }
  1342.     return nw
  1343.   }
  1344.   function markedSpansAfter(old, endCh, isInsert) {
  1345.     var nw;
  1346.     if (old) { for (var i = 0; i < old.length; ++i) {
  1347.       var span = old[i], marker = span.marker;
  1348.       var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  1349.       if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  1350.         var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  1351.         ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  1352.                                               span.to == null ? null : span.to - endCh));
  1353.       }
  1354.     } }
  1355.     return nw
  1356.   }
  1357.  
  1358.   // Given a change object, compute the new set of marker spans that
  1359.   // cover the line in which the change took place. Removes spans
  1360.   // entirely within the change, reconnects spans belonging to the
  1361.   // same marker that appear on both sides of the change, and cuts off
  1362.   // spans partially within the change. Returns an array of span
  1363.   // arrays with one element for each line in (after) the change.
  1364.   function stretchSpansOverChange(doc, change) {
  1365.     if (change.full) { return null }
  1366.     var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  1367.     var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  1368.     if (!oldFirst && !oldLast) { return null }
  1369.  
  1370.     var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  1371.     // Get the spans that 'stick out' on both sides
  1372.     var first = markedSpansBefore(oldFirst, startCh, isInsert);
  1373.     var last = markedSpansAfter(oldLast, endCh, isInsert);
  1374.  
  1375.     // Next, merge those two ends
  1376.     var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  1377.     if (first) {
  1378.       // Fix up .to properties of first
  1379.       for (var i = 0; i < first.length; ++i) {
  1380.         var span = first[i];
  1381.         if (span.to == null) {
  1382.           var found = getMarkedSpanFor(last, span.marker);
  1383.           if (!found) { span.to = startCh; }
  1384.           else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  1385.         }
  1386.       }
  1387.     }
  1388.     if (last) {
  1389.       // Fix up .from in last (or move them into first in case of sameLine)
  1390.       for (var i$1 = 0; i$1 < last.length; ++i$1) {
  1391.         var span$1 = last[i$1];
  1392.         if (span$1.to != null) { span$1.to += offset; }
  1393.         if (span$1.from == null) {
  1394.           var found$1 = getMarkedSpanFor(first, span$1.marker);
  1395.           if (!found$1) {
  1396.             span$1.from = offset;
  1397.             if (sameLine) { (first || (first = [])).push(span$1); }
  1398.           }
  1399.         } else {
  1400.           span$1.from += offset;
  1401.           if (sameLine) { (first || (first = [])).push(span$1); }
  1402.         }
  1403.       }
  1404.     }
  1405.     // Make sure we didn't create any zero-length spans
  1406.     if (first) { first = clearEmptySpans(first); }
  1407.     if (last && last != first) { last = clearEmptySpans(last); }
  1408.  
  1409.     var newMarkers = [first];
  1410.     if (!sameLine) {
  1411.       // Fill gap with whole-line-spans
  1412.       var gap = change.text.length - 2, gapMarkers;
  1413.       if (gap > 0 && first)
  1414.         { for (var i$2 = 0; i$2 < first.length; ++i$2)
  1415.           { if (first[i$2].to == null)
  1416.             { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  1417.       for (var i$3 = 0; i$3 < gap; ++i$3)
  1418.         { newMarkers.push(gapMarkers); }
  1419.       newMarkers.push(last);
  1420.     }
  1421.     return newMarkers
  1422.   }
  1423.  
  1424.   // Remove spans that are empty and don't have a clearWhenEmpty
  1425.   // option of false.
  1426.   function clearEmptySpans(spans) {
  1427.     for (var i = 0; i < spans.length; ++i) {
  1428.       var span = spans[i];
  1429.       if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  1430.         { spans.splice(i--, 1); }
  1431.     }
  1432.     if (!spans.length) { return null }
  1433.     return spans
  1434.   }
  1435.  
  1436.   // Used to 'clip' out readOnly ranges when making a change.
  1437.   function removeReadOnlyRanges(doc, from, to) {
  1438.     var markers = null;
  1439.     doc.iter(from.line, to.line + 1, function (line) {
  1440.       if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  1441.         var mark = line.markedSpans[i].marker;
  1442.         if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  1443.           { (markers || (markers = [])).push(mark); }
  1444.       } }
  1445.     });
  1446.     if (!markers) { return null }
  1447.     var parts = [{from: from, to: to}];
  1448.     for (var i = 0; i < markers.length; ++i) {
  1449.       var mk = markers[i], m = mk.find(0);
  1450.       for (var j = 0; j < parts.length; ++j) {
  1451.         var p = parts[j];
  1452.         if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  1453.         var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  1454.         if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  1455.           { newParts.push({from: p.from, to: m.from}); }
  1456.         if (dto > 0 || !mk.inclusiveRight && !dto)
  1457.           { newParts.push({from: m.to, to: p.to}); }
  1458.         parts.splice.apply(parts, newParts);
  1459.         j += newParts.length - 3;
  1460.       }
  1461.     }
  1462.     return parts
  1463.   }
  1464.  
  1465.   // Connect or disconnect spans from a line.
  1466.   function detachMarkedSpans(line) {
  1467.     var spans = line.markedSpans;
  1468.     if (!spans) { return }
  1469.     for (var i = 0; i < spans.length; ++i)
  1470.       { spans[i].marker.detachLine(line); }
  1471.     line.markedSpans = null;
  1472.   }
  1473.   function attachMarkedSpans(line, spans) {
  1474.     if (!spans) { return }
  1475.     for (var i = 0; i < spans.length; ++i)
  1476.       { spans[i].marker.attachLine(line); }
  1477.     line.markedSpans = spans;
  1478.   }
  1479.  
  1480.   // Helpers used when computing which overlapping collapsed span
  1481.   // counts as the larger one.
  1482.   function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  1483.   function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  1484.  
  1485.   // Returns a number indicating which of two overlapping collapsed
  1486.   // spans is larger (and thus includes the other). Falls back to
  1487.   // comparing ids when the spans cover exactly the same range.
  1488.   function compareCollapsedMarkers(a, b) {
  1489.     var lenDiff = a.lines.length - b.lines.length;
  1490.     if (lenDiff != 0) { return lenDiff }
  1491.     var aPos = a.find(), bPos = b.find();
  1492.     var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  1493.     if (fromCmp) { return -fromCmp }
  1494.     var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  1495.     if (toCmp) { return toCmp }
  1496.     return b.id - a.id
  1497.   }
  1498.  
  1499.   // Find out whether a line ends or starts in a collapsed span. If
  1500.   // so, return the marker for that span.
  1501.   function collapsedSpanAtSide(line, start) {
  1502.     var sps = sawCollapsedSpans && line.markedSpans, found;
  1503.     if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1504.       sp = sps[i];
  1505.       if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  1506.           (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  1507.         { found = sp.marker; }
  1508.     } }
  1509.     return found
  1510.   }
  1511.   function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  1512.   function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  1513.  
  1514.   function collapsedSpanAround(line, ch) {
  1515.     var sps = sawCollapsedSpans && line.markedSpans, found;
  1516.     if (sps) { for (var i = 0; i < sps.length; ++i) {
  1517.       var sp = sps[i];
  1518.       if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
  1519.           (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
  1520.     } }
  1521.     return found
  1522.   }
  1523.  
  1524.   // Test whether there exists a collapsed span that partially
  1525.   // overlaps (covers the start or end, but not both) of a new span.
  1526.   // Such overlap is not allowed.
  1527.   function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  1528.     var line = getLine(doc, lineNo);
  1529.     var sps = sawCollapsedSpans && line.markedSpans;
  1530.     if (sps) { for (var i = 0; i < sps.length; ++i) {
  1531.       var sp = sps[i];
  1532.       if (!sp.marker.collapsed) { continue }
  1533.       var found = sp.marker.find(0);
  1534.       var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  1535.       var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  1536.       if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  1537.       if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  1538.           fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  1539.         { return true }
  1540.     } }
  1541.   }
  1542.  
  1543.   // A visual line is a line as drawn on the screen. Folding, for
  1544.   // example, can cause multiple logical lines to appear on the same
  1545.   // visual line. This finds the start of the visual line that the
  1546.   // given line is part of (usually that is the line itself).
  1547.   function visualLine(line) {
  1548.     var merged;
  1549.     while (merged = collapsedSpanAtStart(line))
  1550.       { line = merged.find(-1, true).line; }
  1551.     return line
  1552.   }
  1553.  
  1554.   function visualLineEnd(line) {
  1555.     var merged;
  1556.     while (merged = collapsedSpanAtEnd(line))
  1557.       { line = merged.find(1, true).line; }
  1558.     return line
  1559.   }
  1560.  
  1561.   // Returns an array of logical lines that continue the visual line
  1562.   // started by the argument, or undefined if there are no such lines.
  1563.   function visualLineContinued(line) {
  1564.     var merged, lines;
  1565.     while (merged = collapsedSpanAtEnd(line)) {
  1566.       line = merged.find(1, true).line
  1567.       ;(lines || (lines = [])).push(line);
  1568.     }
  1569.     return lines
  1570.   }
  1571.  
  1572.   // Get the line number of the start of the visual line that the
  1573.   // given line number is part of.
  1574.   function visualLineNo(doc, lineN) {
  1575.     var line = getLine(doc, lineN), vis = visualLine(line);
  1576.     if (line == vis) { return lineN }
  1577.     return lineNo(vis)
  1578.   }
  1579.  
  1580.   // Get the line number of the start of the next visual line after
  1581.   // the given line.
  1582.   function visualLineEndNo(doc, lineN) {
  1583.     if (lineN > doc.lastLine()) { return lineN }
  1584.     var line = getLine(doc, lineN), merged;
  1585.     if (!lineIsHidden(doc, line)) { return lineN }
  1586.     while (merged = collapsedSpanAtEnd(line))
  1587.       { line = merged.find(1, true).line; }
  1588.     return lineNo(line) + 1
  1589.   }
  1590.  
  1591.   // Compute whether a line is hidden. Lines count as hidden when they
  1592.   // are part of a visual line that starts with another line, or when
  1593.   // they are entirely covered by collapsed, non-widget span.
  1594.   function lineIsHidden(doc, line) {
  1595.     var sps = sawCollapsedSpans && line.markedSpans;
  1596.     if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1597.       sp = sps[i];
  1598.       if (!sp.marker.collapsed) { continue }
  1599.       if (sp.from == null) { return true }
  1600.       if (sp.marker.widgetNode) { continue }
  1601.       if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  1602.         { return true }
  1603.     } }
  1604.   }
  1605.   function lineIsHiddenInner(doc, line, span) {
  1606.     if (span.to == null) {
  1607.       var end = span.marker.find(1, true);
  1608.       return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  1609.     }
  1610.     if (span.marker.inclusiveRight && span.to == line.text.length)
  1611.       { return true }
  1612.     for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  1613.       sp = line.markedSpans[i];
  1614.       if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  1615.           (sp.to == null || sp.to != span.from) &&
  1616.           (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  1617.           lineIsHiddenInner(doc, line, sp)) { return true }
  1618.     }
  1619.   }
  1620.  
  1621.   // Find the height above the given line.
  1622.   function heightAtLine(lineObj) {
  1623.     lineObj = visualLine(lineObj);
  1624.  
  1625.     var h = 0, chunk = lineObj.parent;
  1626.     for (var i = 0; i < chunk.lines.length; ++i) {
  1627.       var line = chunk.lines[i];
  1628.       if (line == lineObj) { break }
  1629.       else { h += line.height; }
  1630.     }
  1631.     for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  1632.       for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  1633.         var cur = p.children[i$1];
  1634.         if (cur == chunk) { break }
  1635.         else { h += cur.height; }
  1636.       }
  1637.     }
  1638.     return h
  1639.   }
  1640.  
  1641.   // Compute the character length of a line, taking into account
  1642.   // collapsed ranges (see markText) that might hide parts, and join
  1643.   // other lines onto it.
  1644.   function lineLength(line) {
  1645.     if (line.height == 0) { return 0 }
  1646.     var len = line.text.length, merged, cur = line;
  1647.     while (merged = collapsedSpanAtStart(cur)) {
  1648.       var found = merged.find(0, true);
  1649.       cur = found.from.line;
  1650.       len += found.from.ch - found.to.ch;
  1651.     }
  1652.     cur = line;
  1653.     while (merged = collapsedSpanAtEnd(cur)) {
  1654.       var found$1 = merged.find(0, true);
  1655.       len -= cur.text.length - found$1.from.ch;
  1656.       cur = found$1.to.line;
  1657.       len += cur.text.length - found$1.to.ch;
  1658.     }
  1659.     return len
  1660.   }
  1661.  
  1662.   // Find the longest line in the document.
  1663.   function findMaxLine(cm) {
  1664.     var d = cm.display, doc = cm.doc;
  1665.     d.maxLine = getLine(doc, doc.first);
  1666.     d.maxLineLength = lineLength(d.maxLine);
  1667.     d.maxLineChanged = true;
  1668.     doc.iter(function (line) {
  1669.       var len = lineLength(line);
  1670.       if (len > d.maxLineLength) {
  1671.         d.maxLineLength = len;
  1672.         d.maxLine = line;
  1673.       }
  1674.     });
  1675.   }
  1676.  
  1677.   // LINE DATA STRUCTURE
  1678.  
  1679.   // Line objects. These hold state related to a line, including
  1680.   // highlighting info (the styles array).
  1681.   var Line = function(text, markedSpans, estimateHeight) {
  1682.     this.text = text;
  1683.     attachMarkedSpans(this, markedSpans);
  1684.     this.height = estimateHeight ? estimateHeight(this) : 1;
  1685.   };
  1686.  
  1687.   Line.prototype.lineNo = function () { return lineNo(this) };
  1688.   eventMixin(Line);
  1689.  
  1690.   // Change the content (text, markers) of a line. Automatically
  1691.   // invalidates cached information and tries to re-estimate the
  1692.   // line's height.
  1693.   function updateLine(line, text, markedSpans, estimateHeight) {
  1694.     line.text = text;
  1695.     if (line.stateAfter) { line.stateAfter = null; }
  1696.     if (line.styles) { line.styles = null; }
  1697.     if (line.order != null) { line.order = null; }
  1698.     detachMarkedSpans(line);
  1699.     attachMarkedSpans(line, markedSpans);
  1700.     var estHeight = estimateHeight ? estimateHeight(line) : 1;
  1701.     if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  1702.   }
  1703.  
  1704.   // Detach a line from the document tree and its markers.
  1705.   function cleanUpLine(line) {
  1706.     line.parent = null;
  1707.     detachMarkedSpans(line);
  1708.   }
  1709.  
  1710.   // Convert a style as returned by a mode (either null, or a string
  1711.   // containing one or more styles) to a CSS style. This is cached,
  1712.   // and also looks for line-wide styles.
  1713.   var styleToClassCache = {}, styleToClassCacheWithMode = {};
  1714.   function interpretTokenStyle(style, options) {
  1715.     if (!style || /^\s*$/.test(style)) { return null }
  1716.     var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  1717.     return cache[style] ||
  1718.       (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1719.   }
  1720.  
  1721.   // Render the DOM representation of the text of a line. Also builds
  1722.   // up a 'line map', which points at the DOM nodes that represent
  1723.   // specific stretches of text, and is used by the measuring code.
  1724.   // The returned object contains the DOM node, this map, and
  1725.   // information about line-wide styles that were set by the mode.
  1726.   function buildLineContent(cm, lineView) {
  1727.     // The padding-right forces the element to have a 'border', which
  1728.     // is needed on Webkit to be able to get line-level bounding
  1729.     // rectangles for it (in measureChar).
  1730.     var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  1731.     var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  1732.                    col: 0, pos: 0, cm: cm,
  1733.                    trailingSpace: false,
  1734.                    splitSpaces: cm.getOption("lineWrapping")};
  1735.     lineView.measure = {};
  1736.  
  1737.     // Iterate over the logical lines that make up this visual line.
  1738.     for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1739.       var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  1740.       builder.pos = 0;
  1741.       builder.addToken = buildToken;
  1742.       // Optionally wire in some hacks into the token-rendering
  1743.       // algorithm, to deal with browser quirks.
  1744.       if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  1745.         { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  1746.       builder.map = [];
  1747.       var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  1748.       insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  1749.       if (line.styleClasses) {
  1750.         if (line.styleClasses.bgClass)
  1751.           { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  1752.         if (line.styleClasses.textClass)
  1753.           { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  1754.       }
  1755.  
  1756.       // Ensure at least a single node is present, for measuring.
  1757.       if (builder.map.length == 0)
  1758.         { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  1759.  
  1760.       // Store the map and a cache object for the current logical line
  1761.       if (i == 0) {
  1762.         lineView.measure.map = builder.map;
  1763.         lineView.measure.cache = {};
  1764.       } else {
  1765.   (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1766.         ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  1767.       }
  1768.     }
  1769.  
  1770.     // See issue #2901
  1771.     if (webkit) {
  1772.       var last = builder.content.lastChild;
  1773.       if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1774.         { builder.content.className = "cm-tab-wrap-hack"; }
  1775.     }
  1776.  
  1777.     signal(cm, "renderLine", cm, lineView.line, builder.pre);
  1778.     if (builder.pre.className)
  1779.       { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  1780.  
  1781.     return builder
  1782.   }
  1783.  
  1784.   function defaultSpecialCharPlaceholder(ch) {
  1785.     var token = elt("span", "\u2022", "cm-invalidchar");
  1786.     token.title = "\\u" + ch.charCodeAt(0).toString(16);
  1787.     token.setAttribute("aria-label", token.title);
  1788.     return token
  1789.   }
  1790.  
  1791.   // Build up the DOM representation for a single token, and add it to
  1792.   // the line map. Takes care to render special characters separately.
  1793.   function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
  1794.     if (!text) { return }
  1795.     var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  1796.     var special = builder.cm.state.specialChars, mustWrap = false;
  1797.     var content;
  1798.     if (!special.test(text)) {
  1799.       builder.col += text.length;
  1800.       content = document.createTextNode(displayText);
  1801.       builder.map.push(builder.pos, builder.pos + text.length, content);
  1802.       if (ie && ie_version < 9) { mustWrap = true; }
  1803.       builder.pos += text.length;
  1804.     } else {
  1805.       content = document.createDocumentFragment();
  1806.       var pos = 0;
  1807.       while (true) {
  1808.         special.lastIndex = pos;
  1809.         var m = special.exec(text);
  1810.         var skipped = m ? m.index - pos : text.length - pos;
  1811.         if (skipped) {
  1812.           var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  1813.           if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  1814.           else { content.appendChild(txt); }
  1815.           builder.map.push(builder.pos, builder.pos + skipped, txt);
  1816.           builder.col += skipped;
  1817.           builder.pos += skipped;
  1818.         }
  1819.         if (!m) { break }
  1820.         pos += skipped + 1;
  1821.         var txt$1 = (void 0);
  1822.         if (m[0] == "\t") {
  1823.           var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  1824.           txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  1825.           txt$1.setAttribute("role", "presentation");
  1826.           txt$1.setAttribute("cm-text", "\t");
  1827.           builder.col += tabWidth;
  1828.         } else if (m[0] == "\r" || m[0] == "\n") {
  1829.           txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  1830.           txt$1.setAttribute("cm-text", m[0]);
  1831.           builder.col += 1;
  1832.         } else {
  1833.           txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  1834.           txt$1.setAttribute("cm-text", m[0]);
  1835.           if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  1836.           else { content.appendChild(txt$1); }
  1837.           builder.col += 1;
  1838.         }
  1839.         builder.map.push(builder.pos, builder.pos + 1, txt$1);
  1840.         builder.pos++;
  1841.       }
  1842.     }
  1843.     builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  1844.     if (style || startStyle || endStyle || mustWrap || css) {
  1845.       var fullStyle = style || "";
  1846.       if (startStyle) { fullStyle += startStyle; }
  1847.       if (endStyle) { fullStyle += endStyle; }
  1848.       var token = elt("span", [content], fullStyle, css);
  1849.       if (attributes) {
  1850.         for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
  1851.           { token.setAttribute(attr, attributes[attr]); } }
  1852.       }
  1853.       return builder.content.appendChild(token)
  1854.     }
  1855.     builder.content.appendChild(content);
  1856.   }
  1857.  
  1858.   // Change some spaces to NBSP to prevent the browser from collapsing
  1859.   // trailing spaces at the end of a line when rendering text (issue #1362).
  1860.   function splitSpaces(text, trailingBefore) {
  1861.     if (text.length > 1 && !/  /.test(text)) { return text }
  1862.     var spaceBefore = trailingBefore, result = "";
  1863.     for (var i = 0; i < text.length; i++) {
  1864.       var ch = text.charAt(i);
  1865.       if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1866.         { ch = "\u00a0"; }
  1867.       result += ch;
  1868.       spaceBefore = ch == " ";
  1869.     }
  1870.     return result
  1871.   }
  1872.  
  1873.   // Work around nonsense dimensions being reported for stretches of
  1874.   // right-to-left text.
  1875.   function buildTokenBadBidi(inner, order) {
  1876.     return function (builder, text, style, startStyle, endStyle, css, attributes) {
  1877.       style = style ? style + " cm-force-border" : "cm-force-border";
  1878.       var start = builder.pos, end = start + text.length;
  1879.       for (;;) {
  1880.         // Find the part that overlaps with the start of this text
  1881.         var part = (void 0);
  1882.         for (var i = 0; i < order.length; i++) {
  1883.           part = order[i];
  1884.           if (part.to > start && part.from <= start) { break }
  1885.         }
  1886.         if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
  1887.         inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
  1888.         startStyle = null;
  1889.         text = text.slice(part.to - start);
  1890.         start = part.to;
  1891.       }
  1892.     }
  1893.   }
  1894.  
  1895.   function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1896.     var widget = !ignoreWidget && marker.widgetNode;
  1897.     if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  1898.     if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1899.       if (!widget)
  1900.         { widget = builder.content.appendChild(document.createElement("span")); }
  1901.       widget.setAttribute("cm-marker", marker.id);
  1902.     }
  1903.     if (widget) {
  1904.       builder.cm.display.input.setUneditable(widget);
  1905.       builder.content.appendChild(widget);
  1906.     }
  1907.     builder.pos += size;
  1908.     builder.trailingSpace = false;
  1909.   }
  1910.  
  1911.   // Outputs a number of spans to make up a line, taking highlighting
  1912.   // and marked text into account.
  1913.   function insertLineContent(line, builder, styles) {
  1914.     var spans = line.markedSpans, allText = line.text, at = 0;
  1915.     if (!spans) {
  1916.       for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1917.         { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  1918.       return
  1919.     }
  1920.  
  1921.     var len = allText.length, pos = 0, i = 1, text = "", style, css;
  1922.     var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
  1923.     for (;;) {
  1924.       if (nextChange == pos) { // Update current marker set
  1925.         spanStyle = spanEndStyle = spanStartStyle = css = "";
  1926.         attributes = null;
  1927.         collapsed = null; nextChange = Infinity;
  1928.         var foundBookmarks = [], endStyles = (void 0);
  1929.         for (var j = 0; j < spans.length; ++j) {
  1930.           var sp = spans[j], m = sp.marker;
  1931.           if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1932.             foundBookmarks.push(m);
  1933.           } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1934.             if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1935.               nextChange = sp.to;
  1936.               spanEndStyle = "";
  1937.             }
  1938.             if (m.className) { spanStyle += " " + m.className; }
  1939.             if (m.css) { css = (css ? css + ";" : "") + m.css; }
  1940.             if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  1941.             if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  1942.             // support for the old title property
  1943.             // https://github.com/codemirror/CodeMirror/pull/5673
  1944.             if (m.title) { (attributes || (attributes = {})).title = m.title; }
  1945.             if (m.attributes) {
  1946.               for (var attr in m.attributes)
  1947.                 { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
  1948.             }
  1949.             if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1950.               { collapsed = sp; }
  1951.           } else if (sp.from > pos && nextChange > sp.from) {
  1952.             nextChange = sp.from;
  1953.           }
  1954.         }
  1955.         if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1956.           { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  1957.  
  1958.         if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1959.           { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  1960.         if (collapsed && (collapsed.from || 0) == pos) {
  1961.           buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1962.                              collapsed.marker, collapsed.from == null);
  1963.           if (collapsed.to == null) { return }
  1964.           if (collapsed.to == pos) { collapsed = false; }
  1965.         }
  1966.       }
  1967.       if (pos >= len) { break }
  1968.  
  1969.       var upto = Math.min(len, nextChange);
  1970.       while (true) {
  1971.         if (text) {
  1972.           var end = pos + text.length;
  1973.           if (!collapsed) {
  1974.             var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  1975.             builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1976.                              spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
  1977.           }
  1978.           if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1979.           pos = end;
  1980.           spanStartStyle = "";
  1981.         }
  1982.         text = allText.slice(at, at = styles[i++]);
  1983.         style = interpretTokenStyle(styles[i++], builder.cm.options);
  1984.       }
  1985.     }
  1986.   }
  1987.  
  1988.  
  1989.   // These objects are used to represent the visible (currently drawn)
  1990.   // part of the document. A LineView may correspond to multiple
  1991.   // logical lines, if those are connected by collapsed ranges.
  1992.   function LineView(doc, line, lineN) {
  1993.     // The starting line
  1994.     this.line = line;
  1995.     // Continuing lines, if any
  1996.     this.rest = visualLineContinued(line);
  1997.     // Number of logical lines in this visual line
  1998.     this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  1999.     this.node = this.text = null;
  2000.     this.hidden = lineIsHidden(doc, line);
  2001.   }
  2002.  
  2003.   // Create a range of LineView objects for the given lines.
  2004.   function buildViewArray(cm, from, to) {
  2005.     var array = [], nextPos;
  2006.     for (var pos = from; pos < to; pos = nextPos) {
  2007.       var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  2008.       nextPos = pos + view.size;
  2009.       array.push(view);
  2010.     }
  2011.     return array
  2012.   }
  2013.  
  2014.   var operationGroup = null;
  2015.  
  2016.   function pushOperation(op) {
  2017.     if (operationGroup) {
  2018.       operationGroup.ops.push(op);
  2019.     } else {
  2020.       op.ownsGroup = operationGroup = {
  2021.         ops: [op],
  2022.         delayedCallbacks: []
  2023.       };
  2024.     }
  2025.   }
  2026.  
  2027.   function fireCallbacksForOps(group) {
  2028.     // Calls delayed callbacks and cursorActivity handlers until no
  2029.     // new ones appear
  2030.     var callbacks = group.delayedCallbacks, i = 0;
  2031.     do {
  2032.       for (; i < callbacks.length; i++)
  2033.         { callbacks[i].call(null); }
  2034.       for (var j = 0; j < group.ops.length; j++) {
  2035.         var op = group.ops[j];
  2036.         if (op.cursorActivityHandlers)
  2037.           { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  2038.             { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  2039.       }
  2040.     } while (i < callbacks.length)
  2041.   }
  2042.  
  2043.   function finishOperation(op, endCb) {
  2044.     var group = op.ownsGroup;
  2045.     if (!group) { return }
  2046.  
  2047.     try { fireCallbacksForOps(group); }
  2048.     finally {
  2049.       operationGroup = null;
  2050.       endCb(group);
  2051.     }
  2052.   }
  2053.  
  2054.   var orphanDelayedCallbacks = null;
  2055.  
  2056.   // Often, we want to signal events at a point where we are in the
  2057.   // middle of some work, but don't want the handler to start calling
  2058.   // other methods on the editor, which might be in an inconsistent
  2059.   // state or simply not expect any other events to happen.
  2060.   // signalLater looks whether there are any handlers, and schedules
  2061.   // them to be executed when the last operation ends, or, if no
  2062.   // operation is active, when a timeout fires.
  2063.   function signalLater(emitter, type /*, values...*/) {
  2064.     var arr = getHandlers(emitter, type);
  2065.     if (!arr.length) { return }
  2066.     var args = Array.prototype.slice.call(arguments, 2), list;
  2067.     if (operationGroup) {
  2068.       list = operationGroup.delayedCallbacks;
  2069.     } else if (orphanDelayedCallbacks) {
  2070.       list = orphanDelayedCallbacks;
  2071.     } else {
  2072.       list = orphanDelayedCallbacks = [];
  2073.       setTimeout(fireOrphanDelayed, 0);
  2074.     }
  2075.     var loop = function ( i ) {
  2076.       list.push(function () { return arr[i].apply(null, args); });
  2077.     };
  2078.  
  2079.     for (var i = 0; i < arr.length; ++i)
  2080.       loop( i );
  2081.   }
  2082.  
  2083.   function fireOrphanDelayed() {
  2084.     var delayed = orphanDelayedCallbacks;
  2085.     orphanDelayedCallbacks = null;
  2086.     for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  2087.   }
  2088.  
  2089.   // When an aspect of a line changes, a string is added to
  2090.   // lineView.changes. This updates the relevant part of the line's
  2091.   // DOM structure.
  2092.   function updateLineForChanges(cm, lineView, lineN, dims) {
  2093.     for (var j = 0; j < lineView.changes.length; j++) {
  2094.       var type = lineView.changes[j];
  2095.       if (type == "text") { updateLineText(cm, lineView); }
  2096.       else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  2097.       else if (type == "class") { updateLineClasses(cm, lineView); }
  2098.       else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  2099.     }
  2100.     lineView.changes = null;
  2101.   }
  2102.  
  2103.   // Lines with gutter elements, widgets or a background class need to
  2104.   // be wrapped, and have the extra elements added to the wrapper div
  2105.   function ensureLineWrapped(lineView) {
  2106.     if (lineView.node == lineView.text) {
  2107.       lineView.node = elt("div", null, null, "position: relative");
  2108.       if (lineView.text.parentNode)
  2109.         { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  2110.       lineView.node.appendChild(lineView.text);
  2111.       if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  2112.     }
  2113.     return lineView.node
  2114.   }
  2115.  
  2116.   function updateLineBackground(cm, lineView) {
  2117.     var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  2118.     if (cls) { cls += " CodeMirror-linebackground"; }
  2119.     if (lineView.background) {
  2120.       if (cls) { lineView.background.className = cls; }
  2121.       else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  2122.     } else if (cls) {
  2123.       var wrap = ensureLineWrapped(lineView);
  2124.       lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  2125.       cm.display.input.setUneditable(lineView.background);
  2126.     }
  2127.   }
  2128.  
  2129.   // Wrapper around buildLineContent which will reuse the structure
  2130.   // in display.externalMeasured when possible.
  2131.   function getLineContent(cm, lineView) {
  2132.     var ext = cm.display.externalMeasured;
  2133.     if (ext && ext.line == lineView.line) {
  2134.       cm.display.externalMeasured = null;
  2135.       lineView.measure = ext.measure;
  2136.       return ext.built
  2137.     }
  2138.     return buildLineContent(cm, lineView)
  2139.   }
  2140.  
  2141.   // Redraw the line's text. Interacts with the background and text
  2142.   // classes because the mode may output tokens that influence these
  2143.   // classes.
  2144.   function updateLineText(cm, lineView) {
  2145.     var cls = lineView.text.className;
  2146.     var built = getLineContent(cm, lineView);
  2147.     if (lineView.text == lineView.node) { lineView.node = built.pre; }
  2148.     lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  2149.     lineView.text = built.pre;
  2150.     if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  2151.       lineView.bgClass = built.bgClass;
  2152.       lineView.textClass = built.textClass;
  2153.       updateLineClasses(cm, lineView);
  2154.     } else if (cls) {
  2155.       lineView.text.className = cls;
  2156.     }
  2157.   }
  2158.  
  2159.   function updateLineClasses(cm, lineView) {
  2160.     updateLineBackground(cm, lineView);
  2161.     if (lineView.line.wrapClass)
  2162.       { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  2163.     else if (lineView.node != lineView.text)
  2164.       { lineView.node.className = ""; }
  2165.     var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  2166.     lineView.text.className = textClass || "";
  2167.   }
  2168.  
  2169.   function updateLineGutter(cm, lineView, lineN, dims) {
  2170.     if (lineView.gutter) {
  2171.       lineView.node.removeChild(lineView.gutter);
  2172.       lineView.gutter = null;
  2173.     }
  2174.     if (lineView.gutterBackground) {
  2175.       lineView.node.removeChild(lineView.gutterBackground);
  2176.       lineView.gutterBackground = null;
  2177.     }
  2178.     if (lineView.line.gutterClass) {
  2179.       var wrap = ensureLineWrapped(lineView);
  2180.       lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  2181.                                       ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  2182.       cm.display.input.setUneditable(lineView.gutterBackground);
  2183.       wrap.insertBefore(lineView.gutterBackground, lineView.text);
  2184.     }
  2185.     var markers = lineView.line.gutterMarkers;
  2186.     if (cm.options.lineNumbers || markers) {
  2187.       var wrap$1 = ensureLineWrapped(lineView);
  2188.       var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  2189.       cm.display.input.setUneditable(gutterWrap);
  2190.       wrap$1.insertBefore(gutterWrap, lineView.text);
  2191.       if (lineView.line.gutterClass)
  2192.         { gutterWrap.className += " " + lineView.line.gutterClass; }
  2193.       if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  2194.         { lineView.lineNumber = gutterWrap.appendChild(
  2195.           elt("div", lineNumberFor(cm.options, lineN),
  2196.               "CodeMirror-linenumber CodeMirror-gutter-elt",
  2197.               ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  2198.       if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
  2199.         var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
  2200.         if (found)
  2201.           { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2202.                                      ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  2203.       } }
  2204.     }
  2205.   }
  2206.  
  2207.   function updateLineWidgets(cm, lineView, dims) {
  2208.     if (lineView.alignable) { lineView.alignable = null; }
  2209.     var isWidget = classTest("CodeMirror-linewidget");
  2210.     for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  2211.       next = node.nextSibling;
  2212.       if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
  2213.     }
  2214.     insertLineWidgets(cm, lineView, dims);
  2215.   }
  2216.  
  2217.   // Build a line's DOM representation from scratch
  2218.   function buildLineElement(cm, lineView, lineN, dims) {
  2219.     var built = getLineContent(cm, lineView);
  2220.     lineView.text = lineView.node = built.pre;
  2221.     if (built.bgClass) { lineView.bgClass = built.bgClass; }
  2222.     if (built.textClass) { lineView.textClass = built.textClass; }
  2223.  
  2224.     updateLineClasses(cm, lineView);
  2225.     updateLineGutter(cm, lineView, lineN, dims);
  2226.     insertLineWidgets(cm, lineView, dims);
  2227.     return lineView.node
  2228.   }
  2229.  
  2230.   // A lineView may contain multiple logical lines (when merged by
  2231.   // collapsed spans). The widgets for all of them need to be drawn.
  2232.   function insertLineWidgets(cm, lineView, dims) {
  2233.     insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  2234.     if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2235.       { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  2236.   }
  2237.  
  2238.   function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2239.     if (!line.widgets) { return }
  2240.     var wrap = ensureLineWrapped(lineView);
  2241.     for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2242.       var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
  2243.       if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  2244.       positionLineWidget(widget, node, lineView, dims);
  2245.       cm.display.input.setUneditable(node);
  2246.       if (allowAbove && widget.above)
  2247.         { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  2248.       else
  2249.         { wrap.appendChild(node); }
  2250.       signalLater(widget, "redraw");
  2251.     }
  2252.   }
  2253.  
  2254.   function positionLineWidget(widget, node, lineView, dims) {
  2255.     if (widget.noHScroll) {
  2256.   (lineView.alignable || (lineView.alignable = [])).push(node);
  2257.       var width = dims.wrapperWidth;
  2258.       node.style.left = dims.fixedPos + "px";
  2259.       if (!widget.coverGutter) {
  2260.         width -= dims.gutterTotalWidth;
  2261.         node.style.paddingLeft = dims.gutterTotalWidth + "px";
  2262.       }
  2263.       node.style.width = width + "px";
  2264.     }
  2265.     if (widget.coverGutter) {
  2266.       node.style.zIndex = 5;
  2267.       node.style.position = "relative";
  2268.       if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  2269.     }
  2270.   }
  2271.  
  2272.   function widgetHeight(widget) {
  2273.     if (widget.height != null) { return widget.height }
  2274.     var cm = widget.doc.cm;
  2275.     if (!cm) { return 0 }
  2276.     if (!contains(document.body, widget.node)) {
  2277.       var parentStyle = "position: relative;";
  2278.       if (widget.coverGutter)
  2279.         { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  2280.       if (widget.noHScroll)
  2281.         { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  2282.       removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  2283.     }
  2284.     return widget.height = widget.node.parentNode.offsetHeight
  2285.   }
  2286.  
  2287.   // Return true when the given mouse event happened in a widget
  2288.   function eventInWidget(display, e) {
  2289.     for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2290.       if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2291.           (n.parentNode == display.sizer && n != display.mover))
  2292.         { return true }
  2293.     }
  2294.   }
  2295.  
  2296.   // POSITION MEASUREMENT
  2297.  
  2298.   function paddingTop(display) {return display.lineSpace.offsetTop}
  2299.   function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2300.   function paddingH(display) {
  2301.     if (display.cachedPaddingH) { return display.cachedPaddingH }
  2302.     var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
  2303.     var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2304.     var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2305.     if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  2306.     return data
  2307.   }
  2308.  
  2309.   function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2310.   function displayWidth(cm) {
  2311.     return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2312.   }
  2313.   function displayHeight(cm) {
  2314.     return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2315.   }
  2316.  
  2317.   // Ensure the lineView.wrapping.heights array is populated. This is
  2318.   // an array of bottom offsets for the lines that make up a drawn
  2319.   // line. When lineWrapping is on, there might be more than one
  2320.   // height.
  2321.   function ensureLineHeights(cm, lineView, rect) {
  2322.     var wrapping = cm.options.lineWrapping;
  2323.     var curWidth = wrapping && displayWidth(cm);
  2324.     if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2325.       var heights = lineView.measure.heights = [];
  2326.       if (wrapping) {
  2327.         lineView.measure.width = curWidth;
  2328.         var rects = lineView.text.firstChild.getClientRects();
  2329.         for (var i = 0; i < rects.length - 1; i++) {
  2330.           var cur = rects[i], next = rects[i + 1];
  2331.           if (Math.abs(cur.bottom - next.bottom) > 2)
  2332.             { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  2333.         }
  2334.       }
  2335.       heights.push(rect.bottom - rect.top);
  2336.     }
  2337.   }
  2338.  
  2339.   // Find a line map (mapping character offsets to text nodes) and a
  2340.   // measurement cache for the given line number. (A line view might
  2341.   // contain multiple lines when collapsed ranges are present.)
  2342.   function mapFromLineView(lineView, line, lineN) {
  2343.     if (lineView.line == line)
  2344.       { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2345.     for (var i = 0; i < lineView.rest.length; i++)
  2346.       { if (lineView.rest[i] == line)
  2347.         { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2348.     for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2349.       { if (lineNo(lineView.rest[i$1]) > lineN)
  2350.         { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2351.   }
  2352.  
  2353.   // Render a line into the hidden node display.externalMeasured. Used
  2354.   // when measurement is needed for a line that's not in the viewport.
  2355.   function updateExternalMeasurement(cm, line) {
  2356.     line = visualLine(line);
  2357.     var lineN = lineNo(line);
  2358.     var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2359.     view.lineN = lineN;
  2360.     var built = view.built = buildLineContent(cm, view);
  2361.     view.text = built.pre;
  2362.     removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2363.     return view
  2364.   }
  2365.  
  2366.   // Get a {top, bottom, left, right} box (in line-local coordinates)
  2367.   // for a given character.
  2368.   function measureChar(cm, line, ch, bias) {
  2369.     return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2370.   }
  2371.  
  2372.   // Find a line view that corresponds to the given line number.
  2373.   function findViewForLine(cm, lineN) {
  2374.     if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2375.       { return cm.display.view[findViewIndex(cm, lineN)] }
  2376.     var ext = cm.display.externalMeasured;
  2377.     if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2378.       { return ext }
  2379.   }
  2380.  
  2381.   // Measurement can be split in two steps, the set-up work that
  2382.   // applies to the whole line, and the measurement of the actual
  2383.   // character. Functions like coordsChar, that need to do a lot of
  2384.   // measurements in a row, can thus ensure that the set-up work is
  2385.   // only done once.
  2386.   function prepareMeasureForLine(cm, line) {
  2387.     var lineN = lineNo(line);
  2388.     var view = findViewForLine(cm, lineN);
  2389.     if (view && !view.text) {
  2390.       view = null;
  2391.     } else if (view && view.changes) {
  2392.       updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2393.       cm.curOp.forceUpdate = true;
  2394.     }
  2395.     if (!view)
  2396.       { view = updateExternalMeasurement(cm, line); }
  2397.  
  2398.     var info = mapFromLineView(view, line, lineN);
  2399.     return {
  2400.       line: line, view: view, rect: null,
  2401.       map: info.map, cache: info.cache, before: info.before,
  2402.       hasHeights: false
  2403.     }
  2404.   }
  2405.  
  2406.   // Given a prepared measurement object, measures the position of an
  2407.   // actual character (or fetches it from the cache).
  2408.   function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2409.     if (prepared.before) { ch = -1; }
  2410.     var key = ch + (bias || ""), found;
  2411.     if (prepared.cache.hasOwnProperty(key)) {
  2412.       found = prepared.cache[key];
  2413.     } else {
  2414.       if (!prepared.rect)
  2415.         { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  2416.       if (!prepared.hasHeights) {
  2417.         ensureLineHeights(cm, prepared.view, prepared.rect);
  2418.         prepared.hasHeights = true;
  2419.       }
  2420.       found = measureCharInner(cm, prepared, ch, bias);
  2421.       if (!found.bogus) { prepared.cache[key] = found; }
  2422.     }
  2423.     return {left: found.left, right: found.right,
  2424.             top: varHeight ? found.rtop : found.top,
  2425.             bottom: varHeight ? found.rbottom : found.bottom}
  2426.   }
  2427.  
  2428.   var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2429.  
  2430.   function nodeAndOffsetInLineMap(map, ch, bias) {
  2431.     var node, start, end, collapse, mStart, mEnd;
  2432.     // First, search the line map for the text node corresponding to,
  2433.     // or closest to, the target character.
  2434.     for (var i = 0; i < map.length; i += 3) {
  2435.       mStart = map[i];
  2436.       mEnd = map[i + 1];
  2437.       if (ch < mStart) {
  2438.         start = 0; end = 1;
  2439.         collapse = "left";
  2440.       } else if (ch < mEnd) {
  2441.         start = ch - mStart;
  2442.         end = start + 1;
  2443.       } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2444.         end = mEnd - mStart;
  2445.         start = end - 1;
  2446.         if (ch >= mEnd) { collapse = "right"; }
  2447.       }
  2448.       if (start != null) {
  2449.         node = map[i + 2];
  2450.         if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2451.           { collapse = bias; }
  2452.         if (bias == "left" && start == 0)
  2453.           { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2454.             node = map[(i -= 3) + 2];
  2455.             collapse = "left";
  2456.           } }
  2457.         if (bias == "right" && start == mEnd - mStart)
  2458.           { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2459.             node = map[(i += 3) + 2];
  2460.             collapse = "right";
  2461.           } }
  2462.         break
  2463.       }
  2464.     }
  2465.     return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2466.   }
  2467.  
  2468.   function getUsefulRect(rects, bias) {
  2469.     var rect = nullRect;
  2470.     if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2471.       if ((rect = rects[i]).left != rect.right) { break }
  2472.     } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2473.       if ((rect = rects[i$1]).left != rect.right) { break }
  2474.     } }
  2475.     return rect
  2476.   }
  2477.  
  2478.   function measureCharInner(cm, prepared, ch, bias) {
  2479.     var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2480.     var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2481.  
  2482.     var rect;
  2483.     if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2484.       for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2485.         while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  2486.         while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  2487.         if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2488.           { rect = node.parentNode.getBoundingClientRect(); }
  2489.         else
  2490.           { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  2491.         if (rect.left || rect.right || start == 0) { break }
  2492.         end = start;
  2493.         start = start - 1;
  2494.         collapse = "right";
  2495.       }
  2496.       if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  2497.     } else { // If it is a widget, simply get the box for the whole widget.
  2498.       if (start > 0) { collapse = bias = "right"; }
  2499.       var rects;
  2500.       if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2501.         { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  2502.       else
  2503.         { rect = node.getBoundingClientRect(); }
  2504.     }
  2505.     if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2506.       var rSpan = node.parentNode.getClientRects()[0];
  2507.       if (rSpan)
  2508.         { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  2509.       else
  2510.         { rect = nullRect; }
  2511.     }
  2512.  
  2513.     var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2514.     var mid = (rtop + rbot) / 2;
  2515.     var heights = prepared.view.measure.heights;
  2516.     var i = 0;
  2517.     for (; i < heights.length - 1; i++)
  2518.       { if (mid < heights[i]) { break } }
  2519.     var top = i ? heights[i - 1] : 0, bot = heights[i];
  2520.     var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2521.                   right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2522.                   top: top, bottom: bot};
  2523.     if (!rect.left && !rect.right) { result.bogus = true; }
  2524.     if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2525.  
  2526.     return result
  2527.   }
  2528.  
  2529.   // Work around problem with bounding client rects on ranges being
  2530.   // returned incorrectly when zoomed on IE10 and below.
  2531.   function maybeUpdateRectForZooming(measure, rect) {
  2532.     if (!window.screen || screen.logicalXDPI == null ||
  2533.         screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2534.       { return rect }
  2535.     var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2536.     var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2537.     return {left: rect.left * scaleX, right: rect.right * scaleX,
  2538.             top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2539.   }
  2540.  
  2541.   function clearLineMeasurementCacheFor(lineView) {
  2542.     if (lineView.measure) {
  2543.       lineView.measure.cache = {};
  2544.       lineView.measure.heights = null;
  2545.       if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2546.         { lineView.measure.caches[i] = {}; } }
  2547.     }
  2548.   }
  2549.  
  2550.   function clearLineMeasurementCache(cm) {
  2551.     cm.display.externalMeasure = null;
  2552.     removeChildren(cm.display.lineMeasure);
  2553.     for (var i = 0; i < cm.display.view.length; i++)
  2554.       { clearLineMeasurementCacheFor(cm.display.view[i]); }
  2555.   }
  2556.  
  2557.   function clearCaches(cm) {
  2558.     clearLineMeasurementCache(cm);
  2559.     cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2560.     if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  2561.     cm.display.lineNumChars = null;
  2562.   }
  2563.  
  2564.   function pageScrollX() {
  2565.     // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  2566.     // which causes page_Offset and bounding client rects to use
  2567.     // different reference viewports and invalidate our calculations.
  2568.     if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  2569.     return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  2570.   }
  2571.   function pageScrollY() {
  2572.     if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  2573.     return window.pageYOffset || (document.documentElement || document.body).scrollTop
  2574.   }
  2575.  
  2576.   function widgetTopHeight(lineObj) {
  2577.     var height = 0;
  2578.     if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
  2579.       { height += widgetHeight(lineObj.widgets[i]); } } }
  2580.     return height
  2581.   }
  2582.  
  2583.   // Converts a {top, bottom, left, right} box from line-local
  2584.   // coordinates into another coordinate system. Context may be one of
  2585.   // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2586.   // or "page".
  2587.   function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2588.     if (!includeWidgets) {
  2589.       var height = widgetTopHeight(lineObj);
  2590.       rect.top += height; rect.bottom += height;
  2591.     }
  2592.     if (context == "line") { return rect }
  2593.     if (!context) { context = "local"; }
  2594.     var yOff = heightAtLine(lineObj);
  2595.     if (context == "local") { yOff += paddingTop(cm.display); }
  2596.     else { yOff -= cm.display.viewOffset; }
  2597.     if (context == "page" || context == "window") {
  2598.       var lOff = cm.display.lineSpace.getBoundingClientRect();
  2599.       yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2600.       var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2601.       rect.left += xOff; rect.right += xOff;
  2602.     }
  2603.     rect.top += yOff; rect.bottom += yOff;
  2604.     return rect
  2605.   }
  2606.  
  2607.   // Coverts a box from "div" coords to another coordinate system.
  2608.   // Context may be "window", "page", "div", or "local"./null.
  2609.   function fromCoordSystem(cm, coords, context) {
  2610.     if (context == "div") { return coords }
  2611.     var left = coords.left, top = coords.top;
  2612.     // First move into "page" coordinate system
  2613.     if (context == "page") {
  2614.       left -= pageScrollX();
  2615.       top -= pageScrollY();
  2616.     } else if (context == "local" || !context) {
  2617.       var localBox = cm.display.sizer.getBoundingClientRect();
  2618.       left += localBox.left;
  2619.       top += localBox.top;
  2620.     }
  2621.  
  2622.     var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2623.     return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2624.   }
  2625.  
  2626.   function charCoords(cm, pos, context, lineObj, bias) {
  2627.     if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  2628.     return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2629.   }
  2630.  
  2631.   // Returns a box for a given cursor position, which may have an
  2632.   // 'other' property containing the position of the secondary cursor
  2633.   // on a bidi boundary.
  2634.   // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2635.   // and after `char - 1` in writing order of `char - 1`
  2636.   // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2637.   // and before `char` in writing order of `char`
  2638.   // Examples (upper-case letters are RTL, lower-case are LTR):
  2639.   //     Pos(0, 1, ...)
  2640.   //     before   after
  2641.   // ab     a|b     a|b
  2642.   // aB     a|B     aB|
  2643.   // Ab     |Ab     A|b
  2644.   // AB     B|A     B|A
  2645.   // Every position after the last character on a line is considered to stick
  2646.   // to the last character on the line.
  2647.   function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2648.     lineObj = lineObj || getLine(cm.doc, pos.line);
  2649.     if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2650.     function get(ch, right) {
  2651.       var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2652.       if (right) { m.left = m.right; } else { m.right = m.left; }
  2653.       return intoCoordSystem(cm, lineObj, m, context)
  2654.     }
  2655.     var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  2656.     if (ch >= lineObj.text.length) {
  2657.       ch = lineObj.text.length;
  2658.       sticky = "before";
  2659.     } else if (ch <= 0) {
  2660.       ch = 0;
  2661.       sticky = "after";
  2662.     }
  2663.     if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2664.  
  2665.     function getBidi(ch, partPos, invert) {
  2666.       var part = order[partPos], right = part.level == 1;
  2667.       return get(invert ? ch - 1 : ch, right != invert)
  2668.     }
  2669.     var partPos = getBidiPartAt(order, ch, sticky);
  2670.     var other = bidiOther;
  2671.     var val = getBidi(ch, partPos, sticky == "before");
  2672.     if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  2673.     return val
  2674.   }
  2675.  
  2676.   // Used to cheaply estimate the coordinates for a position. Used for
  2677.   // intermediate scroll updates.
  2678.   function estimateCoords(cm, pos) {
  2679.     var left = 0;
  2680.     pos = clipPos(cm.doc, pos);
  2681.     if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  2682.     var lineObj = getLine(cm.doc, pos.line);
  2683.     var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2684.     return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2685.   }
  2686.  
  2687.   // Positions returned by coordsChar contain some extra information.
  2688.   // xRel is the relative x position of the input coordinates compared
  2689.   // to the found position (so xRel > 0 means the coordinates are to
  2690.   // the right of the character position, for example). When outside
  2691.   // is true, that means the coordinates lie outside the line's
  2692.   // vertical range.
  2693.   function PosWithInfo(line, ch, sticky, outside, xRel) {
  2694.     var pos = Pos(line, ch, sticky);
  2695.     pos.xRel = xRel;
  2696.     if (outside) { pos.outside = outside; }
  2697.     return pos
  2698.   }
  2699.  
  2700.   // Compute the character position closest to the given coordinates.
  2701.   // Input must be lineSpace-local ("div" coordinate system).
  2702.   function coordsChar(cm, x, y) {
  2703.     var doc = cm.doc;
  2704.     y += cm.display.viewOffset;
  2705.     if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
  2706.     var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2707.     if (lineN > last)
  2708.       { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
  2709.     if (x < 0) { x = 0; }
  2710.  
  2711.     var lineObj = getLine(doc, lineN);
  2712.     for (;;) {
  2713.       var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2714.       var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
  2715.       if (!collapsed) { return found }
  2716.       var rangeEnd = collapsed.find(1);
  2717.       if (rangeEnd.line == lineN) { return rangeEnd }
  2718.       lineObj = getLine(doc, lineN = rangeEnd.line);
  2719.     }
  2720.   }
  2721.  
  2722.   function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2723.     y -= widgetTopHeight(lineObj);
  2724.     var end = lineObj.text.length;
  2725.     var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  2726.     end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  2727.     return {begin: begin, end: end}
  2728.   }
  2729.  
  2730.   function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2731.     if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2732.     var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  2733.     return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2734.   }
  2735.  
  2736.   // Returns true if the given side of a box is after the given
  2737.   // coordinates, in top-to-bottom, left-to-right order.
  2738.   function boxIsAfter(box, x, y, left) {
  2739.     return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  2740.   }
  2741.  
  2742.   function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2743.     // Move y into line-local coordinate space
  2744.     y -= heightAtLine(lineObj);
  2745.     var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2746.     // When directly calling `measureCharPrepared`, we have to adjust
  2747.     // for the widgets at this line.
  2748.     var widgetHeight = widgetTopHeight(lineObj);
  2749.     var begin = 0, end = lineObj.text.length, ltr = true;
  2750.  
  2751.     var order = getOrder(lineObj, cm.doc.direction);
  2752.     // If the line isn't plain left-to-right text, first figure out
  2753.     // which bidi section the coordinates fall into.
  2754.     if (order) {
  2755.       var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  2756.                    (cm, lineObj, lineNo, preparedMeasure, order, x, y);
  2757.       ltr = part.level != 1;
  2758.       // The awkward -1 offsets are needed because findFirst (called
  2759.       // on these below) will treat its first bound as inclusive,
  2760.       // second as exclusive, but we want to actually address the
  2761.       // characters in the part's range
  2762.       begin = ltr ? part.from : part.to - 1;
  2763.       end = ltr ? part.to : part.from - 1;
  2764.     }
  2765.  
  2766.     // A binary search to find the first character whose bounding box
  2767.     // starts after the coordinates. If we run across any whose box wrap
  2768.     // the coordinates, store that.
  2769.     var chAround = null, boxAround = null;
  2770.     var ch = findFirst(function (ch) {
  2771.       var box = measureCharPrepared(cm, preparedMeasure, ch);
  2772.       box.top += widgetHeight; box.bottom += widgetHeight;
  2773.       if (!boxIsAfter(box, x, y, false)) { return false }
  2774.       if (box.top <= y && box.left <= x) {
  2775.         chAround = ch;
  2776.         boxAround = box;
  2777.       }
  2778.       return true
  2779.     }, begin, end);
  2780.  
  2781.     var baseX, sticky, outside = false;
  2782.     // If a box around the coordinates was found, use that
  2783.     if (boxAround) {
  2784.       // Distinguish coordinates nearer to the left or right side of the box
  2785.       var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  2786.       ch = chAround + (atStart ? 0 : 1);
  2787.       sticky = atStart ? "after" : "before";
  2788.       baseX = atLeft ? boxAround.left : boxAround.right;
  2789.     } else {
  2790.       // (Adjust for extended bound, if necessary.)
  2791.       if (!ltr && (ch == end || ch == begin)) { ch++; }
  2792.       // To determine which side to associate with, get the box to the
  2793.       // left of the character and compare it's vertical position to the
  2794.       // coordinates
  2795.       sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  2796.         (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
  2797.         "after" : "before";
  2798.       // Now get accurate coordinates for this place, in order to get a
  2799.       // base X position
  2800.       var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
  2801.       baseX = coords.left;
  2802.       outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
  2803.     }
  2804.  
  2805.     ch = skipExtendingChars(lineObj.text, ch, 1);
  2806.     return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  2807.   }
  2808.  
  2809.   function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
  2810.     // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  2811.     // situation, we can take this ordering to correspond to the visual
  2812.     // ordering. This finds the first part whose end is after the given
  2813.     // coordinates.
  2814.     var index = findFirst(function (i) {
  2815.       var part = order[i], ltr = part.level != 1;
  2816.       return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
  2817.                                      "line", lineObj, preparedMeasure), x, y, true)
  2818.     }, 0, order.length - 1);
  2819.     var part = order[index];
  2820.     // If this isn't the first part, the part's start is also after
  2821.     // the coordinates, and the coordinates aren't on the same line as
  2822.     // that start, move one part back.
  2823.     if (index > 0) {
  2824.       var ltr = part.level != 1;
  2825.       var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
  2826.                                "line", lineObj, preparedMeasure);
  2827.       if (boxIsAfter(start, x, y, true) && start.top > y)
  2828.         { part = order[index - 1]; }
  2829.     }
  2830.     return part
  2831.   }
  2832.  
  2833.   function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  2834.     // In a wrapped line, rtl text on wrapping boundaries can do things
  2835.     // that don't correspond to the ordering in our `order` array at
  2836.     // all, so a binary search doesn't work, and we want to return a
  2837.     // part that only spans one line so that the binary search in
  2838.     // coordsCharInner is safe. As such, we first find the extent of the
  2839.     // wrapped line, and then do a flat search in which we discard any
  2840.     // spans that aren't on the line.
  2841.     var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  2842.     var begin = ref.begin;
  2843.     var end = ref.end;
  2844.     if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  2845.     var part = null, closestDist = null;
  2846.     for (var i = 0; i < order.length; i++) {
  2847.       var p = order[i];
  2848.       if (p.from >= end || p.to <= begin) { continue }
  2849.       var ltr = p.level != 1;
  2850.       var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  2851.       // Weigh against spans ending before this, so that they are only
  2852.       // picked if nothing ends after
  2853.       var dist = endX < x ? x - endX + 1e9 : endX - x;
  2854.       if (!part || closestDist > dist) {
  2855.         part = p;
  2856.         closestDist = dist;
  2857.       }
  2858.     }
  2859.     if (!part) { part = order[order.length - 1]; }
  2860.     // Clip the part to the wrapped line.
  2861.     if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  2862.     if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  2863.     return part
  2864.   }
  2865.  
  2866.   var measureText;
  2867.   // Compute the default text height.
  2868.   function textHeight(display) {
  2869.     if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2870.     if (measureText == null) {
  2871.       measureText = elt("pre", null, "CodeMirror-line-like");
  2872.       // Measure a bunch of lines, for browsers that compute
  2873.       // fractional heights.
  2874.       for (var i = 0; i < 49; ++i) {
  2875.         measureText.appendChild(document.createTextNode("x"));
  2876.         measureText.appendChild(elt("br"));
  2877.       }
  2878.       measureText.appendChild(document.createTextNode("x"));
  2879.     }
  2880.     removeChildrenAndAdd(display.measure, measureText);
  2881.     var height = measureText.offsetHeight / 50;
  2882.     if (height > 3) { display.cachedTextHeight = height; }
  2883.     removeChildren(display.measure);
  2884.     return height || 1
  2885.   }
  2886.  
  2887.   // Compute the default character width.
  2888.   function charWidth(display) {
  2889.     if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2890.     var anchor = elt("span", "xxxxxxxxxx");
  2891.     var pre = elt("pre", [anchor], "CodeMirror-line-like");
  2892.     removeChildrenAndAdd(display.measure, pre);
  2893.     var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2894.     if (width > 2) { display.cachedCharWidth = width; }
  2895.     return width || 10
  2896.   }
  2897.  
  2898.   // Do a bulk-read of the DOM positions and sizes needed to draw the
  2899.   // view, so that we don't interleave reading and writing to the DOM.
  2900.   function getDimensions(cm) {
  2901.     var d = cm.display, left = {}, width = {};
  2902.     var gutterLeft = d.gutters.clientLeft;
  2903.     for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2904.       var id = cm.display.gutterSpecs[i].className;
  2905.       left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
  2906.       width[id] = n.clientWidth;
  2907.     }
  2908.     return {fixedPos: compensateForHScroll(d),
  2909.             gutterTotalWidth: d.gutters.offsetWidth,
  2910.             gutterLeft: left,
  2911.             gutterWidth: width,
  2912.             wrapperWidth: d.wrapper.clientWidth}
  2913.   }
  2914.  
  2915.   // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2916.   // but using getBoundingClientRect to get a sub-pixel-accurate
  2917.   // result.
  2918.   function compensateForHScroll(display) {
  2919.     return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2920.   }
  2921.  
  2922.   // Returns a function that estimates the height of a line, to use as
  2923.   // first approximation until the line becomes visible (and is thus
  2924.   // properly measurable).
  2925.   function estimateHeight(cm) {
  2926.     var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  2927.     var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  2928.     return function (line) {
  2929.       if (lineIsHidden(cm.doc, line)) { return 0 }
  2930.  
  2931.       var widgetsHeight = 0;
  2932.       if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2933.         if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  2934.       } }
  2935.  
  2936.       if (wrapping)
  2937.         { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2938.       else
  2939.         { return widgetsHeight + th }
  2940.     }
  2941.   }
  2942.  
  2943.   function estimateLineHeights(cm) {
  2944.     var doc = cm.doc, est = estimateHeight(cm);
  2945.     doc.iter(function (line) {
  2946.       var estHeight = est(line);
  2947.       if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  2948.     });
  2949.   }
  2950.  
  2951.   // Given a mouse event, find the corresponding position. If liberal
  2952.   // is false, it checks whether a gutter or scrollbar was clicked,
  2953.   // and returns null if it was. forRect is used by rectangular
  2954.   // selections, and tries to estimate a character position even for
  2955.   // coordinates beyond the right of the text.
  2956.   function posFromMouse(cm, e, liberal, forRect) {
  2957.     var display = cm.display;
  2958.     if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2959.  
  2960.     var x, y, space = display.lineSpace.getBoundingClientRect();
  2961.     // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2962.     try { x = e.clientX - space.left; y = e.clientY - space.top; }
  2963.     catch (e) { return null }
  2964.     var coords = coordsChar(cm, x, y), line;
  2965.     if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2966.       var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  2967.       coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  2968.     }
  2969.     return coords
  2970.   }
  2971.  
  2972.   // Find the view element corresponding to a given line. Return null
  2973.   // when the line isn't visible.
  2974.   function findViewIndex(cm, n) {
  2975.     if (n >= cm.display.viewTo) { return null }
  2976.     n -= cm.display.viewFrom;
  2977.     if (n < 0) { return null }
  2978.     var view = cm.display.view;
  2979.     for (var i = 0; i < view.length; i++) {
  2980.       n -= view[i].size;
  2981.       if (n < 0) { return i }
  2982.     }
  2983.   }
  2984.  
  2985.   // Updates the display.view data structure for a given change to the
  2986.   // document. From and to are in pre-change coordinates. Lendiff is
  2987.   // the amount of lines added or subtracted by the change. This is
  2988.   // used for changes that span multiple lines, or change the way
  2989.   // lines are divided into visual lines. regLineChange (below)
  2990.   // registers single-line changes.
  2991.   function regChange(cm, from, to, lendiff) {
  2992.     if (from == null) { from = cm.doc.first; }
  2993.     if (to == null) { to = cm.doc.first + cm.doc.size; }
  2994.     if (!lendiff) { lendiff = 0; }
  2995.  
  2996.     var display = cm.display;
  2997.     if (lendiff && to < display.viewTo &&
  2998.         (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2999.       { display.updateLineNumbers = from; }
  3000.  
  3001.     cm.curOp.viewChanged = true;
  3002.  
  3003.     if (from >= display.viewTo) { // Change after
  3004.       if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  3005.         { resetView(cm); }
  3006.     } else if (to <= display.viewFrom) { // Change before
  3007.       if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  3008.         resetView(cm);
  3009.       } else {
  3010.         display.viewFrom += lendiff;
  3011.         display.viewTo += lendiff;
  3012.       }
  3013.     } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  3014.       resetView(cm);
  3015.     } else if (from <= display.viewFrom) { // Top overlap
  3016.       var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  3017.       if (cut) {
  3018.         display.view = display.view.slice(cut.index);
  3019.         display.viewFrom = cut.lineN;
  3020.         display.viewTo += lendiff;
  3021.       } else {
  3022.         resetView(cm);
  3023.       }
  3024.     } else if (to >= display.viewTo) { // Bottom overlap
  3025.       var cut$1 = viewCuttingPoint(cm, from, from, -1);
  3026.       if (cut$1) {
  3027.         display.view = display.view.slice(0, cut$1.index);
  3028.         display.viewTo = cut$1.lineN;
  3029.       } else {
  3030.         resetView(cm);
  3031.       }
  3032.     } else { // Gap in the middle
  3033.       var cutTop = viewCuttingPoint(cm, from, from, -1);
  3034.       var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  3035.       if (cutTop && cutBot) {
  3036.         display.view = display.view.slice(0, cutTop.index)
  3037.           .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  3038.           .concat(display.view.slice(cutBot.index));
  3039.         display.viewTo += lendiff;
  3040.       } else {
  3041.         resetView(cm);
  3042.       }
  3043.     }
  3044.  
  3045.     var ext = display.externalMeasured;
  3046.     if (ext) {
  3047.       if (to < ext.lineN)
  3048.         { ext.lineN += lendiff; }
  3049.       else if (from < ext.lineN + ext.size)
  3050.         { display.externalMeasured = null; }
  3051.     }
  3052.   }
  3053.  
  3054.   // Register a change to a single line. Type must be one of "text",
  3055.   // "gutter", "class", "widget"
  3056.   function regLineChange(cm, line, type) {
  3057.     cm.curOp.viewChanged = true;
  3058.     var display = cm.display, ext = cm.display.externalMeasured;
  3059.     if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  3060.       { display.externalMeasured = null; }
  3061.  
  3062.     if (line < display.viewFrom || line >= display.viewTo) { return }
  3063.     var lineView = display.view[findViewIndex(cm, line)];
  3064.     if (lineView.node == null) { return }
  3065.     var arr = lineView.changes || (lineView.changes = []);
  3066.     if (indexOf(arr, type) == -1) { arr.push(type); }
  3067.   }
  3068.  
  3069.   // Clear the view.
  3070.   function resetView(cm) {
  3071.     cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  3072.     cm.display.view = [];
  3073.     cm.display.viewOffset = 0;
  3074.   }
  3075.  
  3076.   function viewCuttingPoint(cm, oldN, newN, dir) {
  3077.     var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  3078.     if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  3079.       { return {index: index, lineN: newN} }
  3080.     var n = cm.display.viewFrom;
  3081.     for (var i = 0; i < index; i++)
  3082.       { n += view[i].size; }
  3083.     if (n != oldN) {
  3084.       if (dir > 0) {
  3085.         if (index == view.length - 1) { return null }
  3086.         diff = (n + view[index].size) - oldN;
  3087.         index++;
  3088.       } else {
  3089.         diff = n - oldN;
  3090.       }
  3091.       oldN += diff; newN += diff;
  3092.     }
  3093.     while (visualLineNo(cm.doc, newN) != newN) {
  3094.       if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  3095.       newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  3096.       index += dir;
  3097.     }
  3098.     return {index: index, lineN: newN}
  3099.   }
  3100.  
  3101.   // Force the view to cover a given range, adding empty view element
  3102.   // or clipping off existing ones as needed.
  3103.   function adjustView(cm, from, to) {
  3104.     var display = cm.display, view = display.view;
  3105.     if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3106.       display.view = buildViewArray(cm, from, to);
  3107.       display.viewFrom = from;
  3108.     } else {
  3109.       if (display.viewFrom > from)
  3110.         { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  3111.       else if (display.viewFrom < from)
  3112.         { display.view = display.view.slice(findViewIndex(cm, from)); }
  3113.       display.viewFrom = from;
  3114.       if (display.viewTo < to)
  3115.         { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  3116.       else if (display.viewTo > to)
  3117.         { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  3118.     }
  3119.     display.viewTo = to;
  3120.   }
  3121.  
  3122.   // Count the number of lines in the view whose DOM representation is
  3123.   // out of date (or nonexistent).
  3124.   function countDirtyView(cm) {
  3125.     var view = cm.display.view, dirty = 0;
  3126.     for (var i = 0; i < view.length; i++) {
  3127.       var lineView = view[i];
  3128.       if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  3129.     }
  3130.     return dirty
  3131.   }
  3132.  
  3133.   function updateSelection(cm) {
  3134.     cm.display.input.showSelection(cm.display.input.prepareSelection());
  3135.   }
  3136.  
  3137.   function prepareSelection(cm, primary) {
  3138.     if ( primary === void 0 ) primary = true;
  3139.  
  3140.     var doc = cm.doc, result = {};
  3141.     var curFragment = result.cursors = document.createDocumentFragment();
  3142.     var selFragment = result.selection = document.createDocumentFragment();
  3143.  
  3144.     for (var i = 0; i < doc.sel.ranges.length; i++) {
  3145.       if (!primary && i == doc.sel.primIndex) { continue }
  3146.       var range = doc.sel.ranges[i];
  3147.       if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
  3148.       var collapsed = range.empty();
  3149.       if (collapsed || cm.options.showCursorWhenSelecting)
  3150.         { drawSelectionCursor(cm, range.head, curFragment); }
  3151.       if (!collapsed)
  3152.         { drawSelectionRange(cm, range, selFragment); }
  3153.     }
  3154.     return result
  3155.   }
  3156.  
  3157.   // Draws a cursor for the given range
  3158.   function drawSelectionCursor(cm, head, output) {
  3159.     var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  3160.  
  3161.     var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  3162.     cursor.style.left = pos.left + "px";
  3163.     cursor.style.top = pos.top + "px";
  3164.     cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  3165.  
  3166.     if (pos.other) {
  3167.       // Secondary cursor, shown when on a 'jump' in bi-directional text
  3168.       var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  3169.       otherCursor.style.display = "";
  3170.       otherCursor.style.left = pos.other.left + "px";
  3171.       otherCursor.style.top = pos.other.top + "px";
  3172.       otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  3173.     }
  3174.   }
  3175.  
  3176.   function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  3177.  
  3178.   // Draws the given range as a highlighted selection
  3179.   function drawSelectionRange(cm, range, output) {
  3180.     var display = cm.display, doc = cm.doc;
  3181.     var fragment = document.createDocumentFragment();
  3182.     var padding = paddingH(cm.display), leftSide = padding.left;
  3183.     var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  3184.     var docLTR = doc.direction == "ltr";
  3185.  
  3186.     function add(left, top, width, bottom) {
  3187.       if (top < 0) { top = 0; }
  3188.       top = Math.round(top);
  3189.       bottom = Math.round(bottom);
  3190.       fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n                             top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n                             height: " + (bottom - top) + "px")));
  3191.     }
  3192.  
  3193.     function drawForLine(line, fromArg, toArg) {
  3194.       var lineObj = getLine(doc, line);
  3195.       var lineLen = lineObj.text.length;
  3196.       var start, end;
  3197.       function coords(ch, bias) {
  3198.         return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  3199.       }
  3200.  
  3201.       function wrapX(pos, dir, side) {
  3202.         var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  3203.         var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  3204.         var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  3205.         return coords(ch, prop)[prop]
  3206.       }
  3207.  
  3208.       var order = getOrder(lineObj, doc.direction);
  3209.       iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  3210.         var ltr = dir == "ltr";
  3211.         var fromPos = coords(from, ltr ? "left" : "right");
  3212.         var toPos = coords(to - 1, ltr ? "right" : "left");
  3213.  
  3214.         var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  3215.         var first = i == 0, last = !order || i == order.length - 1;
  3216.         if (toPos.top - fromPos.top <= 3) { // Single line
  3217.           var openLeft = (docLTR ? openStart : openEnd) && first;
  3218.           var openRight = (docLTR ? openEnd : openStart) && last;
  3219.           var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  3220.           var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  3221.           add(left, fromPos.top, right - left, fromPos.bottom);
  3222.         } else { // Multiple lines
  3223.           var topLeft, topRight, botLeft, botRight;
  3224.           if (ltr) {
  3225.             topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  3226.             topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  3227.             botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  3228.             botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  3229.           } else {
  3230.             topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  3231.             topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  3232.             botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  3233.             botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  3234.           }
  3235.           add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  3236.           if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  3237.           add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  3238.         }
  3239.  
  3240.         if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  3241.         if (cmpCoords(toPos, start) < 0) { start = toPos; }
  3242.         if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  3243.         if (cmpCoords(toPos, end) < 0) { end = toPos; }
  3244.       });
  3245.       return {start: start, end: end}
  3246.     }
  3247.  
  3248.     var sFrom = range.from(), sTo = range.to();
  3249.     if (sFrom.line == sTo.line) {
  3250.       drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  3251.     } else {
  3252.       var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  3253.       var singleVLine = visualLine(fromLine) == visualLine(toLine);
  3254.       var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  3255.       var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  3256.       if (singleVLine) {
  3257.         if (leftEnd.top < rightStart.top - 2) {
  3258.           add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  3259.           add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  3260.         } else {
  3261.           add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  3262.         }
  3263.       }
  3264.       if (leftEnd.bottom < rightStart.top)
  3265.         { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  3266.     }
  3267.  
  3268.     output.appendChild(fragment);
  3269.   }
  3270.  
  3271.   // Cursor-blinking
  3272.   function restartBlink(cm) {
  3273.     if (!cm.state.focused) { return }
  3274.     var display = cm.display;
  3275.     clearInterval(display.blinker);
  3276.     var on = true;
  3277.     display.cursorDiv.style.visibility = "";
  3278.     if (cm.options.cursorBlinkRate > 0)
  3279.       { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  3280.         cm.options.cursorBlinkRate); }
  3281.     else if (cm.options.cursorBlinkRate < 0)
  3282.       { display.cursorDiv.style.visibility = "hidden"; }
  3283.   }
  3284.  
  3285.   function ensureFocus(cm) {
  3286.     if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  3287.   }
  3288.  
  3289.   function delayBlurEvent(cm) {
  3290.     cm.state.delayingBlurEvent = true;
  3291.     setTimeout(function () { if (cm.state.delayingBlurEvent) {
  3292.       cm.state.delayingBlurEvent = false;
  3293.       onBlur(cm);
  3294.     } }, 100);
  3295.   }
  3296.  
  3297.   function onFocus(cm, e) {
  3298.     if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
  3299.  
  3300.     if (cm.options.readOnly == "nocursor") { return }
  3301.     if (!cm.state.focused) {
  3302.       signal(cm, "focus", cm, e);
  3303.       cm.state.focused = true;
  3304.       addClass(cm.display.wrapper, "CodeMirror-focused");
  3305.       // This test prevents this from firing when a context
  3306.       // menu is closed (since the input reset would kill the
  3307.       // select-all detection hack)
  3308.       if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3309.         cm.display.input.reset();
  3310.         if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  3311.       }
  3312.       cm.display.input.receivedFocus();
  3313.     }
  3314.     restartBlink(cm);
  3315.   }
  3316.   function onBlur(cm, e) {
  3317.     if (cm.state.delayingBlurEvent) { return }
  3318.  
  3319.     if (cm.state.focused) {
  3320.       signal(cm, "blur", cm, e);
  3321.       cm.state.focused = false;
  3322.       rmClass(cm.display.wrapper, "CodeMirror-focused");
  3323.     }
  3324.     clearInterval(cm.display.blinker);
  3325.     setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  3326.   }
  3327.  
  3328.   // Read the actual heights of the rendered lines, and update their
  3329.   // stored heights to match.
  3330.   function updateHeightsInViewport(cm) {
  3331.     var display = cm.display;
  3332.     var prevBottom = display.lineDiv.offsetTop;
  3333.     for (var i = 0; i < display.view.length; i++) {
  3334.       var cur = display.view[i], wrapping = cm.options.lineWrapping;
  3335.       var height = (void 0), width = 0;
  3336.       if (cur.hidden) { continue }
  3337.       if (ie && ie_version < 8) {
  3338.         var bot = cur.node.offsetTop + cur.node.offsetHeight;
  3339.         height = bot - prevBottom;
  3340.         prevBottom = bot;
  3341.       } else {
  3342.         var box = cur.node.getBoundingClientRect();
  3343.         height = box.bottom - box.top;
  3344.         // Check that lines don't extend past the right of the current
  3345.         // editor width
  3346.         if (!wrapping && cur.text.firstChild)
  3347.           { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
  3348.       }
  3349.       var diff = cur.line.height - height;
  3350.       if (diff > .005 || diff < -.005) {
  3351.         updateLineHeight(cur.line, height);
  3352.         updateWidgetHeight(cur.line);
  3353.         if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  3354.           { updateWidgetHeight(cur.rest[j]); } }
  3355.       }
  3356.       if (width > cm.display.sizerWidth) {
  3357.         var chWidth = Math.ceil(width / charWidth(cm.display));
  3358.         if (chWidth > cm.display.maxLineLength) {
  3359.           cm.display.maxLineLength = chWidth;
  3360.           cm.display.maxLine = cur.line;
  3361.           cm.display.maxLineChanged = true;
  3362.         }
  3363.       }
  3364.     }
  3365.   }
  3366.  
  3367.   // Read and store the height of line widgets associated with the
  3368.   // given line.
  3369.   function updateWidgetHeight(line) {
  3370.     if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  3371.       var w = line.widgets[i], parent = w.node.parentNode;
  3372.       if (parent) { w.height = parent.offsetHeight; }
  3373.     } }
  3374.   }
  3375.  
  3376.   // Compute the lines that are visible in a given viewport (defaults
  3377.   // the the current scroll position). viewport may contain top,
  3378.   // height, and ensure (see op.scrollToPos) properties.
  3379.   function visibleLines(display, doc, viewport) {
  3380.     var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  3381.     top = Math.floor(top - paddingTop(display));
  3382.     var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  3383.  
  3384.     var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  3385.     // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  3386.     // forces those lines into the viewport (if possible).
  3387.     if (viewport && viewport.ensure) {
  3388.       var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  3389.       if (ensureFrom < from) {
  3390.         from = ensureFrom;
  3391.         to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  3392.       } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  3393.         from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  3394.         to = ensureTo;
  3395.       }
  3396.     }
  3397.     return {from: from, to: Math.max(to, from + 1)}
  3398.   }
  3399.  
  3400.   // SCROLLING THINGS INTO VIEW
  3401.  
  3402.   // If an editor sits on the top or bottom of the window, partially
  3403.   // scrolled out of view, this ensures that the cursor is visible.
  3404.   function maybeScrollWindow(cm, rect) {
  3405.     if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3406.  
  3407.     var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  3408.     if (rect.top + box.top < 0) { doScroll = true; }
  3409.     else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
  3410.     if (doScroll != null && !phantom) {
  3411.       var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n                         top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n                         height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n                         left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
  3412.       cm.display.lineSpace.appendChild(scrollNode);
  3413.       scrollNode.scrollIntoView(doScroll);
  3414.       cm.display.lineSpace.removeChild(scrollNode);
  3415.     }
  3416.   }
  3417.  
  3418.   // Scroll a given position into view (immediately), verifying that
  3419.   // it actually became visible (as line heights are accurately
  3420.   // measured, the position of something may 'drift' during drawing).
  3421.   function scrollPosIntoView(cm, pos, end, margin) {
  3422.     if (margin == null) { margin = 0; }
  3423.     var rect;
  3424.     if (!cm.options.lineWrapping && pos == end) {
  3425.       // Set pos and end to the cursor positions around the character pos sticks to
  3426.       // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  3427.       // If pos == Pos(_, 0, "before"), pos and end are unchanged
  3428.       pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  3429.       end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  3430.     }
  3431.     for (var limit = 0; limit < 5; limit++) {
  3432.       var changed = false;
  3433.       var coords = cursorCoords(cm, pos);
  3434.       var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  3435.       rect = {left: Math.min(coords.left, endCoords.left),
  3436.               top: Math.min(coords.top, endCoords.top) - margin,
  3437.               right: Math.max(coords.left, endCoords.left),
  3438.               bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  3439.       var scrollPos = calculateScrollPos(cm, rect);
  3440.       var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  3441.       if (scrollPos.scrollTop != null) {
  3442.         updateScrollTop(cm, scrollPos.scrollTop);
  3443.         if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  3444.       }
  3445.       if (scrollPos.scrollLeft != null) {
  3446.         setScrollLeft(cm, scrollPos.scrollLeft);
  3447.         if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  3448.       }
  3449.       if (!changed) { break }
  3450.     }
  3451.     return rect
  3452.   }
  3453.  
  3454.   // Scroll a given set of coordinates into view (immediately).
  3455.   function scrollIntoView(cm, rect) {
  3456.     var scrollPos = calculateScrollPos(cm, rect);
  3457.     if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  3458.     if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  3459.   }
  3460.  
  3461.   // Calculate a new scroll position needed to scroll the given
  3462.   // rectangle into view. Returns an object with scrollTop and
  3463.   // scrollLeft properties. When these are undefined, the
  3464.   // vertical/horizontal position does not need to be adjusted.
  3465.   function calculateScrollPos(cm, rect) {
  3466.     var display = cm.display, snapMargin = textHeight(cm.display);
  3467.     if (rect.top < 0) { rect.top = 0; }
  3468.     var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  3469.     var screen = displayHeight(cm), result = {};
  3470.     if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  3471.     var docBottom = cm.doc.height + paddingVert(display);
  3472.     var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  3473.     if (rect.top < screentop) {
  3474.       result.scrollTop = atTop ? 0 : rect.top;
  3475.     } else if (rect.bottom > screentop + screen) {
  3476.       var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  3477.       if (newTop != screentop) { result.scrollTop = newTop; }
  3478.     }
  3479.  
  3480.     var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  3481.     var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  3482.     var tooWide = rect.right - rect.left > screenw;
  3483.     if (tooWide) { rect.right = rect.left + screenw; }
  3484.     if (rect.left < 10)
  3485.       { result.scrollLeft = 0; }
  3486.     else if (rect.left < screenleft)
  3487.       { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
  3488.     else if (rect.right > screenw + screenleft - 3)
  3489.       { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  3490.     return result
  3491.   }
  3492.  
  3493.   // Store a relative adjustment to the scroll position in the current
  3494.   // operation (to be applied when the operation finishes).
  3495.   function addToScrollTop(cm, top) {
  3496.     if (top == null) { return }
  3497.     resolveScrollToPos(cm);
  3498.     cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  3499.   }
  3500.  
  3501.   // Make sure that at the end of the operation the current cursor is
  3502.   // shown.
  3503.   function ensureCursorVisible(cm) {
  3504.     resolveScrollToPos(cm);
  3505.     var cur = cm.getCursor();
  3506.     cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  3507.   }
  3508.  
  3509.   function scrollToCoords(cm, x, y) {
  3510.     if (x != null || y != null) { resolveScrollToPos(cm); }
  3511.     if (x != null) { cm.curOp.scrollLeft = x; }
  3512.     if (y != null) { cm.curOp.scrollTop = y; }
  3513.   }
  3514.  
  3515.   function scrollToRange(cm, range) {
  3516.     resolveScrollToPos(cm);
  3517.     cm.curOp.scrollToPos = range;
  3518.   }
  3519.  
  3520.   // When an operation has its scrollToPos property set, and another
  3521.   // scroll action is applied before the end of the operation, this
  3522.   // 'simulates' scrolling that position into view in a cheap way, so
  3523.   // that the effect of intermediate scroll commands is not ignored.
  3524.   function resolveScrollToPos(cm) {
  3525.     var range = cm.curOp.scrollToPos;
  3526.     if (range) {
  3527.       cm.curOp.scrollToPos = null;
  3528.       var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  3529.       scrollToCoordsRange(cm, from, to, range.margin);
  3530.     }
  3531.   }
  3532.  
  3533.   function scrollToCoordsRange(cm, from, to, margin) {
  3534.     var sPos = calculateScrollPos(cm, {
  3535.       left: Math.min(from.left, to.left),
  3536.       top: Math.min(from.top, to.top) - margin,
  3537.       right: Math.max(from.right, to.right),
  3538.       bottom: Math.max(from.bottom, to.bottom) + margin
  3539.     });
  3540.     scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  3541.   }
  3542.  
  3543.   // Sync the scrollable area and scrollbars, ensure the viewport
  3544.   // covers the visible area.
  3545.   function updateScrollTop(cm, val) {
  3546.     if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  3547.     if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  3548.     setScrollTop(cm, val, true);
  3549.     if (gecko) { updateDisplaySimple(cm); }
  3550.     startWorker(cm, 100);
  3551.   }
  3552.  
  3553.   function setScrollTop(cm, val, forceScroll) {
  3554.     val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
  3555.     if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  3556.     cm.doc.scrollTop = val;
  3557.     cm.display.scrollbars.setScrollTop(val);
  3558.     if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  3559.   }
  3560.  
  3561.   // Sync scroller and scrollbar, ensure the gutter elements are
  3562.   // aligned.
  3563.   function setScrollLeft(cm, val, isScroller, forceScroll) {
  3564.     val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
  3565.     if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  3566.     cm.doc.scrollLeft = val;
  3567.     alignHorizontally(cm);
  3568.     if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  3569.     cm.display.scrollbars.setScrollLeft(val);
  3570.   }
  3571.  
  3572.   // SCROLLBARS
  3573.  
  3574.   // Prepare DOM reads needed to update the scrollbars. Done in one
  3575.   // shot to minimize update/measure roundtrips.
  3576.   function measureForScrollbars(cm) {
  3577.     var d = cm.display, gutterW = d.gutters.offsetWidth;
  3578.     var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  3579.     return {
  3580.       clientHeight: d.scroller.clientHeight,
  3581.       viewHeight: d.wrapper.clientHeight,
  3582.       scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3583.       viewWidth: d.wrapper.clientWidth,
  3584.       barLeft: cm.options.fixedGutter ? gutterW : 0,
  3585.       docHeight: docH,
  3586.       scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3587.       nativeBarWidth: d.nativeBarWidth,
  3588.       gutterWidth: gutterW
  3589.     }
  3590.   }
  3591.  
  3592.   var NativeScrollbars = function(place, scroll, cm) {
  3593.     this.cm = cm;
  3594.     var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  3595.     var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  3596.     vert.tabIndex = horiz.tabIndex = -1;
  3597.     place(vert); place(horiz);
  3598.  
  3599.     on(vert, "scroll", function () {
  3600.       if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  3601.     });
  3602.     on(horiz, "scroll", function () {
  3603.       if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  3604.     });
  3605.  
  3606.     this.checkedZeroWidth = false;
  3607.     // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3608.     if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  3609.   };
  3610.  
  3611.   NativeScrollbars.prototype.update = function (measure) {
  3612.     var needsH = measure.scrollWidth > measure.clientWidth + 1;
  3613.     var needsV = measure.scrollHeight > measure.clientHeight + 1;
  3614.     var sWidth = measure.nativeBarWidth;
  3615.  
  3616.     if (needsV) {
  3617.       this.vert.style.display = "block";
  3618.       this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  3619.       var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  3620.       // A bug in IE8 can cause this value to be negative, so guard it.
  3621.       this.vert.firstChild.style.height =
  3622.         Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  3623.     } else {
  3624.       this.vert.style.display = "";
  3625.       this.vert.firstChild.style.height = "0";
  3626.     }
  3627.  
  3628.     if (needsH) {
  3629.       this.horiz.style.display = "block";
  3630.       this.horiz.style.right = needsV ? sWidth + "px" : "0";
  3631.       this.horiz.style.left = measure.barLeft + "px";
  3632.       var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  3633.       this.horiz.firstChild.style.width =
  3634.         Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  3635.     } else {
  3636.       this.horiz.style.display = "";
  3637.       this.horiz.firstChild.style.width = "0";
  3638.     }
  3639.  
  3640.     if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3641.       if (sWidth == 0) { this.zeroWidthHack(); }
  3642.       this.checkedZeroWidth = true;
  3643.     }
  3644.  
  3645.     return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3646.   };
  3647.  
  3648.   NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3649.     if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  3650.     if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  3651.   };
  3652.  
  3653.   NativeScrollbars.prototype.setScrollTop = function (pos) {
  3654.     if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  3655.     if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  3656.   };
  3657.  
  3658.   NativeScrollbars.prototype.zeroWidthHack = function () {
  3659.     var w = mac && !mac_geMountainLion ? "12px" : "18px";
  3660.     this.horiz.style.height = this.vert.style.width = w;
  3661.     this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  3662.     this.disableHoriz = new Delayed;
  3663.     this.disableVert = new Delayed;
  3664.   };
  3665.  
  3666.   NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  3667.     bar.style.pointerEvents = "auto";
  3668.     function maybeDisable() {
  3669.       // To find out whether the scrollbar is still visible, we
  3670.       // check whether the element under the pixel in the bottom
  3671.       // right corner of the scrollbar box is the scrollbar box
  3672.       // itself (when the bar is still visible) or its filler child
  3673.       // (when the bar is hidden). If it is still visible, we keep
  3674.       // it enabled, if it's hidden, we disable pointer events.
  3675.       var box = bar.getBoundingClientRect();
  3676.       var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  3677.           : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  3678.       if (elt != bar) { bar.style.pointerEvents = "none"; }
  3679.       else { delay.set(1000, maybeDisable); }
  3680.     }
  3681.     delay.set(1000, maybeDisable);
  3682.   };
  3683.  
  3684.   NativeScrollbars.prototype.clear = function () {
  3685.     var parent = this.horiz.parentNode;
  3686.     parent.removeChild(this.horiz);
  3687.     parent.removeChild(this.vert);
  3688.   };
  3689.  
  3690.   var NullScrollbars = function () {};
  3691.  
  3692.   NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3693.   NullScrollbars.prototype.setScrollLeft = function () {};
  3694.   NullScrollbars.prototype.setScrollTop = function () {};
  3695.   NullScrollbars.prototype.clear = function () {};
  3696.  
  3697.   function updateScrollbars(cm, measure) {
  3698.     if (!measure) { measure = measureForScrollbars(cm); }
  3699.     var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  3700.     updateScrollbarsInner(cm, measure);
  3701.     for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3702.       if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3703.         { updateHeightsInViewport(cm); }
  3704.       updateScrollbarsInner(cm, measureForScrollbars(cm));
  3705.       startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  3706.     }
  3707.   }
  3708.  
  3709.   // Re-synchronize the fake scrollbars with the actual size of the
  3710.   // content.
  3711.   function updateScrollbarsInner(cm, measure) {
  3712.     var d = cm.display;
  3713.     var sizes = d.scrollbars.update(measure);
  3714.  
  3715.     d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  3716.     d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  3717.     d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  3718.  
  3719.     if (sizes.right && sizes.bottom) {
  3720.       d.scrollbarFiller.style.display = "block";
  3721.       d.scrollbarFiller.style.height = sizes.bottom + "px";
  3722.       d.scrollbarFiller.style.width = sizes.right + "px";
  3723.     } else { d.scrollbarFiller.style.display = ""; }
  3724.     if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3725.       d.gutterFiller.style.display = "block";
  3726.       d.gutterFiller.style.height = sizes.bottom + "px";
  3727.       d.gutterFiller.style.width = measure.gutterWidth + "px";
  3728.     } else { d.gutterFiller.style.display = ""; }
  3729.   }
  3730.  
  3731.   var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  3732.  
  3733.   function initScrollbars(cm) {
  3734.     if (cm.display.scrollbars) {
  3735.       cm.display.scrollbars.clear();
  3736.       if (cm.display.scrollbars.addClass)
  3737.         { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3738.     }
  3739.  
  3740.     cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3741.       cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  3742.       // Prevent clicks in the scrollbars from killing focus
  3743.       on(node, "mousedown", function () {
  3744.         if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  3745.       });
  3746.       node.setAttribute("cm-not-content", "true");
  3747.     }, function (pos, axis) {
  3748.       if (axis == "horizontal") { setScrollLeft(cm, pos); }
  3749.       else { updateScrollTop(cm, pos); }
  3750.     }, cm);
  3751.     if (cm.display.scrollbars.addClass)
  3752.       { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3753.   }
  3754.  
  3755.   // Operations are used to wrap a series of changes to the editor
  3756.   // state in such a way that each change won't have to update the
  3757.   // cursor and display (which would be awkward, slow, and
  3758.   // error-prone). Instead, display updates are batched and then all
  3759.   // combined and executed at once.
  3760.  
  3761.   var nextOpId = 0;
  3762.   // Start a new operation.
  3763.   function startOperation(cm) {
  3764.     cm.curOp = {
  3765.       cm: cm,
  3766.       viewChanged: false,      // Flag that indicates that lines might need to be redrawn
  3767.       startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3768.       forceUpdate: false,      // Used to force a redraw
  3769.       updateInput: 0,       // Whether to reset the input textarea
  3770.       typing: false,           // Whether this reset should be careful to leave existing text (for compositing)
  3771.       changeObjs: null,        // Accumulated changes, for firing change events
  3772.       cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3773.       cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3774.       selectionChanged: false, // Whether the selection needs to be redrawn
  3775.       updateMaxLine: false,    // Set when the widest line needs to be determined anew
  3776.       scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3777.       scrollToPos: null,       // Used to scroll to a specific position
  3778.       focus: false,
  3779.       id: ++nextOpId           // Unique ID
  3780.     };
  3781.     pushOperation(cm.curOp);
  3782.   }
  3783.  
  3784.   // Finish an operation, updating the display and signalling delayed events
  3785.   function endOperation(cm) {
  3786.     var op = cm.curOp;
  3787.     if (op) { finishOperation(op, function (group) {
  3788.       for (var i = 0; i < group.ops.length; i++)
  3789.         { group.ops[i].cm.curOp = null; }
  3790.       endOperations(group);
  3791.     }); }
  3792.   }
  3793.  
  3794.   // The DOM updates done when an operation finishes are batched so
  3795.   // that the minimum number of relayouts are required.
  3796.   function endOperations(group) {
  3797.     var ops = group.ops;
  3798.     for (var i = 0; i < ops.length; i++) // Read DOM
  3799.       { endOperation_R1(ops[i]); }
  3800.     for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3801.       { endOperation_W1(ops[i$1]); }
  3802.     for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3803.       { endOperation_R2(ops[i$2]); }
  3804.     for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3805.       { endOperation_W2(ops[i$3]); }
  3806.     for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3807.       { endOperation_finish(ops[i$4]); }
  3808.   }
  3809.  
  3810.   function endOperation_R1(op) {
  3811.     var cm = op.cm, display = cm.display;
  3812.     maybeClipScrollbars(cm);
  3813.     if (op.updateMaxLine) { findMaxLine(cm); }
  3814.  
  3815.     op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3816.       op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3817.                          op.scrollToPos.to.line >= display.viewTo) ||
  3818.       display.maxLineChanged && cm.options.lineWrapping;
  3819.     op.update = op.mustUpdate &&
  3820.       new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  3821.   }
  3822.  
  3823.   function endOperation_W1(op) {
  3824.     op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  3825.   }
  3826.  
  3827.   function endOperation_R2(op) {
  3828.     var cm = op.cm, display = cm.display;
  3829.     if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  3830.  
  3831.     op.barMeasure = measureForScrollbars(cm);
  3832.  
  3833.     // If the max line changed since it was last measured, measure it,
  3834.     // and ensure the document's width matches it.
  3835.     // updateDisplay_W2 will use these properties to do the actual resizing
  3836.     if (display.maxLineChanged && !cm.options.lineWrapping) {
  3837.       op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  3838.       cm.display.sizerWidth = op.adjustWidthTo;
  3839.       op.barMeasure.scrollWidth =
  3840.         Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  3841.       op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  3842.     }
  3843.  
  3844.     if (op.updatedDisplay || op.selectionChanged)
  3845.       { op.preparedSelection = display.input.prepareSelection(); }
  3846.   }
  3847.  
  3848.   function endOperation_W2(op) {
  3849.     var cm = op.cm;
  3850.  
  3851.     if (op.adjustWidthTo != null) {
  3852.       cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  3853.       if (op.maxScrollLeft < cm.doc.scrollLeft)
  3854.         { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  3855.       cm.display.maxLineChanged = false;
  3856.     }
  3857.  
  3858.     var takeFocus = op.focus && op.focus == activeElt();
  3859.     if (op.preparedSelection)
  3860.       { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  3861.     if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3862.       { updateScrollbars(cm, op.barMeasure); }
  3863.     if (op.updatedDisplay)
  3864.       { setDocumentHeight(cm, op.barMeasure); }
  3865.  
  3866.     if (op.selectionChanged) { restartBlink(cm); }
  3867.  
  3868.     if (cm.state.focused && op.updateInput)
  3869.       { cm.display.input.reset(op.typing); }
  3870.     if (takeFocus) { ensureFocus(op.cm); }
  3871.   }
  3872.  
  3873.   function endOperation_finish(op) {
  3874.     var cm = op.cm, display = cm.display, doc = cm.doc;
  3875.  
  3876.     if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  3877.  
  3878.     // Abort mouse wheel delta measurement, when scrolling explicitly
  3879.     if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3880.       { display.wheelStartX = display.wheelStartY = null; }
  3881.  
  3882.     // Propagate the scroll position to the actual DOM scroller
  3883.     if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  3884.  
  3885.     if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  3886.     // If we need to scroll a specific position into view, do so.
  3887.     if (op.scrollToPos) {
  3888.       var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3889.                                    clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  3890.       maybeScrollWindow(cm, rect);
  3891.     }
  3892.  
  3893.     // Fire events for markers that are hidden/unidden by editing or
  3894.     // undoing
  3895.     var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  3896.     if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3897.       { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  3898.     if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3899.       { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  3900.  
  3901.     if (display.wrapper.offsetHeight)
  3902.       { doc.scrollTop = cm.display.scroller.scrollTop; }
  3903.  
  3904.     // Fire change events, and delayed event handlers
  3905.     if (op.changeObjs)
  3906.       { signal(cm, "changes", cm, op.changeObjs); }
  3907.     if (op.update)
  3908.       { op.update.finish(); }
  3909.   }
  3910.  
  3911.   // Run the given function in an operation
  3912.   function runInOp(cm, f) {
  3913.     if (cm.curOp) { return f() }
  3914.     startOperation(cm);
  3915.     try { return f() }
  3916.     finally { endOperation(cm); }
  3917.   }
  3918.   // Wraps a function in an operation. Returns the wrapped function.
  3919.   function operation(cm, f) {
  3920.     return function() {
  3921.       if (cm.curOp) { return f.apply(cm, arguments) }
  3922.       startOperation(cm);
  3923.       try { return f.apply(cm, arguments) }
  3924.       finally { endOperation(cm); }
  3925.     }
  3926.   }
  3927.   // Used to add methods to editor and doc instances, wrapping them in
  3928.   // operations.
  3929.   function methodOp(f) {
  3930.     return function() {
  3931.       if (this.curOp) { return f.apply(this, arguments) }
  3932.       startOperation(this);
  3933.       try { return f.apply(this, arguments) }
  3934.       finally { endOperation(this); }
  3935.     }
  3936.   }
  3937.   function docMethodOp(f) {
  3938.     return function() {
  3939.       var cm = this.cm;
  3940.       if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3941.       startOperation(cm);
  3942.       try { return f.apply(this, arguments) }
  3943.       finally { endOperation(cm); }
  3944.     }
  3945.   }
  3946.  
  3947.   // HIGHLIGHT WORKER
  3948.  
  3949.   function startWorker(cm, time) {
  3950.     if (cm.doc.highlightFrontier < cm.display.viewTo)
  3951.       { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  3952.   }
  3953.  
  3954.   function highlightWorker(cm) {
  3955.     var doc = cm.doc;
  3956.     if (doc.highlightFrontier >= cm.display.viewTo) { return }
  3957.     var end = +new Date + cm.options.workTime;
  3958.     var context = getContextBefore(cm, doc.highlightFrontier);
  3959.     var changedLines = [];
  3960.  
  3961.     doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3962.       if (context.line >= cm.display.viewFrom) { // Visible
  3963.         var oldStyles = line.styles;
  3964.         var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  3965.         var highlighted = highlightLine(cm, line, context, true);
  3966.         if (resetState) { context.state = resetState; }
  3967.         line.styles = highlighted.styles;
  3968.         var oldCls = line.styleClasses, newCls = highlighted.classes;
  3969.         if (newCls) { line.styleClasses = newCls; }
  3970.         else if (oldCls) { line.styleClasses = null; }
  3971.         var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3972.           oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  3973.         for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  3974.         if (ischange) { changedLines.push(context.line); }
  3975.         line.stateAfter = context.save();
  3976.         context.nextLine();
  3977.       } else {
  3978.         if (line.text.length <= cm.options.maxHighlightLength)
  3979.           { processLine(cm, line.text, context); }
  3980.         line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  3981.         context.nextLine();
  3982.       }
  3983.       if (+new Date > end) {
  3984.         startWorker(cm, cm.options.workDelay);
  3985.         return true
  3986.       }
  3987.     });
  3988.     doc.highlightFrontier = context.line;
  3989.     doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  3990.     if (changedLines.length) { runInOp(cm, function () {
  3991.       for (var i = 0; i < changedLines.length; i++)
  3992.         { regLineChange(cm, changedLines[i], "text"); }
  3993.     }); }
  3994.   }
  3995.  
  3996.   // DISPLAY DRAWING
  3997.  
  3998.   var DisplayUpdate = function(cm, viewport, force) {
  3999.     var display = cm.display;
  4000.  
  4001.     this.viewport = viewport;
  4002.     // Store some values that we'll need later (but don't want to force a relayout for)
  4003.     this.visible = visibleLines(display, cm.doc, viewport);
  4004.     this.editorIsHidden = !display.wrapper.offsetWidth;
  4005.     this.wrapperHeight = display.wrapper.clientHeight;
  4006.     this.wrapperWidth = display.wrapper.clientWidth;
  4007.     this.oldDisplayWidth = displayWidth(cm);
  4008.     this.force = force;
  4009.     this.dims = getDimensions(cm);
  4010.     this.events = [];
  4011.   };
  4012.  
  4013.   DisplayUpdate.prototype.signal = function (emitter, type) {
  4014.     if (hasHandler(emitter, type))
  4015.       { this.events.push(arguments); }
  4016.   };
  4017.   DisplayUpdate.prototype.finish = function () {
  4018.     for (var i = 0; i < this.events.length; i++)
  4019.       { signal.apply(null, this.events[i]); }
  4020.   };
  4021.  
  4022.   function maybeClipScrollbars(cm) {
  4023.     var display = cm.display;
  4024.     if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  4025.       display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  4026.       display.heightForcer.style.height = scrollGap(cm) + "px";
  4027.       display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  4028.       display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  4029.       display.scrollbarsClipped = true;
  4030.     }
  4031.   }
  4032.  
  4033.   function selectionSnapshot(cm) {
  4034.     if (cm.hasFocus()) { return null }
  4035.     var active = activeElt();
  4036.     if (!active || !contains(cm.display.lineDiv, active)) { return null }
  4037.     var result = {activeElt: active};
  4038.     if (window.getSelection) {
  4039.       var sel = window.getSelection();
  4040.       if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  4041.         result.anchorNode = sel.anchorNode;
  4042.         result.anchorOffset = sel.anchorOffset;
  4043.         result.focusNode = sel.focusNode;
  4044.         result.focusOffset = sel.focusOffset;
  4045.       }
  4046.     }
  4047.     return result
  4048.   }
  4049.  
  4050.   function restoreSelection(snapshot) {
  4051.     if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  4052.     snapshot.activeElt.focus();
  4053.     if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
  4054.         snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  4055.       var sel = window.getSelection(), range = document.createRange();
  4056.       range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  4057.       range.collapse(false);
  4058.       sel.removeAllRanges();
  4059.       sel.addRange(range);
  4060.       sel.extend(snapshot.focusNode, snapshot.focusOffset);
  4061.     }
  4062.   }
  4063.  
  4064.   // Does the actual updating of the line display. Bails out
  4065.   // (returning false) when there is nothing to be done and forced is
  4066.   // false.
  4067.   function updateDisplayIfNeeded(cm, update) {
  4068.     var display = cm.display, doc = cm.doc;
  4069.  
  4070.     if (update.editorIsHidden) {
  4071.       resetView(cm);
  4072.       return false
  4073.     }
  4074.  
  4075.     // Bail out if the visible area is already rendered and nothing changed.
  4076.     if (!update.force &&
  4077.         update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  4078.         (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  4079.         display.renderedView == display.view && countDirtyView(cm) == 0)
  4080.       { return false }
  4081.  
  4082.     if (maybeUpdateLineNumberWidth(cm)) {
  4083.       resetView(cm);
  4084.       update.dims = getDimensions(cm);
  4085.     }
  4086.  
  4087.     // Compute a suitable new viewport (from & to)
  4088.     var end = doc.first + doc.size;
  4089.     var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  4090.     var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  4091.     if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  4092.     if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  4093.     if (sawCollapsedSpans) {
  4094.       from = visualLineNo(cm.doc, from);
  4095.       to = visualLineEndNo(cm.doc, to);
  4096.     }
  4097.  
  4098.     var different = from != display.viewFrom || to != display.viewTo ||
  4099.       display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  4100.     adjustView(cm, from, to);
  4101.  
  4102.     display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  4103.     // Position the mover div to align with the current scroll position
  4104.     cm.display.mover.style.top = display.viewOffset + "px";
  4105.  
  4106.     var toUpdate = countDirtyView(cm);
  4107.     if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  4108.         (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  4109.       { return false }
  4110.  
  4111.     // For big changes, we hide the enclosing element during the
  4112.     // update, since that speeds up the operations on most browsers.
  4113.     var selSnapshot = selectionSnapshot(cm);
  4114.     if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  4115.     patchDisplay(cm, display.updateLineNumbers, update.dims);
  4116.     if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  4117.     display.renderedView = display.view;
  4118.     // There might have been a widget with a focused element that got
  4119.     // hidden or updated, if so re-focus it.
  4120.     restoreSelection(selSnapshot);
  4121.  
  4122.     // Prevent selection and cursors from interfering with the scroll
  4123.     // width and height.
  4124.     removeChildren(display.cursorDiv);
  4125.     removeChildren(display.selectionDiv);
  4126.     display.gutters.style.height = display.sizer.style.minHeight = 0;
  4127.  
  4128.     if (different) {
  4129.       display.lastWrapHeight = update.wrapperHeight;
  4130.       display.lastWrapWidth = update.wrapperWidth;
  4131.       startWorker(cm, 400);
  4132.     }
  4133.  
  4134.     display.updateLineNumbers = null;
  4135.  
  4136.     return true
  4137.   }
  4138.  
  4139.   function postUpdateDisplay(cm, update) {
  4140.     var viewport = update.viewport;
  4141.  
  4142.     for (var first = true;; first = false) {
  4143.       if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  4144.         // Clip forced viewport to actual scrollable area.
  4145.         if (viewport && viewport.top != null)
  4146.           { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  4147.         // Updated line heights might result in the drawn area not
  4148.         // actually covering the viewport. Keep looping until it does.
  4149.         update.visible = visibleLines(cm.display, cm.doc, viewport);
  4150.         if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  4151.           { break }
  4152.       } else if (first) {
  4153.         update.visible = visibleLines(cm.display, cm.doc, viewport);
  4154.       }
  4155.       if (!updateDisplayIfNeeded(cm, update)) { break }
  4156.       updateHeightsInViewport(cm);
  4157.       var barMeasure = measureForScrollbars(cm);
  4158.       updateSelection(cm);
  4159.       updateScrollbars(cm, barMeasure);
  4160.       setDocumentHeight(cm, barMeasure);
  4161.       update.force = false;
  4162.     }
  4163.  
  4164.     update.signal(cm, "update", cm);
  4165.     if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  4166.       update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  4167.       cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  4168.     }
  4169.   }
  4170.  
  4171.   function updateDisplaySimple(cm, viewport) {
  4172.     var update = new DisplayUpdate(cm, viewport);
  4173.     if (updateDisplayIfNeeded(cm, update)) {
  4174.       updateHeightsInViewport(cm);
  4175.       postUpdateDisplay(cm, update);
  4176.       var barMeasure = measureForScrollbars(cm);
  4177.       updateSelection(cm);
  4178.       updateScrollbars(cm, barMeasure);
  4179.       setDocumentHeight(cm, barMeasure);
  4180.       update.finish();
  4181.     }
  4182.   }
  4183.  
  4184.   // Sync the actual display DOM structure with display.view, removing
  4185.   // nodes for lines that are no longer in view, and creating the ones
  4186.   // that are not there yet, and updating the ones that are out of
  4187.   // date.
  4188.   function patchDisplay(cm, updateNumbersFrom, dims) {
  4189.     var display = cm.display, lineNumbers = cm.options.lineNumbers;
  4190.     var container = display.lineDiv, cur = container.firstChild;
  4191.  
  4192.     function rm(node) {
  4193.       var next = node.nextSibling;
  4194.       // Works around a throw-scroll bug in OS X Webkit
  4195.       if (webkit && mac && cm.display.currentWheelTarget == node)
  4196.         { node.style.display = "none"; }
  4197.       else
  4198.         { node.parentNode.removeChild(node); }
  4199.       return next
  4200.     }
  4201.  
  4202.     var view = display.view, lineN = display.viewFrom;
  4203.     // Loop over the elements in the view, syncing cur (the DOM nodes
  4204.     // in display.lineDiv) with the view as we go.
  4205.     for (var i = 0; i < view.length; i++) {
  4206.       var lineView = view[i];
  4207.       if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  4208.         var node = buildLineElement(cm, lineView, lineN, dims);
  4209.         container.insertBefore(node, cur);
  4210.       } else { // Already drawn
  4211.         while (cur != lineView.node) { cur = rm(cur); }
  4212.         var updateNumber = lineNumbers && updateNumbersFrom != null &&
  4213.           updateNumbersFrom <= lineN && lineView.lineNumber;
  4214.         if (lineView.changes) {
  4215.           if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  4216.           updateLineForChanges(cm, lineView, lineN, dims);
  4217.         }
  4218.         if (updateNumber) {
  4219.           removeChildren(lineView.lineNumber);
  4220.           lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  4221.         }
  4222.         cur = lineView.node.nextSibling;
  4223.       }
  4224.       lineN += lineView.size;
  4225.     }
  4226.     while (cur) { cur = rm(cur); }
  4227.   }
  4228.  
  4229.   function updateGutterSpace(display) {
  4230.     var width = display.gutters.offsetWidth;
  4231.     display.sizer.style.marginLeft = width + "px";
  4232.   }
  4233.  
  4234.   function setDocumentHeight(cm, measure) {
  4235.     cm.display.sizer.style.minHeight = measure.docHeight + "px";
  4236.     cm.display.heightForcer.style.top = measure.docHeight + "px";
  4237.     cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  4238.   }
  4239.  
  4240.   // Re-align line numbers and gutter marks to compensate for
  4241.   // horizontal scrolling.
  4242.   function alignHorizontally(cm) {
  4243.     var display = cm.display, view = display.view;
  4244.     if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  4245.     var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  4246.     var gutterW = display.gutters.offsetWidth, left = comp + "px";
  4247.     for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  4248.       if (cm.options.fixedGutter) {
  4249.         if (view[i].gutter)
  4250.           { view[i].gutter.style.left = left; }
  4251.         if (view[i].gutterBackground)
  4252.           { view[i].gutterBackground.style.left = left; }
  4253.       }
  4254.       var align = view[i].alignable;
  4255.       if (align) { for (var j = 0; j < align.length; j++)
  4256.         { align[j].style.left = left; } }
  4257.     } }
  4258.     if (cm.options.fixedGutter)
  4259.       { display.gutters.style.left = (comp + gutterW) + "px"; }
  4260.   }
  4261.  
  4262.   // Used to ensure that the line number gutter is still the right
  4263.   // size for the current document size. Returns true when an update
  4264.   // is needed.
  4265.   function maybeUpdateLineNumberWidth(cm) {
  4266.     if (!cm.options.lineNumbers) { return false }
  4267.     var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  4268.     if (last.length != display.lineNumChars) {
  4269.       var test = display.measure.appendChild(elt("div", [elt("div", last)],
  4270.                                                  "CodeMirror-linenumber CodeMirror-gutter-elt"));
  4271.       var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  4272.       display.lineGutter.style.width = "";
  4273.       display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  4274.       display.lineNumWidth = display.lineNumInnerWidth + padding;
  4275.       display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  4276.       display.lineGutter.style.width = display.lineNumWidth + "px";
  4277.       updateGutterSpace(cm.display);
  4278.       return true
  4279.     }
  4280.     return false
  4281.   }
  4282.  
  4283.   function getGutters(gutters, lineNumbers) {
  4284.     var result = [], sawLineNumbers = false;
  4285.     for (var i = 0; i < gutters.length; i++) {
  4286.       var name = gutters[i], style = null;
  4287.       if (typeof name != "string") { style = name.style; name = name.className; }
  4288.       if (name == "CodeMirror-linenumbers") {
  4289.         if (!lineNumbers) { continue }
  4290.         else { sawLineNumbers = true; }
  4291.       }
  4292.       result.push({className: name, style: style});
  4293.     }
  4294.     if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
  4295.     return result
  4296.   }
  4297.  
  4298.   // Rebuild the gutter elements, ensure the margin to the left of the
  4299.   // code matches their width.
  4300.   function renderGutters(display) {
  4301.     var gutters = display.gutters, specs = display.gutterSpecs;
  4302.     removeChildren(gutters);
  4303.     display.lineGutter = null;
  4304.     for (var i = 0; i < specs.length; ++i) {
  4305.       var ref = specs[i];
  4306.       var className = ref.className;
  4307.       var style = ref.style;
  4308.       var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
  4309.       if (style) { gElt.style.cssText = style; }
  4310.       if (className == "CodeMirror-linenumbers") {
  4311.         display.lineGutter = gElt;
  4312.         gElt.style.width = (display.lineNumWidth || 1) + "px";
  4313.       }
  4314.     }
  4315.     gutters.style.display = specs.length ? "" : "none";
  4316.     updateGutterSpace(display);
  4317.   }
  4318.  
  4319.   function updateGutters(cm) {
  4320.     renderGutters(cm.display);
  4321.     regChange(cm);
  4322.     alignHorizontally(cm);
  4323.   }
  4324.  
  4325.   // The display handles the DOM integration, both for input reading
  4326.   // and content drawing. It holds references to DOM nodes and
  4327.   // display-related state.
  4328.  
  4329.   function Display(place, doc, input, options) {
  4330.     var d = this;
  4331.     this.input = input;
  4332.  
  4333.     // Covers bottom-right square when both scrollbars are present.
  4334.     d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  4335.     d.scrollbarFiller.setAttribute("cm-not-content", "true");
  4336.     // Covers bottom of gutter when coverGutterNextToScrollbar is on
  4337.     // and h scrollbar is present.
  4338.     d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  4339.     d.gutterFiller.setAttribute("cm-not-content", "true");
  4340.     // Will contain the actual code, positioned to cover the viewport.
  4341.     d.lineDiv = eltP("div", null, "CodeMirror-code");
  4342.     // Elements are added to these to represent selection and cursors.
  4343.     d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  4344.     d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  4345.     // A visibility: hidden element used to find the size of things.
  4346.     d.measure = elt("div", null, "CodeMirror-measure");
  4347.     // When lines outside of the viewport are measured, they are drawn in this.
  4348.     d.lineMeasure = elt("div", null, "CodeMirror-measure");
  4349.     // Wraps everything that needs to exist inside the vertically-padded coordinate system
  4350.     d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  4351.                       null, "position: relative; outline: none");
  4352.     var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  4353.     // Moved around its parent to cover visible view.
  4354.     d.mover = elt("div", [lines], null, "position: relative");
  4355.     // Set to the height of the document, allowing scrolling.
  4356.     d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  4357.     d.sizerWidth = null;
  4358.     // Behavior of elts with overflow: auto and padding is
  4359.     // inconsistent across browsers. This is used to ensure the
  4360.     // scrollable area is big enough.
  4361.     d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  4362.     // Will contain the gutters, if any.
  4363.     d.gutters = elt("div", null, "CodeMirror-gutters");
  4364.     d.lineGutter = null;
  4365.     // Actual scrollable element.
  4366.     d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  4367.     d.scroller.setAttribute("tabIndex", "-1");
  4368.     // The element in which the editor lives.
  4369.     d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  4370.  
  4371.     // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  4372.     if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  4373.     if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  4374.  
  4375.     if (place) {
  4376.       if (place.appendChild) { place.appendChild(d.wrapper); }
  4377.       else { place(d.wrapper); }
  4378.     }
  4379.  
  4380.     // Current rendered range (may be bigger than the view window).
  4381.     d.viewFrom = d.viewTo = doc.first;
  4382.     d.reportedViewFrom = d.reportedViewTo = doc.first;
  4383.     // Information about the rendered lines.
  4384.     d.view = [];
  4385.     d.renderedView = null;
  4386.     // Holds info about a single rendered line when it was rendered
  4387.     // for measurement, while not in view.
  4388.     d.externalMeasured = null;
  4389.     // Empty space (in pixels) above the view
  4390.     d.viewOffset = 0;
  4391.     d.lastWrapHeight = d.lastWrapWidth = 0;
  4392.     d.updateLineNumbers = null;
  4393.  
  4394.     d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  4395.     d.scrollbarsClipped = false;
  4396.  
  4397.     // Used to only resize the line number gutter when necessary (when
  4398.     // the amount of lines crosses a boundary that makes its width change)
  4399.     d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  4400.     // Set to true when a non-horizontal-scrolling line widget is
  4401.     // added. As an optimization, line widget aligning is skipped when
  4402.     // this is false.
  4403.     d.alignWidgets = false;
  4404.  
  4405.     d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  4406.  
  4407.     // Tracks the maximum line length so that the horizontal scrollbar
  4408.     // can be kept static when scrolling.
  4409.     d.maxLine = null;
  4410.     d.maxLineLength = 0;
  4411.     d.maxLineChanged = false;
  4412.  
  4413.     // Used for measuring wheel scrolling granularity
  4414.     d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  4415.  
  4416.     // True when shift is held down.
  4417.     d.shift = false;
  4418.  
  4419.     // Used to track whether anything happened since the context menu
  4420.     // was opened.
  4421.     d.selForContextMenu = null;
  4422.  
  4423.     d.activeTouch = null;
  4424.  
  4425.     d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
  4426.     renderGutters(d);
  4427.  
  4428.     input.init(d);
  4429.   }
  4430.  
  4431.   // Since the delta values reported on mouse wheel events are
  4432.   // unstandardized between browsers and even browser versions, and
  4433.   // generally horribly unpredictable, this code starts by measuring
  4434.   // the scroll effect that the first few mouse wheel events have,
  4435.   // and, from that, detects the way it can convert deltas to pixel
  4436.   // offsets afterwards.
  4437.   //
  4438.   // The reason we want to know the amount a wheel event will scroll
  4439.   // is that it gives us a chance to update the display before the
  4440.   // actual scrolling happens, reducing flickering.
  4441.  
  4442.   var wheelSamples = 0, wheelPixelsPerUnit = null;
  4443.   // Fill in a browser-detected starting value on browsers where we
  4444.   // know one. These don't have to be accurate -- the result of them
  4445.   // being wrong would just be a slight flicker on the first wheel
  4446.   // scroll (if it is large enough).
  4447.   if (ie) { wheelPixelsPerUnit = -.53; }
  4448.   else if (gecko) { wheelPixelsPerUnit = 15; }
  4449.   else if (chrome) { wheelPixelsPerUnit = -.7; }
  4450.   else if (safari) { wheelPixelsPerUnit = -1/3; }
  4451.  
  4452.   function wheelEventDelta(e) {
  4453.     var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  4454.     if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  4455.     if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  4456.     else if (dy == null) { dy = e.wheelDelta; }
  4457.     return {x: dx, y: dy}
  4458.   }
  4459.   function wheelEventPixels(e) {
  4460.     var delta = wheelEventDelta(e);
  4461.     delta.x *= wheelPixelsPerUnit;
  4462.     delta.y *= wheelPixelsPerUnit;
  4463.     return delta
  4464.   }
  4465.  
  4466.   function onScrollWheel(cm, e) {
  4467.     var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  4468.  
  4469.     var display = cm.display, scroll = display.scroller;
  4470.     // Quit if there's nothing to scroll here
  4471.     var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  4472.     var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  4473.     if (!(dx && canScrollX || dy && canScrollY)) { return }
  4474.  
  4475.     // Webkit browsers on OS X abort momentum scrolls when the target
  4476.     // of the scroll event is removed from the scrollable element.
  4477.     // This hack (see related code in patchDisplay) makes sure the
  4478.     // element is kept around.
  4479.     if (dy && mac && webkit) {
  4480.       outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  4481.         for (var i = 0; i < view.length; i++) {
  4482.           if (view[i].node == cur) {
  4483.             cm.display.currentWheelTarget = cur;
  4484.             break outer
  4485.           }
  4486.         }
  4487.       }
  4488.     }
  4489.  
  4490.     // On some browsers, horizontal scrolling will cause redraws to
  4491.     // happen before the gutter has been realigned, causing it to
  4492.     // wriggle around in a most unseemly way. When we have an
  4493.     // estimated pixels/delta value, we just handle horizontal
  4494.     // scrolling entirely here. It'll be slightly off from native, but
  4495.     // better than glitching out.
  4496.     if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  4497.       if (dy && canScrollY)
  4498.         { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
  4499.       setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
  4500.       // Only prevent default scrolling if vertical scrolling is
  4501.       // actually possible. Otherwise, it causes vertical scroll
  4502.       // jitter on OSX trackpads when deltaX is small and deltaY
  4503.       // is large (issue #3579)
  4504.       if (!dy || (dy && canScrollY))
  4505.         { e_preventDefault(e); }
  4506.       display.wheelStartX = null; // Abort measurement, if in progress
  4507.       return
  4508.     }
  4509.  
  4510.     // 'Project' the visible viewport to cover the area that is being
  4511.     // scrolled into view (if we know enough to estimate it).
  4512.     if (dy && wheelPixelsPerUnit != null) {
  4513.       var pixels = dy * wheelPixelsPerUnit;
  4514.       var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  4515.       if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  4516.       else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  4517.       updateDisplaySimple(cm, {top: top, bottom: bot});
  4518.     }
  4519.  
  4520.     if (wheelSamples < 20) {
  4521.       if (display.wheelStartX == null) {
  4522.         display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  4523.         display.wheelDX = dx; display.wheelDY = dy;
  4524.         setTimeout(function () {
  4525.           if (display.wheelStartX == null) { return }
  4526.           var movedX = scroll.scrollLeft - display.wheelStartX;
  4527.           var movedY = scroll.scrollTop - display.wheelStartY;
  4528.           var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  4529.             (movedX && display.wheelDX && movedX / display.wheelDX);
  4530.           display.wheelStartX = display.wheelStartY = null;
  4531.           if (!sample) { return }
  4532.           wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  4533.           ++wheelSamples;
  4534.         }, 200);
  4535.       } else {
  4536.         display.wheelDX += dx; display.wheelDY += dy;
  4537.       }
  4538.     }
  4539.   }
  4540.  
  4541.   // Selection objects are immutable. A new one is created every time
  4542.   // the selection changes. A selection is one or more non-overlapping
  4543.   // (and non-touching) ranges, sorted, and an integer that indicates
  4544.   // which one is the primary selection (the one that's scrolled into
  4545.   // view, that getCursor returns, etc).
  4546.   var Selection = function(ranges, primIndex) {
  4547.     this.ranges = ranges;
  4548.     this.primIndex = primIndex;
  4549.   };
  4550.  
  4551.   Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  4552.  
  4553.   Selection.prototype.equals = function (other) {
  4554.     if (other == this) { return true }
  4555.     if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  4556.     for (var i = 0; i < this.ranges.length; i++) {
  4557.       var here = this.ranges[i], there = other.ranges[i];
  4558.       if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  4559.     }
  4560.     return true
  4561.   };
  4562.  
  4563.   Selection.prototype.deepCopy = function () {
  4564.     var out = [];
  4565.     for (var i = 0; i < this.ranges.length; i++)
  4566.       { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
  4567.     return new Selection(out, this.primIndex)
  4568.   };
  4569.  
  4570.   Selection.prototype.somethingSelected = function () {
  4571.     for (var i = 0; i < this.ranges.length; i++)
  4572.       { if (!this.ranges[i].empty()) { return true } }
  4573.     return false
  4574.   };
  4575.  
  4576.   Selection.prototype.contains = function (pos, end) {
  4577.     if (!end) { end = pos; }
  4578.     for (var i = 0; i < this.ranges.length; i++) {
  4579.       var range = this.ranges[i];
  4580.       if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  4581.         { return i }
  4582.     }
  4583.     return -1
  4584.   };
  4585.  
  4586.   var Range = function(anchor, head) {
  4587.     this.anchor = anchor; this.head = head;
  4588.   };
  4589.  
  4590.   Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  4591.   Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  4592.   Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  4593.  
  4594.   // Take an unsorted, potentially overlapping set of ranges, and
  4595.   // build a selection out of it. 'Consumes' ranges array (modifying
  4596.   // it).
  4597.   function normalizeSelection(cm, ranges, primIndex) {
  4598.     var mayTouch = cm && cm.options.selectionsMayTouch;
  4599.     var prim = ranges[primIndex];
  4600.     ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  4601.     primIndex = indexOf(ranges, prim);
  4602.     for (var i = 1; i < ranges.length; i++) {
  4603.       var cur = ranges[i], prev = ranges[i - 1];
  4604.       var diff = cmp(prev.to(), cur.from());
  4605.       if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
  4606.         var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  4607.         var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  4608.         if (i <= primIndex) { --primIndex; }
  4609.         ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  4610.       }
  4611.     }
  4612.     return new Selection(ranges, primIndex)
  4613.   }
  4614.  
  4615.   function simpleSelection(anchor, head) {
  4616.     return new Selection([new Range(anchor, head || anchor)], 0)
  4617.   }
  4618.  
  4619.   // Compute the position of the end of a change (its 'to' property
  4620.   // refers to the pre-change end).
  4621.   function changeEnd(change) {
  4622.     if (!change.text) { return change.to }
  4623.     return Pos(change.from.line + change.text.length - 1,
  4624.                lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  4625.   }
  4626.  
  4627.   // Adjust a position to refer to the post-change position of the
  4628.   // same text, or the end of the change if the change covers it.
  4629.   function adjustForChange(pos, change) {
  4630.     if (cmp(pos, change.from) < 0) { return pos }
  4631.     if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  4632.  
  4633.     var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  4634.     if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  4635.     return Pos(line, ch)
  4636.   }
  4637.  
  4638.   function computeSelAfterChange(doc, change) {
  4639.     var out = [];
  4640.     for (var i = 0; i < doc.sel.ranges.length; i++) {
  4641.       var range = doc.sel.ranges[i];
  4642.       out.push(new Range(adjustForChange(range.anchor, change),
  4643.                          adjustForChange(range.head, change)));
  4644.     }
  4645.     return normalizeSelection(doc.cm, out, doc.sel.primIndex)
  4646.   }
  4647.  
  4648.   function offsetPos(pos, old, nw) {
  4649.     if (pos.line == old.line)
  4650.       { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4651.     else
  4652.       { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4653.   }
  4654.  
  4655.   // Used by replaceSelections to allow moving the selection to the
  4656.   // start or around the replaced test. Hint may be "start" or "around".
  4657.   function computeReplacedSel(doc, changes, hint) {
  4658.     var out = [];
  4659.     var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  4660.     for (var i = 0; i < changes.length; i++) {
  4661.       var change = changes[i];
  4662.       var from = offsetPos(change.from, oldPrev, newPrev);
  4663.       var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  4664.       oldPrev = change.to;
  4665.       newPrev = to;
  4666.       if (hint == "around") {
  4667.         var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  4668.         out[i] = new Range(inv ? to : from, inv ? from : to);
  4669.       } else {
  4670.         out[i] = new Range(from, from);
  4671.       }
  4672.     }
  4673.     return new Selection(out, doc.sel.primIndex)
  4674.   }
  4675.  
  4676.   // Used to get the editor into a consistent state again when options change.
  4677.  
  4678.   function loadMode(cm) {
  4679.     cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  4680.     resetModeState(cm);
  4681.   }
  4682.  
  4683.   function resetModeState(cm) {
  4684.     cm.doc.iter(function (line) {
  4685.       if (line.stateAfter) { line.stateAfter = null; }
  4686.       if (line.styles) { line.styles = null; }
  4687.     });
  4688.     cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  4689.     startWorker(cm, 100);
  4690.     cm.state.modeGen++;
  4691.     if (cm.curOp) { regChange(cm); }
  4692.   }
  4693.  
  4694.   // DOCUMENT DATA STRUCTURE
  4695.  
  4696.   // By default, updates that start and end at the beginning of a line
  4697.   // are treated specially, in order to make the association of line
  4698.   // widgets and marker elements with the text behave more intuitive.
  4699.   function isWholeLineUpdate(doc, change) {
  4700.     return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4701.       (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4702.   }
  4703.  
  4704.   // Perform a change on the document data structure.
  4705.   function updateDoc(doc, change, markedSpans, estimateHeight) {
  4706.     function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  4707.     function update(line, text, spans) {
  4708.       updateLine(line, text, spans, estimateHeight);
  4709.       signalLater(line, "change", line, change);
  4710.     }
  4711.     function linesFor(start, end) {
  4712.       var result = [];
  4713.       for (var i = start; i < end; ++i)
  4714.         { result.push(new Line(text[i], spansFor(i), estimateHeight)); }
  4715.       return result
  4716.     }
  4717.  
  4718.     var from = change.from, to = change.to, text = change.text;
  4719.     var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  4720.     var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  4721.  
  4722.     // Adjust the line structure
  4723.     if (change.full) {
  4724.       doc.insert(0, linesFor(0, text.length));
  4725.       doc.remove(text.length, doc.size - text.length);
  4726.     } else if (isWholeLineUpdate(doc, change)) {
  4727.       // This is a whole-line replace. Treated specially to make
  4728.       // sure line objects move the way they are supposed to.
  4729.       var added = linesFor(0, text.length - 1);
  4730.       update(lastLine, lastLine.text, lastSpans);
  4731.       if (nlines) { doc.remove(from.line, nlines); }
  4732.       if (added.length) { doc.insert(from.line, added); }
  4733.     } else if (firstLine == lastLine) {
  4734.       if (text.length == 1) {
  4735.         update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  4736.       } else {
  4737.         var added$1 = linesFor(1, text.length - 1);
  4738.         added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  4739.         update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4740.         doc.insert(from.line + 1, added$1);
  4741.       }
  4742.     } else if (text.length == 1) {
  4743.       update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  4744.       doc.remove(from.line + 1, nlines);
  4745.     } else {
  4746.       update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4747.       update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  4748.       var added$2 = linesFor(1, text.length - 1);
  4749.       if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  4750.       doc.insert(from.line + 1, added$2);
  4751.     }
  4752.  
  4753.     signalLater(doc, "change", doc, change);
  4754.   }
  4755.  
  4756.   // Call f for all linked documents.
  4757.   function linkedDocs(doc, f, sharedHistOnly) {
  4758.     function propagate(doc, skip, sharedHist) {
  4759.       if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4760.         var rel = doc.linked[i];
  4761.         if (rel.doc == skip) { continue }
  4762.         var shared = sharedHist && rel.sharedHist;
  4763.         if (sharedHistOnly && !shared) { continue }
  4764.         f(rel.doc, shared);
  4765.         propagate(rel.doc, doc, shared);
  4766.       } }
  4767.     }
  4768.     propagate(doc, null, true);
  4769.   }
  4770.  
  4771.   // Attach a document to an editor.
  4772.   function attachDoc(cm, doc) {
  4773.     if (doc.cm) { throw new Error("This document is already in use.") }
  4774.     cm.doc = doc;
  4775.     doc.cm = cm;
  4776.     estimateLineHeights(cm);
  4777.     loadMode(cm);
  4778.     setDirectionClass(cm);
  4779.     if (!cm.options.lineWrapping) { findMaxLine(cm); }
  4780.     cm.options.mode = doc.modeOption;
  4781.     regChange(cm);
  4782.   }
  4783.  
  4784.   function setDirectionClass(cm) {
  4785.   (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  4786.   }
  4787.  
  4788.   function directionChanged(cm) {
  4789.     runInOp(cm, function () {
  4790.       setDirectionClass(cm);
  4791.       regChange(cm);
  4792.     });
  4793.   }
  4794.  
  4795.   function History(startGen) {
  4796.     // Arrays of change events and selections. Doing something adds an
  4797.     // event to done and clears undo. Undoing moves events from done
  4798.     // to undone, redoing moves them in the other direction.
  4799.     this.done = []; this.undone = [];
  4800.     this.undoDepth = Infinity;
  4801.     // Used to track when changes can be merged into a single undo
  4802.     // event
  4803.     this.lastModTime = this.lastSelTime = 0;
  4804.     this.lastOp = this.lastSelOp = null;
  4805.     this.lastOrigin = this.lastSelOrigin = null;
  4806.     // Used by the isClean() method
  4807.     this.generation = this.maxGeneration = startGen || 1;
  4808.   }
  4809.  
  4810.   // Create a history change event from an updateDoc-style change
  4811.   // object.
  4812.   function historyChangeFromChange(doc, change) {
  4813.     var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  4814.     attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  4815.     linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  4816.     return histChange
  4817.   }
  4818.  
  4819.   // Pop all selection events off the end of a history array. Stop at
  4820.   // a change event.
  4821.   function clearSelectionEvents(array) {
  4822.     while (array.length) {
  4823.       var last = lst(array);
  4824.       if (last.ranges) { array.pop(); }
  4825.       else { break }
  4826.     }
  4827.   }
  4828.  
  4829.   // Find the top change event in the history. Pop off selection
  4830.   // events that are in the way.
  4831.   function lastChangeEvent(hist, force) {
  4832.     if (force) {
  4833.       clearSelectionEvents(hist.done);
  4834.       return lst(hist.done)
  4835.     } else if (hist.done.length && !lst(hist.done).ranges) {
  4836.       return lst(hist.done)
  4837.     } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4838.       hist.done.pop();
  4839.       return lst(hist.done)
  4840.     }
  4841.   }
  4842.  
  4843.   // Register a change in the history. Merges changes that are within
  4844.   // a single operation, or are close together with an origin that
  4845.   // allows merging (starting with "+") into a single event.
  4846.   function addChangeToHistory(doc, change, selAfter, opId) {
  4847.     var hist = doc.history;
  4848.     hist.undone.length = 0;
  4849.     var time = +new Date, cur;
  4850.     var last;
  4851.  
  4852.     if ((hist.lastOp == opId ||
  4853.          hist.lastOrigin == change.origin && change.origin &&
  4854.          ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
  4855.           change.origin.charAt(0) == "*")) &&
  4856.         (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4857.       // Merge this change into the last event
  4858.       last = lst(cur.changes);
  4859.       if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4860.         // Optimized case for simple insertion -- don't want to add
  4861.         // new changesets for every character typed
  4862.         last.to = changeEnd(change);
  4863.       } else {
  4864.         // Add new sub-event
  4865.         cur.changes.push(historyChangeFromChange(doc, change));
  4866.       }
  4867.     } else {
  4868.       // Can not be merged, start a new event.
  4869.       var before = lst(hist.done);
  4870.       if (!before || !before.ranges)
  4871.         { pushSelectionToHistory(doc.sel, hist.done); }
  4872.       cur = {changes: [historyChangeFromChange(doc, change)],
  4873.              generation: hist.generation};
  4874.       hist.done.push(cur);
  4875.       while (hist.done.length > hist.undoDepth) {
  4876.         hist.done.shift();
  4877.         if (!hist.done[0].ranges) { hist.done.shift(); }
  4878.       }
  4879.     }
  4880.     hist.done.push(selAfter);
  4881.     hist.generation = ++hist.maxGeneration;
  4882.     hist.lastModTime = hist.lastSelTime = time;
  4883.     hist.lastOp = hist.lastSelOp = opId;
  4884.     hist.lastOrigin = hist.lastSelOrigin = change.origin;
  4885.  
  4886.     if (!last) { signal(doc, "historyAdded"); }
  4887.   }
  4888.  
  4889.   function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4890.     var ch = origin.charAt(0);
  4891.     return ch == "*" ||
  4892.       ch == "+" &&
  4893.       prev.ranges.length == sel.ranges.length &&
  4894.       prev.somethingSelected() == sel.somethingSelected() &&
  4895.       new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4896.   }
  4897.  
  4898.   // Called whenever the selection changes, sets the new selection as
  4899.   // the pending selection in the history, and pushes the old pending
  4900.   // selection into the 'done' array when it was significantly
  4901.   // different (in number of selected ranges, emptiness, or time).
  4902.   function addSelectionToHistory(doc, sel, opId, options) {
  4903.     var hist = doc.history, origin = options && options.origin;
  4904.  
  4905.     // A new event is started when the previous origin does not match
  4906.     // the current, or the origins don't allow matching. Origins
  4907.     // starting with * are always merged, those starting with + are
  4908.     // merged when similar and close together in time.
  4909.     if (opId == hist.lastSelOp ||
  4910.         (origin && hist.lastSelOrigin == origin &&
  4911.          (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4912.           selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4913.       { hist.done[hist.done.length - 1] = sel; }
  4914.     else
  4915.       { pushSelectionToHistory(sel, hist.done); }
  4916.  
  4917.     hist.lastSelTime = +new Date;
  4918.     hist.lastSelOrigin = origin;
  4919.     hist.lastSelOp = opId;
  4920.     if (options && options.clearRedo !== false)
  4921.       { clearSelectionEvents(hist.undone); }
  4922.   }
  4923.  
  4924.   function pushSelectionToHistory(sel, dest) {
  4925.     var top = lst(dest);
  4926.     if (!(top && top.ranges && top.equals(sel)))
  4927.       { dest.push(sel); }
  4928.   }
  4929.  
  4930.   // Used to store marked span information in the history.
  4931.   function attachLocalSpans(doc, change, from, to) {
  4932.     var existing = change["spans_" + doc.id], n = 0;
  4933.     doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4934.       if (line.markedSpans)
  4935.         { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  4936.       ++n;
  4937.     });
  4938.   }
  4939.  
  4940.   // When un/re-doing restores text containing marked spans, those
  4941.   // that have been explicitly cleared should not be restored.
  4942.   function removeClearedSpans(spans) {
  4943.     if (!spans) { return null }
  4944.     var out;
  4945.     for (var i = 0; i < spans.length; ++i) {
  4946.       if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  4947.       else if (out) { out.push(spans[i]); }
  4948.     }
  4949.     return !out ? spans : out.length ? out : null
  4950.   }
  4951.  
  4952.   // Retrieve and filter the old marked spans stored in a change event.
  4953.   function getOldSpans(doc, change) {
  4954.     var found = change["spans_" + doc.id];
  4955.     if (!found) { return null }
  4956.     var nw = [];
  4957.     for (var i = 0; i < change.text.length; ++i)
  4958.       { nw.push(removeClearedSpans(found[i])); }
  4959.     return nw
  4960.   }
  4961.  
  4962.   // Used for un/re-doing changes from the history. Combines the
  4963.   // result of computing the existing spans with the set of spans that
  4964.   // existed in the history (so that deleting around a span and then
  4965.   // undoing brings back the span).
  4966.   function mergeOldSpans(doc, change) {
  4967.     var old = getOldSpans(doc, change);
  4968.     var stretched = stretchSpansOverChange(doc, change);
  4969.     if (!old) { return stretched }
  4970.     if (!stretched) { return old }
  4971.  
  4972.     for (var i = 0; i < old.length; ++i) {
  4973.       var oldCur = old[i], stretchCur = stretched[i];
  4974.       if (oldCur && stretchCur) {
  4975.         spans: for (var j = 0; j < stretchCur.length; ++j) {
  4976.           var span = stretchCur[j];
  4977.           for (var k = 0; k < oldCur.length; ++k)
  4978.             { if (oldCur[k].marker == span.marker) { continue spans } }
  4979.           oldCur.push(span);
  4980.         }
  4981.       } else if (stretchCur) {
  4982.         old[i] = stretchCur;
  4983.       }
  4984.     }
  4985.     return old
  4986.   }
  4987.  
  4988.   // Used both to provide a JSON-safe object in .getHistory, and, when
  4989.   // detaching a document, to split the history in two
  4990.   function copyHistoryArray(events, newGroup, instantiateSel) {
  4991.     var copy = [];
  4992.     for (var i = 0; i < events.length; ++i) {
  4993.       var event = events[i];
  4994.       if (event.ranges) {
  4995.         copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  4996.         continue
  4997.       }
  4998.       var changes = event.changes, newChanges = [];
  4999.       copy.push({changes: newChanges});
  5000.       for (var j = 0; j < changes.length; ++j) {
  5001.         var change = changes[j], m = (void 0);
  5002.         newChanges.push({from: change.from, to: change.to, text: change.text});
  5003.         if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  5004.           if (indexOf(newGroup, Number(m[1])) > -1) {
  5005.             lst(newChanges)[prop] = change[prop];
  5006.             delete change[prop];
  5007.           }
  5008.         } } }
  5009.       }
  5010.     }
  5011.     return copy
  5012.   }
  5013.  
  5014.   // The 'scroll' parameter given to many of these indicated whether
  5015.   // the new cursor position should be scrolled into view after
  5016.   // modifying the selection.
  5017.  
  5018.   // If shift is held or the extend flag is set, extends a range to
  5019.   // include a given position (and optionally a second position).
  5020.   // Otherwise, simply returns the range between the given positions.
  5021.   // Used for cursor motion and such.
  5022.   function extendRange(range, head, other, extend) {
  5023.     if (extend) {
  5024.       var anchor = range.anchor;
  5025.       if (other) {
  5026.         var posBefore = cmp(head, anchor) < 0;
  5027.         if (posBefore != (cmp(other, anchor) < 0)) {
  5028.           anchor = head;
  5029.           head = other;
  5030.         } else if (posBefore != (cmp(head, other) < 0)) {
  5031.           head = other;
  5032.         }
  5033.       }
  5034.       return new Range(anchor, head)
  5035.     } else {
  5036.       return new Range(other || head, head)
  5037.     }
  5038.   }
  5039.  
  5040.   // Extend the primary selection range, discard the rest.
  5041.   function extendSelection(doc, head, other, options, extend) {
  5042.     if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  5043.     setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  5044.   }
  5045.  
  5046.   // Extend all selections (pos is an array of selections with length
  5047.   // equal the number of selections)
  5048.   function extendSelections(doc, heads, options) {
  5049.     var out = [];
  5050.     var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  5051.     for (var i = 0; i < doc.sel.ranges.length; i++)
  5052.       { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  5053.     var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
  5054.     setSelection(doc, newSel, options);
  5055.   }
  5056.  
  5057.   // Updates a single range in the selection.
  5058.   function replaceOneSelection(doc, i, range, options) {
  5059.     var ranges = doc.sel.ranges.slice(0);
  5060.     ranges[i] = range;
  5061.     setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
  5062.   }
  5063.  
  5064.   // Reset the selection to a single range.
  5065.   function setSimpleSelection(doc, anchor, head, options) {
  5066.     setSelection(doc, simpleSelection(anchor, head), options);
  5067.   }
  5068.  
  5069.   // Give beforeSelectionChange handlers a change to influence a
  5070.   // selection update.
  5071.   function filterSelectionChange(doc, sel, options) {
  5072.     var obj = {
  5073.       ranges: sel.ranges,
  5074.       update: function(ranges) {
  5075.         this.ranges = [];
  5076.         for (var i = 0; i < ranges.length; i++)
  5077.           { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  5078.                                      clipPos(doc, ranges[i].head)); }
  5079.       },
  5080.       origin: options && options.origin
  5081.     };
  5082.     signal(doc, "beforeSelectionChange", doc, obj);
  5083.     if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  5084.     if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
  5085.     else { return sel }
  5086.   }
  5087.  
  5088.   function setSelectionReplaceHistory(doc, sel, options) {
  5089.     var done = doc.history.done, last = lst(done);
  5090.     if (last && last.ranges) {
  5091.       done[done.length - 1] = sel;
  5092.       setSelectionNoUndo(doc, sel, options);
  5093.     } else {
  5094.       setSelection(doc, sel, options);
  5095.     }
  5096.   }
  5097.  
  5098.   // Set a new selection.
  5099.   function setSelection(doc, sel, options) {
  5100.     setSelectionNoUndo(doc, sel, options);
  5101.     addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  5102.   }
  5103.  
  5104.   function setSelectionNoUndo(doc, sel, options) {
  5105.     if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  5106.       { sel = filterSelectionChange(doc, sel, options); }
  5107.  
  5108.     var bias = options && options.bias ||
  5109.       (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  5110.     setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  5111.  
  5112.     if (!(options && options.scroll === false) && doc.cm)
  5113.       { ensureCursorVisible(doc.cm); }
  5114.   }
  5115.  
  5116.   function setSelectionInner(doc, sel) {
  5117.     if (sel.equals(doc.sel)) { return }
  5118.  
  5119.     doc.sel = sel;
  5120.  
  5121.     if (doc.cm) {
  5122.       doc.cm.curOp.updateInput = 1;
  5123.       doc.cm.curOp.selectionChanged = true;
  5124.       signalCursorActivity(doc.cm);
  5125.     }
  5126.     signalLater(doc, "cursorActivity", doc);
  5127.   }
  5128.  
  5129.   // Verify that the selection does not partially select any atomic
  5130.   // marked ranges.
  5131.   function reCheckSelection(doc) {
  5132.     setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  5133.   }
  5134.  
  5135.   // Return a selection that does not partially select any atomic
  5136.   // ranges.
  5137.   function skipAtomicInSelection(doc, sel, bias, mayClear) {
  5138.     var out;
  5139.     for (var i = 0; i < sel.ranges.length; i++) {
  5140.       var range = sel.ranges[i];
  5141.       var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  5142.       var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  5143.       var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  5144.       if (out || newAnchor != range.anchor || newHead != range.head) {
  5145.         if (!out) { out = sel.ranges.slice(0, i); }
  5146.         out[i] = new Range(newAnchor, newHead);
  5147.       }
  5148.     }
  5149.     return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
  5150.   }
  5151.  
  5152.   function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  5153.     var line = getLine(doc, pos.line);
  5154.     if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  5155.       var sp = line.markedSpans[i], m = sp.marker;
  5156.  
  5157.       // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
  5158.       // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
  5159.       // is with selectLeft/Right
  5160.       var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
  5161.       var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
  5162.  
  5163.       if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  5164.           (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  5165.         if (mayClear) {
  5166.           signal(m, "beforeCursorEnter");
  5167.           if (m.explicitlyCleared) {
  5168.             if (!line.markedSpans) { break }
  5169.             else {--i; continue}
  5170.           }
  5171.         }
  5172.         if (!m.atomic) { continue }
  5173.  
  5174.         if (oldPos) {
  5175.           var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  5176.           if (dir < 0 ? preventCursorRight : preventCursorLeft)
  5177.             { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  5178.           if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  5179.             { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  5180.         }
  5181.  
  5182.         var far = m.find(dir < 0 ? -1 : 1);
  5183.         if (dir < 0 ? preventCursorLeft : preventCursorRight)
  5184.           { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  5185.         return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  5186.       }
  5187.     } }
  5188.     return pos
  5189.   }
  5190.  
  5191.   // Ensure a given position is not inside an atomic range.
  5192.   function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  5193.     var dir = bias || 1;
  5194.     var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  5195.         (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  5196.         skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  5197.         (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  5198.     if (!found) {
  5199.       doc.cantEdit = true;
  5200.       return Pos(doc.first, 0)
  5201.     }
  5202.     return found
  5203.   }
  5204.  
  5205.   function movePos(doc, pos, dir, line) {
  5206.     if (dir < 0 && pos.ch == 0) {
  5207.       if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  5208.       else { return null }
  5209.     } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  5210.       if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  5211.       else { return null }
  5212.     } else {
  5213.       return new Pos(pos.line, pos.ch + dir)
  5214.     }
  5215.   }
  5216.  
  5217.   function selectAll(cm) {
  5218.     cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  5219.   }
  5220.  
  5221.   // UPDATING
  5222.  
  5223.   // Allow "beforeChange" event handlers to influence a change
  5224.   function filterChange(doc, change, update) {
  5225.     var obj = {
  5226.       canceled: false,
  5227.       from: change.from,
  5228.       to: change.to,
  5229.       text: change.text,
  5230.       origin: change.origin,
  5231.       cancel: function () { return obj.canceled = true; }
  5232.     };
  5233.     if (update) { obj.update = function (from, to, text, origin) {
  5234.       if (from) { obj.from = clipPos(doc, from); }
  5235.       if (to) { obj.to = clipPos(doc, to); }
  5236.       if (text) { obj.text = text; }
  5237.       if (origin !== undefined) { obj.origin = origin; }
  5238.     }; }
  5239.     signal(doc, "beforeChange", doc, obj);
  5240.     if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  5241.  
  5242.     if (obj.canceled) {
  5243.       if (doc.cm) { doc.cm.curOp.updateInput = 2; }
  5244.       return null
  5245.     }
  5246.     return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  5247.   }
  5248.  
  5249.   // Apply a change to a document, and add it to the document's
  5250.   // history, and propagating it to all linked documents.
  5251.   function makeChange(doc, change, ignoreReadOnly) {
  5252.     if (doc.cm) {
  5253.       if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  5254.       if (doc.cm.state.suppressEdits) { return }
  5255.     }
  5256.  
  5257.     if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  5258.       change = filterChange(doc, change, true);
  5259.       if (!change) { return }
  5260.     }
  5261.  
  5262.     // Possibly split or suppress the update based on the presence
  5263.     // of read-only spans in its range.
  5264.     var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  5265.     if (split) {
  5266.       for (var i = split.length - 1; i >= 0; --i)
  5267.         { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  5268.     } else {
  5269.       makeChangeInner(doc, change);
  5270.     }
  5271.   }
  5272.  
  5273.   function makeChangeInner(doc, change) {
  5274.     if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  5275.     var selAfter = computeSelAfterChange(doc, change);
  5276.     addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  5277.  
  5278.     makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  5279.     var rebased = [];
  5280.  
  5281.     linkedDocs(doc, function (doc, sharedHist) {
  5282.       if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  5283.         rebaseHist(doc.history, change);
  5284.         rebased.push(doc.history);
  5285.       }
  5286.       makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  5287.     });
  5288.   }
  5289.  
  5290.   // Revert a change stored in a document's history.
  5291.   function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  5292.     var suppress = doc.cm && doc.cm.state.suppressEdits;
  5293.     if (suppress && !allowSelectionOnly) { return }
  5294.  
  5295.     var hist = doc.history, event, selAfter = doc.sel;
  5296.     var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  5297.  
  5298.     // Verify that there is a useable event (so that ctrl-z won't
  5299.     // needlessly clear selection events)
  5300.     var i = 0;
  5301.     for (; i < source.length; i++) {
  5302.       event = source[i];
  5303.       if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  5304.         { break }
  5305.     }
  5306.     if (i == source.length) { return }
  5307.     hist.lastOrigin = hist.lastSelOrigin = null;
  5308.  
  5309.     for (;;) {
  5310.       event = source.pop();
  5311.       if (event.ranges) {
  5312.         pushSelectionToHistory(event, dest);
  5313.         if (allowSelectionOnly && !event.equals(doc.sel)) {
  5314.           setSelection(doc, event, {clearRedo: false});
  5315.           return
  5316.         }
  5317.         selAfter = event;
  5318.       } else if (suppress) {
  5319.         source.push(event);
  5320.         return
  5321.       } else { break }
  5322.     }
  5323.  
  5324.     // Build up a reverse change object to add to the opposite history
  5325.     // stack (redo when undoing, and vice versa).
  5326.     var antiChanges = [];
  5327.     pushSelectionToHistory(selAfter, dest);
  5328.     dest.push({changes: antiChanges, generation: hist.generation});
  5329.     hist.generation = event.generation || ++hist.maxGeneration;
  5330.  
  5331.     var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  5332.  
  5333.     var loop = function ( i ) {
  5334.       var change = event.changes[i];
  5335.       change.origin = type;
  5336.       if (filter && !filterChange(doc, change, false)) {
  5337.         source.length = 0;
  5338.         return {}
  5339.       }
  5340.  
  5341.       antiChanges.push(historyChangeFromChange(doc, change));
  5342.  
  5343.       var after = i ? computeSelAfterChange(doc, change) : lst(source);
  5344.       makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  5345.       if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  5346.       var rebased = [];
  5347.  
  5348.       // Propagate to the linked documents
  5349.       linkedDocs(doc, function (doc, sharedHist) {
  5350.         if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  5351.           rebaseHist(doc.history, change);
  5352.           rebased.push(doc.history);
  5353.         }
  5354.         makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  5355.       });
  5356.     };
  5357.  
  5358.     for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  5359.       var returned = loop( i$1 );
  5360.  
  5361.       if ( returned ) return returned.v;
  5362.     }
  5363.   }
  5364.  
  5365.   // Sub-views need their line numbers shifted when text is added
  5366.   // above or below them in the parent document.
  5367.   function shiftDoc(doc, distance) {
  5368.     if (distance == 0) { return }
  5369.     doc.first += distance;
  5370.     doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  5371.       Pos(range.anchor.line + distance, range.anchor.ch),
  5372.       Pos(range.head.line + distance, range.head.ch)
  5373.     ); }), doc.sel.primIndex);
  5374.     if (doc.cm) {
  5375.       regChange(doc.cm, doc.first, doc.first - distance, distance);
  5376.       for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  5377.         { regLineChange(doc.cm, l, "gutter"); }
  5378.     }
  5379.   }
  5380.  
  5381.   // More lower-level change function, handling only a single document
  5382.   // (not linked ones).
  5383.   function makeChangeSingleDoc(doc, change, selAfter, spans) {
  5384.     if (doc.cm && !doc.cm.curOp)
  5385.       { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  5386.  
  5387.     if (change.to.line < doc.first) {
  5388.       shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  5389.       return
  5390.     }
  5391.     if (change.from.line > doc.lastLine()) { return }
  5392.  
  5393.     // Clip the change to the size of this doc
  5394.     if (change.from.line < doc.first) {
  5395.       var shift = change.text.length - 1 - (doc.first - change.from.line);
  5396.       shiftDoc(doc, shift);
  5397.       change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  5398.                 text: [lst(change.text)], origin: change.origin};
  5399.     }
  5400.     var last = doc.lastLine();
  5401.     if (change.to.line > last) {
  5402.       change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  5403.                 text: [change.text[0]], origin: change.origin};
  5404.     }
  5405.  
  5406.     change.removed = getBetween(doc, change.from, change.to);
  5407.  
  5408.     if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  5409.     if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  5410.     else { updateDoc(doc, change, spans); }
  5411.     setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  5412.  
  5413.     if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
  5414.       { doc.cantEdit = false; }
  5415.   }
  5416.  
  5417.   // Handle the interaction of a change to a document with the editor
  5418.   // that this document is part of.
  5419.   function makeChangeSingleDocInEditor(cm, change, spans) {
  5420.     var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  5421.  
  5422.     var recomputeMaxLength = false, checkWidthStart = from.line;
  5423.     if (!cm.options.lineWrapping) {
  5424.       checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  5425.       doc.iter(checkWidthStart, to.line + 1, function (line) {
  5426.         if (line == display.maxLine) {
  5427.           recomputeMaxLength = true;
  5428.           return true
  5429.         }
  5430.       });
  5431.     }
  5432.  
  5433.     if (doc.sel.contains(change.from, change.to) > -1)
  5434.       { signalCursorActivity(cm); }
  5435.  
  5436.     updateDoc(doc, change, spans, estimateHeight(cm));
  5437.  
  5438.     if (!cm.options.lineWrapping) {
  5439.       doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  5440.         var len = lineLength(line);
  5441.         if (len > display.maxLineLength) {
  5442.           display.maxLine = line;
  5443.           display.maxLineLength = len;
  5444.           display.maxLineChanged = true;
  5445.           recomputeMaxLength = false;
  5446.         }
  5447.       });
  5448.       if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  5449.     }
  5450.  
  5451.     retreatFrontier(doc, from.line);
  5452.     startWorker(cm, 400);
  5453.  
  5454.     var lendiff = change.text.length - (to.line - from.line) - 1;
  5455.     // Remember that these lines changed, for updating the display
  5456.     if (change.full)
  5457.       { regChange(cm); }
  5458.     else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  5459.       { regLineChange(cm, from.line, "text"); }
  5460.     else
  5461.       { regChange(cm, from.line, to.line + 1, lendiff); }
  5462.  
  5463.     var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  5464.     if (changeHandler || changesHandler) {
  5465.       var obj = {
  5466.         from: from, to: to,
  5467.         text: change.text,
  5468.         removed: change.removed,
  5469.         origin: change.origin
  5470.       };
  5471.       if (changeHandler) { signalLater(cm, "change", cm, obj); }
  5472.       if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  5473.     }
  5474.     cm.display.selForContextMenu = null;
  5475.   }
  5476.  
  5477.   function replaceRange(doc, code, from, to, origin) {
  5478.     var assign;
  5479.  
  5480.     if (!to) { to = from; }
  5481.     if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
  5482.     if (typeof code == "string") { code = doc.splitLines(code); }
  5483.     makeChange(doc, {from: from, to: to, text: code, origin: origin});
  5484.   }
  5485.  
  5486.   // Rebasing/resetting history to deal with externally-sourced changes
  5487.  
  5488.   function rebaseHistSelSingle(pos, from, to, diff) {
  5489.     if (to < pos.line) {
  5490.       pos.line += diff;
  5491.     } else if (from < pos.line) {
  5492.       pos.line = from;
  5493.       pos.ch = 0;
  5494.     }
  5495.   }
  5496.  
  5497.   // Tries to rebase an array of history events given a change in the
  5498.   // document. If the change touches the same lines as the event, the
  5499.   // event, and everything 'behind' it, is discarded. If the change is
  5500.   // before the event, the event's positions are updated. Uses a
  5501.   // copy-on-write scheme for the positions, to avoid having to
  5502.   // reallocate them all on every rebase, but also avoid problems with
  5503.   // shared position objects being unsafely updated.
  5504.   function rebaseHistArray(array, from, to, diff) {
  5505.     for (var i = 0; i < array.length; ++i) {
  5506.       var sub = array[i], ok = true;
  5507.       if (sub.ranges) {
  5508.         if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  5509.         for (var j = 0; j < sub.ranges.length; j++) {
  5510.           rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  5511.           rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  5512.         }
  5513.         continue
  5514.       }
  5515.       for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  5516.         var cur = sub.changes[j$1];
  5517.         if (to < cur.from.line) {
  5518.           cur.from = Pos(cur.from.line + diff, cur.from.ch);
  5519.           cur.to = Pos(cur.to.line + diff, cur.to.ch);
  5520.         } else if (from <= cur.to.line) {
  5521.           ok = false;
  5522.           break
  5523.         }
  5524.       }
  5525.       if (!ok) {
  5526.         array.splice(0, i + 1);
  5527.         i = 0;
  5528.       }
  5529.     }
  5530.   }
  5531.  
  5532.   function rebaseHist(hist, change) {
  5533.     var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  5534.     rebaseHistArray(hist.done, from, to, diff);
  5535.     rebaseHistArray(hist.undone, from, to, diff);
  5536.   }
  5537.  
  5538.   // Utility for applying a change to a line by handle or number,
  5539.   // returning the number and optionally registering the line as
  5540.   // changed.
  5541.   function changeLine(doc, handle, changeType, op) {
  5542.     var no = handle, line = handle;
  5543.     if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  5544.     else { no = lineNo(handle); }
  5545.     if (no == null) { return null }
  5546.     if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  5547.     return line
  5548.   }
  5549.  
  5550.   // The document is represented as a BTree consisting of leaves, with
  5551.   // chunk of lines in them, and branches, with up to ten leaves or
  5552.   // other branch nodes below them. The top node is always a branch
  5553.   // node, and is the document object itself (meaning it has
  5554.   // additional methods and properties).
  5555.   //
  5556.   // All nodes have parent links. The tree is used both to go from
  5557.   // line numbers to line objects, and to go from objects to numbers.
  5558.   // It also indexes by height, and is used to convert between height
  5559.   // and line object, and to find the total height of the document.
  5560.   //
  5561.   // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  5562.  
  5563.   function LeafChunk(lines) {
  5564.     this.lines = lines;
  5565.     this.parent = null;
  5566.     var height = 0;
  5567.     for (var i = 0; i < lines.length; ++i) {
  5568.       lines[i].parent = this;
  5569.       height += lines[i].height;
  5570.     }
  5571.     this.height = height;
  5572.   }
  5573.  
  5574.   LeafChunk.prototype = {
  5575.     chunkSize: function() { return this.lines.length },
  5576.  
  5577.     // Remove the n lines at offset 'at'.
  5578.     removeInner: function(at, n) {
  5579.       for (var i = at, e = at + n; i < e; ++i) {
  5580.         var line = this.lines[i];
  5581.         this.height -= line.height;
  5582.         cleanUpLine(line);
  5583.         signalLater(line, "delete");
  5584.       }
  5585.       this.lines.splice(at, n);
  5586.     },
  5587.  
  5588.     // Helper used to collapse a small branch into a single leaf.
  5589.     collapse: function(lines) {
  5590.       lines.push.apply(lines, this.lines);
  5591.     },
  5592.  
  5593.     // Insert the given array of lines at offset 'at', count them as
  5594.     // having the given height.
  5595.     insertInner: function(at, lines, height) {
  5596.       this.height += height;
  5597.       this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  5598.       for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
  5599.     },
  5600.  
  5601.     // Used to iterate over a part of the tree.
  5602.     iterN: function(at, n, op) {
  5603.       for (var e = at + n; at < e; ++at)
  5604.         { if (op(this.lines[at])) { return true } }
  5605.     }
  5606.   };
  5607.  
  5608.   function BranchChunk(children) {
  5609.     this.children = children;
  5610.     var size = 0, height = 0;
  5611.     for (var i = 0; i < children.length; ++i) {
  5612.       var ch = children[i];
  5613.       size += ch.chunkSize(); height += ch.height;
  5614.       ch.parent = this;
  5615.     }
  5616.     this.size = size;
  5617.     this.height = height;
  5618.     this.parent = null;
  5619.   }
  5620.  
  5621.   BranchChunk.prototype = {
  5622.     chunkSize: function() { return this.size },
  5623.  
  5624.     removeInner: function(at, n) {
  5625.       this.size -= n;
  5626.       for (var i = 0; i < this.children.length; ++i) {
  5627.         var child = this.children[i], sz = child.chunkSize();
  5628.         if (at < sz) {
  5629.           var rm = Math.min(n, sz - at), oldHeight = child.height;
  5630.           child.removeInner(at, rm);
  5631.           this.height -= oldHeight - child.height;
  5632.           if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  5633.           if ((n -= rm) == 0) { break }
  5634.           at = 0;
  5635.         } else { at -= sz; }
  5636.       }
  5637.       // If the result is smaller than 25 lines, ensure that it is a
  5638.       // single leaf node.
  5639.       if (this.size - n < 25 &&
  5640.           (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  5641.         var lines = [];
  5642.         this.collapse(lines);
  5643.         this.children = [new LeafChunk(lines)];
  5644.         this.children[0].parent = this;
  5645.       }
  5646.     },
  5647.  
  5648.     collapse: function(lines) {
  5649.       for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
  5650.     },
  5651.  
  5652.     insertInner: function(at, lines, height) {
  5653.       this.size += lines.length;
  5654.       this.height += height;
  5655.       for (var i = 0; i < this.children.length; ++i) {
  5656.         var child = this.children[i], sz = child.chunkSize();
  5657.         if (at <= sz) {
  5658.           child.insertInner(at, lines, height);
  5659.           if (child.lines && child.lines.length > 50) {
  5660.             // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  5661.             // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  5662.             var remaining = child.lines.length % 25 + 25;
  5663.             for (var pos = remaining; pos < child.lines.length;) {
  5664.               var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  5665.               child.height -= leaf.height;
  5666.               this.children.splice(++i, 0, leaf);
  5667.               leaf.parent = this;
  5668.             }
  5669.             child.lines = child.lines.slice(0, remaining);
  5670.             this.maybeSpill();
  5671.           }
  5672.           break
  5673.         }
  5674.         at -= sz;
  5675.       }
  5676.     },
  5677.  
  5678.     // When a node has grown, check whether it should be split.
  5679.     maybeSpill: function() {
  5680.       if (this.children.length <= 10) { return }
  5681.       var me = this;
  5682.       do {
  5683.         var spilled = me.children.splice(me.children.length - 5, 5);
  5684.         var sibling = new BranchChunk(spilled);
  5685.         if (!me.parent) { // Become the parent node
  5686.           var copy = new BranchChunk(me.children);
  5687.           copy.parent = me;
  5688.           me.children = [copy, sibling];
  5689.           me = copy;
  5690.        } else {
  5691.           me.size -= sibling.size;
  5692.           me.height -= sibling.height;
  5693.           var myIndex = indexOf(me.parent.children, me);
  5694.           me.parent.children.splice(myIndex + 1, 0, sibling);
  5695.         }
  5696.         sibling.parent = me.parent;
  5697.       } while (me.children.length > 10)
  5698.       me.parent.maybeSpill();
  5699.     },
  5700.  
  5701.     iterN: function(at, n, op) {
  5702.       for (var i = 0; i < this.children.length; ++i) {
  5703.         var child = this.children[i], sz = child.chunkSize();
  5704.         if (at < sz) {
  5705.           var used = Math.min(n, sz - at);
  5706.           if (child.iterN(at, used, op)) { return true }
  5707.           if ((n -= used) == 0) { break }
  5708.           at = 0;
  5709.         } else { at -= sz; }
  5710.       }
  5711.     }
  5712.   };
  5713.  
  5714.   // Line widgets are block elements displayed above or below a line.
  5715.  
  5716.   var LineWidget = function(doc, node, options) {
  5717.     if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  5718.       { this[opt] = options[opt]; } } }
  5719.     this.doc = doc;
  5720.     this.node = node;
  5721.   };
  5722.  
  5723.   LineWidget.prototype.clear = function () {
  5724.     var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  5725.     if (no == null || !ws) { return }
  5726.     for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
  5727.     if (!ws.length) { line.widgets = null; }
  5728.     var height = widgetHeight(this);
  5729.     updateLineHeight(line, Math.max(0, line.height - height));
  5730.     if (cm) {
  5731.       runInOp(cm, function () {
  5732.         adjustScrollWhenAboveVisible(cm, line, -height);
  5733.         regLineChange(cm, no, "widget");
  5734.       });
  5735.       signalLater(cm, "lineWidgetCleared", cm, this, no);
  5736.     }
  5737.   };
  5738.  
  5739.   LineWidget.prototype.changed = function () {
  5740.       var this$1 = this;
  5741.  
  5742.     var oldH = this.height, cm = this.doc.cm, line = this.line;
  5743.     this.height = null;
  5744.     var diff = widgetHeight(this) - oldH;
  5745.     if (!diff) { return }
  5746.     if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
  5747.     if (cm) {
  5748.       runInOp(cm, function () {
  5749.         cm.curOp.forceUpdate = true;
  5750.         adjustScrollWhenAboveVisible(cm, line, diff);
  5751.         signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  5752.       });
  5753.     }
  5754.   };
  5755.   eventMixin(LineWidget);
  5756.  
  5757.   function adjustScrollWhenAboveVisible(cm, line, diff) {
  5758.     if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5759.       { addToScrollTop(cm, diff); }
  5760.   }
  5761.  
  5762.   function addLineWidget(doc, handle, node, options) {
  5763.     var widget = new LineWidget(doc, node, options);
  5764.     var cm = doc.cm;
  5765.     if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  5766.     changeLine(doc, handle, "widget", function (line) {
  5767.       var widgets = line.widgets || (line.widgets = []);
  5768.       if (widget.insertAt == null) { widgets.push(widget); }
  5769.       else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
  5770.       widget.line = line;
  5771.       if (cm && !lineIsHidden(doc, line)) {
  5772.         var aboveVisible = heightAtLine(line) < doc.scrollTop;
  5773.         updateLineHeight(line, line.height + widgetHeight(widget));
  5774.         if (aboveVisible) { addToScrollTop(cm, widget.height); }
  5775.         cm.curOp.forceUpdate = true;
  5776.       }
  5777.       return true
  5778.     });
  5779.     if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
  5780.     return widget
  5781.   }
  5782.  
  5783.   // TEXTMARKERS
  5784.  
  5785.   // Created with markText and setBookmark methods. A TextMarker is a
  5786.   // handle that can be used to clear or find a marked position in the
  5787.   // document. Line objects hold arrays (markedSpans) containing
  5788.   // {from, to, marker} object pointing to such marker objects, and
  5789.   // indicating that such a marker is present on that line. Multiple
  5790.   // lines may point to the same marker when it spans across lines.
  5791.   // The spans will have null for their from/to properties when the
  5792.   // marker continues beyond the start/end of the line. Markers have
  5793.   // links back to the lines they currently touch.
  5794.  
  5795.   // Collapsed markers have unique ids, in order to be able to order
  5796.   // them, which is needed for uniquely determining an outer marker
  5797.   // when they overlap (they may nest, but not partially overlap).
  5798.   var nextMarkerId = 0;
  5799.  
  5800.   var TextMarker = function(doc, type) {
  5801.     this.lines = [];
  5802.     this.type = type;
  5803.     this.doc = doc;
  5804.     this.id = ++nextMarkerId;
  5805.   };
  5806.  
  5807.   // Clear the marker.
  5808.   TextMarker.prototype.clear = function () {
  5809.     if (this.explicitlyCleared) { return }
  5810.     var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5811.     if (withOp) { startOperation(cm); }
  5812.     if (hasHandler(this, "clear")) {
  5813.       var found = this.find();
  5814.       if (found) { signalLater(this, "clear", found.from, found.to); }
  5815.     }
  5816.     var min = null, max = null;
  5817.     for (var i = 0; i < this.lines.length; ++i) {
  5818.       var line = this.lines[i];
  5819.       var span = getMarkedSpanFor(line.markedSpans, this);
  5820.       if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  5821.       else if (cm) {
  5822.         if (span.to != null) { max = lineNo(line); }
  5823.         if (span.from != null) { min = lineNo(line); }
  5824.       }
  5825.       line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5826.       if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  5827.         { updateLineHeight(line, textHeight(cm.display)); }
  5828.     }
  5829.     if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5830.       var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
  5831.       if (len > cm.display.maxLineLength) {
  5832.         cm.display.maxLine = visual;
  5833.         cm.display.maxLineLength = len;
  5834.         cm.display.maxLineChanged = true;
  5835.       }
  5836.     } }
  5837.  
  5838.     if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  5839.     this.lines.length = 0;
  5840.     this.explicitlyCleared = true;
  5841.     if (this.atomic && this.doc.cantEdit) {
  5842.       this.doc.cantEdit = false;
  5843.       if (cm) { reCheckSelection(cm.doc); }
  5844.     }
  5845.     if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  5846.     if (withOp) { endOperation(cm); }
  5847.     if (this.parent) { this.parent.clear(); }
  5848.   };
  5849.  
  5850.   // Find the position of the marker in the document. Returns a {from,
  5851.   // to} object by default. Side can be passed to get a specific side
  5852.   // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5853.   // Pos objects returned contain a line object, rather than a line
  5854.   // number (used to prevent looking up the same line twice).
  5855.   TextMarker.prototype.find = function (side, lineObj) {
  5856.     if (side == null && this.type == "bookmark") { side = 1; }
  5857.     var from, to;
  5858.     for (var i = 0; i < this.lines.length; ++i) {
  5859.       var line = this.lines[i];
  5860.       var span = getMarkedSpanFor(line.markedSpans, this);
  5861.       if (span.from != null) {
  5862.         from = Pos(lineObj ? line : lineNo(line), span.from);
  5863.         if (side == -1) { return from }
  5864.       }
  5865.       if (span.to != null) {
  5866.         to = Pos(lineObj ? line : lineNo(line), span.to);
  5867.         if (side == 1) { return to }
  5868.       }
  5869.     }
  5870.     return from && {from: from, to: to}
  5871.   };
  5872.  
  5873.   // Signals that the marker's widget changed, and surrounding layout
  5874.   // should be recomputed.
  5875.   TextMarker.prototype.changed = function () {
  5876.       var this$1 = this;
  5877.  
  5878.     var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5879.     if (!pos || !cm) { return }
  5880.     runInOp(cm, function () {
  5881.       var line = pos.line, lineN = lineNo(pos.line);
  5882.       var view = findViewForLine(cm, lineN);
  5883.       if (view) {
  5884.         clearLineMeasurementCacheFor(view);
  5885.         cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5886.       }
  5887.       cm.curOp.updateMaxLine = true;
  5888.       if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5889.         var oldHeight = widget.height;
  5890.         widget.height = null;
  5891.         var dHeight = widgetHeight(widget) - oldHeight;
  5892.         if (dHeight)
  5893.           { updateLineHeight(line, line.height + dHeight); }
  5894.       }
  5895.       signalLater(cm, "markerChanged", cm, this$1);
  5896.     });
  5897.   };
  5898.  
  5899.   TextMarker.prototype.attachLine = function (line) {
  5900.     if (!this.lines.length && this.doc.cm) {
  5901.       var op = this.doc.cm.curOp;
  5902.       if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5903.         { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  5904.     }
  5905.     this.lines.push(line);
  5906.   };
  5907.  
  5908.   TextMarker.prototype.detachLine = function (line) {
  5909.     this.lines.splice(indexOf(this.lines, line), 1);
  5910.     if (!this.lines.length && this.doc.cm) {
  5911.       var op = this.doc.cm.curOp
  5912.       ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5913.     }
  5914.   };
  5915.   eventMixin(TextMarker);
  5916.  
  5917.   // Create a marker, wire it up to the right lines, and
  5918.   function markText(doc, from, to, options, type) {
  5919.     // Shared markers (across linked documents) are handled separately
  5920.     // (markTextShared will call out to this again, once per
  5921.     // document).
  5922.     if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5923.     // Ensure we are in an operation.
  5924.     if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5925.  
  5926.     var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5927.     if (options) { copyObj(options, marker, false); }
  5928.     // Don't connect empty markers unless clearWhenEmpty is false
  5929.     if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5930.       { return marker }
  5931.     if (marker.replacedWith) {
  5932.       // Showing up as a widget implies collapsed (widget replaces text)
  5933.       marker.collapsed = true;
  5934.       marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  5935.       if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  5936.       if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  5937.     }
  5938.     if (marker.collapsed) {
  5939.       if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5940.           from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5941.         { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5942.       seeCollapsedSpans();
  5943.     }
  5944.  
  5945.     if (marker.addToHistory)
  5946.       { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  5947.  
  5948.     var curLine = from.line, cm = doc.cm, updateMaxLine;
  5949.     doc.iter(curLine, to.line + 1, function (line) {
  5950.       if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5951.         { updateMaxLine = true; }
  5952.       if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  5953.       addMarkedSpan(line, new MarkedSpan(marker,
  5954.                                          curLine == from.line ? from.ch : null,
  5955.                                          curLine == to.line ? to.ch : null));
  5956.       ++curLine;
  5957.     });
  5958.     // lineIsHidden depends on the presence of the spans, so needs a second pass
  5959.     if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5960.       if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  5961.     }); }
  5962.  
  5963.     if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  5964.  
  5965.     if (marker.readOnly) {
  5966.       seeReadOnlySpans();
  5967.       if (doc.history.done.length || doc.history.undone.length)
  5968.         { doc.clearHistory(); }
  5969.     }
  5970.     if (marker.collapsed) {
  5971.       marker.id = ++nextMarkerId;
  5972.       marker.atomic = true;
  5973.     }
  5974.     if (cm) {
  5975.       // Sync editor state
  5976.       if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  5977.       if (marker.collapsed)
  5978.         { regChange(cm, from.line, to.line + 1); }
  5979.       else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
  5980.                marker.attributes || marker.title)
  5981.         { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  5982.       if (marker.atomic) { reCheckSelection(cm.doc); }
  5983.       signalLater(cm, "markerAdded", cm, marker);
  5984.     }
  5985.     return marker
  5986.   }
  5987.  
  5988.   // SHARED TEXTMARKERS
  5989.  
  5990.   // A shared marker spans multiple linked documents. It is
  5991.   // implemented as a meta-marker-object controlling multiple normal
  5992.   // markers.
  5993.   var SharedTextMarker = function(markers, primary) {
  5994.     this.markers = markers;
  5995.     this.primary = primary;
  5996.     for (var i = 0; i < markers.length; ++i)
  5997.       { markers[i].parent = this; }
  5998.   };
  5999.  
  6000.   SharedTextMarker.prototype.clear = function () {
  6001.     if (this.explicitlyCleared) { return }
  6002.     this.explicitlyCleared = true;
  6003.     for (var i = 0; i < this.markers.length; ++i)
  6004.       { this.markers[i].clear(); }
  6005.     signalLater(this, "clear");
  6006.   };
  6007.  
  6008.   SharedTextMarker.prototype.find = function (side, lineObj) {
  6009.     return this.primary.find(side, lineObj)
  6010.   };
  6011.   eventMixin(SharedTextMarker);
  6012.  
  6013.   function markTextShared(doc, from, to, options, type) {
  6014.     options = copyObj(options);
  6015.     options.shared = false;
  6016.     var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  6017.     var widget = options.widgetNode;
  6018.     linkedDocs(doc, function (doc) {
  6019.       if (widget) { options.widgetNode = widget.cloneNode(true); }
  6020.       markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  6021.       for (var i = 0; i < doc.linked.length; ++i)
  6022.         { if (doc.linked[i].isParent) { return } }
  6023.       primary = lst(markers);
  6024.     });
  6025.     return new SharedTextMarker(markers, primary)
  6026.   }
  6027.  
  6028.   function findSharedMarkers(doc) {
  6029.     return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  6030.   }
  6031.  
  6032.   function copySharedMarkers(doc, markers) {
  6033.     for (var i = 0; i < markers.length; i++) {
  6034.       var marker = markers[i], pos = marker.find();
  6035.       var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  6036.       if (cmp(mFrom, mTo)) {
  6037.         var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  6038.         marker.markers.push(subMark);
  6039.         subMark.parent = marker;
  6040.       }
  6041.     }
  6042.   }
  6043.  
  6044.   function detachSharedMarkers(markers) {
  6045.     var loop = function ( i ) {
  6046.       var marker = markers[i], linked = [marker.primary.doc];
  6047.       linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  6048.       for (var j = 0; j < marker.markers.length; j++) {
  6049.         var subMarker = marker.markers[j];
  6050.         if (indexOf(linked, subMarker.doc) == -1) {
  6051.           subMarker.parent = null;
  6052.           marker.markers.splice(j--, 1);
  6053.         }
  6054.       }
  6055.     };
  6056.  
  6057.     for (var i = 0; i < markers.length; i++) loop( i );
  6058.   }
  6059.  
  6060.   var nextDocId = 0;
  6061.   var Doc = function(text, mode, firstLine, lineSep, direction) {
  6062.     if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  6063.     if (firstLine == null) { firstLine = 0; }
  6064.  
  6065.     BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  6066.     this.first = firstLine;
  6067.     this.scrollTop = this.scrollLeft = 0;
  6068.     this.cantEdit = false;
  6069.     this.cleanGeneration = 1;
  6070.     this.modeFrontier = this.highlightFrontier = firstLine;
  6071.     var start = Pos(firstLine, 0);
  6072.     this.sel = simpleSelection(start);
  6073.     this.history = new History(null);
  6074.     this.id = ++nextDocId;
  6075.     this.modeOption = mode;
  6076.     this.lineSep = lineSep;
  6077.     this.direction = (direction == "rtl") ? "rtl" : "ltr";
  6078.     this.extend = false;
  6079.  
  6080.     if (typeof text == "string") { text = this.splitLines(text); }
  6081.     updateDoc(this, {from: start, to: start, text: text});
  6082.     setSelection(this, simpleSelection(start), sel_dontScroll);
  6083.   };
  6084.  
  6085.   Doc.prototype = createObj(BranchChunk.prototype, {
  6086.     constructor: Doc,
  6087.     // Iterate over the document. Supports two forms -- with only one
  6088.     // argument, it calls that for each line in the document. With
  6089.     // three, it iterates over the range given by the first two (with
  6090.     // the second being non-inclusive).
  6091.     iter: function(from, to, op) {
  6092.       if (op) { this.iterN(from - this.first, to - from, op); }
  6093.       else { this.iterN(this.first, this.first + this.size, from); }
  6094.     },
  6095.  
  6096.     // Non-public interface for adding and removing lines.
  6097.     insert: function(at, lines) {
  6098.       var height = 0;
  6099.       for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  6100.       this.insertInner(at - this.first, lines, height);
  6101.     },
  6102.     remove: function(at, n) { this.removeInner(at - this.first, n); },
  6103.  
  6104.     // From here, the methods are part of the public interface. Most
  6105.     // are also available from CodeMirror (editor) instances.
  6106.  
  6107.     getValue: function(lineSep) {
  6108.       var lines = getLines(this, this.first, this.first + this.size);
  6109.       if (lineSep === false) { return lines }
  6110.       return lines.join(lineSep || this.lineSeparator())
  6111.     },
  6112.     setValue: docMethodOp(function(code) {
  6113.       var top = Pos(this.first, 0), last = this.first + this.size - 1;
  6114.       makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  6115.                         text: this.splitLines(code), origin: "setValue", full: true}, true);
  6116.       if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  6117.       setSelection(this, simpleSelection(top), sel_dontScroll);
  6118.     }),
  6119.     replaceRange: function(code, from, to, origin) {
  6120.       from = clipPos(this, from);
  6121.       to = to ? clipPos(this, to) : from;
  6122.       replaceRange(this, code, from, to, origin);
  6123.     },
  6124.     getRange: function(from, to, lineSep) {
  6125.       var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  6126.       if (lineSep === false) { return lines }
  6127.       return lines.join(lineSep || this.lineSeparator())
  6128.     },
  6129.  
  6130.     getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  6131.  
  6132.     getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  6133.     getLineNumber: function(line) {return lineNo(line)},
  6134.  
  6135.     getLineHandleVisualStart: function(line) {
  6136.       if (typeof line == "number") { line = getLine(this, line); }
  6137.       return visualLine(line)
  6138.     },
  6139.  
  6140.     lineCount: function() {return this.size},
  6141.     firstLine: function() {return this.first},
  6142.     lastLine: function() {return this.first + this.size - 1},
  6143.  
  6144.     clipPos: function(pos) {return clipPos(this, pos)},
  6145.  
  6146.     getCursor: function(start) {
  6147.       var range = this.sel.primary(), pos;
  6148.       if (start == null || start == "head") { pos = range.head; }
  6149.       else if (start == "anchor") { pos = range.anchor; }
  6150.       else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
  6151.       else { pos = range.from(); }
  6152.       return pos
  6153.     },
  6154.     listSelections: function() { return this.sel.ranges },
  6155.     somethingSelected: function() {return this.sel.somethingSelected()},
  6156.  
  6157.     setCursor: docMethodOp(function(line, ch, options) {
  6158.       setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  6159.     }),
  6160.     setSelection: docMethodOp(function(anchor, head, options) {
  6161.       setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  6162.     }),
  6163.     extendSelection: docMethodOp(function(head, other, options) {
  6164.       extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  6165.     }),
  6166.     extendSelections: docMethodOp(function(heads, options) {
  6167.       extendSelections(this, clipPosArray(this, heads), options);
  6168.     }),
  6169.     extendSelectionsBy: docMethodOp(function(f, options) {
  6170.       var heads = map(this.sel.ranges, f);
  6171.       extendSelections(this, clipPosArray(this, heads), options);
  6172.     }),
  6173.     setSelections: docMethodOp(function(ranges, primary, options) {
  6174.       if (!ranges.length) { return }
  6175.       var out = [];
  6176.       for (var i = 0; i < ranges.length; i++)
  6177.         { out[i] = new Range(clipPos(this, ranges[i].anchor),
  6178.                            clipPos(this, ranges[i].head)); }
  6179.       if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  6180.       setSelection(this, normalizeSelection(this.cm, out, primary), options);
  6181.     }),
  6182.     addSelection: docMethodOp(function(anchor, head, options) {
  6183.       var ranges = this.sel.ranges.slice(0);
  6184.       ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  6185.       setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
  6186.     }),
  6187.  
  6188.     getSelection: function(lineSep) {
  6189.       var ranges = this.sel.ranges, lines;
  6190.       for (var i = 0; i < ranges.length; i++) {
  6191.         var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6192.         lines = lines ? lines.concat(sel) : sel;
  6193.       }
  6194.       if (lineSep === false) { return lines }
  6195.       else { return lines.join(lineSep || this.lineSeparator()) }
  6196.     },
  6197.     getSelections: function(lineSep) {
  6198.       var parts = [], ranges = this.sel.ranges;
  6199.       for (var i = 0; i < ranges.length; i++) {
  6200.         var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6201.         if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
  6202.         parts[i] = sel;
  6203.       }
  6204.       return parts
  6205.     },
  6206.     replaceSelection: function(code, collapse, origin) {
  6207.       var dup = [];
  6208.       for (var i = 0; i < this.sel.ranges.length; i++)
  6209.         { dup[i] = code; }
  6210.       this.replaceSelections(dup, collapse, origin || "+input");
  6211.     },
  6212.     replaceSelections: docMethodOp(function(code, collapse, origin) {
  6213.       var changes = [], sel = this.sel;
  6214.       for (var i = 0; i < sel.ranges.length; i++) {
  6215.         var range = sel.ranges[i];
  6216.         changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  6217.       }
  6218.       var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  6219.       for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  6220.         { makeChange(this, changes[i$1]); }
  6221.       if (newSel) { setSelectionReplaceHistory(this, newSel); }
  6222.       else if (this.cm) { ensureCursorVisible(this.cm); }
  6223.     }),
  6224.     undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  6225.     redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  6226.     undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  6227.     redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  6228.  
  6229.     setExtending: function(val) {this.extend = val;},
  6230.     getExtending: function() {return this.extend},
  6231.  
  6232.     historySize: function() {
  6233.       var hist = this.history, done = 0, undone = 0;
  6234.       for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  6235.       for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  6236.       return {undo: done, redo: undone}
  6237.     },
  6238.     clearHistory: function() {
  6239.       var this$1 = this;
  6240.  
  6241.       this.history = new History(this.history.maxGeneration);
  6242.       linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
  6243.     },
  6244.  
  6245.     markClean: function() {
  6246.       this.cleanGeneration = this.changeGeneration(true);
  6247.     },
  6248.     changeGeneration: function(forceSplit) {
  6249.       if (forceSplit)
  6250.         { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  6251.       return this.history.generation
  6252.     },
  6253.     isClean: function (gen) {
  6254.       return this.history.generation == (gen || this.cleanGeneration)
  6255.     },
  6256.  
  6257.     getHistory: function() {
  6258.       return {done: copyHistoryArray(this.history.done),
  6259.               undone: copyHistoryArray(this.history.undone)}
  6260.     },
  6261.     setHistory: function(histData) {
  6262.       var hist = this.history = new History(this.history.maxGeneration);
  6263.       hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  6264.       hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  6265.     },
  6266.  
  6267.     setGutterMarker: docMethodOp(function(line, gutterID, value) {
  6268.       return changeLine(this, line, "gutter", function (line) {
  6269.         var markers = line.gutterMarkers || (line.gutterMarkers = {});
  6270.         markers[gutterID] = value;
  6271.         if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  6272.         return true
  6273.       })
  6274.     }),
  6275.  
  6276.     clearGutter: docMethodOp(function(gutterID) {
  6277.       var this$1 = this;
  6278.  
  6279.       this.iter(function (line) {
  6280.         if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  6281.           changeLine(this$1, line, "gutter", function () {
  6282.             line.gutterMarkers[gutterID] = null;
  6283.             if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  6284.             return true
  6285.           });
  6286.         }
  6287.       });
  6288.     }),
  6289.  
  6290.     lineInfo: function(line) {
  6291.       var n;
  6292.       if (typeof line == "number") {
  6293.         if (!isLine(this, line)) { return null }
  6294.         n = line;
  6295.         line = getLine(this, line);
  6296.         if (!line) { return null }
  6297.       } else {
  6298.         n = lineNo(line);
  6299.         if (n == null) { return null }
  6300.       }
  6301.       return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  6302.               textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  6303.               widgets: line.widgets}
  6304.     },
  6305.  
  6306.     addLineClass: docMethodOp(function(handle, where, cls) {
  6307.       return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  6308.         var prop = where == "text" ? "textClass"
  6309.                  : where == "background" ? "bgClass"
  6310.                  : where == "gutter" ? "gutterClass" : "wrapClass";
  6311.         if (!line[prop]) { line[prop] = cls; }
  6312.         else if (classTest(cls).test(line[prop])) { return false }
  6313.         else { line[prop] += " " + cls; }
  6314.         return true
  6315.       })
  6316.     }),
  6317.     removeLineClass: docMethodOp(function(handle, where, cls) {
  6318.       return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  6319.         var prop = where == "text" ? "textClass"
  6320.                  : where == "background" ? "bgClass"
  6321.                  : where == "gutter" ? "gutterClass" : "wrapClass";
  6322.         var cur = line[prop];
  6323.         if (!cur) { return false }
  6324.         else if (cls == null) { line[prop] = null; }
  6325.         else {
  6326.           var found = cur.match(classTest(cls));
  6327.           if (!found) { return false }
  6328.           var end = found.index + found[0].length;
  6329.           line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  6330.         }
  6331.         return true
  6332.       })
  6333.     }),
  6334.  
  6335.     addLineWidget: docMethodOp(function(handle, node, options) {
  6336.       return addLineWidget(this, handle, node, options)
  6337.     }),
  6338.     removeLineWidget: function(widget) { widget.clear(); },
  6339.  
  6340.     markText: function(from, to, options) {
  6341.       return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  6342.     },
  6343.     setBookmark: function(pos, options) {
  6344.       var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  6345.                       insertLeft: options && options.insertLeft,
  6346.                       clearWhenEmpty: false, shared: options && options.shared,
  6347.                       handleMouseEvents: options && options.handleMouseEvents};
  6348.       pos = clipPos(this, pos);
  6349.       return markText(this, pos, pos, realOpts, "bookmark")
  6350.     },
  6351.     findMarksAt: function(pos) {
  6352.       pos = clipPos(this, pos);
  6353.       var markers = [], spans = getLine(this, pos.line).markedSpans;
  6354.       if (spans) { for (var i = 0; i < spans.length; ++i) {
  6355.         var span = spans[i];
  6356.         if ((span.from == null || span.from <= pos.ch) &&
  6357.             (span.to == null || span.to >= pos.ch))
  6358.           { markers.push(span.marker.parent || span.marker); }
  6359.       } }
  6360.       return markers
  6361.     },
  6362.     findMarks: function(from, to, filter) {
  6363.       from = clipPos(this, from); to = clipPos(this, to);
  6364.       var found = [], lineNo = from.line;
  6365.       this.iter(from.line, to.line + 1, function (line) {
  6366.         var spans = line.markedSpans;
  6367.         if (spans) { for (var i = 0; i < spans.length; i++) {
  6368.           var span = spans[i];
  6369.           if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  6370.                 span.from == null && lineNo != from.line ||
  6371.                 span.from != null && lineNo == to.line && span.from >= to.ch) &&
  6372.               (!filter || filter(span.marker)))
  6373.             { found.push(span.marker.parent || span.marker); }
  6374.         } }
  6375.         ++lineNo;
  6376.       });
  6377.       return found
  6378.     },
  6379.     getAllMarks: function() {
  6380.       var markers = [];
  6381.       this.iter(function (line) {
  6382.         var sps = line.markedSpans;
  6383.         if (sps) { for (var i = 0; i < sps.length; ++i)
  6384.           { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  6385.       });
  6386.       return markers
  6387.     },
  6388.  
  6389.     posFromIndex: function(off) {
  6390.       var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  6391.       this.iter(function (line) {
  6392.         var sz = line.text.length + sepSize;
  6393.         if (sz > off) { ch = off; return true }
  6394.         off -= sz;
  6395.         ++lineNo;
  6396.       });
  6397.       return clipPos(this, Pos(lineNo, ch))
  6398.     },
  6399.     indexFromPos: function (coords) {
  6400.       coords = clipPos(this, coords);
  6401.       var index = coords.ch;
  6402.       if (coords.line < this.first || coords.ch < 0) { return 0 }
  6403.       var sepSize = this.lineSeparator().length;
  6404.       this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  6405.         index += line.text.length + sepSize;
  6406.       });
  6407.       return index
  6408.     },
  6409.  
  6410.     copy: function(copyHistory) {
  6411.       var doc = new Doc(getLines(this, this.first, this.first + this.size),
  6412.                         this.modeOption, this.first, this.lineSep, this.direction);
  6413.       doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  6414.       doc.sel = this.sel;
  6415.       doc.extend = false;
  6416.       if (copyHistory) {
  6417.         doc.history.undoDepth = this.history.undoDepth;
  6418.         doc.setHistory(this.getHistory());
  6419.       }
  6420.       return doc
  6421.     },
  6422.  
  6423.     linkedDoc: function(options) {
  6424.       if (!options) { options = {}; }
  6425.       var from = this.first, to = this.first + this.size;
  6426.       if (options.from != null && options.from > from) { from = options.from; }
  6427.       if (options.to != null && options.to < to) { to = options.to; }
  6428.       var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  6429.       if (options.sharedHist) { copy.history = this.history
  6430.       ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  6431.       copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  6432.       copySharedMarkers(copy, findSharedMarkers(this));
  6433.       return copy
  6434.     },
  6435.     unlinkDoc: function(other) {
  6436.       if (other instanceof CodeMirror) { other = other.doc; }
  6437.       if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  6438.         var link = this.linked[i];
  6439.         if (link.doc != other) { continue }
  6440.         this.linked.splice(i, 1);
  6441.         other.unlinkDoc(this);
  6442.         detachSharedMarkers(findSharedMarkers(this));
  6443.         break
  6444.       } }
  6445.       // If the histories were shared, split them again
  6446.       if (other.history == this.history) {
  6447.         var splitIds = [other.id];
  6448.         linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  6449.         other.history = new History(null);
  6450.         other.history.done = copyHistoryArray(this.history.done, splitIds);
  6451.         other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  6452.       }
  6453.     },
  6454.     iterLinkedDocs: function(f) {linkedDocs(this, f);},
  6455.  
  6456.     getMode: function() {return this.mode},
  6457.     getEditor: function() {return this.cm},
  6458.  
  6459.     splitLines: function(str) {
  6460.       if (this.lineSep) { return str.split(this.lineSep) }
  6461.       return splitLinesAuto(str)
  6462.     },
  6463.     lineSeparator: function() { return this.lineSep || "\n" },
  6464.  
  6465.     setDirection: docMethodOp(function (dir) {
  6466.       if (dir != "rtl") { dir = "ltr"; }
  6467.       if (dir == this.direction) { return }
  6468.       this.direction = dir;
  6469.       this.iter(function (line) { return line.order = null; });
  6470.       if (this.cm) { directionChanged(this.cm); }
  6471.     })
  6472.   });
  6473.  
  6474.   // Public alias.
  6475.   Doc.prototype.eachLine = Doc.prototype.iter;
  6476.  
  6477.   // Kludge to work around strange IE behavior where it'll sometimes
  6478.   // re-fire a series of drag-related events right after the drop (#1551)
  6479.   var lastDrop = 0;
  6480.  
  6481.   function onDrop(e) {
  6482.     var cm = this;
  6483.     clearDragCursor(cm);
  6484.     if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  6485.       { return }
  6486.     e_preventDefault(e);
  6487.     if (ie) { lastDrop = +new Date; }
  6488.     var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  6489.     if (!pos || cm.isReadOnly()) { return }
  6490.     // Might be a file drop, in which case we simply extract the text
  6491.     // and insert it.
  6492.     if (files && files.length && window.FileReader && window.File) {
  6493.       var n = files.length, text = Array(n), read = 0;
  6494.       var markAsReadAndPasteIfAllFilesAreRead = function () {
  6495.         if (++read == n) {
  6496.           operation(cm, function () {
  6497.             pos = clipPos(cm.doc, pos);
  6498.             var change = {from: pos, to: pos,
  6499.                           text: cm.doc.splitLines(
  6500.                               text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
  6501.                           origin: "paste"};
  6502.             makeChange(cm.doc, change);
  6503.             setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
  6504.           })();
  6505.         }
  6506.       };
  6507.       var readTextFromFile = function (file, i) {
  6508.         if (cm.options.allowDropFileTypes &&
  6509.             indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
  6510.           markAsReadAndPasteIfAllFilesAreRead();
  6511.           return
  6512.         }
  6513.         var reader = new FileReader;
  6514.         reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
  6515.         reader.onload = function () {
  6516.           var content = reader.result;
  6517.           if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
  6518.             markAsReadAndPasteIfAllFilesAreRead();
  6519.             return
  6520.           }
  6521.           text[i] = content;
  6522.           markAsReadAndPasteIfAllFilesAreRead();
  6523.         };
  6524.         reader.readAsText(file);
  6525.       };
  6526.       for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
  6527.     } else { // Normal drop
  6528.       // Don't do a replace if the drop happened inside of the selected text.
  6529.       if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  6530.         cm.state.draggingText(e);
  6531.         // Ensure the editor is re-focused
  6532.         setTimeout(function () { return cm.display.input.focus(); }, 20);
  6533.         return
  6534.       }
  6535.       try {
  6536.         var text$1 = e.dataTransfer.getData("Text");
  6537.         if (text$1) {
  6538.           var selected;
  6539.           if (cm.state.draggingText && !cm.state.draggingText.copy)
  6540.             { selected = cm.listSelections(); }
  6541.           setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  6542.           if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  6543.             { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  6544.           cm.replaceSelection(text$1, "around", "paste");
  6545.           cm.display.input.focus();
  6546.         }
  6547.       }
  6548.       catch(e){}
  6549.     }
  6550.   }
  6551.  
  6552.   function onDragStart(cm, e) {
  6553.     if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  6554.     if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  6555.  
  6556.     e.dataTransfer.setData("Text", cm.getSelection());
  6557.     e.dataTransfer.effectAllowed = "copyMove";
  6558.  
  6559.     // Use dummy image instead of default browsers image.
  6560.     // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  6561.     if (e.dataTransfer.setDragImage && !safari) {
  6562.       var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  6563.       img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  6564.       if (presto) {
  6565.         img.width = img.height = 1;
  6566.         cm.display.wrapper.appendChild(img);
  6567.         // Force a relayout, or Opera won't use our image for some obscure reason
  6568.         img._top = img.offsetTop;
  6569.       }
  6570.       e.dataTransfer.setDragImage(img, 0, 0);
  6571.       if (presto) { img.parentNode.removeChild(img); }
  6572.     }
  6573.   }
  6574.  
  6575.   function onDragOver(cm, e) {
  6576.     var pos = posFromMouse(cm, e);
  6577.     if (!pos) { return }
  6578.     var frag = document.createDocumentFragment();
  6579.     drawSelectionCursor(cm, pos, frag);
  6580.     if (!cm.display.dragCursor) {
  6581.       cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  6582.       cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  6583.     }
  6584.     removeChildrenAndAdd(cm.display.dragCursor, frag);
  6585.   }
  6586.  
  6587.   function clearDragCursor(cm) {
  6588.     if (cm.display.dragCursor) {
  6589.       cm.display.lineSpace.removeChild(cm.display.dragCursor);
  6590.       cm.display.dragCursor = null;
  6591.     }
  6592.   }
  6593.  
  6594.   // These must be handled carefully, because naively registering a
  6595.   // handler for each editor will cause the editors to never be
  6596.   // garbage collected.
  6597.  
  6598.   function forEachCodeMirror(f) {
  6599.     if (!document.getElementsByClassName) { return }
  6600.     var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
  6601.     for (var i = 0; i < byClass.length; i++) {
  6602.       var cm = byClass[i].CodeMirror;
  6603.       if (cm) { editors.push(cm); }
  6604.     }
  6605.     if (editors.length) { editors[0].operation(function () {
  6606.       for (var i = 0; i < editors.length; i++) { f(editors[i]); }
  6607.     }); }
  6608.   }
  6609.  
  6610.   var globalsRegistered = false;
  6611.   function ensureGlobalHandlers() {
  6612.     if (globalsRegistered) { return }
  6613.     registerGlobalHandlers();
  6614.     globalsRegistered = true;
  6615.   }
  6616.   function registerGlobalHandlers() {
  6617.     // When the window resizes, we need to refresh active editors.
  6618.     var resizeTimer;
  6619.     on(window, "resize", function () {
  6620.       if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  6621.         resizeTimer = null;
  6622.         forEachCodeMirror(onResize);
  6623.       }, 100); }
  6624.     });
  6625.     // When the window loses focus, we want to show the editor as blurred
  6626.     on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  6627.   }
  6628.   // Called when the window resizes
  6629.   function onResize(cm) {
  6630.     var d = cm.display;
  6631.     // Might be a text scaling operation, clear size caches.
  6632.     d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  6633.     d.scrollbarsClipped = false;
  6634.     cm.setSize();
  6635.   }
  6636.  
  6637.   var keyNames = {
  6638.     3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  6639.     19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  6640.     36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  6641.     46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  6642.     106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
  6643.     173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  6644.     221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  6645.     63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  6646.   };
  6647.  
  6648.   // Number keys
  6649.   for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  6650.   // Alphabetic keys
  6651.   for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  6652.   // Function keys
  6653.   for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  6654.  
  6655.   var keyMap = {};
  6656.  
  6657.   keyMap.basic = {
  6658.     "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  6659.     "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  6660.     "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  6661.     "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  6662.     "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  6663.     "Esc": "singleSelection"
  6664.   };
  6665.   // Note that the save and find-related commands aren't defined by
  6666.   // default. User code or addons can define them. Unknown commands
  6667.   // are simply ignored.
  6668.   keyMap.pcDefault = {
  6669.     "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  6670.     "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  6671.     "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  6672.     "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  6673.     "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  6674.     "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  6675.     "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  6676.     "fallthrough": "basic"
  6677.   };
  6678.   // Very basic readline/emacs-style bindings, which are standard on Mac.
  6679.   keyMap.emacsy = {
  6680.     "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  6681.     "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  6682.     "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  6683.     "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  6684.     "Ctrl-O": "openLine"
  6685.   };
  6686.   keyMap.macDefault = {
  6687.     "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  6688.     "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  6689.     "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  6690.     "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  6691.     "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  6692.     "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  6693.     "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  6694.     "fallthrough": ["basic", "emacsy"]
  6695.   };
  6696.   keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  6697.  
  6698.   // KEYMAP DISPATCH
  6699.  
  6700.   function normalizeKeyName(name) {
  6701.     var parts = name.split(/-(?!$)/);
  6702.     name = parts[parts.length - 1];
  6703.     var alt, ctrl, shift, cmd;
  6704.     for (var i = 0; i < parts.length - 1; i++) {
  6705.       var mod = parts[i];
  6706.       if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  6707.       else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  6708.       else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  6709.       else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  6710.       else { throw new Error("Unrecognized modifier name: " + mod) }
  6711.     }
  6712.     if (alt) { name = "Alt-" + name; }
  6713.     if (ctrl) { name = "Ctrl-" + name; }
  6714.     if (cmd) { name = "Cmd-" + name; }
  6715.     if (shift) { name = "Shift-" + name; }
  6716.     return name
  6717.   }
  6718.  
  6719.   // This is a kludge to keep keymaps mostly working as raw objects
  6720.   // (backwards compatibility) while at the same time support features
  6721.   // like normalization and multi-stroke key bindings. It compiles a
  6722.   // new normalized keymap, and then updates the old object to reflect
  6723.   // this.
  6724.   function normalizeKeyMap(keymap) {
  6725.     var copy = {};
  6726.     for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  6727.       var value = keymap[keyname];
  6728.       if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  6729.       if (value == "...") { delete keymap[keyname]; continue }
  6730.  
  6731.       var keys = map(keyname.split(" "), normalizeKeyName);
  6732.       for (var i = 0; i < keys.length; i++) {
  6733.         var val = (void 0), name = (void 0);
  6734.         if (i == keys.length - 1) {
  6735.           name = keys.join(" ");
  6736.           val = value;
  6737.         } else {
  6738.           name = keys.slice(0, i + 1).join(" ");
  6739.           val = "...";
  6740.         }
  6741.         var prev = copy[name];
  6742.         if (!prev) { copy[name] = val; }
  6743.         else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  6744.       }
  6745.       delete keymap[keyname];
  6746.     } }
  6747.     for (var prop in copy) { keymap[prop] = copy[prop]; }
  6748.     return keymap
  6749.   }
  6750.  
  6751.   function lookupKey(key, map, handle, context) {
  6752.     map = getKeyMap(map);
  6753.     var found = map.call ? map.call(key, context) : map[key];
  6754.     if (found === false) { return "nothing" }
  6755.     if (found === "...") { return "multi" }
  6756.     if (found != null && handle(found)) { return "handled" }
  6757.  
  6758.     if (map.fallthrough) {
  6759.       if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  6760.         { return lookupKey(key, map.fallthrough, handle, context) }
  6761.       for (var i = 0; i < map.fallthrough.length; i++) {
  6762.         var result = lookupKey(key, map.fallthrough[i], handle, context);
  6763.         if (result) { return result }
  6764.       }
  6765.     }
  6766.   }
  6767.  
  6768.   // Modifier key presses don't count as 'real' key presses for the
  6769.   // purpose of keymap fallthrough.
  6770.   function isModifierKey(value) {
  6771.     var name = typeof value == "string" ? value : keyNames[value.keyCode];
  6772.     return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  6773.   }
  6774.  
  6775.   function addModifierNames(name, event, noShift) {
  6776.     var base = name;
  6777.     if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  6778.     if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  6779.     if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
  6780.     if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  6781.     return name
  6782.   }
  6783.  
  6784.   // Look up the name of a key as indicated by an event object.
  6785.   function keyName(event, noShift) {
  6786.     if (presto && event.keyCode == 34 && event["char"]) { return false }
  6787.     var name = keyNames[event.keyCode];
  6788.     if (name == null || event.altGraphKey) { return false }
  6789.     // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  6790.     // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  6791.     if (event.keyCode == 3 && event.code) { name = event.code; }
  6792.     return addModifierNames(name, event, noShift)
  6793.   }
  6794.  
  6795.   function getKeyMap(val) {
  6796.     return typeof val == "string" ? keyMap[val] : val
  6797.   }
  6798.  
  6799.   // Helper for deleting text near the selection(s), used to implement
  6800.   // backspace, delete, and similar functionality.
  6801.   function deleteNearSelection(cm, compute) {
  6802.     var ranges = cm.doc.sel.ranges, kill = [];
  6803.     // Build up a set of ranges to kill first, merging overlapping
  6804.     // ranges.
  6805.     for (var i = 0; i < ranges.length; i++) {
  6806.       var toKill = compute(ranges[i]);
  6807.       while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6808.         var replaced = kill.pop();
  6809.         if (cmp(replaced.from, toKill.from) < 0) {
  6810.           toKill.from = replaced.from;
  6811.           break
  6812.         }
  6813.       }
  6814.       kill.push(toKill);
  6815.     }
  6816.     // Next, remove those actual ranges.
  6817.     runInOp(cm, function () {
  6818.       for (var i = kill.length - 1; i >= 0; i--)
  6819.         { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  6820.       ensureCursorVisible(cm);
  6821.     });
  6822.   }
  6823.  
  6824.   function moveCharLogically(line, ch, dir) {
  6825.     var target = skipExtendingChars(line.text, ch + dir, dir);
  6826.     return target < 0 || target > line.text.length ? null : target
  6827.   }
  6828.  
  6829.   function moveLogically(line, start, dir) {
  6830.     var ch = moveCharLogically(line, start.ch, dir);
  6831.     return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  6832.   }
  6833.  
  6834.   function endOfLine(visually, cm, lineObj, lineNo, dir) {
  6835.     if (visually) {
  6836.       if (cm.doc.direction == "rtl") { dir = -dir; }
  6837.       var order = getOrder(lineObj, cm.doc.direction);
  6838.       if (order) {
  6839.         var part = dir < 0 ? lst(order) : order[0];
  6840.         var moveInStorageOrder = (dir < 0) == (part.level == 1);
  6841.         var sticky = moveInStorageOrder ? "after" : "before";
  6842.         var ch;
  6843.         // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  6844.         // it could be that the last bidi part is not on the last visual line,
  6845.         // since visual lines contain content order-consecutive chunks.
  6846.         // Thus, in rtl, we are looking for the first (content-order) character
  6847.         // in the rtl chunk that is on the last line (that is, the same line
  6848.         // as the last (content-order) character).
  6849.         if (part.level > 0 || cm.doc.direction == "rtl") {
  6850.           var prep = prepareMeasureForLine(cm, lineObj);
  6851.           ch = dir < 0 ? lineObj.text.length - 1 : 0;
  6852.           var targetTop = measureCharPrepared(cm, prep, ch).top;
  6853.           ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  6854.           if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  6855.         } else { ch = dir < 0 ? part.to : part.from; }
  6856.         return new Pos(lineNo, ch, sticky)
  6857.       }
  6858.     }
  6859.     return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  6860.   }
  6861.  
  6862.   function moveVisually(cm, line, start, dir) {
  6863.     var bidi = getOrder(line, cm.doc.direction);
  6864.     if (!bidi) { return moveLogically(line, start, dir) }
  6865.     if (start.ch >= line.text.length) {
  6866.       start.ch = line.text.length;
  6867.       start.sticky = "before";
  6868.     } else if (start.ch <= 0) {
  6869.       start.ch = 0;
  6870.       start.sticky = "after";
  6871.     }
  6872.     var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  6873.     if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  6874.       // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  6875.       // nothing interesting happens.
  6876.       return moveLogically(line, start, dir)
  6877.     }
  6878.  
  6879.     var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  6880.     var prep;
  6881.     var getWrappedLineExtent = function (ch) {
  6882.       if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  6883.       prep = prep || prepareMeasureForLine(cm, line);
  6884.       return wrappedLineExtentChar(cm, line, prep, ch)
  6885.     };
  6886.     var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  6887.  
  6888.     if (cm.doc.direction == "rtl" || part.level == 1) {
  6889.       var moveInStorageOrder = (part.level == 1) == (dir < 0);
  6890.       var ch = mv(start, moveInStorageOrder ? 1 : -1);
  6891.       if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  6892.         // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  6893.         var sticky = moveInStorageOrder ? "before" : "after";
  6894.         return new Pos(start.line, ch, sticky)
  6895.       }
  6896.     }
  6897.  
  6898.     // Case 3: Could not move within this bidi part in this visual line, so leave
  6899.     // the current bidi part
  6900.  
  6901.     var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  6902.       var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  6903.         ? new Pos(start.line, mv(ch, 1), "before")
  6904.         : new Pos(start.line, ch, "after"); };
  6905.  
  6906.       for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  6907.         var part = bidi[partPos];
  6908.         var moveInStorageOrder = (dir > 0) == (part.level != 1);
  6909.         var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  6910.         if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  6911.         ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  6912.         if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  6913.       }
  6914.     };
  6915.  
  6916.     // Case 3a: Look for other bidi parts on the same visual line
  6917.     var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  6918.     if (res) { return res }
  6919.  
  6920.     // Case 3b: Look for other bidi parts on the next visual line
  6921.     var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  6922.     if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  6923.       res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  6924.       if (res) { return res }
  6925.     }
  6926.  
  6927.     // Case 4: Nowhere to move
  6928.     return null
  6929.   }
  6930.  
  6931.   // Commands are parameter-less actions that can be performed on an
  6932.   // editor, mostly used for keybindings.
  6933.   var commands = {
  6934.     selectAll: selectAll,
  6935.     singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  6936.     killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  6937.       if (range.empty()) {
  6938.         var len = getLine(cm.doc, range.head.line).text.length;
  6939.         if (range.head.ch == len && range.head.line < cm.lastLine())
  6940.           { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  6941.         else
  6942.           { return {from: range.head, to: Pos(range.head.line, len)} }
  6943.       } else {
  6944.         return {from: range.from(), to: range.to()}
  6945.       }
  6946.     }); },
  6947.     deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6948.       from: Pos(range.from().line, 0),
  6949.       to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  6950.     }); }); },
  6951.     delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6952.       from: Pos(range.from().line, 0), to: range.from()
  6953.     }); }); },
  6954.     delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  6955.       var top = cm.charCoords(range.head, "div").top + 5;
  6956.       var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  6957.       return {from: leftPos, to: range.from()}
  6958.     }); },
  6959.     delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  6960.       var top = cm.charCoords(range.head, "div").top + 5;
  6961.       var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  6962.       return {from: range.from(), to: rightPos }
  6963.     }); },
  6964.     undo: function (cm) { return cm.undo(); },
  6965.     redo: function (cm) { return cm.redo(); },
  6966.     undoSelection: function (cm) { return cm.undoSelection(); },
  6967.     redoSelection: function (cm) { return cm.redoSelection(); },
  6968.     goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  6969.     goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  6970.     goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  6971.       {origin: "+move", bias: 1}
  6972.     ); },
  6973.     goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  6974.       {origin: "+move", bias: 1}
  6975.     ); },
  6976.     goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  6977.       {origin: "+move", bias: -1}
  6978.     ); },
  6979.     goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  6980.       var top = cm.cursorCoords(range.head, "div").top + 5;
  6981.       return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6982.     }, sel_move); },
  6983.     goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  6984.       var top = cm.cursorCoords(range.head, "div").top + 5;
  6985.       return cm.coordsChar({left: 0, top: top}, "div")
  6986.     }, sel_move); },
  6987.     goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  6988.       var top = cm.cursorCoords(range.head, "div").top + 5;
  6989.       var pos = cm.coordsChar({left: 0, top: top}, "div");
  6990.       if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  6991.       return pos
  6992.     }, sel_move); },
  6993.     goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  6994.     goLineDown: function (cm) { return cm.moveV(1, "line"); },
  6995.     goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  6996.     goPageDown: function (cm) { return cm.moveV(1, "page"); },
  6997.     goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  6998.     goCharRight: function (cm) { return cm.moveH(1, "char"); },
  6999.     goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  7000.     goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  7001.     goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  7002.     goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  7003.     goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  7004.     goWordRight: function (cm) { return cm.moveH(1, "word"); },
  7005.     delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  7006.     delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  7007.     delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  7008.     delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  7009.     delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  7010.     delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  7011.     indentAuto: function (cm) { return cm.indentSelection("smart"); },
  7012.     indentMore: function (cm) { return cm.indentSelection("add"); },
  7013.     indentLess: function (cm) { return cm.indentSelection("subtract"); },
  7014.     insertTab: function (cm) { return cm.replaceSelection("\t"); },
  7015.     insertSoftTab: function (cm) {
  7016.       var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  7017.       for (var i = 0; i < ranges.length; i++) {
  7018.         var pos = ranges[i].from();
  7019.         var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  7020.         spaces.push(spaceStr(tabSize - col % tabSize));
  7021.       }
  7022.       cm.replaceSelections(spaces);
  7023.     },
  7024.     defaultTab: function (cm) {
  7025.       if (cm.somethingSelected()) { cm.indentSelection("add"); }
  7026.       else { cm.execCommand("insertTab"); }
  7027.     },
  7028.     // Swap the two chars left and right of each selection's head.
  7029.     // Move cursor behind the two swapped characters afterwards.
  7030.     //
  7031.     // Doesn't consider line feeds a character.
  7032.     // Doesn't scan more than one line above to find a character.
  7033.     // Doesn't do anything on an empty line.
  7034.     // Doesn't do anything with non-empty selections.
  7035.     transposeChars: function (cm) { return runInOp(cm, function () {
  7036.       var ranges = cm.listSelections(), newSel = [];
  7037.       for (var i = 0; i < ranges.length; i++) {
  7038.         if (!ranges[i].empty()) { continue }
  7039.         var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  7040.         if (line) {
  7041.           if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  7042.           if (cur.ch > 0) {
  7043.             cur = new Pos(cur.line, cur.ch + 1);
  7044.             cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  7045.                             Pos(cur.line, cur.ch - 2), cur, "+transpose");
  7046.           } else if (cur.line > cm.doc.first) {
  7047.             var prev = getLine(cm.doc, cur.line - 1).text;
  7048.             if (prev) {
  7049.               cur = new Pos(cur.line, 1);
  7050.               cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  7051.                               prev.charAt(prev.length - 1),
  7052.                               Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  7053.             }
  7054.           }
  7055.         }
  7056.         newSel.push(new Range(cur, cur));
  7057.       }
  7058.       cm.setSelections(newSel);
  7059.     }); },
  7060.     newlineAndIndent: function (cm) { return runInOp(cm, function () {
  7061.       var sels = cm.listSelections();
  7062.       for (var i = sels.length - 1; i >= 0; i--)
  7063.         { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  7064.       sels = cm.listSelections();
  7065.       for (var i$1 = 0; i$1 < sels.length; i$1++)
  7066.         { cm.indentLine(sels[i$1].from().line, null, true); }
  7067.       ensureCursorVisible(cm);
  7068.     }); },
  7069.     openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  7070.     toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  7071.   };
  7072.  
  7073.  
  7074.   function lineStart(cm, lineN) {
  7075.     var line = getLine(cm.doc, lineN);
  7076.     var visual = visualLine(line);
  7077.     if (visual != line) { lineN = lineNo(visual); }
  7078.     return endOfLine(true, cm, visual, lineN, 1)
  7079.   }
  7080.   function lineEnd(cm, lineN) {
  7081.     var line = getLine(cm.doc, lineN);
  7082.     var visual = visualLineEnd(line);
  7083.     if (visual != line) { lineN = lineNo(visual); }
  7084.     return endOfLine(true, cm, line, lineN, -1)
  7085.   }
  7086.   function lineStartSmart(cm, pos) {
  7087.     var start = lineStart(cm, pos.line);
  7088.     var line = getLine(cm.doc, start.line);
  7089.     var order = getOrder(line, cm.doc.direction);
  7090.     if (!order || order[0].level == 0) {
  7091.       var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
  7092.       var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  7093.       return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  7094.     }
  7095.     return start
  7096.   }
  7097.  
  7098.   // Run a handler that was bound to a key.
  7099.   function doHandleBinding(cm, bound, dropShift) {
  7100.     if (typeof bound == "string") {
  7101.       bound = commands[bound];
  7102.       if (!bound) { return false }
  7103.     }
  7104.     // Ensure previous input has been read, so that the handler sees a
  7105.     // consistent view of the document
  7106.     cm.display.input.ensurePolled();
  7107.     var prevShift = cm.display.shift, done = false;
  7108.     try {
  7109.       if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  7110.       if (dropShift) { cm.display.shift = false; }
  7111.       done = bound(cm) != Pass;
  7112.     } finally {
  7113.       cm.display.shift = prevShift;
  7114.       cm.state.suppressEdits = false;
  7115.     }
  7116.     return done
  7117.   }
  7118.  
  7119.   function lookupKeyForEditor(cm, name, handle) {
  7120.     for (var i = 0; i < cm.state.keyMaps.length; i++) {
  7121.       var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  7122.       if (result) { return result }
  7123.     }
  7124.     return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  7125.       || lookupKey(name, cm.options.keyMap, handle, cm)
  7126.   }
  7127.  
  7128.   // Note that, despite the name, this function is also used to check
  7129.   // for bound mouse clicks.
  7130.  
  7131.   var stopSeq = new Delayed;
  7132.  
  7133.   function dispatchKey(cm, name, e, handle) {
  7134.     var seq = cm.state.keySeq;
  7135.     if (seq) {
  7136.       if (isModifierKey(name)) { return "handled" }
  7137.       if (/\'$/.test(name))
  7138.         { cm.state.keySeq = null; }
  7139.       else
  7140.         { stopSeq.set(50, function () {
  7141.           if (cm.state.keySeq == seq) {
  7142.             cm.state.keySeq = null;
  7143.             cm.display.input.reset();
  7144.           }
  7145.         }); }
  7146.       if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  7147.     }
  7148.     return dispatchKeyInner(cm, name, e, handle)
  7149.   }
  7150.  
  7151.   function dispatchKeyInner(cm, name, e, handle) {
  7152.     var result = lookupKeyForEditor(cm, name, handle);
  7153.  
  7154.     if (result == "multi")
  7155.       { cm.state.keySeq = name; }
  7156.     if (result == "handled")
  7157.       { signalLater(cm, "keyHandled", cm, name, e); }
  7158.  
  7159.     if (result == "handled" || result == "multi") {
  7160.       e_preventDefault(e);
  7161.       restartBlink(cm);
  7162.     }
  7163.  
  7164.     return !!result
  7165.   }
  7166.  
  7167.   // Handle a key from the keydown event.
  7168.   function handleKeyBinding(cm, e) {
  7169.     var name = keyName(e, true);
  7170.     if (!name) { return false }
  7171.  
  7172.     if (e.shiftKey && !cm.state.keySeq) {
  7173.       // First try to resolve full name (including 'Shift-'). Failing
  7174.       // that, see if there is a cursor-motion command (starting with
  7175.       // 'go') bound to the keyname without 'Shift-'.
  7176.       return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  7177.           || dispatchKey(cm, name, e, function (b) {
  7178.                if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  7179.                  { return doHandleBinding(cm, b) }
  7180.              })
  7181.     } else {
  7182.       return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  7183.     }
  7184.   }
  7185.  
  7186.   // Handle a key from the keypress event
  7187.   function handleCharBinding(cm, e, ch) {
  7188.     return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  7189.   }
  7190.  
  7191.   var lastStoppedKey = null;
  7192.   function onKeyDown(e) {
  7193.     var cm = this;
  7194.     if (e.target && e.target != cm.display.input.getField()) { return }
  7195.     cm.curOp.focus = activeElt();
  7196.     if (signalDOMEvent(cm, e)) { return }
  7197.     // IE does strange things with escape.
  7198.     if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  7199.     var code = e.keyCode;
  7200.     cm.display.shift = code == 16 || e.shiftKey;
  7201.     var handled = handleKeyBinding(cm, e);
  7202.     if (presto) {
  7203.       lastStoppedKey = handled ? code : null;
  7204.       // Opera has no cut event... we try to at least catch the key combo
  7205.       if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  7206.         { cm.replaceSelection("", null, "cut"); }
  7207.     }
  7208.     if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
  7209.       { document.execCommand("cut"); }
  7210.  
  7211.     // Turn mouse into crosshair when Alt is held on Mac.
  7212.     if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  7213.       { showCrossHair(cm); }
  7214.   }
  7215.  
  7216.   function showCrossHair(cm) {
  7217.     var lineDiv = cm.display.lineDiv;
  7218.     addClass(lineDiv, "CodeMirror-crosshair");
  7219.  
  7220.     function up(e) {
  7221.       if (e.keyCode == 18 || !e.altKey) {
  7222.         rmClass(lineDiv, "CodeMirror-crosshair");
  7223.         off(document, "keyup", up);
  7224.         off(document, "mouseover", up);
  7225.       }
  7226.     }
  7227.     on(document, "keyup", up);
  7228.     on(document, "mouseover", up);
  7229.   }
  7230.  
  7231.   function onKeyUp(e) {
  7232.     if (e.keyCode == 16) { this.doc.sel.shift = false; }
  7233.     signalDOMEvent(this, e);
  7234.   }
  7235.  
  7236.   function onKeyPress(e) {
  7237.     var cm = this;
  7238.     if (e.target && e.target != cm.display.input.getField()) { return }
  7239.     if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  7240.     var keyCode = e.keyCode, charCode = e.charCode;
  7241.     if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  7242.     if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  7243.     var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  7244.     // Some browsers fire keypress events for backspace
  7245.     if (ch == "\x08") { return }
  7246.     if (handleCharBinding(cm, e, ch)) { return }
  7247.     cm.display.input.onKeyPress(e);
  7248.   }
  7249.  
  7250.   var DOUBLECLICK_DELAY = 400;
  7251.  
  7252.   var PastClick = function(time, pos, button) {
  7253.     this.time = time;
  7254.     this.pos = pos;
  7255.     this.button = button;
  7256.   };
  7257.  
  7258.   PastClick.prototype.compare = function (time, pos, button) {
  7259.     return this.time + DOUBLECLICK_DELAY > time &&
  7260.       cmp(pos, this.pos) == 0 && button == this.button
  7261.   };
  7262.  
  7263.   var lastClick, lastDoubleClick;
  7264.   function clickRepeat(pos, button) {
  7265.     var now = +new Date;
  7266.     if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  7267.       lastClick = lastDoubleClick = null;
  7268.       return "triple"
  7269.     } else if (lastClick && lastClick.compare(now, pos, button)) {
  7270.       lastDoubleClick = new PastClick(now, pos, button);
  7271.       lastClick = null;
  7272.       return "double"
  7273.     } else {
  7274.       lastClick = new PastClick(now, pos, button);
  7275.       lastDoubleClick = null;
  7276.       return "single"
  7277.     }
  7278.   }
  7279.  
  7280.   // A mouse down can be a single click, double click, triple click,
  7281.   // start of selection drag, start of text drag, new cursor
  7282.   // (ctrl-click), rectangle drag (alt-drag), or xwin
  7283.   // middle-click-paste. Or it might be a click on something we should
  7284.   // not interfere with, such as a scrollbar or widget.
  7285.   function onMouseDown(e) {
  7286.     var cm = this, display = cm.display;
  7287.     if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  7288.     display.input.ensurePolled();
  7289.     display.shift = e.shiftKey;
  7290.  
  7291.     if (eventInWidget(display, e)) {
  7292.       if (!webkit) {
  7293.         // Briefly turn off draggability, to allow widgets to do
  7294.         // normal dragging things.
  7295.         display.scroller.draggable = false;
  7296.         setTimeout(function () { return display.scroller.draggable = true; }, 100);
  7297.       }
  7298.       return
  7299.     }
  7300.     if (clickInGutter(cm, e)) { return }
  7301.     var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  7302.     window.focus();
  7303.  
  7304.     // #3261: make sure, that we're not starting a second selection
  7305.     if (button == 1 && cm.state.selectingText)
  7306.       { cm.state.selectingText(e); }
  7307.  
  7308.     if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  7309.  
  7310.     if (button == 1) {
  7311.       if (pos) { leftButtonDown(cm, pos, repeat, e); }
  7312.       else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  7313.     } else if (button == 2) {
  7314.       if (pos) { extendSelection(cm.doc, pos); }
  7315.       setTimeout(function () { return display.input.focus(); }, 20);
  7316.     } else if (button == 3) {
  7317.       if (captureRightClick) { cm.display.input.onContextMenu(e); }
  7318.       else { delayBlurEvent(cm); }
  7319.     }
  7320.   }
  7321.  
  7322.   function handleMappedButton(cm, button, pos, repeat, event) {
  7323.     var name = "Click";
  7324.     if (repeat == "double") { name = "Double" + name; }
  7325.     else if (repeat == "triple") { name = "Triple" + name; }
  7326.     name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  7327.  
  7328.     return dispatchKey(cm,  addModifierNames(name, event), event, function (bound) {
  7329.       if (typeof bound == "string") { bound = commands[bound]; }
  7330.       if (!bound) { return false }
  7331.       var done = false;
  7332.       try {
  7333.         if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  7334.         done = bound(cm, pos) != Pass;
  7335.       } finally {
  7336.         cm.state.suppressEdits = false;
  7337.       }
  7338.       return done
  7339.     })
  7340.   }
  7341.  
  7342.   function configureMouse(cm, repeat, event) {
  7343.     var option = cm.getOption("configureMouse");
  7344.     var value = option ? option(cm, repeat, event) : {};
  7345.     if (value.unit == null) {
  7346.       var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  7347.       value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  7348.     }
  7349.     if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  7350.     if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  7351.     if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  7352.     return value
  7353.   }
  7354.  
  7355.   function leftButtonDown(cm, pos, repeat, event) {
  7356.     if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  7357.     else { cm.curOp.focus = activeElt(); }
  7358.  
  7359.     var behavior = configureMouse(cm, repeat, event);
  7360.  
  7361.     var sel = cm.doc.sel, contained;
  7362.     if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  7363.         repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  7364.         (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  7365.         (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  7366.       { leftButtonStartDrag(cm, event, pos, behavior); }
  7367.     else
  7368.       { leftButtonSelect(cm, event, pos, behavior); }
  7369.   }
  7370.  
  7371.   // Start a text drag. When it ends, see if any dragging actually
  7372.   // happen, and treat as a click if it didn't.
  7373.   function leftButtonStartDrag(cm, event, pos, behavior) {
  7374.     var display = cm.display, moved = false;
  7375.     var dragEnd = operation(cm, function (e) {
  7376.       if (webkit) { display.scroller.draggable = false; }
  7377.       cm.state.draggingText = false;
  7378.       off(display.wrapper.ownerDocument, "mouseup", dragEnd);
  7379.       off(display.wrapper.ownerDocument, "mousemove", mouseMove);
  7380.       off(display.scroller, "dragstart", dragStart);
  7381.       off(display.scroller, "drop", dragEnd);
  7382.       if (!moved) {
  7383.         e_preventDefault(e);
  7384.         if (!behavior.addNew)
  7385.           { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  7386.         // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  7387.         if ((webkit && !safari) || ie && ie_version == 9)
  7388.           { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
  7389.         else
  7390.           { display.input.focus(); }
  7391.       }
  7392.     });
  7393.     var mouseMove = function(e2) {
  7394.       moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  7395.     };
  7396.     var dragStart = function () { return moved = true; };
  7397.     // Let the drag handler handle this.
  7398.     if (webkit) { display.scroller.draggable = true; }
  7399.     cm.state.draggingText = dragEnd;
  7400.     dragEnd.copy = !behavior.moveOnDrag;
  7401.     // IE's approach to draggable
  7402.     if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  7403.     on(display.wrapper.ownerDocument, "mouseup", dragEnd);
  7404.     on(display.wrapper.ownerDocument, "mousemove", mouseMove);
  7405.     on(display.scroller, "dragstart", dragStart);
  7406.     on(display.scroller, "drop", dragEnd);
  7407.  
  7408.     delayBlurEvent(cm);
  7409.     setTimeout(function () { return display.input.focus(); }, 20);
  7410.   }
  7411.  
  7412.   function rangeForUnit(cm, pos, unit) {
  7413.     if (unit == "char") { return new Range(pos, pos) }
  7414.     if (unit == "word") { return cm.findWordAt(pos) }
  7415.     if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  7416.     var result = unit(cm, pos);
  7417.     return new Range(result.from, result.to)
  7418.   }
  7419.  
  7420.   // Normal selection, as opposed to text dragging.
  7421.   function leftButtonSelect(cm, event, start, behavior) {
  7422.     var display = cm.display, doc = cm.doc;
  7423.     e_preventDefault(event);
  7424.  
  7425.     var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  7426.     if (behavior.addNew && !behavior.extend) {
  7427.       ourIndex = doc.sel.contains(start);
  7428.       if (ourIndex > -1)
  7429.         { ourRange = ranges[ourIndex]; }
  7430.       else
  7431.         { ourRange = new Range(start, start); }
  7432.     } else {
  7433.       ourRange = doc.sel.primary();
  7434.       ourIndex = doc.sel.primIndex;
  7435.     }
  7436.  
  7437.     if (behavior.unit == "rectangle") {
  7438.       if (!behavior.addNew) { ourRange = new Range(start, start); }
  7439.       start = posFromMouse(cm, event, true, true);
  7440.       ourIndex = -1;
  7441.     } else {
  7442.       var range = rangeForUnit(cm, start, behavior.unit);
  7443.       if (behavior.extend)
  7444.         { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
  7445.       else
  7446.         { ourRange = range; }
  7447.     }
  7448.  
  7449.     if (!behavior.addNew) {
  7450.       ourIndex = 0;
  7451.       setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  7452.       startSel = doc.sel;
  7453.     } else if (ourIndex == -1) {
  7454.       ourIndex = ranges.length;
  7455.       setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
  7456.                    {scroll: false, origin: "*mouse"});
  7457.     } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  7458.       setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  7459.                    {scroll: false, origin: "*mouse"});
  7460.       startSel = doc.sel;
  7461.     } else {
  7462.       replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  7463.     }
  7464.  
  7465.     var lastPos = start;
  7466.     function extendTo(pos) {
  7467.       if (cmp(lastPos, pos) == 0) { return }
  7468.       lastPos = pos;
  7469.  
  7470.       if (behavior.unit == "rectangle") {
  7471.         var ranges = [], tabSize = cm.options.tabSize;
  7472.         var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  7473.         var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  7474.         var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  7475.         for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  7476.              line <= end; line++) {
  7477.           var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  7478.           if (left == right)
  7479.             { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  7480.           else if (text.length > leftPos)
  7481.             { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  7482.         }
  7483.         if (!ranges.length) { ranges.push(new Range(start, start)); }
  7484.         setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  7485.                      {origin: "*mouse", scroll: false});
  7486.         cm.scrollIntoView(pos);
  7487.       } else {
  7488.         var oldRange = ourRange;
  7489.         var range = rangeForUnit(cm, pos, behavior.unit);
  7490.         var anchor = oldRange.anchor, head;
  7491.         if (cmp(range.anchor, anchor) > 0) {
  7492.           head = range.head;
  7493.           anchor = minPos(oldRange.from(), range.anchor);
  7494.         } else {
  7495.           head = range.anchor;
  7496.           anchor = maxPos(oldRange.to(), range.head);
  7497.         }
  7498.         var ranges$1 = startSel.ranges.slice(0);
  7499.         ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
  7500.         setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
  7501.       }
  7502.     }
  7503.  
  7504.     var editorSize = display.wrapper.getBoundingClientRect();
  7505.     // Used to ensure timeout re-tries don't fire when another extend
  7506.     // happened in the meantime (clearTimeout isn't reliable -- at
  7507.     // least on Chrome, the timeouts still happen even when cleared,
  7508.     // if the clear happens after their scheduled firing time).
  7509.     var counter = 0;
  7510.  
  7511.     function extend(e) {
  7512.       var curCount = ++counter;
  7513.       var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  7514.       if (!cur) { return }
  7515.       if (cmp(cur, lastPos) != 0) {
  7516.         cm.curOp.focus = activeElt();
  7517.         extendTo(cur);
  7518.         var visible = visibleLines(display, doc);
  7519.         if (cur.line >= visible.to || cur.line < visible.from)
  7520.           { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  7521.       } else {
  7522.         var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  7523.         if (outside) { setTimeout(operation(cm, function () {
  7524.           if (counter != curCount) { return }
  7525.           display.scroller.scrollTop += outside;
  7526.           extend(e);
  7527.         }), 50); }
  7528.       }
  7529.     }
  7530.  
  7531.     function done(e) {
  7532.       cm.state.selectingText = false;
  7533.       counter = Infinity;
  7534.       // If e is null or undefined we interpret this as someone trying
  7535.       // to explicitly cancel the selection rather than the user
  7536.       // letting go of the mouse button.
  7537.       if (e) {
  7538.         e_preventDefault(e);
  7539.         display.input.focus();
  7540.       }
  7541.       off(display.wrapper.ownerDocument, "mousemove", move);
  7542.       off(display.wrapper.ownerDocument, "mouseup", up);
  7543.       doc.history.lastSelOrigin = null;
  7544.     }
  7545.  
  7546.     var move = operation(cm, function (e) {
  7547.       if (e.buttons === 0 || !e_button(e)) { done(e); }
  7548.       else { extend(e); }
  7549.     });
  7550.     var up = operation(cm, done);
  7551.     cm.state.selectingText = up;
  7552.     on(display.wrapper.ownerDocument, "mousemove", move);
  7553.     on(display.wrapper.ownerDocument, "mouseup", up);
  7554.   }
  7555.  
  7556.   // Used when mouse-selecting to adjust the anchor to the proper side
  7557.   // of a bidi jump depending on the visual position of the head.
  7558.   function bidiSimplify(cm, range) {
  7559.     var anchor = range.anchor;
  7560.     var head = range.head;
  7561.     var anchorLine = getLine(cm.doc, anchor.line);
  7562.     if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
  7563.     var order = getOrder(anchorLine);
  7564.     if (!order) { return range }
  7565.     var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  7566.     if (part.from != anchor.ch && part.to != anchor.ch) { return range }
  7567.     var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  7568.     if (boundary == 0 || boundary == order.length) { return range }
  7569.  
  7570.     // Compute the relative visual position of the head compared to the
  7571.     // anchor (<0 is to the left, >0 to the right)
  7572.     var leftSide;
  7573.     if (head.line != anchor.line) {
  7574.       leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  7575.     } else {
  7576.       var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  7577.       var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  7578.       if (headIndex == boundary - 1 || headIndex == boundary)
  7579.         { leftSide = dir < 0; }
  7580.       else
  7581.         { leftSide = dir > 0; }
  7582.     }
  7583.  
  7584.     var usePart = order[boundary + (leftSide ? -1 : 0)];
  7585.     var from = leftSide == (usePart.level == 1);
  7586.     var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  7587.     return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  7588.   }
  7589.  
  7590.  
  7591.   // Determines whether an event happened in the gutter, and fires the
  7592.   // handlers for the corresponding event.
  7593.   function gutterEvent(cm, e, type, prevent) {
  7594.     var mX, mY;
  7595.     if (e.touches) {
  7596.       mX = e.touches[0].clientX;
  7597.       mY = e.touches[0].clientY;
  7598.     } else {
  7599.       try { mX = e.clientX; mY = e.clientY; }
  7600.       catch(e) { return false }
  7601.     }
  7602.     if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  7603.     if (prevent) { e_preventDefault(e); }
  7604.  
  7605.     var display = cm.display;
  7606.     var lineBox = display.lineDiv.getBoundingClientRect();
  7607.  
  7608.     if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  7609.     mY -= lineBox.top - display.viewOffset;
  7610.  
  7611.     for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
  7612.       var g = display.gutters.childNodes[i];
  7613.       if (g && g.getBoundingClientRect().right >= mX) {
  7614.         var line = lineAtHeight(cm.doc, mY);
  7615.         var gutter = cm.display.gutterSpecs[i];
  7616.         signal(cm, type, cm, line, gutter.className, e);
  7617.         return e_defaultPrevented(e)
  7618.       }
  7619.     }
  7620.   }
  7621.  
  7622.   function clickInGutter(cm, e) {
  7623.     return gutterEvent(cm, e, "gutterClick", true)
  7624.   }
  7625.  
  7626.   // CONTEXT MENU HANDLING
  7627.  
  7628.   // To make the context menu work, we need to briefly unhide the
  7629.   // textarea (making it as unobtrusive as possible) to let the
  7630.   // right-click take effect on it.
  7631.   function onContextMenu(cm, e) {
  7632.     if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  7633.     if (signalDOMEvent(cm, e, "contextmenu")) { return }
  7634.     if (!captureRightClick) { cm.display.input.onContextMenu(e); }
  7635.   }
  7636.  
  7637.   function contextMenuInGutter(cm, e) {
  7638.     if (!hasHandler(cm, "gutterContextMenu")) { return false }
  7639.     return gutterEvent(cm, e, "gutterContextMenu", false)
  7640.   }
  7641.  
  7642.   function themeChanged(cm) {
  7643.     cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  7644.       cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  7645.     clearCaches(cm);
  7646.   }
  7647.  
  7648.   var Init = {toString: function(){return "CodeMirror.Init"}};
  7649.  
  7650.   var defaults = {};
  7651.   var optionHandlers = {};
  7652.  
  7653.   function defineOptions(CodeMirror) {
  7654.     var optionHandlers = CodeMirror.optionHandlers;
  7655.  
  7656.     function option(name, deflt, handle, notOnInit) {
  7657.       CodeMirror.defaults[name] = deflt;
  7658.       if (handle) { optionHandlers[name] =
  7659.         notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  7660.     }
  7661.  
  7662.     CodeMirror.defineOption = option;
  7663.  
  7664.     // Passed to option handlers when there is no old value.
  7665.     CodeMirror.Init = Init;
  7666.  
  7667.     // These two are, on init, called from the constructor because they
  7668.     // have to be initialized before the editor can start at all.
  7669.     option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  7670.     option("mode", null, function (cm, val) {
  7671.       cm.doc.modeOption = val;
  7672.       loadMode(cm);
  7673.     }, true);
  7674.  
  7675.     option("indentUnit", 2, loadMode, true);
  7676.     option("indentWithTabs", false);
  7677.     option("smartIndent", true);
  7678.     option("tabSize", 4, function (cm) {
  7679.       resetModeState(cm);
  7680.       clearCaches(cm);
  7681.       regChange(cm);
  7682.     }, true);
  7683.  
  7684.     option("lineSeparator", null, function (cm, val) {
  7685.       cm.doc.lineSep = val;
  7686.       if (!val) { return }
  7687.       var newBreaks = [], lineNo = cm.doc.first;
  7688.       cm.doc.iter(function (line) {
  7689.         for (var pos = 0;;) {
  7690.           var found = line.text.indexOf(val, pos);
  7691.           if (found == -1) { break }
  7692.           pos = found + val.length;
  7693.           newBreaks.push(Pos(lineNo, found));
  7694.         }
  7695.         lineNo++;
  7696.       });
  7697.       for (var i = newBreaks.length - 1; i >= 0; i--)
  7698.         { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  7699.     });
  7700.     option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
  7701.       cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  7702.       if (old != Init) { cm.refresh(); }
  7703.     });
  7704.     option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  7705.     option("electricChars", true);
  7706.     option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  7707.       throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  7708.     }, true);
  7709.     option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  7710.     option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
  7711.     option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
  7712.     option("rtlMoveVisually", !windows);
  7713.     option("wholeLineUpdateBefore", true);
  7714.  
  7715.     option("theme", "default", function (cm) {
  7716.       themeChanged(cm);
  7717.       updateGutters(cm);
  7718.     }, true);
  7719.     option("keyMap", "default", function (cm, val, old) {
  7720.       var next = getKeyMap(val);
  7721.       var prev = old != Init && getKeyMap(old);
  7722.       if (prev && prev.detach) { prev.detach(cm, next); }
  7723.       if (next.attach) { next.attach(cm, prev || null); }
  7724.     });
  7725.     option("extraKeys", null);
  7726.     option("configureMouse", null);
  7727.  
  7728.     option("lineWrapping", false, wrappingChanged, true);
  7729.     option("gutters", [], function (cm, val) {
  7730.       cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
  7731.       updateGutters(cm);
  7732.     }, true);
  7733.     option("fixedGutter", true, function (cm, val) {
  7734.       cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  7735.       cm.refresh();
  7736.     }, true);
  7737.     option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  7738.     option("scrollbarStyle", "native", function (cm) {
  7739.       initScrollbars(cm);
  7740.       updateScrollbars(cm);
  7741.       cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  7742.       cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  7743.     }, true);
  7744.     option("lineNumbers", false, function (cm, val) {
  7745.       cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
  7746.       updateGutters(cm);
  7747.     }, true);
  7748.     option("firstLineNumber", 1, updateGutters, true);
  7749.     option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
  7750.     option("showCursorWhenSelecting", false, updateSelection, true);
  7751.  
  7752.     option("resetSelectionOnContextMenu", true);
  7753.     option("lineWiseCopyCut", true);
  7754.     option("pasteLinesPerSelection", true);
  7755.     option("selectionsMayTouch", false);
  7756.  
  7757.     option("readOnly", false, function (cm, val) {
  7758.       if (val == "nocursor") {
  7759.         onBlur(cm);
  7760.         cm.display.input.blur();
  7761.       }
  7762.       cm.display.input.readOnlyChanged(val);
  7763.     });
  7764.  
  7765.     option("screenReaderLabel", null, function (cm, val) {
  7766.       val = (val === '') ? null : val;
  7767.       cm.display.input.screenReaderLabelChanged(val);
  7768.     });
  7769.  
  7770.     option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  7771.     option("dragDrop", true, dragDropChanged);
  7772.     option("allowDropFileTypes", null);
  7773.  
  7774.     option("cursorBlinkRate", 530);
  7775.     option("cursorScrollMargin", 0);
  7776.     option("cursorHeight", 1, updateSelection, true);
  7777.     option("singleCursorHeightPerLine", true, updateSelection, true);
  7778.     option("workTime", 100);
  7779.     option("workDelay", 100);
  7780.     option("flattenSpans", true, resetModeState, true);
  7781.     option("addModeClass", false, resetModeState, true);
  7782.     option("pollInterval", 100);
  7783.     option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  7784.     option("historyEventDelay", 1250);
  7785.     option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  7786.     option("maxHighlightLength", 10000, resetModeState, true);
  7787.     option("moveInputWithCursor", true, function (cm, val) {
  7788.       if (!val) { cm.display.input.resetPosition(); }
  7789.     });
  7790.  
  7791.     option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  7792.     option("autofocus", null);
  7793.     option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  7794.     option("phrases", null);
  7795.   }
  7796.  
  7797.   function dragDropChanged(cm, value, old) {
  7798.     var wasOn = old && old != Init;
  7799.     if (!value != !wasOn) {
  7800.       var funcs = cm.display.dragFunctions;
  7801.       var toggle = value ? on : off;
  7802.       toggle(cm.display.scroller, "dragstart", funcs.start);
  7803.       toggle(cm.display.scroller, "dragenter", funcs.enter);
  7804.       toggle(cm.display.scroller, "dragover", funcs.over);
  7805.       toggle(cm.display.scroller, "dragleave", funcs.leave);
  7806.       toggle(cm.display.scroller, "drop", funcs.drop);
  7807.     }
  7808.   }
  7809.  
  7810.   function wrappingChanged(cm) {
  7811.     if (cm.options.lineWrapping) {
  7812.       addClass(cm.display.wrapper, "CodeMirror-wrap");
  7813.       cm.display.sizer.style.minWidth = "";
  7814.       cm.display.sizerWidth = null;
  7815.     } else {
  7816.       rmClass(cm.display.wrapper, "CodeMirror-wrap");
  7817.       findMaxLine(cm);
  7818.     }
  7819.     estimateLineHeights(cm);
  7820.     regChange(cm);
  7821.     clearCaches(cm);
  7822.     setTimeout(function () { return updateScrollbars(cm); }, 100);
  7823.   }
  7824.  
  7825.   // A CodeMirror instance represents an editor. This is the object
  7826.   // that user code is usually dealing with.
  7827.  
  7828.   function CodeMirror(place, options) {
  7829.     var this$1 = this;
  7830.  
  7831.     if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  7832.  
  7833.     this.options = options = options ? copyObj(options) : {};
  7834.     // Determine effective options based on given values and defaults.
  7835.     copyObj(defaults, options, false);
  7836.  
  7837.     var doc = options.value;
  7838.     if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  7839.     else if (options.mode) { doc.modeOption = options.mode; }
  7840.     this.doc = doc;
  7841.  
  7842.     var input = new CodeMirror.inputStyles[options.inputStyle](this);
  7843.     var display = this.display = new Display(place, doc, input, options);
  7844.     display.wrapper.CodeMirror = this;
  7845.     themeChanged(this);
  7846.     if (options.lineWrapping)
  7847.       { this.display.wrapper.className += " CodeMirror-wrap"; }
  7848.     initScrollbars(this);
  7849.  
  7850.     this.state = {
  7851.       keyMaps: [],  // stores maps added by addKeyMap
  7852.       overlays: [], // highlighting overlays, as added by addOverlay
  7853.       modeGen: 0,   // bumped when mode/overlay changes, used to invalidate highlighting info
  7854.       overwrite: false,
  7855.       delayingBlurEvent: false,
  7856.       focused: false,
  7857.       suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  7858.       pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
  7859.       selectingText: false,
  7860.       draggingText: false,
  7861.       highlight: new Delayed(), // stores highlight worker timeout
  7862.       keySeq: null,  // Unfinished key sequence
  7863.       specialChars: null
  7864.     };
  7865.  
  7866.     if (options.autofocus && !mobile) { display.input.focus(); }
  7867.  
  7868.     // Override magic textarea content restore that IE sometimes does
  7869.     // on our hidden textarea on reload
  7870.     if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  7871.  
  7872.     registerEventHandlers(this);
  7873.     ensureGlobalHandlers();
  7874.  
  7875.     startOperation(this);
  7876.     this.curOp.forceUpdate = true;
  7877.     attachDoc(this, doc);
  7878.  
  7879.     if ((options.autofocus && !mobile) || this.hasFocus())
  7880.       { setTimeout(bind(onFocus, this), 20); }
  7881.     else
  7882.       { onBlur(this); }
  7883.  
  7884.     for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  7885.       { optionHandlers[opt](this, options[opt], Init); } }
  7886.     maybeUpdateLineNumberWidth(this);
  7887.     if (options.finishInit) { options.finishInit(this); }
  7888.     for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
  7889.     endOperation(this);
  7890.     // Suppress optimizelegibility in Webkit, since it breaks text
  7891.     // measuring on line wrapping boundaries.
  7892.     if (webkit && options.lineWrapping &&
  7893.         getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  7894.       { display.lineDiv.style.textRendering = "auto"; }
  7895.   }
  7896.  
  7897.   // The default configuration options.
  7898.   CodeMirror.defaults = defaults;
  7899.   // Functions to run when options are changed.
  7900.   CodeMirror.optionHandlers = optionHandlers;
  7901.  
  7902.   // Attach the necessary event handlers when initializing the editor
  7903.   function registerEventHandlers(cm) {
  7904.     var d = cm.display;
  7905.     on(d.scroller, "mousedown", operation(cm, onMouseDown));
  7906.     // Older IE's will not fire a second mousedown for a double click
  7907.     if (ie && ie_version < 11)
  7908.       { on(d.scroller, "dblclick", operation(cm, function (e) {
  7909.         if (signalDOMEvent(cm, e)) { return }
  7910.         var pos = posFromMouse(cm, e);
  7911.         if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  7912.         e_preventDefault(e);
  7913.         var word = cm.findWordAt(pos);
  7914.         extendSelection(cm.doc, word.anchor, word.head);
  7915.       })); }
  7916.     else
  7917.       { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  7918.     // Some browsers fire contextmenu *after* opening the menu, at
  7919.     // which point we can't mess with it anymore. Context menu is
  7920.     // handled in onMouseDown for these browsers.
  7921.     on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
  7922.     on(d.input.getField(), "contextmenu", function (e) {
  7923.       if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
  7924.     });
  7925.  
  7926.     // Used to suppress mouse event handling when a touch happens
  7927.     var touchFinished, prevTouch = {end: 0};
  7928.     function finishTouch() {
  7929.       if (d.activeTouch) {
  7930.         touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  7931.         prevTouch = d.activeTouch;
  7932.         prevTouch.end = +new Date;
  7933.       }
  7934.     }
  7935.     function isMouseLikeTouchEvent(e) {
  7936.       if (e.touches.length != 1) { return false }
  7937.       var touch = e.touches[0];
  7938.       return touch.radiusX <= 1 && touch.radiusY <= 1
  7939.     }
  7940.     function farAway(touch, other) {
  7941.       if (other.left == null) { return true }
  7942.       var dx = other.left - touch.left, dy = other.top - touch.top;
  7943.       return dx * dx + dy * dy > 20 * 20
  7944.     }
  7945.     on(d.scroller, "touchstart", function (e) {
  7946.       if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  7947.         d.input.ensurePolled();
  7948.         clearTimeout(touchFinished);
  7949.         var now = +new Date;
  7950.         d.activeTouch = {start: now, moved: false,
  7951.                          prev: now - prevTouch.end <= 300 ? prevTouch : null};
  7952.         if (e.touches.length == 1) {
  7953.           d.activeTouch.left = e.touches[0].pageX;
  7954.           d.activeTouch.top = e.touches[0].pageY;
  7955.         }
  7956.       }
  7957.     });
  7958.     on(d.scroller, "touchmove", function () {
  7959.       if (d.activeTouch) { d.activeTouch.moved = true; }
  7960.     });
  7961.     on(d.scroller, "touchend", function (e) {
  7962.       var touch = d.activeTouch;
  7963.       if (touch && !eventInWidget(d, e) && touch.left != null &&
  7964.           !touch.moved && new Date - touch.start < 300) {
  7965.         var pos = cm.coordsChar(d.activeTouch, "page"), range;
  7966.         if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  7967.           { range = new Range(pos, pos); }
  7968.         else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  7969.           { range = cm.findWordAt(pos); }
  7970.         else // Triple tap
  7971.           { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  7972.         cm.setSelection(range.anchor, range.head);
  7973.         cm.focus();
  7974.         e_preventDefault(e);
  7975.       }
  7976.       finishTouch();
  7977.     });
  7978.     on(d.scroller, "touchcancel", finishTouch);
  7979.  
  7980.     // Sync scrolling between fake scrollbars and real scrollable
  7981.     // area, ensure viewport is updated when scrolling.
  7982.     on(d.scroller, "scroll", function () {
  7983.       if (d.scroller.clientHeight) {
  7984.         updateScrollTop(cm, d.scroller.scrollTop);
  7985.         setScrollLeft(cm, d.scroller.scrollLeft, true);
  7986.         signal(cm, "scroll", cm);
  7987.       }
  7988.     });
  7989.  
  7990.     // Listen to wheel events in order to try and update the viewport on time.
  7991.     on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  7992.     on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  7993.  
  7994.     // Prevent wrapper from ever scrolling
  7995.     on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  7996.  
  7997.     d.dragFunctions = {
  7998.       enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  7999.       over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  8000.       start: function (e) { return onDragStart(cm, e); },
  8001.       drop: operation(cm, onDrop),
  8002.       leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  8003.     };
  8004.  
  8005.     var inp = d.input.getField();
  8006.     on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  8007.     on(inp, "keydown", operation(cm, onKeyDown));
  8008.     on(inp, "keypress", operation(cm, onKeyPress));
  8009.     on(inp, "focus", function (e) { return onFocus(cm, e); });
  8010.     on(inp, "blur", function (e) { return onBlur(cm, e); });
  8011.   }
  8012.  
  8013.   var initHooks = [];
  8014.   CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
  8015.  
  8016.   // Indent the given line. The how parameter can be "smart",
  8017.   // "add"/null, "subtract", or "prev". When aggressive is false
  8018.   // (typically set to true for forced single-line indents), empty
  8019.   // lines are not indented, and places where the mode returns Pass
  8020.   // are left alone.
  8021.   function indentLine(cm, n, how, aggressive) {
  8022.     var doc = cm.doc, state;
  8023.     if (how == null) { how = "add"; }
  8024.     if (how == "smart") {
  8025.       // Fall back to "prev" when the mode doesn't have an indentation
  8026.       // method.
  8027.       if (!doc.mode.indent) { how = "prev"; }
  8028.       else { state = getContextBefore(cm, n).state; }
  8029.     }
  8030.  
  8031.     var tabSize = cm.options.tabSize;
  8032.     var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  8033.     if (line.stateAfter) { line.stateAfter = null; }
  8034.     var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  8035.     if (!aggressive && !/\S/.test(line.text)) {
  8036.       indentation = 0;
  8037.       how = "not";
  8038.     } else if (how == "smart") {
  8039.       indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  8040.       if (indentation == Pass || indentation > 150) {
  8041.         if (!aggressive) { return }
  8042.         how = "prev";
  8043.       }
  8044.     }
  8045.     if (how == "prev") {
  8046.       if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  8047.       else { indentation = 0; }
  8048.     } else if (how == "add") {
  8049.       indentation = curSpace + cm.options.indentUnit;
  8050.     } else if (how == "subtract") {
  8051.       indentation = curSpace - cm.options.indentUnit;
  8052.     } else if (typeof how == "number") {
  8053.       indentation = curSpace + how;
  8054.     }
  8055.     indentation = Math.max(0, indentation);
  8056.  
  8057.     var indentString = "", pos = 0;
  8058.     if (cm.options.indentWithTabs)
  8059.       { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  8060.     if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  8061.  
  8062.     if (indentString != curSpaceString) {
  8063.       replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  8064.       line.stateAfter = null;
  8065.       return true
  8066.     } else {
  8067.       // Ensure that, if the cursor was in the whitespace at the start
  8068.       // of the line, it is moved to the end of that space.
  8069.       for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  8070.         var range = doc.sel.ranges[i$1];
  8071.         if (range.head.line == n && range.head.ch < curSpaceString.length) {
  8072.           var pos$1 = Pos(n, curSpaceString.length);
  8073.           replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  8074.           break
  8075.         }
  8076.       }
  8077.     }
  8078.   }
  8079.  
  8080.   // This will be set to a {lineWise: bool, text: [string]} object, so
  8081.   // that, when pasting, we know what kind of selections the copied
  8082.   // text was made out of.
  8083.   var lastCopied = null;
  8084.  
  8085.   function setLastCopied(newLastCopied) {
  8086.     lastCopied = newLastCopied;
  8087.   }
  8088.  
  8089.   function applyTextInput(cm, inserted, deleted, sel, origin) {
  8090.     var doc = cm.doc;
  8091.     cm.display.shift = false;
  8092.     if (!sel) { sel = doc.sel; }
  8093.  
  8094.     var recent = +new Date - 200;
  8095.     var paste = origin == "paste" || cm.state.pasteIncoming > recent;
  8096.     var textLines = splitLinesAuto(inserted), multiPaste = null;
  8097.     // When pasting N lines into N selections, insert one line per selection
  8098.     if (paste && sel.ranges.length > 1) {
  8099.       if (lastCopied && lastCopied.text.join("\n") == inserted) {
  8100.         if (sel.ranges.length % lastCopied.text.length == 0) {
  8101.           multiPaste = [];
  8102.           for (var i = 0; i < lastCopied.text.length; i++)
  8103.             { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  8104.         }
  8105.       } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  8106.         multiPaste = map(textLines, function (l) { return [l]; });
  8107.       }
  8108.     }
  8109.  
  8110.     var updateInput = cm.curOp.updateInput;
  8111.     // Normal behavior is to insert the new text into every selection
  8112.     for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  8113.       var range = sel.ranges[i$1];
  8114.       var from = range.from(), to = range.to();
  8115.       if (range.empty()) {
  8116.         if (deleted && deleted > 0) // Handle deletion
  8117.           { from = Pos(from.line, from.ch - deleted); }
  8118.         else if (cm.state.overwrite && !paste) // Handle overwrite
  8119.           { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  8120.         else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  8121.           { from = to = Pos(from.line, 0); }
  8122.       }
  8123.       var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  8124.                          origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
  8125.       makeChange(cm.doc, changeEvent);
  8126.       signalLater(cm, "inputRead", cm, changeEvent);
  8127.     }
  8128.     if (inserted && !paste)
  8129.       { triggerElectric(cm, inserted); }
  8130.  
  8131.     ensureCursorVisible(cm);
  8132.     if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
  8133.     cm.curOp.typing = true;
  8134.     cm.state.pasteIncoming = cm.state.cutIncoming = -1;
  8135.   }
  8136.  
  8137.   function handlePaste(e, cm) {
  8138.     var pasted = e.clipboardData && e.clipboardData.getData("Text");
  8139.     if (pasted) {
  8140.       e.preventDefault();
  8141.       if (!cm.isReadOnly() && !cm.options.disableInput)
  8142.         { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  8143.       return true
  8144.     }
  8145.   }
  8146.  
  8147.   function triggerElectric(cm, inserted) {
  8148.     // When an 'electric' character is inserted, immediately trigger a reindent
  8149.     if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  8150.     var sel = cm.doc.sel;
  8151.  
  8152.     for (var i = sel.ranges.length - 1; i >= 0; i--) {
  8153.       var range = sel.ranges[i];
  8154.       if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
  8155.       var mode = cm.getModeAt(range.head);
  8156.       var indented = false;
  8157.       if (mode.electricChars) {
  8158.         for (var j = 0; j < mode.electricChars.length; j++)
  8159.           { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  8160.             indented = indentLine(cm, range.head.line, "smart");
  8161.             break
  8162.           } }
  8163.       } else if (mode.electricInput) {
  8164.         if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  8165.           { indented = indentLine(cm, range.head.line, "smart"); }
  8166.       }
  8167.       if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
  8168.     }
  8169.   }
  8170.  
  8171.   function copyableRanges(cm) {
  8172.     var text = [], ranges = [];
  8173.     for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  8174.       var line = cm.doc.sel.ranges[i].head.line;
  8175.       var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  8176.       ranges.push(lineRange);
  8177.       text.push(cm.getRange(lineRange.anchor, lineRange.head));
  8178.     }
  8179.     return {text: text, ranges: ranges}
  8180.   }
  8181.  
  8182.   function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
  8183.     field.setAttribute("autocorrect", autocorrect ? "" : "off");
  8184.     field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
  8185.     field.setAttribute("spellcheck", !!spellcheck);
  8186.   }
  8187.  
  8188.   function hiddenTextarea() {
  8189.     var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
  8190.     var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  8191.     // The textarea is kept positioned near the cursor to prevent the
  8192.     // fact that it'll be scrolled into view on input from scrolling
  8193.     // our fake cursor out of view. On webkit, when wrap=off, paste is
  8194.     // very slow. So make the area wide instead.
  8195.     if (webkit) { te.style.width = "1000px"; }
  8196.     else { te.setAttribute("wrap", "off"); }
  8197.     // If border: 0; -- iOS fails to open keyboard (issue #1287)
  8198.     if (ios) { te.style.border = "1px solid black"; }
  8199.     disableBrowserMagic(te);
  8200.     return div
  8201.   }
  8202.  
  8203.   // The publicly visible API. Note that methodOp(f) means
  8204.   // 'wrap f in an operation, performed on its `this` parameter'.
  8205.  
  8206.   // This is not the complete set of editor methods. Most of the
  8207.   // methods defined on the Doc type are also injected into
  8208.   // CodeMirror.prototype, for backwards compatibility and
  8209.   // convenience.
  8210.  
  8211.   function addEditorMethods(CodeMirror) {
  8212.     var optionHandlers = CodeMirror.optionHandlers;
  8213.  
  8214.     var helpers = CodeMirror.helpers = {};
  8215.  
  8216.     CodeMirror.prototype = {
  8217.       constructor: CodeMirror,
  8218.       focus: function(){window.focus(); this.display.input.focus();},
  8219.  
  8220.       setOption: function(option, value) {
  8221.         var options = this.options, old = options[option];
  8222.         if (options[option] == value && option != "mode") { return }
  8223.         options[option] = value;
  8224.         if (optionHandlers.hasOwnProperty(option))
  8225.           { operation(this, optionHandlers[option])(this, value, old); }
  8226.         signal(this, "optionChange", this, option);
  8227.       },
  8228.  
  8229.       getOption: function(option) {return this.options[option]},
  8230.       getDoc: function() {return this.doc},
  8231.  
  8232.       addKeyMap: function(map, bottom) {
  8233.         this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  8234.       },
  8235.       removeKeyMap: function(map) {
  8236.         var maps = this.state.keyMaps;
  8237.         for (var i = 0; i < maps.length; ++i)
  8238.           { if (maps[i] == map || maps[i].name == map) {
  8239.             maps.splice(i, 1);
  8240.             return true
  8241.           } }
  8242.       },
  8243.  
  8244.       addOverlay: methodOp(function(spec, options) {
  8245.         var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  8246.         if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  8247.         insertSorted(this.state.overlays,
  8248.                      {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  8249.                       priority: (options && options.priority) || 0},
  8250.                      function (overlay) { return overlay.priority; });
  8251.         this.state.modeGen++;
  8252.         regChange(this);
  8253.       }),
  8254.       removeOverlay: methodOp(function(spec) {
  8255.         var overlays = this.state.overlays;
  8256.         for (var i = 0; i < overlays.length; ++i) {
  8257.           var cur = overlays[i].modeSpec;
  8258.           if (cur == spec || typeof spec == "string" && cur.name == spec) {
  8259.             overlays.splice(i, 1);
  8260.             this.state.modeGen++;
  8261.             regChange(this);
  8262.             return
  8263.           }
  8264.         }
  8265.       }),
  8266.  
  8267.       indentLine: methodOp(function(n, dir, aggressive) {
  8268.         if (typeof dir != "string" && typeof dir != "number") {
  8269.           if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  8270.           else { dir = dir ? "add" : "subtract"; }
  8271.         }
  8272.         if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  8273.       }),
  8274.       indentSelection: methodOp(function(how) {
  8275.         var ranges = this.doc.sel.ranges, end = -1;
  8276.         for (var i = 0; i < ranges.length; i++) {
  8277.           var range = ranges[i];
  8278.           if (!range.empty()) {
  8279.             var from = range.from(), to = range.to();
  8280.             var start = Math.max(end, from.line);
  8281.             end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  8282.             for (var j = start; j < end; ++j)
  8283.               { indentLine(this, j, how); }
  8284.             var newRanges = this.doc.sel.ranges;
  8285.             if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  8286.               { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  8287.           } else if (range.head.line > end) {
  8288.             indentLine(this, range.head.line, how, true);
  8289.             end = range.head.line;
  8290.             if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
  8291.           }
  8292.         }
  8293.       }),
  8294.  
  8295.       // Fetch the parser token for a given character. Useful for hacks
  8296.       // that want to inspect the mode state (say, for completion).
  8297.       getTokenAt: function(pos, precise) {
  8298.         return takeToken(this, pos, precise)
  8299.       },
  8300.  
  8301.       getLineTokens: function(line, precise) {
  8302.         return takeToken(this, Pos(line), precise, true)
  8303.       },
  8304.  
  8305.       getTokenTypeAt: function(pos) {
  8306.         pos = clipPos(this.doc, pos);
  8307.         var styles = getLineStyles(this, getLine(this.doc, pos.line));
  8308.         var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  8309.         var type;
  8310.         if (ch == 0) { type = styles[2]; }
  8311.         else { for (;;) {
  8312.           var mid = (before + after) >> 1;
  8313.           if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  8314.           else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  8315.           else { type = styles[mid * 2 + 2]; break }
  8316.         } }
  8317.         var cut = type ? type.indexOf("overlay ") : -1;
  8318.         return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  8319.       },
  8320.  
  8321.       getModeAt: function(pos) {
  8322.         var mode = this.doc.mode;
  8323.         if (!mode.innerMode) { return mode }
  8324.         return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  8325.       },
  8326.  
  8327.       getHelper: function(pos, type) {
  8328.         return this.getHelpers(pos, type)[0]
  8329.       },
  8330.  
  8331.       getHelpers: function(pos, type) {
  8332.         var found = [];
  8333.         if (!helpers.hasOwnProperty(type)) { return found }
  8334.         var help = helpers[type], mode = this.getModeAt(pos);
  8335.         if (typeof mode[type] == "string") {
  8336.           if (help[mode[type]]) { found.push(help[mode[type]]); }
  8337.         } else if (mode[type]) {
  8338.           for (var i = 0; i < mode[type].length; i++) {
  8339.             var val = help[mode[type][i]];
  8340.             if (val) { found.push(val); }
  8341.           }
  8342.         } else if (mode.helperType && help[mode.helperType]) {
  8343.           found.push(help[mode.helperType]);
  8344.         } else if (help[mode.name]) {
  8345.           found.push(help[mode.name]);
  8346.         }
  8347.         for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  8348.           var cur = help._global[i$1];
  8349.           if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  8350.             { found.push(cur.val); }
  8351.         }
  8352.         return found
  8353.       },
  8354.  
  8355.       getStateAfter: function(line, precise) {
  8356.         var doc = this.doc;
  8357.         line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  8358.         return getContextBefore(this, line + 1, precise).state
  8359.       },
  8360.  
  8361.       cursorCoords: function(start, mode) {
  8362.         var pos, range = this.doc.sel.primary();
  8363.         if (start == null) { pos = range.head; }
  8364.         else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  8365.         else { pos = start ? range.from() : range.to(); }
  8366.         return cursorCoords(this, pos, mode || "page")
  8367.       },
  8368.  
  8369.       charCoords: function(pos, mode) {
  8370.         return charCoords(this, clipPos(this.doc, pos), mode || "page")
  8371.       },
  8372.  
  8373.       coordsChar: function(coords, mode) {
  8374.         coords = fromCoordSystem(this, coords, mode || "page");
  8375.         return coordsChar(this, coords.left, coords.top)
  8376.       },
  8377.  
  8378.       lineAtHeight: function(height, mode) {
  8379.         height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  8380.         return lineAtHeight(this.doc, height + this.display.viewOffset)
  8381.       },
  8382.       heightAtLine: function(line, mode, includeWidgets) {
  8383.         var end = false, lineObj;
  8384.         if (typeof line == "number") {
  8385.           var last = this.doc.first + this.doc.size - 1;
  8386.           if (line < this.doc.first) { line = this.doc.first; }
  8387.           else if (line > last) { line = last; end = true; }
  8388.           lineObj = getLine(this.doc, line);
  8389.         } else {
  8390.           lineObj = line;
  8391.         }
  8392.         return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  8393.           (end ? this.doc.height - heightAtLine(lineObj) : 0)
  8394.       },
  8395.  
  8396.       defaultTextHeight: function() { return textHeight(this.display) },
  8397.       defaultCharWidth: function() { return charWidth(this.display) },
  8398.  
  8399.       getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  8400.  
  8401.       addWidget: function(pos, node, scroll, vert, horiz) {
  8402.         var display = this.display;
  8403.         pos = cursorCoords(this, clipPos(this.doc, pos));
  8404.         var top = pos.bottom, left = pos.left;
  8405.         node.style.position = "absolute";
  8406.         node.setAttribute("cm-ignore-events", "true");
  8407.         this.display.input.setUneditable(node);
  8408.         display.sizer.appendChild(node);
  8409.         if (vert == "over") {
  8410.           top = pos.top;
  8411.         } else if (vert == "above" || vert == "near") {
  8412.           var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  8413.           hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  8414.           // Default to positioning above (if specified and possible); otherwise default to positioning below
  8415.           if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  8416.             { top = pos.top - node.offsetHeight; }
  8417.           else if (pos.bottom + node.offsetHeight <= vspace)
  8418.             { top = pos.bottom; }
  8419.           if (left + node.offsetWidth > hspace)
  8420.             { left = hspace - node.offsetWidth; }
  8421.         }
  8422.         node.style.top = top + "px";
  8423.         node.style.left = node.style.right = "";
  8424.         if (horiz == "right") {
  8425.           left = display.sizer.clientWidth - node.offsetWidth;
  8426.           node.style.right = "0px";
  8427.         } else {
  8428.           if (horiz == "left") { left = 0; }
  8429.           else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  8430.           node.style.left = left + "px";
  8431.         }
  8432.         if (scroll)
  8433.           { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  8434.       },
  8435.  
  8436.       triggerOnKeyDown: methodOp(onKeyDown),
  8437.       triggerOnKeyPress: methodOp(onKeyPress),
  8438.       triggerOnKeyUp: onKeyUp,
  8439.       triggerOnMouseDown: methodOp(onMouseDown),
  8440.  
  8441.       execCommand: function(cmd) {
  8442.         if (commands.hasOwnProperty(cmd))
  8443.           { return commands[cmd].call(null, this) }
  8444.       },
  8445.  
  8446.       triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  8447.  
  8448.       findPosH: function(from, amount, unit, visually) {
  8449.         var dir = 1;
  8450.         if (amount < 0) { dir = -1; amount = -amount; }
  8451.         var cur = clipPos(this.doc, from);
  8452.         for (var i = 0; i < amount; ++i) {
  8453.           cur = findPosH(this.doc, cur, dir, unit, visually);
  8454.           if (cur.hitSide) { break }
  8455.         }
  8456.         return cur
  8457.       },
  8458.  
  8459.       moveH: methodOp(function(dir, unit) {
  8460.         var this$1 = this;
  8461.  
  8462.         this.extendSelectionsBy(function (range) {
  8463.           if (this$1.display.shift || this$1.doc.extend || range.empty())
  8464.             { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
  8465.           else
  8466.             { return dir < 0 ? range.from() : range.to() }
  8467.         }, sel_move);
  8468.       }),
  8469.  
  8470.       deleteH: methodOp(function(dir, unit) {
  8471.         var sel = this.doc.sel, doc = this.doc;
  8472.         if (sel.somethingSelected())
  8473.           { doc.replaceSelection("", null, "+delete"); }
  8474.         else
  8475.           { deleteNearSelection(this, function (range) {
  8476.             var other = findPosH(doc, range.head, dir, unit, false);
  8477.             return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
  8478.           }); }
  8479.       }),
  8480.  
  8481.       findPosV: function(from, amount, unit, goalColumn) {
  8482.         var dir = 1, x = goalColumn;
  8483.         if (amount < 0) { dir = -1; amount = -amount; }
  8484.         var cur = clipPos(this.doc, from);
  8485.         for (var i = 0; i < amount; ++i) {
  8486.           var coords = cursorCoords(this, cur, "div");
  8487.           if (x == null) { x = coords.left; }
  8488.           else { coords.left = x; }
  8489.           cur = findPosV(this, coords, dir, unit);
  8490.           if (cur.hitSide) { break }
  8491.         }
  8492.         return cur
  8493.       },
  8494.  
  8495.       moveV: methodOp(function(dir, unit) {
  8496.         var this$1 = this;
  8497.  
  8498.         var doc = this.doc, goals = [];
  8499.         var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  8500.         doc.extendSelectionsBy(function (range) {
  8501.           if (collapse)
  8502.             { return dir < 0 ? range.from() : range.to() }
  8503.           var headPos = cursorCoords(this$1, range.head, "div");
  8504.           if (range.goalColumn != null) { headPos.left = range.goalColumn; }
  8505.           goals.push(headPos.left);
  8506.           var pos = findPosV(this$1, headPos, dir, unit);
  8507.           if (unit == "page" && range == doc.sel.primary())
  8508.             { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  8509.           return pos
  8510.         }, sel_move);
  8511.         if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  8512.           { doc.sel.ranges[i].goalColumn = goals[i]; } }
  8513.       }),
  8514.  
  8515.       // Find the word at the given position (as returned by coordsChar).
  8516.       findWordAt: function(pos) {
  8517.         var doc = this.doc, line = getLine(doc, pos.line).text;
  8518.         var start = pos.ch, end = pos.ch;
  8519.         if (line) {
  8520.           var helper = this.getHelper(pos, "wordChars");
  8521.           if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  8522.           var startChar = line.charAt(start);
  8523.           var check = isWordChar(startChar, helper)
  8524.             ? function (ch) { return isWordChar(ch, helper); }
  8525.             : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  8526.             : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  8527.           while (start > 0 && check(line.charAt(start - 1))) { --start; }
  8528.           while (end < line.length && check(line.charAt(end))) { ++end; }
  8529.         }
  8530.         return new Range(Pos(pos.line, start), Pos(pos.line, end))
  8531.       },
  8532.  
  8533.       toggleOverwrite: function(value) {
  8534.         if (value != null && value == this.state.overwrite) { return }
  8535.         if (this.state.overwrite = !this.state.overwrite)
  8536.           { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  8537.         else
  8538.           { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  8539.  
  8540.         signal(this, "overwriteToggle", this, this.state.overwrite);
  8541.       },
  8542.       hasFocus: function() { return this.display.input.getField() == activeElt() },
  8543.       isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  8544.  
  8545.       scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  8546.       getScrollInfo: function() {
  8547.         var scroller = this.display.scroller;
  8548.         return {left: scroller.scrollLeft, top: scroller.scrollTop,
  8549.                 height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  8550.                 width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  8551.                 clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  8552.       },
  8553.  
  8554.       scrollIntoView: methodOp(function(range, margin) {
  8555.         if (range == null) {
  8556.           range = {from: this.doc.sel.primary().head, to: null};
  8557.           if (margin == null) { margin = this.options.cursorScrollMargin; }
  8558.         } else if (typeof range == "number") {
  8559.           range = {from: Pos(range, 0), to: null};
  8560.         } else if (range.from == null) {
  8561.           range = {from: range, to: null};
  8562.         }
  8563.         if (!range.to) { range.to = range.from; }
  8564.         range.margin = margin || 0;
  8565.  
  8566.         if (range.from.line != null) {
  8567.           scrollToRange(this, range);
  8568.         } else {
  8569.           scrollToCoordsRange(this, range.from, range.to, range.margin);
  8570.         }
  8571.       }),
  8572.  
  8573.       setSize: methodOp(function(width, height) {
  8574.         var this$1 = this;
  8575.  
  8576.         var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  8577.         if (width != null) { this.display.wrapper.style.width = interpret(width); }
  8578.         if (height != null) { this.display.wrapper.style.height = interpret(height); }
  8579.         if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  8580.         var lineNo = this.display.viewFrom;
  8581.         this.doc.iter(lineNo, this.display.viewTo, function (line) {
  8582.           if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  8583.             { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
  8584.           ++lineNo;
  8585.         });
  8586.         this.curOp.forceUpdate = true;
  8587.         signal(this, "refresh", this);
  8588.       }),
  8589.  
  8590.       operation: function(f){return runInOp(this, f)},
  8591.       startOperation: function(){return startOperation(this)},
  8592.       endOperation: function(){return endOperation(this)},
  8593.  
  8594.       refresh: methodOp(function() {
  8595.         var oldHeight = this.display.cachedTextHeight;
  8596.         regChange(this);
  8597.         this.curOp.forceUpdate = true;
  8598.         clearCaches(this);
  8599.         scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  8600.         updateGutterSpace(this.display);
  8601.         if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
  8602.           { estimateLineHeights(this); }
  8603.         signal(this, "refresh", this);
  8604.       }),
  8605.  
  8606.       swapDoc: methodOp(function(doc) {
  8607.         var old = this.doc;
  8608.         old.cm = null;
  8609.         // Cancel the current text selection if any (#5821)
  8610.         if (this.state.selectingText) { this.state.selectingText(); }
  8611.         attachDoc(this, doc);
  8612.         clearCaches(this);
  8613.         this.display.input.reset();
  8614.         scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  8615.         this.curOp.forceScroll = true;
  8616.         signalLater(this, "swapDoc", this, old);
  8617.         return old
  8618.       }),
  8619.  
  8620.       phrase: function(phraseText) {
  8621.         var phrases = this.options.phrases;
  8622.         return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
  8623.       },
  8624.  
  8625.       getInputField: function(){return this.display.input.getField()},
  8626.       getWrapperElement: function(){return this.display.wrapper},
  8627.       getScrollerElement: function(){return this.display.scroller},
  8628.       getGutterElement: function(){return this.display.gutters}
  8629.     };
  8630.     eventMixin(CodeMirror);
  8631.  
  8632.     CodeMirror.registerHelper = function(type, name, value) {
  8633.       if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  8634.       helpers[type][name] = value;
  8635.     };
  8636.     CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  8637.       CodeMirror.registerHelper(type, name, value);
  8638.       helpers[type]._global.push({pred: predicate, val: value});
  8639.     };
  8640.   }
  8641.  
  8642.   // Used for horizontal relative motion. Dir is -1 or 1 (left or
  8643.   // right), unit can be "char", "column" (like char, but doesn't
  8644.   // cross line boundaries), "word" (across next word), or "group" (to
  8645.   // the start of next group of word or non-word-non-whitespace
  8646.   // chars). The visually param controls whether, in right-to-left
  8647.   // text, direction 1 means to move towards the next index in the
  8648.   // string, or towards the character to the right of the current
  8649.   // position. The resulting position will have a hitSide=true
  8650.   // property if it reached the end of the document.
  8651.   function findPosH(doc, pos, dir, unit, visually) {
  8652.     var oldPos = pos;
  8653.     var origDir = dir;
  8654.     var lineObj = getLine(doc, pos.line);
  8655.     var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
  8656.     function findNextLine() {
  8657.       var l = pos.line + lineDir;
  8658.       if (l < doc.first || l >= doc.first + doc.size) { return false }
  8659.       pos = new Pos(l, pos.ch, pos.sticky);
  8660.       return lineObj = getLine(doc, l)
  8661.     }
  8662.     function moveOnce(boundToLine) {
  8663.       var next;
  8664.       if (visually) {
  8665.         next = moveVisually(doc.cm, lineObj, pos, dir);
  8666.       } else {
  8667.         next = moveLogically(lineObj, pos, dir);
  8668.       }
  8669.       if (next == null) {
  8670.         if (!boundToLine && findNextLine())
  8671.           { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
  8672.         else
  8673.           { return false }
  8674.       } else {
  8675.         pos = next;
  8676.       }
  8677.       return true
  8678.     }
  8679.  
  8680.     if (unit == "char") {
  8681.       moveOnce();
  8682.     } else if (unit == "column") {
  8683.       moveOnce(true);
  8684.     } else if (unit == "word" || unit == "group") {
  8685.       var sawType = null, group = unit == "group";
  8686.       var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  8687.       for (var first = true;; first = false) {
  8688.         if (dir < 0 && !moveOnce(!first)) { break }
  8689.         var cur = lineObj.text.charAt(pos.ch) || "\n";
  8690.         var type = isWordChar(cur, helper) ? "w"
  8691.           : group && cur == "\n" ? "n"
  8692.           : !group || /\s/.test(cur) ? null
  8693.           : "p";
  8694.         if (group && !first && !type) { type = "s"; }
  8695.         if (sawType && sawType != type) {
  8696.           if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  8697.           break
  8698.         }
  8699.  
  8700.         if (type) { sawType = type; }
  8701.         if (dir > 0 && !moveOnce(!first)) { break }
  8702.       }
  8703.     }
  8704.     var result = skipAtomic(doc, pos, oldPos, origDir, true);
  8705.     if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  8706.     return result
  8707.   }
  8708.  
  8709.   // For relative vertical movement. Dir may be -1 or 1. Unit can be
  8710.   // "page" or "line". The resulting position will have a hitSide=true
  8711.   // property if it reached the end of the document.
  8712.   function findPosV(cm, pos, dir, unit) {
  8713.     var doc = cm.doc, x = pos.left, y;
  8714.     if (unit == "page") {
  8715.       var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  8716.       var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  8717.       y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  8718.  
  8719.     } else if (unit == "line") {
  8720.       y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  8721.     }
  8722.     var target;
  8723.     for (;;) {
  8724.       target = coordsChar(cm, x, y);
  8725.       if (!target.outside) { break }
  8726.       if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  8727.       y += dir * 5;
  8728.     }
  8729.     return target
  8730.   }
  8731.  
  8732.   // CONTENTEDITABLE INPUT STYLE
  8733.  
  8734.   var ContentEditableInput = function(cm) {
  8735.     this.cm = cm;
  8736.     this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  8737.     this.polling = new Delayed();
  8738.     this.composing = null;
  8739.     this.gracePeriod = false;
  8740.     this.readDOMTimeout = null;
  8741.   };
  8742.  
  8743.   ContentEditableInput.prototype.init = function (display) {
  8744.       var this$1 = this;
  8745.  
  8746.     var input = this, cm = input.cm;
  8747.     var div = input.div = display.lineDiv;
  8748.     disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
  8749.  
  8750.     function belongsToInput(e) {
  8751.       for (var t = e.target; t; t = t.parentNode) {
  8752.         if (t == div) { return true }
  8753.         if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
  8754.       }
  8755.       return false
  8756.     }
  8757.  
  8758.     on(div, "paste", function (e) {
  8759.       if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8760.       // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  8761.       if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  8762.     });
  8763.  
  8764.     on(div, "compositionstart", function (e) {
  8765.       this$1.composing = {data: e.data, done: false};
  8766.     });
  8767.     on(div, "compositionupdate", function (e) {
  8768.       if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  8769.     });
  8770.     on(div, "compositionend", function (e) {
  8771.       if (this$1.composing) {
  8772.         if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  8773.         this$1.composing.done = true;
  8774.       }
  8775.     });
  8776.  
  8777.     on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  8778.  
  8779.     on(div, "input", function () {
  8780.       if (!this$1.composing) { this$1.readFromDOMSoon(); }
  8781.     });
  8782.  
  8783.     function onCopyCut(e) {
  8784.       if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
  8785.       if (cm.somethingSelected()) {
  8786.         setLastCopied({lineWise: false, text: cm.getSelections()});
  8787.         if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  8788.       } else if (!cm.options.lineWiseCopyCut) {
  8789.         return
  8790.       } else {
  8791.         var ranges = copyableRanges(cm);
  8792.         setLastCopied({lineWise: true, text: ranges.text});
  8793.         if (e.type == "cut") {
  8794.           cm.operation(function () {
  8795.             cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  8796.             cm.replaceSelection("", null, "cut");
  8797.           });
  8798.         }
  8799.       }
  8800.       if (e.clipboardData) {
  8801.         e.clipboardData.clearData();
  8802.         var content = lastCopied.text.join("\n");
  8803.         // iOS exposes the clipboard API, but seems to discard content inserted into it
  8804.         e.clipboardData.setData("Text", content);
  8805.         if (e.clipboardData.getData("Text") == content) {
  8806.           e.preventDefault();
  8807.           return
  8808.         }
  8809.       }
  8810.       // Old-fashioned briefly-focus-a-textarea hack
  8811.       var kludge = hiddenTextarea(), te = kludge.firstChild;
  8812.       cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  8813.       te.value = lastCopied.text.join("\n");
  8814.       var hadFocus = document.activeElement;
  8815.       selectInput(te);
  8816.       setTimeout(function () {
  8817.         cm.display.lineSpace.removeChild(kludge);
  8818.         hadFocus.focus();
  8819.         if (hadFocus == div) { input.showPrimarySelection(); }
  8820.       }, 50);
  8821.     }
  8822.     on(div, "copy", onCopyCut);
  8823.     on(div, "cut", onCopyCut);
  8824.   };
  8825.  
  8826.   ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
  8827.     // Label for screenreaders, accessibility
  8828.     if(label) {
  8829.       this.div.setAttribute('aria-label', label);
  8830.     } else {
  8831.       this.div.removeAttribute('aria-label');
  8832.     }
  8833.   };
  8834.  
  8835.   ContentEditableInput.prototype.prepareSelection = function () {
  8836.     var result = prepareSelection(this.cm, false);
  8837.     result.focus = document.activeElement == this.div;
  8838.     return result
  8839.   };
  8840.  
  8841.   ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  8842.     if (!info || !this.cm.display.view.length) { return }
  8843.     if (info.focus || takeFocus) { this.showPrimarySelection(); }
  8844.     this.showMultipleSelections(info);
  8845.   };
  8846.  
  8847.   ContentEditableInput.prototype.getSelection = function () {
  8848.     return this.cm.display.wrapper.ownerDocument.getSelection()
  8849.   };
  8850.  
  8851.   ContentEditableInput.prototype.showPrimarySelection = function () {
  8852.     var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  8853.     var from = prim.from(), to = prim.to();
  8854.  
  8855.     if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  8856.       sel.removeAllRanges();
  8857.       return
  8858.     }
  8859.  
  8860.     var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8861.     var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  8862.     if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  8863.         cmp(minPos(curAnchor, curFocus), from) == 0 &&
  8864.         cmp(maxPos(curAnchor, curFocus), to) == 0)
  8865.       { return }
  8866.  
  8867.     var view = cm.display.view;
  8868.     var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  8869.         {node: view[0].measure.map[2], offset: 0};
  8870.     var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  8871.     if (!end) {
  8872.       var measure = view[view.length - 1].measure;
  8873.       var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  8874.       end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  8875.     }
  8876.  
  8877.     if (!start || !end) {
  8878.       sel.removeAllRanges();
  8879.       return
  8880.     }
  8881.  
  8882.     var old = sel.rangeCount && sel.getRangeAt(0), rng;
  8883.     try { rng = range(start.node, start.offset, end.offset, end.node); }
  8884.     catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  8885.     if (rng) {
  8886.       if (!gecko && cm.state.focused) {
  8887.         sel.collapse(start.node, start.offset);
  8888.         if (!rng.collapsed) {
  8889.           sel.removeAllRanges();
  8890.           sel.addRange(rng);
  8891.         }
  8892.       } else {
  8893.         sel.removeAllRanges();
  8894.         sel.addRange(rng);
  8895.       }
  8896.       if (old && sel.anchorNode == null) { sel.addRange(old); }
  8897.       else if (gecko) { this.startGracePeriod(); }
  8898.     }
  8899.     this.rememberSelection();
  8900.   };
  8901.  
  8902.   ContentEditableInput.prototype.startGracePeriod = function () {
  8903.       var this$1 = this;
  8904.  
  8905.     clearTimeout(this.gracePeriod);
  8906.     this.gracePeriod = setTimeout(function () {
  8907.       this$1.gracePeriod = false;
  8908.       if (this$1.selectionChanged())
  8909.         { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  8910.     }, 20);
  8911.   };
  8912.  
  8913.   ContentEditableInput.prototype.showMultipleSelections = function (info) {
  8914.     removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  8915.     removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  8916.   };
  8917.  
  8918.   ContentEditableInput.prototype.rememberSelection = function () {
  8919.     var sel = this.getSelection();
  8920.     this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  8921.     this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  8922.   };
  8923.  
  8924.   ContentEditableInput.prototype.selectionInEditor = function () {
  8925.     var sel = this.getSelection();
  8926.     if (!sel.rangeCount) { return false }
  8927.     var node = sel.getRangeAt(0).commonAncestorContainer;
  8928.     return contains(this.div, node)
  8929.   };
  8930.  
  8931.   ContentEditableInput.prototype.focus = function () {
  8932.     if (this.cm.options.readOnly != "nocursor") {
  8933.       if (!this.selectionInEditor() || document.activeElement != this.div)
  8934.         { this.showSelection(this.prepareSelection(), true); }
  8935.       this.div.focus();
  8936.     }
  8937.   };
  8938.   ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  8939.   ContentEditableInput.prototype.getField = function () { return this.div };
  8940.  
  8941.   ContentEditableInput.prototype.supportsTouch = function () { return true };
  8942.  
  8943.   ContentEditableInput.prototype.receivedFocus = function () {
  8944.     var input = this;
  8945.     if (this.selectionInEditor())
  8946.       { this.pollSelection(); }
  8947.     else
  8948.       { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  8949.  
  8950.     function poll() {
  8951.       if (input.cm.state.focused) {
  8952.         input.pollSelection();
  8953.         input.polling.set(input.cm.options.pollInterval, poll);
  8954.       }
  8955.     }
  8956.     this.polling.set(this.cm.options.pollInterval, poll);
  8957.   };
  8958.  
  8959.   ContentEditableInput.prototype.selectionChanged = function () {
  8960.     var sel = this.getSelection();
  8961.     return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  8962.       sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  8963.   };
  8964.  
  8965.   ContentEditableInput.prototype.pollSelection = function () {
  8966.     if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  8967.     var sel = this.getSelection(), cm = this.cm;
  8968.     // On Android Chrome (version 56, at least), backspacing into an
  8969.     // uneditable block element will put the cursor in that element,
  8970.     // and then, because it's not editable, hide the virtual keyboard.
  8971.     // Because Android doesn't allow us to actually detect backspace
  8972.     // presses in a sane way, this code checks for when that happens
  8973.     // and simulates a backspace press in this case.
  8974.     if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
  8975.       this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  8976.       this.blur();
  8977.       this.focus();
  8978.       return
  8979.     }
  8980.     if (this.composing) { return }
  8981.     this.rememberSelection();
  8982.     var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8983.     var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  8984.     if (anchor && head) { runInOp(cm, function () {
  8985.       setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  8986.       if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  8987.     }); }
  8988.   };
  8989.  
  8990.   ContentEditableInput.prototype.pollContent = function () {
  8991.     if (this.readDOMTimeout != null) {
  8992.       clearTimeout(this.readDOMTimeout);
  8993.       this.readDOMTimeout = null;
  8994.     }
  8995.  
  8996.     var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  8997.     var from = sel.from(), to = sel.to();
  8998.     if (from.ch == 0 && from.line > cm.firstLine())
  8999.       { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  9000.     if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  9001.       { to = Pos(to.line + 1, 0); }
  9002.     if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  9003.  
  9004.     var fromIndex, fromLine, fromNode;
  9005.     if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  9006.       fromLine = lineNo(display.view[0].line);
  9007.       fromNode = display.view[0].node;
  9008.     } else {
  9009.       fromLine = lineNo(display.view[fromIndex].line);
  9010.       fromNode = display.view[fromIndex - 1].node.nextSibling;
  9011.     }
  9012.     var toIndex = findViewIndex(cm, to.line);
  9013.     var toLine, toNode;
  9014.     if (toIndex == display.view.length - 1) {
  9015.       toLine = display.viewTo - 1;
  9016.       toNode = display.lineDiv.lastChild;
  9017.     } else {
  9018.       toLine = lineNo(display.view[toIndex + 1].line) - 1;
  9019.       toNode = display.view[toIndex + 1].node.previousSibling;
  9020.     }
  9021.  
  9022.     if (!fromNode) { return false }
  9023.     var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  9024.     var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  9025.     while (newText.length > 1 && oldText.length > 1) {
  9026.       if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  9027.       else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  9028.       else { break }
  9029.     }
  9030.  
  9031.     var cutFront = 0, cutEnd = 0;
  9032.     var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  9033.     while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  9034.       { ++cutFront; }
  9035.     var newBot = lst(newText), oldBot = lst(oldText);
  9036.     var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  9037.                              oldBot.length - (oldText.length == 1 ? cutFront : 0));
  9038.     while (cutEnd < maxCutEnd &&
  9039.            newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  9040.       { ++cutEnd; }
  9041.     // Try to move start of change to start of selection if ambiguous
  9042.     if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  9043.       while (cutFront && cutFront > from.ch &&
  9044.              newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  9045.         cutFront--;
  9046.         cutEnd++;
  9047.       }
  9048.     }
  9049.  
  9050.     newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  9051.     newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  9052.  
  9053.     var chFrom = Pos(fromLine, cutFront);
  9054.     var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  9055.     if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  9056.       replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  9057.       return true
  9058.     }
  9059.   };
  9060.  
  9061.   ContentEditableInput.prototype.ensurePolled = function () {
  9062.     this.forceCompositionEnd();
  9063.   };
  9064.   ContentEditableInput.prototype.reset = function () {
  9065.     this.forceCompositionEnd();
  9066.   };
  9067.   ContentEditableInput.prototype.forceCompositionEnd = function () {
  9068.     if (!this.composing) { return }
  9069.     clearTimeout(this.readDOMTimeout);
  9070.     this.composing = null;
  9071.     this.updateFromDOM();
  9072.     this.div.blur();
  9073.     this.div.focus();
  9074.   };
  9075.   ContentEditableInput.prototype.readFromDOMSoon = function () {
  9076.       var this$1 = this;
  9077.  
  9078.     if (this.readDOMTimeout != null) { return }
  9079.     this.readDOMTimeout = setTimeout(function () {
  9080.       this$1.readDOMTimeout = null;
  9081.       if (this$1.composing) {
  9082.         if (this$1.composing.done) { this$1.composing = null; }
  9083.         else { return }
  9084.       }
  9085.       this$1.updateFromDOM();
  9086.     }, 80);
  9087.   };
  9088.  
  9089.   ContentEditableInput.prototype.updateFromDOM = function () {
  9090.       var this$1 = this;
  9091.  
  9092.     if (this.cm.isReadOnly() || !this.pollContent())
  9093.       { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  9094.   };
  9095.  
  9096.   ContentEditableInput.prototype.setUneditable = function (node) {
  9097.     node.contentEditable = "false";
  9098.   };
  9099.  
  9100.   ContentEditableInput.prototype.onKeyPress = function (e) {
  9101.     if (e.charCode == 0 || this.composing) { return }
  9102.     e.preventDefault();
  9103.     if (!this.cm.isReadOnly())
  9104.       { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  9105.   };
  9106.  
  9107.   ContentEditableInput.prototype.readOnlyChanged = function (val) {
  9108.     this.div.contentEditable = String(val != "nocursor");
  9109.   };
  9110.  
  9111.   ContentEditableInput.prototype.onContextMenu = function () {};
  9112.   ContentEditableInput.prototype.resetPosition = function () {};
  9113.  
  9114.   ContentEditableInput.prototype.needsContentAttribute = true;
  9115.  
  9116.   function posToDOM(cm, pos) {
  9117.     var view = findViewForLine(cm, pos.line);
  9118.     if (!view || view.hidden) { return null }
  9119.     var line = getLine(cm.doc, pos.line);
  9120.     var info = mapFromLineView(view, line, pos.line);
  9121.  
  9122.     var order = getOrder(line, cm.doc.direction), side = "left";
  9123.     if (order) {
  9124.       var partPos = getBidiPartAt(order, pos.ch);
  9125.       side = partPos % 2 ? "right" : "left";
  9126.     }
  9127.     var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  9128.     result.offset = result.collapse == "right" ? result.end : result.start;
  9129.     return result
  9130.   }
  9131.  
  9132.   function isInGutter(node) {
  9133.     for (var scan = node; scan; scan = scan.parentNode)
  9134.       { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  9135.     return false
  9136.   }
  9137.  
  9138.   function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  9139.  
  9140.   function domTextBetween(cm, from, to, fromLine, toLine) {
  9141.     var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
  9142.     function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  9143.     function close() {
  9144.       if (closing) {
  9145.         text += lineSep;
  9146.         if (extraLinebreak) { text += lineSep; }
  9147.         closing = extraLinebreak = false;
  9148.       }
  9149.     }
  9150.     function addText(str) {
  9151.       if (str) {
  9152.         close();
  9153.         text += str;
  9154.       }
  9155.     }
  9156.     function walk(node) {
  9157.       if (node.nodeType == 1) {
  9158.         var cmText = node.getAttribute("cm-text");
  9159.         if (cmText) {
  9160.           addText(cmText);
  9161.           return
  9162.         }
  9163.         var markerID = node.getAttribute("cm-marker"), range;
  9164.         if (markerID) {
  9165.           var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  9166.           if (found.length && (range = found[0].find(0)))
  9167.             { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
  9168.           return
  9169.         }
  9170.         if (node.getAttribute("contenteditable") == "false") { return }
  9171.         var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
  9172.         if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
  9173.  
  9174.         if (isBlock) { close(); }
  9175.         for (var i = 0; i < node.childNodes.length; i++)
  9176.           { walk(node.childNodes[i]); }
  9177.  
  9178.         if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
  9179.         if (isBlock) { closing = true; }
  9180.       } else if (node.nodeType == 3) {
  9181.         addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
  9182.       }
  9183.     }
  9184.     for (;;) {
  9185.       walk(from);
  9186.       if (from == to) { break }
  9187.       from = from.nextSibling;
  9188.       extraLinebreak = false;
  9189.     }
  9190.     return text
  9191.   }
  9192.  
  9193.   function domToPos(cm, node, offset) {
  9194.     var lineNode;
  9195.     if (node == cm.display.lineDiv) {
  9196.       lineNode = cm.display.lineDiv.childNodes[offset];
  9197.       if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  9198.       node = null; offset = 0;
  9199.     } else {
  9200.       for (lineNode = node;; lineNode = lineNode.parentNode) {
  9201.         if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  9202.         if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  9203.       }
  9204.     }
  9205.     for (var i = 0; i < cm.display.view.length; i++) {
  9206.       var lineView = cm.display.view[i];
  9207.       if (lineView.node == lineNode)
  9208.         { return locateNodeInLineView(lineView, node, offset) }
  9209.     }
  9210.   }
  9211.  
  9212.   function locateNodeInLineView(lineView, node, offset) {
  9213.     var wrapper = lineView.text.firstChild, bad = false;
  9214.     if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  9215.     if (node == wrapper) {
  9216.       bad = true;
  9217.       node = wrapper.childNodes[offset];
  9218.       offset = 0;
  9219.       if (!node) {
  9220.         var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  9221.         return badPos(Pos(lineNo(line), line.text.length), bad)
  9222.       }
  9223.     }
  9224.  
  9225.     var textNode = node.nodeType == 3 ? node : null, topNode = node;
  9226.     if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  9227.       textNode = node.firstChild;
  9228.       if (offset) { offset = textNode.nodeValue.length; }
  9229.     }
  9230.     while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  9231.     var measure = lineView.measure, maps = measure.maps;
  9232.  
  9233.     function find(textNode, topNode, offset) {
  9234.       for (var i = -1; i < (maps ? maps.length : 0); i++) {
  9235.         var map = i < 0 ? measure.map : maps[i];
  9236.         for (var j = 0; j < map.length; j += 3) {
  9237.           var curNode = map[j + 2];
  9238.           if (curNode == textNode || curNode == topNode) {
  9239.             var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  9240.             var ch = map[j] + offset;
  9241.             if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
  9242.             return Pos(line, ch)
  9243.           }
  9244.         }
  9245.       }
  9246.     }
  9247.     var found = find(textNode, topNode, offset);
  9248.     if (found) { return badPos(found, bad) }
  9249.  
  9250.     // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  9251.     for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  9252.       found = find(after, after.firstChild, 0);
  9253.       if (found)
  9254.         { return badPos(Pos(found.line, found.ch - dist), bad) }
  9255.       else
  9256.         { dist += after.textContent.length; }
  9257.     }
  9258.     for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  9259.       found = find(before, before.firstChild, -1);
  9260.       if (found)
  9261.         { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  9262.       else
  9263.         { dist$1 += before.textContent.length; }
  9264.     }
  9265.   }
  9266.  
  9267.   // TEXTAREA INPUT STYLE
  9268.  
  9269.   var TextareaInput = function(cm) {
  9270.     this.cm = cm;
  9271.     // See input.poll and input.reset
  9272.     this.prevInput = "";
  9273.  
  9274.     // Flag that indicates whether we expect input to appear real soon
  9275.     // now (after some event like 'keypress' or 'input') and are
  9276.     // polling intensively.
  9277.     this.pollingFast = false;
  9278.     // Self-resetting timeout for the poller
  9279.     this.polling = new Delayed();
  9280.     // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  9281.     this.hasSelection = false;
  9282.     this.composing = null;
  9283.   };
  9284.  
  9285.   TextareaInput.prototype.init = function (display) {
  9286.       var this$1 = this;
  9287.  
  9288.     var input = this, cm = this.cm;
  9289.     this.createField(display);
  9290.     var te = this.textarea;
  9291.  
  9292.     display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
  9293.  
  9294.     // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  9295.     if (ios) { te.style.width = "0px"; }
  9296.  
  9297.     on(te, "input", function () {
  9298.       if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  9299.       input.poll();
  9300.     });
  9301.  
  9302.     on(te, "paste", function (e) {
  9303.       if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  9304.  
  9305.       cm.state.pasteIncoming = +new Date;
  9306.       input.fastPoll();
  9307.     });
  9308.  
  9309.     function prepareCopyCut(e) {
  9310.       if (signalDOMEvent(cm, e)) { return }
  9311.       if (cm.somethingSelected()) {
  9312.         setLastCopied({lineWise: false, text: cm.getSelections()});
  9313.       } else if (!cm.options.lineWiseCopyCut) {
  9314.         return
  9315.       } else {
  9316.         var ranges = copyableRanges(cm);
  9317.         setLastCopied({lineWise: true, text: ranges.text});
  9318.         if (e.type == "cut") {
  9319.           cm.setSelections(ranges.ranges, null, sel_dontScroll);
  9320.         } else {
  9321.           input.prevInput = "";
  9322.           te.value = ranges.text.join("\n");
  9323.           selectInput(te);
  9324.         }
  9325.       }
  9326.       if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
  9327.     }
  9328.     on(te, "cut", prepareCopyCut);
  9329.     on(te, "copy", prepareCopyCut);
  9330.  
  9331.     on(display.scroller, "paste", function (e) {
  9332.       if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  9333.       if (!te.dispatchEvent) {
  9334.         cm.state.pasteIncoming = +new Date;
  9335.         input.focus();
  9336.         return
  9337.       }
  9338.  
  9339.       // Pass the `paste` event to the textarea so it's handled by its event listener.
  9340.       var event = new Event("paste");
  9341.       event.clipboardData = e.clipboardData;
  9342.       te.dispatchEvent(event);
  9343.     });
  9344.  
  9345.     // Prevent normal selection in the editor (we handle our own)
  9346.     on(display.lineSpace, "selectstart", function (e) {
  9347.       if (!eventInWidget(display, e)) { e_preventDefault(e); }
  9348.     });
  9349.  
  9350.     on(te, "compositionstart", function () {
  9351.       var start = cm.getCursor("from");
  9352.       if (input.composing) { input.composing.range.clear(); }
  9353.       input.composing = {
  9354.         start: start,
  9355.         range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  9356.       };
  9357.     });
  9358.     on(te, "compositionend", function () {
  9359.       if (input.composing) {
  9360.         input.poll();
  9361.         input.composing.range.clear();
  9362.         input.composing = null;
  9363.       }
  9364.     });
  9365.   };
  9366.  
  9367.   TextareaInput.prototype.createField = function (_display) {
  9368.     // Wraps and hides input textarea
  9369.     this.wrapper = hiddenTextarea();
  9370.     // The semihidden textarea that is focused when the editor is
  9371.     // focused, and receives input.
  9372.     this.textarea = this.wrapper.firstChild;
  9373.   };
  9374.  
  9375.   TextareaInput.prototype.screenReaderLabelChanged = function (label) {
  9376.     // Label for screenreaders, accessibility
  9377.     if(label) {
  9378.       this.textarea.setAttribute('aria-label', label);
  9379.     } else {
  9380.       this.textarea.removeAttribute('aria-label');
  9381.     }
  9382.   };
  9383.  
  9384.   TextareaInput.prototype.prepareSelection = function () {
  9385.     // Redraw the selection and/or cursor
  9386.     var cm = this.cm, display = cm.display, doc = cm.doc;
  9387.     var result = prepareSelection(cm);
  9388.  
  9389.     // Move the hidden textarea near the cursor to prevent scrolling artifacts
  9390.     if (cm.options.moveInputWithCursor) {
  9391.       var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  9392.       var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  9393.       result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  9394.                                           headPos.top + lineOff.top - wrapOff.top));
  9395.       result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  9396.                                            headPos.left + lineOff.left - wrapOff.left));
  9397.     }
  9398.  
  9399.     return result
  9400.   };
  9401.  
  9402.   TextareaInput.prototype.showSelection = function (drawn) {
  9403.     var cm = this.cm, display = cm.display;
  9404.     removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  9405.     removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  9406.     if (drawn.teTop != null) {
  9407.       this.wrapper.style.top = drawn.teTop + "px";
  9408.       this.wrapper.style.left = drawn.teLeft + "px";
  9409.     }
  9410.   };
  9411.  
  9412.   // Reset the input to correspond to the selection (or to be empty,
  9413.   // when not typing and nothing is selected)
  9414.   TextareaInput.prototype.reset = function (typing) {
  9415.     if (this.contextMenuPending || this.composing) { return }
  9416.     var cm = this.cm;
  9417.     if (cm.somethingSelected()) {
  9418.       this.prevInput = "";
  9419.       var content = cm.getSelection();
  9420.       this.textarea.value = content;
  9421.       if (cm.state.focused) { selectInput(this.textarea); }
  9422.       if (ie && ie_version >= 9) { this.hasSelection = content; }
  9423.     } else if (!typing) {
  9424.       this.prevInput = this.textarea.value = "";
  9425.       if (ie && ie_version >= 9) { this.hasSelection = null; }
  9426.     }
  9427.   };
  9428.  
  9429.   TextareaInput.prototype.getField = function () { return this.textarea };
  9430.  
  9431.   TextareaInput.prototype.supportsTouch = function () { return false };
  9432.  
  9433.   TextareaInput.prototype.focus = function () {
  9434.     if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  9435.       try { this.textarea.focus(); }
  9436.       catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  9437.     }
  9438.   };
  9439.  
  9440.   TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  9441.  
  9442.   TextareaInput.prototype.resetPosition = function () {
  9443.     this.wrapper.style.top = this.wrapper.style.left = 0;
  9444.   };
  9445.  
  9446.   TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  9447.  
  9448.   // Poll for input changes, using the normal rate of polling. This
  9449.   // runs as long as the editor is focused.
  9450.   TextareaInput.prototype.slowPoll = function () {
  9451.       var this$1 = this;
  9452.  
  9453.     if (this.pollingFast) { return }
  9454.     this.polling.set(this.cm.options.pollInterval, function () {
  9455.       this$1.poll();
  9456.       if (this$1.cm.state.focused) { this$1.slowPoll(); }
  9457.     });
  9458.   };
  9459.  
  9460.   // When an event has just come in that is likely to add or change
  9461.   // something in the input textarea, we poll faster, to ensure that
  9462.   // the change appears on the screen quickly.
  9463.   TextareaInput.prototype.fastPoll = function () {
  9464.     var missed = false, input = this;
  9465.     input.pollingFast = true;
  9466.     function p() {
  9467.       var changed = input.poll();
  9468.       if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  9469.       else {input.pollingFast = false; input.slowPoll();}
  9470.     }
  9471.     input.polling.set(20, p);
  9472.   };
  9473.  
  9474.   // Read input from the textarea, and update the document to match.
  9475.   // When something is selected, it is present in the textarea, and
  9476.   // selected (unless it is huge, in which case a placeholder is
  9477.   // used). When nothing is selected, the cursor sits after previously
  9478.   // seen text (can be empty), which is stored in prevInput (we must
  9479.   // not reset the textarea when typing, because that breaks IME).
  9480.   TextareaInput.prototype.poll = function () {
  9481.       var this$1 = this;
  9482.  
  9483.     var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  9484.     // Since this is called a *lot*, try to bail out as cheaply as
  9485.     // possible when it is clear that nothing happened. hasSelection
  9486.     // will be the case when there is a lot of text in the textarea,
  9487.     // in which case reading its value would be expensive.
  9488.     if (this.contextMenuPending || !cm.state.focused ||
  9489.         (hasSelection(input) && !prevInput && !this.composing) ||
  9490.         cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  9491.       { return false }
  9492.  
  9493.     var text = input.value;
  9494.     // If nothing changed, bail.
  9495.     if (text == prevInput && !cm.somethingSelected()) { return false }
  9496.     // Work around nonsensical selection resetting in IE9/10, and
  9497.     // inexplicable appearance of private area unicode characters on
  9498.     // some key combos in Mac (#2689).
  9499.     if (ie && ie_version >= 9 && this.hasSelection === text ||
  9500.         mac && /[\uf700-\uf7ff]/.test(text)) {
  9501.       cm.display.input.reset();
  9502.       return false
  9503.     }
  9504.  
  9505.     if (cm.doc.sel == cm.display.selForContextMenu) {
  9506.       var first = text.charCodeAt(0);
  9507.       if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  9508.       if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  9509.     }
  9510.     // Find the part of the input that is actually new
  9511.     var same = 0, l = Math.min(prevInput.length, text.length);
  9512.     while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  9513.  
  9514.     runInOp(cm, function () {
  9515.       applyTextInput(cm, text.slice(same), prevInput.length - same,
  9516.                      null, this$1.composing ? "*compose" : null);
  9517.  
  9518.       // Don't leave long text in the textarea, since it makes further polling slow
  9519.       if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  9520.       else { this$1.prevInput = text; }
  9521.  
  9522.       if (this$1.composing) {
  9523.         this$1.composing.range.clear();
  9524.         this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  9525.                                            {className: "CodeMirror-composing"});
  9526.       }
  9527.     });
  9528.     return true
  9529.   };
  9530.  
  9531.   TextareaInput.prototype.ensurePolled = function () {
  9532.     if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  9533.   };
  9534.  
  9535.   TextareaInput.prototype.onKeyPress = function () {
  9536.     if (ie && ie_version >= 9) { this.hasSelection = null; }
  9537.     this.fastPoll();
  9538.   };
  9539.  
  9540.   TextareaInput.prototype.onContextMenu = function (e) {
  9541.     var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  9542.     if (input.contextMenuPending) { input.contextMenuPending(); }
  9543.     var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  9544.     if (!pos || presto) { return } // Opera is difficult.
  9545.  
  9546.     // Reset the current text selection only if the click is done outside of the selection
  9547.     // and 'resetSelectionOnContextMenu' option is true.
  9548.     var reset = cm.options.resetSelectionOnContextMenu;
  9549.     if (reset && cm.doc.sel.contains(pos) == -1)
  9550.       { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  9551.  
  9552.     var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  9553.     var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
  9554.     input.wrapper.style.cssText = "position: static";
  9555.     te.style.cssText = "position: absolute; width: 30px; height: 30px;\n      top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n      z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n      outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  9556.     var oldScrollY;
  9557.     if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
  9558.     display.input.focus();
  9559.     if (webkit) { window.scrollTo(null, oldScrollY); }
  9560.     display.input.reset();
  9561.     // Adds "Select all" to context menu in FF
  9562.     if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  9563.     input.contextMenuPending = rehide;
  9564.     display.selForContextMenu = cm.doc.sel;
  9565.     clearTimeout(display.detectingSelectAll);
  9566.  
  9567.     // Select-all will be greyed out if there's nothing to select, so
  9568.     // this adds a zero-width space so that we can later check whether
  9569.     // it got selected.
  9570.     function prepareSelectAllHack() {
  9571.       if (te.selectionStart != null) {
  9572.         var selected = cm.somethingSelected();
  9573.         var extval = "\u200b" + (selected ? te.value : "");
  9574.         te.value = "\u21da"; // Used to catch context-menu undo
  9575.         te.value = extval;
  9576.         input.prevInput = selected ? "" : "\u200b";
  9577.         te.selectionStart = 1; te.selectionEnd = extval.length;
  9578.         // Re-set this, in case some other handler touched the
  9579.         // selection in the meantime.
  9580.         display.selForContextMenu = cm.doc.sel;
  9581.       }
  9582.     }
  9583.     function rehide() {
  9584.       if (input.contextMenuPending != rehide) { return }
  9585.       input.contextMenuPending = false;
  9586.       input.wrapper.style.cssText = oldWrapperCSS;
  9587.       te.style.cssText = oldCSS;
  9588.       if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  9589.  
  9590.       // Try to detect the user choosing select-all
  9591.       if (te.selectionStart != null) {
  9592.         if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  9593.         var i = 0, poll = function () {
  9594.           if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  9595.               te.selectionEnd > 0 && input.prevInput == "\u200b") {
  9596.             operation(cm, selectAll)(cm);
  9597.           } else if (i++ < 10) {
  9598.             display.detectingSelectAll = setTimeout(poll, 500);
  9599.           } else {
  9600.             display.selForContextMenu = null;
  9601.             display.input.reset();
  9602.           }
  9603.         };
  9604.         display.detectingSelectAll = setTimeout(poll, 200);
  9605.       }
  9606.     }
  9607.  
  9608.     if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  9609.     if (captureRightClick) {
  9610.       e_stop(e);
  9611.       var mouseup = function () {
  9612.         off(window, "mouseup", mouseup);
  9613.         setTimeout(rehide, 20);
  9614.       };
  9615.       on(window, "mouseup", mouseup);
  9616.     } else {
  9617.       setTimeout(rehide, 50);
  9618.     }
  9619.   };
  9620.  
  9621.   TextareaInput.prototype.readOnlyChanged = function (val) {
  9622.     if (!val) { this.reset(); }
  9623.     this.textarea.disabled = val == "nocursor";
  9624.   };
  9625.  
  9626.   TextareaInput.prototype.setUneditable = function () {};
  9627.  
  9628.   TextareaInput.prototype.needsContentAttribute = false;
  9629.  
  9630.   function fromTextArea(textarea, options) {
  9631.     options = options ? copyObj(options) : {};
  9632.     options.value = textarea.value;
  9633.     if (!options.tabindex && textarea.tabIndex)
  9634.       { options.tabindex = textarea.tabIndex; }
  9635.     if (!options.placeholder && textarea.placeholder)
  9636.       { options.placeholder = textarea.placeholder; }
  9637.     // Set autofocus to true if this textarea is focused, or if it has
  9638.     // autofocus and no other element is focused.
  9639.     if (options.autofocus == null) {
  9640.       var hasFocus = activeElt();
  9641.       options.autofocus = hasFocus == textarea ||
  9642.         textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  9643.     }
  9644.  
  9645.     function save() {textarea.value = cm.getValue();}
  9646.  
  9647.     var realSubmit;
  9648.     if (textarea.form) {
  9649.       on(textarea.form, "submit", save);
  9650.       // Deplorable hack to make the submit method do the right thing.
  9651.       if (!options.leaveSubmitMethodAlone) {
  9652.         var form = textarea.form;
  9653.         realSubmit = form.submit;
  9654.         try {
  9655.           var wrappedSubmit = form.submit = function () {
  9656.             save();
  9657.             form.submit = realSubmit;
  9658.             form.submit();
  9659.             form.submit = wrappedSubmit;
  9660.           };
  9661.         } catch(e) {}
  9662.       }
  9663.     }
  9664.  
  9665.     options.finishInit = function (cm) {
  9666.       cm.save = save;
  9667.       cm.getTextArea = function () { return textarea; };
  9668.       cm.toTextArea = function () {
  9669.         cm.toTextArea = isNaN; // Prevent this from being ran twice
  9670.         save();
  9671.         textarea.parentNode.removeChild(cm.getWrapperElement());
  9672.         textarea.style.display = "";
  9673.         if (textarea.form) {
  9674.           off(textarea.form, "submit", save);
  9675.           if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
  9676.             { textarea.form.submit = realSubmit; }
  9677.         }
  9678.       };
  9679.     };
  9680.  
  9681.     textarea.style.display = "none";
  9682.     var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  9683.       options);
  9684.     return cm
  9685.   }
  9686.  
  9687.   function addLegacyProps(CodeMirror) {
  9688.     CodeMirror.off = off;
  9689.     CodeMirror.on = on;
  9690.     CodeMirror.wheelEventPixels = wheelEventPixels;
  9691.     CodeMirror.Doc = Doc;
  9692.     CodeMirror.splitLines = splitLinesAuto;
  9693.     CodeMirror.countColumn = countColumn;
  9694.     CodeMirror.findColumn = findColumn;
  9695.     CodeMirror.isWordChar = isWordCharBasic;
  9696.     CodeMirror.Pass = Pass;
  9697.     CodeMirror.signal = signal;
  9698.     CodeMirror.Line = Line;
  9699.     CodeMirror.changeEnd = changeEnd;
  9700.     CodeMirror.scrollbarModel = scrollbarModel;
  9701.     CodeMirror.Pos = Pos;
  9702.     CodeMirror.cmpPos = cmp;
  9703.     CodeMirror.modes = modes;
  9704.     CodeMirror.mimeModes = mimeModes;
  9705.     CodeMirror.resolveMode = resolveMode;
  9706.     CodeMirror.getMode = getMode;
  9707.     CodeMirror.modeExtensions = modeExtensions;
  9708.     CodeMirror.extendMode = extendMode;
  9709.     CodeMirror.copyState = copyState;
  9710.     CodeMirror.startState = startState;
  9711.     CodeMirror.innerMode = innerMode;
  9712.     CodeMirror.commands = commands;
  9713.     CodeMirror.keyMap = keyMap;
  9714.     CodeMirror.keyName = keyName;
  9715.     CodeMirror.isModifierKey = isModifierKey;
  9716.     CodeMirror.lookupKey = lookupKey;
  9717.     CodeMirror.normalizeKeyMap = normalizeKeyMap;
  9718.     CodeMirror.StringStream = StringStream;
  9719.     CodeMirror.SharedTextMarker = SharedTextMarker;
  9720.     CodeMirror.TextMarker = TextMarker;
  9721.     CodeMirror.LineWidget = LineWidget;
  9722.     CodeMirror.e_preventDefault = e_preventDefault;
  9723.     CodeMirror.e_stopPropagation = e_stopPropagation;
  9724.     CodeMirror.e_stop = e_stop;
  9725.     CodeMirror.addClass = addClass;
  9726.     CodeMirror.contains = contains;
  9727.     CodeMirror.rmClass = rmClass;
  9728.     CodeMirror.keyNames = keyNames;
  9729.   }
  9730.  
  9731.   // EDITOR CONSTRUCTOR
  9732.  
  9733.   defineOptions(CodeMirror);
  9734.  
  9735.   addEditorMethods(CodeMirror);
  9736.  
  9737.   // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  9738.   var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  9739.   for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  9740.     { CodeMirror.prototype[prop] = (function(method) {
  9741.       return function() {return method.apply(this.doc, arguments)}
  9742.     })(Doc.prototype[prop]); } }
  9743.  
  9744.   eventMixin(Doc);
  9745.   CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  9746.  
  9747.   // Extra arguments are stored as the mode's dependencies, which is
  9748.   // used by (legacy) mechanisms like loadmode.js to automatically
  9749.   // load a mode. (Preferred mechanism is the require/define calls.)
  9750.   CodeMirror.defineMode = function(name/*, mode, …*/) {
  9751.     if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
  9752.     defineMode.apply(this, arguments);
  9753.   };
  9754.  
  9755.   CodeMirror.defineMIME = defineMIME;
  9756.  
  9757.   // Minimal default mode.
  9758.   CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  9759.   CodeMirror.defineMIME("text/plain", "null");
  9760.  
  9761.   // EXTENSIONS
  9762.  
  9763.   CodeMirror.defineExtension = function (name, func) {
  9764.     CodeMirror.prototype[name] = func;
  9765.   };
  9766.   CodeMirror.defineDocExtension = function (name, func) {
  9767.     Doc.prototype[name] = func;
  9768.   };
  9769.  
  9770.   CodeMirror.fromTextArea = fromTextArea;
  9771.  
  9772.   addLegacyProps(CodeMirror);
  9773.  
  9774.   CodeMirror.version = "5.54.0";
  9775.  
  9776.   return CodeMirror;
  9777.  
  9778. })));
  9779.