Subversion Repositories wimsdev

Rev

Rev 16493 | Rev 17702 | 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/5/LICENSE
  3.  
  4. // This is CodeMirror (https://codemirror.net/5), 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\/(\d+)/.exec(userAgent);
  30.   var chrome_version = chrome && +chrome[1];
  31.   var presto = /Opera\//.test(userAgent);
  32.   var safari = /Apple Computer/.test(navigator.vendor);
  33.   var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  34.   var phantom = /PhantomJS/.test(userAgent);
  35.  
  36.   var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2);
  37.   var android = /Android/.test(userAgent);
  38.   // This is woefully incomplete. Suggestions for alternative methods welcome.
  39.   var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  40.   var mac = ios || /Mac/.test(platform);
  41.   var chromeOS = /\bCrOS\b/.test(userAgent);
  42.   var windows = /win/i.test(platform);
  43.  
  44.   var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  45.   if (presto_version) { presto_version = Number(presto_version[1]); }
  46.   if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  47.   // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  48.   var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  49.   var captureRightClick = gecko || (ie && ie_version >= 9);
  50.  
  51.   function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  52.  
  53.   var rmClass = function(node, cls) {
  54.     var current = node.className;
  55.     var match = classTest(cls).exec(current);
  56.     if (match) {
  57.       var after = current.slice(match.index + match[0].length);
  58.       node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  59.     }
  60.   };
  61.  
  62.   function removeChildren(e) {
  63.     for (var count = e.childNodes.length; count > 0; --count)
  64.       { e.removeChild(e.firstChild); }
  65.     return e
  66.   }
  67.  
  68.   function removeChildrenAndAdd(parent, e) {
  69.     return removeChildren(parent).appendChild(e)
  70.   }
  71.  
  72.   function elt(tag, content, className, style) {
  73.     var e = document.createElement(tag);
  74.     if (className) { e.className = className; }
  75.     if (style) { e.style.cssText = style; }
  76.     if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
  77.     else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
  78.     return e
  79.   }
  80.   // wrapper for elt, which removes the elt from the accessibility tree
  81.   function eltP(tag, content, className, style) {
  82.     var e = elt(tag, content, className, style);
  83.     e.setAttribute("role", "presentation");
  84.     return e
  85.   }
  86.  
  87.   var range;
  88.   if (document.createRange) { range = function(node, start, end, endNode) {
  89.     var r = document.createRange();
  90.     r.setEnd(endNode || node, end);
  91.     r.setStart(node, start);
  92.     return r
  93.   }; }
  94.   else { range = function(node, start, end) {
  95.     var r = document.body.createTextRange();
  96.     try { r.moveToElementText(node.parentNode); }
  97.     catch(e) { return r }
  98.     r.collapse(true);
  99.     r.moveEnd("character", end);
  100.     r.moveStart("character", start);
  101.     return r
  102.   }; }
  103.  
  104.   function contains(parent, child) {
  105.     if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  106.       { child = child.parentNode; }
  107.     if (parent.contains)
  108.       { return parent.contains(child) }
  109.     do {
  110.       if (child.nodeType == 11) { child = child.host; }
  111.       if (child == parent) { return true }
  112.     } while (child = child.parentNode)
  113.   }
  114.  
  115.   function activeElt() {
  116.     // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  117.     // IE < 10 will throw when accessed while the page is loading or in an iframe.
  118.     // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  119.     var activeElement;
  120.     try {
  121.       activeElement = document.activeElement;
  122.     } catch(e) {
  123.       activeElement = document.body || null;
  124.     }
  125.     while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  126.       { activeElement = activeElement.shadowRoot.activeElement; }
  127.     return activeElement
  128.   }
  129.  
  130.   function addClass(node, cls) {
  131.     var current = node.className;
  132.     if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
  133.   }
  134.   function joinClasses(a, b) {
  135.     var as = a.split(" ");
  136.     for (var i = 0; i < as.length; i++)
  137.       { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
  138.     return b
  139.   }
  140.  
  141.   var selectInput = function(node) { node.select(); };
  142.   if (ios) // Mobile Safari apparently has a bug where select() is broken.
  143.     { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
  144.   else if (ie) // Suppress mysterious IE10 errors
  145.     { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
  146.  
  147.   function bind(f) {
  148.     var args = Array.prototype.slice.call(arguments, 1);
  149.     return function(){return f.apply(null, args)}
  150.   }
  151.  
  152.   function copyObj(obj, target, overwrite) {
  153.     if (!target) { target = {}; }
  154.     for (var prop in obj)
  155.       { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  156.         { target[prop] = obj[prop]; } }
  157.     return target
  158.   }
  159.  
  160.   // Counts the column offset in a string, taking tabs into account.
  161.   // Used mostly to find indentation.
  162.   function countColumn(string, end, tabSize, startIndex, startValue) {
  163.     if (end == null) {
  164.       end = string.search(/[^\s\u00a0]/);
  165.       if (end == -1) { end = string.length; }
  166.     }
  167.     for (var i = startIndex || 0, n = startValue || 0;;) {
  168.       var nextTab = string.indexOf("\t", i);
  169.       if (nextTab < 0 || nextTab >= end)
  170.         { return n + (end - i) }
  171.       n += nextTab - i;
  172.       n += tabSize - (n % tabSize);
  173.       i = nextTab + 1;
  174.     }
  175.   }
  176.  
  177.   var Delayed = function() {
  178.     this.id = null;
  179.     this.f = null;
  180.     this.time = 0;
  181.     this.handler = bind(this.onTimeout, this);
  182.   };
  183.   Delayed.prototype.onTimeout = function (self) {
  184.     self.id = 0;
  185.     if (self.time <= +new Date) {
  186.       self.f();
  187.     } else {
  188.       setTimeout(self.handler, self.time - +new Date);
  189.     }
  190.   };
  191.   Delayed.prototype.set = function (ms, f) {
  192.     this.f = f;
  193.     var time = +new Date + ms;
  194.     if (!this.id || time < this.time) {
  195.       clearTimeout(this.id);
  196.       this.id = setTimeout(this.handler, ms);
  197.       this.time = time;
  198.     }
  199.   };
  200.  
  201.   function indexOf(array, elt) {
  202.     for (var i = 0; i < array.length; ++i)
  203.       { if (array[i] == elt) { return i } }
  204.     return -1
  205.   }
  206.  
  207.   // Number of pixels added to scroller and sizer to hide scrollbar
  208.   var scrollerGap = 50;
  209.  
  210.   // Returned or thrown by various protocols to signal 'I'm not
  211.   // handling this'.
  212.   var Pass = {toString: function(){return "CodeMirror.Pass"}};
  213.  
  214.   // Reused option objects for setSelection & friends
  215.   var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  216.  
  217.   // The inverse of countColumn -- find the offset that corresponds to
  218.   // a particular column.
  219.   function findColumn(string, goal, tabSize) {
  220.     for (var pos = 0, col = 0;;) {
  221.       var nextTab = string.indexOf("\t", pos);
  222.       if (nextTab == -1) { nextTab = string.length; }
  223.       var skipped = nextTab - pos;
  224.       if (nextTab == string.length || col + skipped >= goal)
  225.         { return pos + Math.min(skipped, goal - col) }
  226.       col += nextTab - pos;
  227.       col += tabSize - (col % tabSize);
  228.       pos = nextTab + 1;
  229.       if (col >= goal) { return pos }
  230.     }
  231.   }
  232.  
  233.   var spaceStrs = [""];
  234.   function spaceStr(n) {
  235.     while (spaceStrs.length <= n)
  236.       { spaceStrs.push(lst(spaceStrs) + " "); }
  237.     return spaceStrs[n]
  238.   }
  239.  
  240.   function lst(arr) { return arr[arr.length-1] }
  241.  
  242.   function map(array, f) {
  243.     var out = [];
  244.     for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  245.     return out
  246.   }
  247.  
  248.   function insertSorted(array, value, score) {
  249.     var pos = 0, priority = score(value);
  250.     while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  251.     array.splice(pos, 0, value);
  252.   }
  253.  
  254.   function nothing() {}
  255.  
  256.   function createObj(base, props) {
  257.     var inst;
  258.     if (Object.create) {
  259.       inst = Object.create(base);
  260.     } else {
  261.       nothing.prototype = base;
  262.       inst = new nothing();
  263.     }
  264.     if (props) { copyObj(props, inst); }
  265.     return inst
  266.   }
  267.  
  268.   var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  269.   function isWordCharBasic(ch) {
  270.     return /\w/.test(ch) || ch > "\x80" &&
  271.       (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  272.   }
  273.   function isWordChar(ch, helper) {
  274.     if (!helper) { return isWordCharBasic(ch) }
  275.     if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  276.     return helper.test(ch)
  277.   }
  278.  
  279.   function isEmpty(obj) {
  280.     for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  281.     return true
  282.   }
  283.  
  284.   // Extending unicode characters. A series of a non-extending char +
  285.   // any number of extending chars is treated as a single unit as far
  286.   // as editing and measuring is concerned. This is not fully correct,
  287.   // since some scripts/fonts/browsers also treat other configurations
  288.   // of code points as a group.
  289.   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]/;
  290.   function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  291.  
  292.   // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  293.   function skipExtendingChars(str, pos, dir) {
  294.     while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  295.     return pos
  296.   }
  297.  
  298.   // Returns the value from the range [`from`; `to`] that satisfies
  299.   // `pred` and is closest to `from`. Assumes that at least `to`
  300.   // satisfies `pred`. Supports `from` being greater than `to`.
  301.   function findFirst(pred, from, to) {
  302.     // At any point we are certain `to` satisfies `pred`, don't know
  303.     // whether `from` does.
  304.     var dir = from > to ? -1 : 1;
  305.     for (;;) {
  306.       if (from == to) { return from }
  307.       var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  308.       if (mid == from) { return pred(mid) ? from : to }
  309.       if (pred(mid)) { to = mid; }
  310.       else { from = mid + dir; }
  311.     }
  312.   }
  313.  
  314.   // BIDI HELPERS
  315.  
  316.   function iterateBidiSections(order, from, to, f) {
  317.     if (!order) { return f(from, to, "ltr", 0) }
  318.     var found = false;
  319.     for (var i = 0; i < order.length; ++i) {
  320.       var part = order[i];
  321.       if (part.from < to && part.to > from || from == to && part.to == from) {
  322.         f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  323.         found = true;
  324.       }
  325.     }
  326.     if (!found) { f(from, to, "ltr"); }
  327.   }
  328.  
  329.   var bidiOther = null;
  330.   function getBidiPartAt(order, ch, sticky) {
  331.     var found;
  332.     bidiOther = null;
  333.     for (var i = 0; i < order.length; ++i) {
  334.       var cur = order[i];
  335.       if (cur.from < ch && cur.to > ch) { return i }
  336.       if (cur.to == ch) {
  337.         if (cur.from != cur.to && sticky == "before") { found = i; }
  338.         else { bidiOther = i; }
  339.       }
  340.       if (cur.from == ch) {
  341.         if (cur.from != cur.to && sticky != "before") { found = i; }
  342.         else { bidiOther = i; }
  343.       }
  344.     }
  345.     return found != null ? found : bidiOther
  346.   }
  347.  
  348.   // Bidirectional ordering algorithm
  349.   // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  350.   // that this (partially) implements.
  351.  
  352.   // One-char codes used for character types:
  353.   // L (L):   Left-to-Right
  354.   // R (R):   Right-to-Left
  355.   // r (AL):  Right-to-Left Arabic
  356.   // 1 (EN):  European Number
  357.   // + (ES):  European Number Separator
  358.   // % (ET):  European Number Terminator
  359.   // n (AN):  Arabic Number
  360.   // , (CS):  Common Number Separator
  361.   // m (NSM): Non-Spacing Mark
  362.   // b (BN):  Boundary Neutral
  363.   // s (B):   Paragraph Separator
  364.   // t (S):   Segment Separator
  365.   // w (WS):  Whitespace
  366.   // N (ON):  Other Neutrals
  367.  
  368.   // Returns null if characters are ordered as they appear
  369.   // (left-to-right), or an array of sections ({from, to, level}
  370.   // objects) in the order in which they occur visually.
  371.   var bidiOrdering = (function() {
  372.     // Character types for codepoints 0 to 0xff
  373.     var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  374.     // Character types for codepoints 0x600 to 0x6f9
  375.     var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  376.     function charType(code) {
  377.       if (code <= 0xf7) { return lowTypes.charAt(code) }
  378.       else if (0x590 <= code && code <= 0x5f4) { return "R" }
  379.       else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  380.       else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  381.       else if (0x2000 <= code && code <= 0x200b) { return "w" }
  382.       else if (code == 0x200c) { return "b" }
  383.       else { return "L" }
  384.     }
  385.  
  386.     var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  387.     var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  388.  
  389.     function BidiSpan(level, from, to) {
  390.       this.level = level;
  391.       this.from = from; this.to = to;
  392.     }
  393.  
  394.     return function(str, direction) {
  395.       var outerType = direction == "ltr" ? "L" : "R";
  396.  
  397.       if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  398.       var len = str.length, types = [];
  399.       for (var i = 0; i < len; ++i)
  400.         { types.push(charType(str.charCodeAt(i))); }
  401.  
  402.       // W1. Examine each non-spacing mark (NSM) in the level run, and
  403.       // change the type of the NSM to the type of the previous
  404.       // character. If the NSM is at the start of the level run, it will
  405.       // get the type of sor.
  406.       for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  407.         var type = types[i$1];
  408.         if (type == "m") { types[i$1] = prev; }
  409.         else { prev = type; }
  410.       }
  411.  
  412.       // W2. Search backwards from each instance of a European number
  413.       // until the first strong type (R, L, AL, or sor) is found. If an
  414.       // AL is found, change the type of the European number to Arabic
  415.       // number.
  416.       // W3. Change all ALs to R.
  417.       for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  418.         var type$1 = types[i$2];
  419.         if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  420.         else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  421.       }
  422.  
  423.       // W4. A single European separator between two European numbers
  424.       // changes to a European number. A single common separator between
  425.       // two numbers of the same type changes to that type.
  426.       for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  427.         var type$2 = types[i$3];
  428.         if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  429.         else if (type$2 == "," && prev$1 == types[i$3+1] &&
  430.                  (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  431.         prev$1 = type$2;
  432.       }
  433.  
  434.       // W5. A sequence of European terminators adjacent to European
  435.       // numbers changes to all European numbers.
  436.       // W6. Otherwise, separators and terminators change to Other
  437.       // Neutral.
  438.       for (var i$4 = 0; i$4 < len; ++i$4) {
  439.         var type$3 = types[i$4];
  440.         if (type$3 == ",") { types[i$4] = "N"; }
  441.         else if (type$3 == "%") {
  442.           var end = (void 0);
  443.           for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  444.           var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  445.           for (var j = i$4; j < end; ++j) { types[j] = replace; }
  446.           i$4 = end - 1;
  447.         }
  448.       }
  449.  
  450.       // W7. Search backwards from each instance of a European number
  451.       // until the first strong type (R, L, or sor) is found. If an L is
  452.       // found, then change the type of the European number to L.
  453.       for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  454.         var type$4 = types[i$5];
  455.         if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  456.         else if (isStrong.test(type$4)) { cur$1 = type$4; }
  457.       }
  458.  
  459.       // N1. A sequence of neutrals takes the direction of the
  460.       // surrounding strong text if the text on both sides has the same
  461.       // direction. European and Arabic numbers act as if they were R in
  462.       // terms of their influence on neutrals. Start-of-level-run (sor)
  463.       // and end-of-level-run (eor) are used at level run boundaries.
  464.       // N2. Any remaining neutrals take the embedding direction.
  465.       for (var i$6 = 0; i$6 < len; ++i$6) {
  466.         if (isNeutral.test(types[i$6])) {
  467.           var end$1 = (void 0);
  468.           for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  469.           var before = (i$6 ? types[i$6-1] : outerType) == "L";
  470.           var after = (end$1 < len ? types[end$1] : outerType) == "L";
  471.           var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  472.           for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  473.           i$6 = end$1 - 1;
  474.         }
  475.       }
  476.  
  477.       // Here we depart from the documented algorithm, in order to avoid
  478.       // building up an actual levels array. Since there are only three
  479.       // levels (0, 1, 2) in an implementation that doesn't take
  480.       // explicit embedding into account, we can build up the order on
  481.       // the fly, without following the level-based algorithm.
  482.       var order = [], m;
  483.       for (var i$7 = 0; i$7 < len;) {
  484.         if (countsAsLeft.test(types[i$7])) {
  485.           var start = i$7;
  486.           for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  487.           order.push(new BidiSpan(0, start, i$7));
  488.         } else {
  489.           var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
  490.           for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  491.           for (var j$2 = pos; j$2 < i$7;) {
  492.             if (countsAsNum.test(types[j$2])) {
  493.               if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
  494.               var nstart = j$2;
  495.               for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  496.               order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  497.               at += isRTL;
  498.               pos = j$2;
  499.             } else { ++j$2; }
  500.           }
  501.           if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  502.         }
  503.       }
  504.       if (direction == "ltr") {
  505.         if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  506.           order[0].from = m[0].length;
  507.           order.unshift(new BidiSpan(0, 0, m[0].length));
  508.         }
  509.         if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  510.           lst(order).to -= m[0].length;
  511.           order.push(new BidiSpan(0, len - m[0].length, len));
  512.         }
  513.       }
  514.  
  515.       return direction == "rtl" ? order.reverse() : order
  516.     }
  517.   })();
  518.  
  519.   // Get the bidi ordering for the given line (and cache it). Returns
  520.   // false for lines that are fully left-to-right, and an array of
  521.   // BidiSpan objects otherwise.
  522.   function getOrder(line, direction) {
  523.     var order = line.order;
  524.     if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  525.     return order
  526.   }
  527.  
  528.   // EVENT HANDLING
  529.  
  530.   // Lightweight event framework. on/off also work on DOM nodes,
  531.   // registering native DOM handlers.
  532.  
  533.   var noHandlers = [];
  534.  
  535.   var on = function(emitter, type, f) {
  536.     if (emitter.addEventListener) {
  537.       emitter.addEventListener(type, f, false);
  538.     } else if (emitter.attachEvent) {
  539.       emitter.attachEvent("on" + type, f);
  540.     } else {
  541.       var map = emitter._handlers || (emitter._handlers = {});
  542.       map[type] = (map[type] || noHandlers).concat(f);
  543.     }
  544.   };
  545.  
  546.   function getHandlers(emitter, type) {
  547.     return emitter._handlers && emitter._handlers[type] || noHandlers
  548.   }
  549.  
  550.   function off(emitter, type, f) {
  551.     if (emitter.removeEventListener) {
  552.       emitter.removeEventListener(type, f, false);
  553.     } else if (emitter.detachEvent) {
  554.       emitter.detachEvent("on" + type, f);
  555.     } else {
  556.       var map = emitter._handlers, arr = map && map[type];
  557.       if (arr) {
  558.         var index = indexOf(arr, f);
  559.         if (index > -1)
  560.           { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  561.       }
  562.     }
  563.   }
  564.  
  565.   function signal(emitter, type /*, values...*/) {
  566.     var handlers = getHandlers(emitter, type);
  567.     if (!handlers.length) { return }
  568.     var args = Array.prototype.slice.call(arguments, 2);
  569.     for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  570.   }
  571.  
  572.   // The DOM events that CodeMirror handles can be overridden by
  573.   // registering a (non-DOM) handler on the editor for the event name,
  574.   // and preventDefault-ing the event in that handler.
  575.   function signalDOMEvent(cm, e, override) {
  576.     if (typeof e == "string")
  577.       { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  578.     signal(cm, override || e.type, cm, e);
  579.     return e_defaultPrevented(e) || e.codemirrorIgnore
  580.   }
  581.  
  582.   function signalCursorActivity(cm) {
  583.     var arr = cm._handlers && cm._handlers.cursorActivity;
  584.     if (!arr) { return }
  585.     var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  586.     for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  587.       { set.push(arr[i]); } }
  588.   }
  589.  
  590.   function hasHandler(emitter, type) {
  591.     return getHandlers(emitter, type).length > 0
  592.   }
  593.  
  594.   // Add on and off methods to a constructor's prototype, to make
  595.   // registering events on such objects more convenient.
  596.   function eventMixin(ctor) {
  597.     ctor.prototype.on = function(type, f) {on(this, type, f);};
  598.     ctor.prototype.off = function(type, f) {off(this, type, f);};
  599.   }
  600.  
  601.   // Due to the fact that we still support jurassic IE versions, some
  602.   // compatibility wrappers are needed.
  603.  
  604.   function e_preventDefault(e) {
  605.     if (e.preventDefault) { e.preventDefault(); }
  606.     else { e.returnValue = false; }
  607.   }
  608.   function e_stopPropagation(e) {
  609.     if (e.stopPropagation) { e.stopPropagation(); }
  610.     else { e.cancelBubble = true; }
  611.   }
  612.   function e_defaultPrevented(e) {
  613.     return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  614.   }
  615.   function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  616.  
  617.   function e_target(e) {return e.target || e.srcElement}
  618.   function e_button(e) {
  619.     var b = e.which;
  620.     if (b == null) {
  621.       if (e.button & 1) { b = 1; }
  622.       else if (e.button & 2) { b = 3; }
  623.       else if (e.button & 4) { b = 2; }
  624.     }
  625.     if (mac && e.ctrlKey && b == 1) { b = 3; }
  626.     return b
  627.   }
  628.  
  629.   // Detect drag-and-drop
  630.   var dragAndDrop = function() {
  631.     // There is *some* kind of drag-and-drop support in IE6-8, but I
  632.     // couldn't get it to work yet.
  633.     if (ie && ie_version < 9) { return false }
  634.     var div = elt('div');
  635.     return "draggable" in div || "dragDrop" in div
  636.   }();
  637.  
  638.   var zwspSupported;
  639.   function zeroWidthElement(measure) {
  640.     if (zwspSupported == null) {
  641.       var test = elt("span", "\u200b");
  642.       removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  643.       if (measure.firstChild.offsetHeight != 0)
  644.         { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  645.     }
  646.     var node = zwspSupported ? elt("span", "\u200b") :
  647.       elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  648.     node.setAttribute("cm-text", "");
  649.     return node
  650.   }
  651.  
  652.   // Feature-detect IE's crummy client rect reporting for bidi text
  653.   var badBidiRects;
  654.   function hasBadBidiRects(measure) {
  655.     if (badBidiRects != null) { return badBidiRects }
  656.     var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  657.     var r0 = range(txt, 0, 1).getBoundingClientRect();
  658.     var r1 = range(txt, 1, 2).getBoundingClientRect();
  659.     removeChildren(measure);
  660.     if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  661.     return badBidiRects = (r1.right - r0.right < 3)
  662.   }
  663.  
  664.   // See if "".split is the broken IE version, if so, provide an
  665.   // alternative way to split lines.
  666.   var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  667.     var pos = 0, result = [], l = string.length;
  668.     while (pos <= l) {
  669.       var nl = string.indexOf("\n", pos);
  670.       if (nl == -1) { nl = string.length; }
  671.       var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  672.       var rt = line.indexOf("\r");
  673.       if (rt != -1) {
  674.         result.push(line.slice(0, rt));
  675.         pos += rt + 1;
  676.       } else {
  677.         result.push(line);
  678.         pos = nl + 1;
  679.       }
  680.     }
  681.     return result
  682.   } : function (string) { return string.split(/\r\n?|\n/); };
  683.  
  684.   var hasSelection = window.getSelection ? function (te) {
  685.     try { return te.selectionStart != te.selectionEnd }
  686.     catch(e) { return false }
  687.   } : function (te) {
  688.     var range;
  689.     try {range = te.ownerDocument.selection.createRange();}
  690.     catch(e) {}
  691.     if (!range || range.parentElement() != te) { return false }
  692.     return range.compareEndPoints("StartToEnd", range) != 0
  693.   };
  694.  
  695.   var hasCopyEvent = (function () {
  696.     var e = elt("div");
  697.     if ("oncopy" in e) { return true }
  698.     e.setAttribute("oncopy", "return;");
  699.     return typeof e.oncopy == "function"
  700.   })();
  701.  
  702.   var badZoomedRects = null;
  703.   function hasBadZoomedRects(measure) {
  704.     if (badZoomedRects != null) { return badZoomedRects }
  705.     var node = removeChildrenAndAdd(measure, elt("span", "x"));
  706.     var normal = node.getBoundingClientRect();
  707.     var fromRange = range(node, 0, 1).getBoundingClientRect();
  708.     return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  709.   }
  710.  
  711.   // Known modes, by name and by MIME
  712.   var modes = {}, mimeModes = {};
  713.  
  714.   // Extra arguments are stored as the mode's dependencies, which is
  715.   // used by (legacy) mechanisms like loadmode.js to automatically
  716.   // load a mode. (Preferred mechanism is the require/define calls.)
  717.   function defineMode(name, mode) {
  718.     if (arguments.length > 2)
  719.       { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  720.     modes[name] = mode;
  721.   }
  722.  
  723.   function defineMIME(mime, spec) {
  724.     mimeModes[mime] = spec;
  725.   }
  726.  
  727.   // Given a MIME type, a {name, ...options} config object, or a name
  728.   // string, return a mode config object.
  729.   function resolveMode(spec) {
  730.     if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  731.       spec = mimeModes[spec];
  732.     } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  733.       var found = mimeModes[spec.name];
  734.       if (typeof found == "string") { found = {name: found}; }
  735.       spec = createObj(found, spec);
  736.       spec.name = found.name;
  737.     } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  738.       return resolveMode("application/xml")
  739.     } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  740.       return resolveMode("application/json")
  741.     }
  742.     if (typeof spec == "string") { return {name: spec} }
  743.     else { return spec || {name: "null"} }
  744.   }
  745.  
  746.   // Given a mode spec (anything that resolveMode accepts), find and
  747.   // initialize an actual mode object.
  748.   function getMode(options, spec) {
  749.     spec = resolveMode(spec);
  750.     var mfactory = modes[spec.name];
  751.     if (!mfactory) { return getMode(options, "text/plain") }
  752.     var modeObj = mfactory(options, spec);
  753.     if (modeExtensions.hasOwnProperty(spec.name)) {
  754.       var exts = modeExtensions[spec.name];
  755.       for (var prop in exts) {
  756.         if (!exts.hasOwnProperty(prop)) { continue }
  757.         if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  758.         modeObj[prop] = exts[prop];
  759.       }
  760.     }
  761.     modeObj.name = spec.name;
  762.     if (spec.helperType) { modeObj.helperType = spec.helperType; }
  763.     if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  764.       { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  765.  
  766.     return modeObj
  767.   }
  768.  
  769.   // This can be used to attach properties to mode objects from
  770.   // outside the actual mode definition.
  771.   var modeExtensions = {};
  772.   function extendMode(mode, properties) {
  773.     var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  774.     copyObj(properties, exts);
  775.   }
  776.  
  777.   function copyState(mode, state) {
  778.     if (state === true) { return state }
  779.     if (mode.copyState) { return mode.copyState(state) }
  780.     var nstate = {};
  781.     for (var n in state) {
  782.       var val = state[n];
  783.       if (val instanceof Array) { val = val.concat([]); }
  784.       nstate[n] = val;
  785.     }
  786.     return nstate
  787.   }
  788.  
  789.   // Given a mode and a state (for that mode), find the inner mode and
  790.   // state at the position that the state refers to.
  791.   function innerMode(mode, state) {
  792.     var info;
  793.     while (mode.innerMode) {
  794.       info = mode.innerMode(state);
  795.       if (!info || info.mode == mode) { break }
  796.       state = info.state;
  797.       mode = info.mode;
  798.     }
  799.     return info || {mode: mode, state: state}
  800.   }
  801.  
  802.   function startState(mode, a1, a2) {
  803.     return mode.startState ? mode.startState(a1, a2) : true
  804.   }
  805.  
  806.   // STRING STREAM
  807.  
  808.   // Fed to the mode parsers, provides helper functions to make
  809.   // parsers more succinct.
  810.  
  811.   var StringStream = function(string, tabSize, lineOracle) {
  812.     this.pos = this.start = 0;
  813.     this.string = string;
  814.     this.tabSize = tabSize || 8;
  815.     this.lastColumnPos = this.lastColumnValue = 0;
  816.     this.lineStart = 0;
  817.     this.lineOracle = lineOracle;
  818.   };
  819.  
  820.   StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  821.   StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  822.   StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  823.   StringStream.prototype.next = function () {
  824.     if (this.pos < this.string.length)
  825.       { return this.string.charAt(this.pos++) }
  826.   };
  827.   StringStream.prototype.eat = function (match) {
  828.     var ch = this.string.charAt(this.pos);
  829.     var ok;
  830.     if (typeof match == "string") { ok = ch == match; }
  831.     else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  832.     if (ok) {++this.pos; return ch}
  833.   };
  834.   StringStream.prototype.eatWhile = function (match) {
  835.     var start = this.pos;
  836.     while (this.eat(match)){}
  837.     return this.pos > start
  838.   };
  839.   StringStream.prototype.eatSpace = function () {
  840.     var start = this.pos;
  841.     while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
  842.     return this.pos > start
  843.   };
  844.   StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  845.   StringStream.prototype.skipTo = function (ch) {
  846.     var found = this.string.indexOf(ch, this.pos);
  847.     if (found > -1) {this.pos = found; return true}
  848.   };
  849.   StringStream.prototype.backUp = function (n) {this.pos -= n;};
  850.   StringStream.prototype.column = function () {
  851.     if (this.lastColumnPos < this.start) {
  852.       this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  853.       this.lastColumnPos = this.start;
  854.     }
  855.     return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  856.   };
  857.   StringStream.prototype.indentation = function () {
  858.     return countColumn(this.string, null, this.tabSize) -
  859.       (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  860.   };
  861.   StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  862.     if (typeof pattern == "string") {
  863.       var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  864.       var substr = this.string.substr(this.pos, pattern.length);
  865.       if (cased(substr) == cased(pattern)) {
  866.         if (consume !== false) { this.pos += pattern.length; }
  867.         return true
  868.       }
  869.     } else {
  870.       var match = this.string.slice(this.pos).match(pattern);
  871.       if (match && match.index > 0) { return null }
  872.       if (match && consume !== false) { this.pos += match[0].length; }
  873.       return match
  874.     }
  875.   };
  876.   StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  877.   StringStream.prototype.hideFirstChars = function (n, inner) {
  878.     this.lineStart += n;
  879.     try { return inner() }
  880.     finally { this.lineStart -= n; }
  881.   };
  882.   StringStream.prototype.lookAhead = function (n) {
  883.     var oracle = this.lineOracle;
  884.     return oracle && oracle.lookAhead(n)
  885.   };
  886.   StringStream.prototype.baseToken = function () {
  887.     var oracle = this.lineOracle;
  888.     return oracle && oracle.baseToken(this.pos)
  889.   };
  890.  
  891.   // Find the line object corresponding to the given line number.
  892.   function getLine(doc, n) {
  893.     n -= doc.first;
  894.     if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  895.     var chunk = doc;
  896.     while (!chunk.lines) {
  897.       for (var i = 0;; ++i) {
  898.         var child = chunk.children[i], sz = child.chunkSize();
  899.         if (n < sz) { chunk = child; break }
  900.         n -= sz;
  901.       }
  902.     }
  903.     return chunk.lines[n]
  904.   }
  905.  
  906.   // Get the part of a document between two positions, as an array of
  907.   // strings.
  908.   function getBetween(doc, start, end) {
  909.     var out = [], n = start.line;
  910.     doc.iter(start.line, end.line + 1, function (line) {
  911.       var text = line.text;
  912.       if (n == end.line) { text = text.slice(0, end.ch); }
  913.       if (n == start.line) { text = text.slice(start.ch); }
  914.       out.push(text);
  915.       ++n;
  916.     });
  917.     return out
  918.   }
  919.   // Get the lines between from and to, as array of strings.
  920.   function getLines(doc, from, to) {
  921.     var out = [];
  922.     doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  923.     return out
  924.   }
  925.  
  926.   // Update the height of a line, propagating the height change
  927.   // upwards to parent nodes.
  928.   function updateLineHeight(line, height) {
  929.     var diff = height - line.height;
  930.     if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  931.   }
  932.  
  933.   // Given a line object, find its line number by walking up through
  934.   // its parent links.
  935.   function lineNo(line) {
  936.     if (line.parent == null) { return null }
  937.     var cur = line.parent, no = indexOf(cur.lines, line);
  938.     for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  939.       for (var i = 0;; ++i) {
  940.         if (chunk.children[i] == cur) { break }
  941.         no += chunk.children[i].chunkSize();
  942.       }
  943.     }
  944.     return no + cur.first
  945.   }
  946.  
  947.   // Find the line at the given vertical position, using the height
  948.   // information in the document tree.
  949.   function lineAtHeight(chunk, h) {
  950.     var n = chunk.first;
  951.     outer: do {
  952.       for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  953.         var child = chunk.children[i$1], ch = child.height;
  954.         if (h < ch) { chunk = child; continue outer }
  955.         h -= ch;
  956.         n += child.chunkSize();
  957.       }
  958.       return n
  959.     } while (!chunk.lines)
  960.     var i = 0;
  961.     for (; i < chunk.lines.length; ++i) {
  962.       var line = chunk.lines[i], lh = line.height;
  963.       if (h < lh) { break }
  964.       h -= lh;
  965.     }
  966.     return n + i
  967.   }
  968.  
  969.   function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  970.  
  971.   function lineNumberFor(options, i) {
  972.     return String(options.lineNumberFormatter(i + options.firstLineNumber))
  973.   }
  974.  
  975.   // A Pos instance represents a position within the text.
  976.   function Pos(line, ch, sticky) {
  977.     if ( sticky === void 0 ) sticky = null;
  978.  
  979.     if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  980.     this.line = line;
  981.     this.ch = ch;
  982.     this.sticky = sticky;
  983.   }
  984.  
  985.   // Compare two positions, return 0 if they are the same, a negative
  986.   // number when a is less, and a positive number otherwise.
  987.   function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  988.  
  989.   function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  990.  
  991.   function copyPos(x) {return Pos(x.line, x.ch)}
  992.   function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  993.   function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  994.  
  995.   // Most of the external API clips given positions to make sure they
  996.   // actually exist within the document.
  997.   function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  998.   function clipPos(doc, pos) {
  999.     if (pos.line < doc.first) { return Pos(doc.first, 0) }
  1000.     var last = doc.first + doc.size - 1;
  1001.     if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  1002.     return clipToLen(pos, getLine(doc, pos.line).text.length)
  1003.   }
  1004.   function clipToLen(pos, linelen) {
  1005.     var ch = pos.ch;
  1006.     if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  1007.     else if (ch < 0) { return Pos(pos.line, 0) }
  1008.     else { return pos }
  1009.   }
  1010.   function clipPosArray(doc, array) {
  1011.     var out = [];
  1012.     for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  1013.     return out
  1014.   }
  1015.  
  1016.   var SavedContext = function(state, lookAhead) {
  1017.     this.state = state;
  1018.     this.lookAhead = lookAhead;
  1019.   };
  1020.  
  1021.   var Context = function(doc, state, line, lookAhead) {
  1022.     this.state = state;
  1023.     this.doc = doc;
  1024.     this.line = line;
  1025.     this.maxLookAhead = lookAhead || 0;
  1026.     this.baseTokens = null;
  1027.     this.baseTokenPos = 1;
  1028.   };
  1029.  
  1030.   Context.prototype.lookAhead = function (n) {
  1031.     var line = this.doc.getLine(this.line + n);
  1032.     if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  1033.     return line
  1034.   };
  1035.  
  1036.   Context.prototype.baseToken = function (n) {
  1037.     if (!this.baseTokens) { return null }
  1038.     while (this.baseTokens[this.baseTokenPos] <= n)
  1039.       { this.baseTokenPos += 2; }
  1040.     var type = this.baseTokens[this.baseTokenPos + 1];
  1041.     return {type: type && type.replace(/( |^)overlay .*/, ""),
  1042.             size: this.baseTokens[this.baseTokenPos] - n}
  1043.   };
  1044.  
  1045.   Context.prototype.nextLine = function () {
  1046.     this.line++;
  1047.     if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  1048.   };
  1049.  
  1050.   Context.fromSaved = function (doc, saved, line) {
  1051.     if (saved instanceof SavedContext)
  1052.       { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  1053.     else
  1054.       { return new Context(doc, copyState(doc.mode, saved), line) }
  1055.   };
  1056.  
  1057.   Context.prototype.save = function (copy) {
  1058.     var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  1059.     return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  1060.   };
  1061.  
  1062.  
  1063.   // Compute a style array (an array starting with a mode generation
  1064.   // -- for invalidation -- followed by pairs of end positions and
  1065.   // style strings), which is used to highlight the tokens on the
  1066.   // line.
  1067.   function highlightLine(cm, line, context, forceToEnd) {
  1068.     // A styles array always starts with a number identifying the
  1069.     // mode/overlays that it is based on (for easy invalidation).
  1070.     var st = [cm.state.modeGen], lineClasses = {};
  1071.     // Compute the base array of styles
  1072.     runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  1073.             lineClasses, forceToEnd);
  1074.     var state = context.state;
  1075.  
  1076.     // Run overlays, adjust style array.
  1077.     var loop = function ( o ) {
  1078.       context.baseTokens = st;
  1079.       var overlay = cm.state.overlays[o], i = 1, at = 0;
  1080.       context.state = true;
  1081.       runMode(cm, line.text, overlay.mode, context, function (end, style) {
  1082.         var start = i;
  1083.         // Ensure there's a token end at the current position, and that i points at it
  1084.         while (at < end) {
  1085.           var i_end = st[i];
  1086.           if (i_end > end)
  1087.             { st.splice(i, 1, end, st[i+1], i_end); }
  1088.           i += 2;
  1089.           at = Math.min(end, i_end);
  1090.         }
  1091.         if (!style) { return }
  1092.         if (overlay.opaque) {
  1093.           st.splice(start, i - start, end, "overlay " + style);
  1094.           i = start + 2;
  1095.         } else {
  1096.           for (; start < i; start += 2) {
  1097.             var cur = st[start+1];
  1098.             st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  1099.           }
  1100.         }
  1101.       }, lineClasses);
  1102.       context.state = state;
  1103.       context.baseTokens = null;
  1104.       context.baseTokenPos = 1;
  1105.     };
  1106.  
  1107.     for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  1108.  
  1109.     return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  1110.   }
  1111.  
  1112.   function getLineStyles(cm, line, updateFrontier) {
  1113.     if (!line.styles || line.styles[0] != cm.state.modeGen) {
  1114.       var context = getContextBefore(cm, lineNo(line));
  1115.       var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  1116.       var result = highlightLine(cm, line, context);
  1117.       if (resetState) { context.state = resetState; }
  1118.       line.stateAfter = context.save(!resetState);
  1119.       line.styles = result.styles;
  1120.       if (result.classes) { line.styleClasses = result.classes; }
  1121.       else if (line.styleClasses) { line.styleClasses = null; }
  1122.       if (updateFrontier === cm.doc.highlightFrontier)
  1123.         { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  1124.     }
  1125.     return line.styles
  1126.   }
  1127.  
  1128.   function getContextBefore(cm, n, precise) {
  1129.     var doc = cm.doc, display = cm.display;
  1130.     if (!doc.mode.startState) { return new Context(doc, true, n) }
  1131.     var start = findStartLine(cm, n, precise);
  1132.     var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  1133.     var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  1134.  
  1135.     doc.iter(start, n, function (line) {
  1136.       processLine(cm, line.text, context);
  1137.       var pos = context.line;
  1138.       line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  1139.       context.nextLine();
  1140.     });
  1141.     if (precise) { doc.modeFrontier = context.line; }
  1142.     return context
  1143.   }
  1144.  
  1145.   // Lightweight form of highlight -- proceed over this line and
  1146.   // update state, but don't save a style array. Used for lines that
  1147.   // aren't currently visible.
  1148.   function processLine(cm, text, context, startAt) {
  1149.     var mode = cm.doc.mode;
  1150.     var stream = new StringStream(text, cm.options.tabSize, context);
  1151.     stream.start = stream.pos = startAt || 0;
  1152.     if (text == "") { callBlankLine(mode, context.state); }
  1153.     while (!stream.eol()) {
  1154.       readToken(mode, stream, context.state);
  1155.       stream.start = stream.pos;
  1156.     }
  1157.   }
  1158.  
  1159.   function callBlankLine(mode, state) {
  1160.     if (mode.blankLine) { return mode.blankLine(state) }
  1161.     if (!mode.innerMode) { return }
  1162.     var inner = innerMode(mode, state);
  1163.     if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1164.   }
  1165.  
  1166.   function readToken(mode, stream, state, inner) {
  1167.     for (var i = 0; i < 10; i++) {
  1168.       if (inner) { inner[0] = innerMode(mode, state).mode; }
  1169.       var style = mode.token(stream, state);
  1170.       if (stream.pos > stream.start) { return style }
  1171.     }
  1172.     throw new Error("Mode " + mode.name + " failed to advance stream.")
  1173.   }
  1174.  
  1175.   var Token = function(stream, type, state) {
  1176.     this.start = stream.start; this.end = stream.pos;
  1177.     this.string = stream.current();
  1178.     this.type = type || null;
  1179.     this.state = state;
  1180.   };
  1181.  
  1182.   // Utility for getTokenAt and getLineTokens
  1183.   function takeToken(cm, pos, precise, asArray) {
  1184.     var doc = cm.doc, mode = doc.mode, style;
  1185.     pos = clipPos(doc, pos);
  1186.     var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  1187.     var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  1188.     if (asArray) { tokens = []; }
  1189.     while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1190.       stream.start = stream.pos;
  1191.       style = readToken(mode, stream, context.state);
  1192.       if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  1193.     }
  1194.     return asArray ? tokens : new Token(stream, style, context.state)
  1195.   }
  1196.  
  1197.   function extractLineClasses(type, output) {
  1198.     if (type) { for (;;) {
  1199.       var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  1200.       if (!lineClass) { break }
  1201.       type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  1202.       var prop = lineClass[1] ? "bgClass" : "textClass";
  1203.       if (output[prop] == null)
  1204.         { output[prop] = lineClass[2]; }
  1205.       else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
  1206.         { output[prop] += " " + lineClass[2]; }
  1207.     } }
  1208.     return type
  1209.   }
  1210.  
  1211.   // Run the given mode's parser over a line, calling f for each token.
  1212.   function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1213.     var flattenSpans = mode.flattenSpans;
  1214.     if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  1215.     var curStart = 0, curStyle = null;
  1216.     var stream = new StringStream(text, cm.options.tabSize, context), style;
  1217.     var inner = cm.options.addModeClass && [null];
  1218.     if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  1219.     while (!stream.eol()) {
  1220.       if (stream.pos > cm.options.maxHighlightLength) {
  1221.         flattenSpans = false;
  1222.         if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  1223.         stream.pos = text.length;
  1224.         style = null;
  1225.       } else {
  1226.         style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  1227.       }
  1228.       if (inner) {
  1229.         var mName = inner[0].name;
  1230.         if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  1231.       }
  1232.       if (!flattenSpans || curStyle != style) {
  1233.         while (curStart < stream.start) {
  1234.           curStart = Math.min(stream.start, curStart + 5000);
  1235.           f(curStart, curStyle);
  1236.         }
  1237.         curStyle = style;
  1238.       }
  1239.       stream.start = stream.pos;
  1240.     }
  1241.     while (curStart < stream.pos) {
  1242.       // Webkit seems to refuse to render text nodes longer than 57444
  1243.       // characters, and returns inaccurate measurements in nodes
  1244.       // starting around 5000 chars.
  1245.       var pos = Math.min(stream.pos, curStart + 5000);
  1246.       f(pos, curStyle);
  1247.       curStart = pos;
  1248.     }
  1249.   }
  1250.  
  1251.   // Finds the line to start with when starting a parse. Tries to
  1252.   // find a line with a stateAfter, so that it can start with a
  1253.   // valid state. If that fails, it returns the line with the
  1254.   // smallest indentation, which tends to need the least context to
  1255.   // parse correctly.
  1256.   function findStartLine(cm, n, precise) {
  1257.     var minindent, minline, doc = cm.doc;
  1258.     var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  1259.     for (var search = n; search > lim; --search) {
  1260.       if (search <= doc.first) { return doc.first }
  1261.       var line = getLine(doc, search - 1), after = line.stateAfter;
  1262.       if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  1263.         { return search }
  1264.       var indented = countColumn(line.text, null, cm.options.tabSize);
  1265.       if (minline == null || minindent > indented) {
  1266.         minline = search - 1;
  1267.         minindent = indented;
  1268.       }
  1269.     }
  1270.     return minline
  1271.   }
  1272.  
  1273.   function retreatFrontier(doc, n) {
  1274.     doc.modeFrontier = Math.min(doc.modeFrontier, n);
  1275.     if (doc.highlightFrontier < n - 10) { return }
  1276.     var start = doc.first;
  1277.     for (var line = n - 1; line > start; line--) {
  1278.       var saved = getLine(doc, line).stateAfter;
  1279.       // change is on 3
  1280.       // state on line 1 looked ahead 2 -- so saw 3
  1281.       // test 1 + 2 < 3 should cover this
  1282.       if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1283.         start = line + 1;
  1284.         break
  1285.       }
  1286.     }
  1287.     doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  1288.   }
  1289.  
  1290.   // Optimize some code when these features are not used.
  1291.   var sawReadOnlySpans = false, sawCollapsedSpans = false;
  1292.  
  1293.   function seeReadOnlySpans() {
  1294.     sawReadOnlySpans = true;
  1295.   }
  1296.  
  1297.   function seeCollapsedSpans() {
  1298.     sawCollapsedSpans = true;
  1299.   }
  1300.  
  1301.   // TEXTMARKER SPANS
  1302.  
  1303.   function MarkedSpan(marker, from, to) {
  1304.     this.marker = marker;
  1305.     this.from = from; this.to = to;
  1306.   }
  1307.  
  1308.   // Search an array of spans for a span matching the given marker.
  1309.   function getMarkedSpanFor(spans, marker) {
  1310.     if (spans) { for (var i = 0; i < spans.length; ++i) {
  1311.       var span = spans[i];
  1312.       if (span.marker == marker) { return span }
  1313.     } }
  1314.   }
  1315.  
  1316.   // Remove a span from an array, returning undefined if no spans are
  1317.   // left (we don't store arrays for lines without spans).
  1318.   function removeMarkedSpan(spans, span) {
  1319.     var r;
  1320.     for (var i = 0; i < spans.length; ++i)
  1321.       { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  1322.     return r
  1323.   }
  1324.  
  1325.   // Add a span to a line.
  1326.   function addMarkedSpan(line, span, op) {
  1327.     var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet));
  1328.     if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) {
  1329.       line.markedSpans.push(span);
  1330.     } else {
  1331.       line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  1332.       if (inThisOp) { inThisOp.add(line.markedSpans); }
  1333.     }
  1334.     span.marker.attachLine(line);
  1335.   }
  1336.  
  1337.   // Used for the algorithm that adjusts markers for a change in the
  1338.   // document. These functions cut an array of spans at a given
  1339.   // character position, returning an array of remaining chunks (or
  1340.   // undefined if nothing remains).
  1341.   function markedSpansBefore(old, startCh, isInsert) {
  1342.     var nw;
  1343.     if (old) { for (var i = 0; i < old.length; ++i) {
  1344.       var span = old[i], marker = span.marker;
  1345.       var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  1346.       if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  1347.         var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  1348.         ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  1349.       }
  1350.     } }
  1351.     return nw
  1352.   }
  1353.   function markedSpansAfter(old, endCh, isInsert) {
  1354.     var nw;
  1355.     if (old) { for (var i = 0; i < old.length; ++i) {
  1356.       var span = old[i], marker = span.marker;
  1357.       var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  1358.       if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  1359.         var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  1360.         ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  1361.                                               span.to == null ? null : span.to - endCh));
  1362.       }
  1363.     } }
  1364.     return nw
  1365.   }
  1366.  
  1367.   // Given a change object, compute the new set of marker spans that
  1368.   // cover the line in which the change took place. Removes spans
  1369.   // entirely within the change, reconnects spans belonging to the
  1370.   // same marker that appear on both sides of the change, and cuts off
  1371.   // spans partially within the change. Returns an array of span
  1372.   // arrays with one element for each line in (after) the change.
  1373.   function stretchSpansOverChange(doc, change) {
  1374.     if (change.full) { return null }
  1375.     var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  1376.     var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  1377.     if (!oldFirst && !oldLast) { return null }
  1378.  
  1379.     var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  1380.     // Get the spans that 'stick out' on both sides
  1381.     var first = markedSpansBefore(oldFirst, startCh, isInsert);
  1382.     var last = markedSpansAfter(oldLast, endCh, isInsert);
  1383.  
  1384.     // Next, merge those two ends
  1385.     var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  1386.     if (first) {
  1387.       // Fix up .to properties of first
  1388.       for (var i = 0; i < first.length; ++i) {
  1389.         var span = first[i];
  1390.         if (span.to == null) {
  1391.           var found = getMarkedSpanFor(last, span.marker);
  1392.           if (!found) { span.to = startCh; }
  1393.           else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  1394.         }
  1395.       }
  1396.     }
  1397.     if (last) {
  1398.       // Fix up .from in last (or move them into first in case of sameLine)
  1399.       for (var i$1 = 0; i$1 < last.length; ++i$1) {
  1400.         var span$1 = last[i$1];
  1401.         if (span$1.to != null) { span$1.to += offset; }
  1402.         if (span$1.from == null) {
  1403.           var found$1 = getMarkedSpanFor(first, span$1.marker);
  1404.           if (!found$1) {
  1405.             span$1.from = offset;
  1406.             if (sameLine) { (first || (first = [])).push(span$1); }
  1407.           }
  1408.         } else {
  1409.           span$1.from += offset;
  1410.           if (sameLine) { (first || (first = [])).push(span$1); }
  1411.         }
  1412.       }
  1413.     }
  1414.     // Make sure we didn't create any zero-length spans
  1415.     if (first) { first = clearEmptySpans(first); }
  1416.     if (last && last != first) { last = clearEmptySpans(last); }
  1417.  
  1418.     var newMarkers = [first];
  1419.     if (!sameLine) {
  1420.       // Fill gap with whole-line-spans
  1421.       var gap = change.text.length - 2, gapMarkers;
  1422.       if (gap > 0 && first)
  1423.         { for (var i$2 = 0; i$2 < first.length; ++i$2)
  1424.           { if (first[i$2].to == null)
  1425.             { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  1426.       for (var i$3 = 0; i$3 < gap; ++i$3)
  1427.         { newMarkers.push(gapMarkers); }
  1428.       newMarkers.push(last);
  1429.     }
  1430.     return newMarkers
  1431.   }
  1432.  
  1433.   // Remove spans that are empty and don't have a clearWhenEmpty
  1434.   // option of false.
  1435.   function clearEmptySpans(spans) {
  1436.     for (var i = 0; i < spans.length; ++i) {
  1437.       var span = spans[i];
  1438.       if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  1439.         { spans.splice(i--, 1); }
  1440.     }
  1441.     if (!spans.length) { return null }
  1442.     return spans
  1443.   }
  1444.  
  1445.   // Used to 'clip' out readOnly ranges when making a change.
  1446.   function removeReadOnlyRanges(doc, from, to) {
  1447.     var markers = null;
  1448.     doc.iter(from.line, to.line + 1, function (line) {
  1449.       if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  1450.         var mark = line.markedSpans[i].marker;
  1451.         if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  1452.           { (markers || (markers = [])).push(mark); }
  1453.       } }
  1454.     });
  1455.     if (!markers) { return null }
  1456.     var parts = [{from: from, to: to}];
  1457.     for (var i = 0; i < markers.length; ++i) {
  1458.       var mk = markers[i], m = mk.find(0);
  1459.       for (var j = 0; j < parts.length; ++j) {
  1460.         var p = parts[j];
  1461.         if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  1462.         var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  1463.         if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  1464.           { newParts.push({from: p.from, to: m.from}); }
  1465.         if (dto > 0 || !mk.inclusiveRight && !dto)
  1466.           { newParts.push({from: m.to, to: p.to}); }
  1467.         parts.splice.apply(parts, newParts);
  1468.         j += newParts.length - 3;
  1469.       }
  1470.     }
  1471.     return parts
  1472.   }
  1473.  
  1474.   // Connect or disconnect spans from a line.
  1475.   function detachMarkedSpans(line) {
  1476.     var spans = line.markedSpans;
  1477.     if (!spans) { return }
  1478.     for (var i = 0; i < spans.length; ++i)
  1479.       { spans[i].marker.detachLine(line); }
  1480.     line.markedSpans = null;
  1481.   }
  1482.   function attachMarkedSpans(line, spans) {
  1483.     if (!spans) { return }
  1484.     for (var i = 0; i < spans.length; ++i)
  1485.       { spans[i].marker.attachLine(line); }
  1486.     line.markedSpans = spans;
  1487.   }
  1488.  
  1489.   // Helpers used when computing which overlapping collapsed span
  1490.   // counts as the larger one.
  1491.   function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  1492.   function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  1493.  
  1494.   // Returns a number indicating which of two overlapping collapsed
  1495.   // spans is larger (and thus includes the other). Falls back to
  1496.   // comparing ids when the spans cover exactly the same range.
  1497.   function compareCollapsedMarkers(a, b) {
  1498.     var lenDiff = a.lines.length - b.lines.length;
  1499.     if (lenDiff != 0) { return lenDiff }
  1500.     var aPos = a.find(), bPos = b.find();
  1501.     var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  1502.     if (fromCmp) { return -fromCmp }
  1503.     var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  1504.     if (toCmp) { return toCmp }
  1505.     return b.id - a.id
  1506.   }
  1507.  
  1508.   // Find out whether a line ends or starts in a collapsed span. If
  1509.   // so, return the marker for that span.
  1510.   function collapsedSpanAtSide(line, start) {
  1511.     var sps = sawCollapsedSpans && line.markedSpans, found;
  1512.     if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1513.       sp = sps[i];
  1514.       if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  1515.           (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  1516.         { found = sp.marker; }
  1517.     } }
  1518.     return found
  1519.   }
  1520.   function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  1521.   function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  1522.  
  1523.   function collapsedSpanAround(line, ch) {
  1524.     var sps = sawCollapsedSpans && line.markedSpans, found;
  1525.     if (sps) { for (var i = 0; i < sps.length; ++i) {
  1526.       var sp = sps[i];
  1527.       if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
  1528.           (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
  1529.     } }
  1530.     return found
  1531.   }
  1532.  
  1533.   // Test whether there exists a collapsed span that partially
  1534.   // overlaps (covers the start or end, but not both) of a new span.
  1535.   // Such overlap is not allowed.
  1536.   function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  1537.     var line = getLine(doc, lineNo);
  1538.     var sps = sawCollapsedSpans && line.markedSpans;
  1539.     if (sps) { for (var i = 0; i < sps.length; ++i) {
  1540.       var sp = sps[i];
  1541.       if (!sp.marker.collapsed) { continue }
  1542.       var found = sp.marker.find(0);
  1543.       var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  1544.       var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  1545.       if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  1546.       if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  1547.           fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  1548.         { return true }
  1549.     } }
  1550.   }
  1551.  
  1552.   // A visual line is a line as drawn on the screen. Folding, for
  1553.   // example, can cause multiple logical lines to appear on the same
  1554.   // visual line. This finds the start of the visual line that the
  1555.   // given line is part of (usually that is the line itself).
  1556.   function visualLine(line) {
  1557.     var merged;
  1558.     while (merged = collapsedSpanAtStart(line))
  1559.       { line = merged.find(-1, true).line; }
  1560.     return line
  1561.   }
  1562.  
  1563.   function visualLineEnd(line) {
  1564.     var merged;
  1565.     while (merged = collapsedSpanAtEnd(line))
  1566.       { line = merged.find(1, true).line; }
  1567.     return line
  1568.   }
  1569.  
  1570.   // Returns an array of logical lines that continue the visual line
  1571.   // started by the argument, or undefined if there are no such lines.
  1572.   function visualLineContinued(line) {
  1573.     var merged, lines;
  1574.     while (merged = collapsedSpanAtEnd(line)) {
  1575.       line = merged.find(1, true).line
  1576.       ;(lines || (lines = [])).push(line);
  1577.     }
  1578.     return lines
  1579.   }
  1580.  
  1581.   // Get the line number of the start of the visual line that the
  1582.   // given line number is part of.
  1583.   function visualLineNo(doc, lineN) {
  1584.     var line = getLine(doc, lineN), vis = visualLine(line);
  1585.     if (line == vis) { return lineN }
  1586.     return lineNo(vis)
  1587.   }
  1588.  
  1589.   // Get the line number of the start of the next visual line after
  1590.   // the given line.
  1591.   function visualLineEndNo(doc, lineN) {
  1592.     if (lineN > doc.lastLine()) { return lineN }
  1593.     var line = getLine(doc, lineN), merged;
  1594.     if (!lineIsHidden(doc, line)) { return lineN }
  1595.     while (merged = collapsedSpanAtEnd(line))
  1596.       { line = merged.find(1, true).line; }
  1597.     return lineNo(line) + 1
  1598.   }
  1599.  
  1600.   // Compute whether a line is hidden. Lines count as hidden when they
  1601.   // are part of a visual line that starts with another line, or when
  1602.   // they are entirely covered by collapsed, non-widget span.
  1603.   function lineIsHidden(doc, line) {
  1604.     var sps = sawCollapsedSpans && line.markedSpans;
  1605.     if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1606.       sp = sps[i];
  1607.       if (!sp.marker.collapsed) { continue }
  1608.       if (sp.from == null) { return true }
  1609.       if (sp.marker.widgetNode) { continue }
  1610.       if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  1611.         { return true }
  1612.     } }
  1613.   }
  1614.   function lineIsHiddenInner(doc, line, span) {
  1615.     if (span.to == null) {
  1616.       var end = span.marker.find(1, true);
  1617.       return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  1618.     }
  1619.     if (span.marker.inclusiveRight && span.to == line.text.length)
  1620.       { return true }
  1621.     for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  1622.       sp = line.markedSpans[i];
  1623.       if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  1624.           (sp.to == null || sp.to != span.from) &&
  1625.           (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  1626.           lineIsHiddenInner(doc, line, sp)) { return true }
  1627.     }
  1628.   }
  1629.  
  1630.   // Find the height above the given line.
  1631.   function heightAtLine(lineObj) {
  1632.     lineObj = visualLine(lineObj);
  1633.  
  1634.     var h = 0, chunk = lineObj.parent;
  1635.     for (var i = 0; i < chunk.lines.length; ++i) {
  1636.       var line = chunk.lines[i];
  1637.       if (line == lineObj) { break }
  1638.       else { h += line.height; }
  1639.     }
  1640.     for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  1641.       for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  1642.         var cur = p.children[i$1];
  1643.         if (cur == chunk) { break }
  1644.         else { h += cur.height; }
  1645.       }
  1646.     }
  1647.     return h
  1648.   }
  1649.  
  1650.   // Compute the character length of a line, taking into account
  1651.   // collapsed ranges (see markText) that might hide parts, and join
  1652.   // other lines onto it.
  1653.   function lineLength(line) {
  1654.     if (line.height == 0) { return 0 }
  1655.     var len = line.text.length, merged, cur = line;
  1656.     while (merged = collapsedSpanAtStart(cur)) {
  1657.       var found = merged.find(0, true);
  1658.       cur = found.from.line;
  1659.       len += found.from.ch - found.to.ch;
  1660.     }
  1661.     cur = line;
  1662.     while (merged = collapsedSpanAtEnd(cur)) {
  1663.       var found$1 = merged.find(0, true);
  1664.       len -= cur.text.length - found$1.from.ch;
  1665.       cur = found$1.to.line;
  1666.       len += cur.text.length - found$1.to.ch;
  1667.     }
  1668.     return len
  1669.   }
  1670.  
  1671.   // Find the longest line in the document.
  1672.   function findMaxLine(cm) {
  1673.     var d = cm.display, doc = cm.doc;
  1674.     d.maxLine = getLine(doc, doc.first);
  1675.     d.maxLineLength = lineLength(d.maxLine);
  1676.     d.maxLineChanged = true;
  1677.     doc.iter(function (line) {
  1678.       var len = lineLength(line);
  1679.       if (len > d.maxLineLength) {
  1680.         d.maxLineLength = len;
  1681.         d.maxLine = line;
  1682.       }
  1683.     });
  1684.   }
  1685.  
  1686.   // LINE DATA STRUCTURE
  1687.  
  1688.   // Line objects. These hold state related to a line, including
  1689.   // highlighting info (the styles array).
  1690.   var Line = function(text, markedSpans, estimateHeight) {
  1691.     this.text = text;
  1692.     attachMarkedSpans(this, markedSpans);
  1693.     this.height = estimateHeight ? estimateHeight(this) : 1;
  1694.   };
  1695.  
  1696.   Line.prototype.lineNo = function () { return lineNo(this) };
  1697.   eventMixin(Line);
  1698.  
  1699.   // Change the content (text, markers) of a line. Automatically
  1700.   // invalidates cached information and tries to re-estimate the
  1701.   // line's height.
  1702.   function updateLine(line, text, markedSpans, estimateHeight) {
  1703.     line.text = text;
  1704.     if (line.stateAfter) { line.stateAfter = null; }
  1705.     if (line.styles) { line.styles = null; }
  1706.     if (line.order != null) { line.order = null; }
  1707.     detachMarkedSpans(line);
  1708.     attachMarkedSpans(line, markedSpans);
  1709.     var estHeight = estimateHeight ? estimateHeight(line) : 1;
  1710.     if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  1711.   }
  1712.  
  1713.   // Detach a line from the document tree and its markers.
  1714.   function cleanUpLine(line) {
  1715.     line.parent = null;
  1716.     detachMarkedSpans(line);
  1717.   }
  1718.  
  1719.   // Convert a style as returned by a mode (either null, or a string
  1720.   // containing one or more styles) to a CSS style. This is cached,
  1721.   // and also looks for line-wide styles.
  1722.   var styleToClassCache = {}, styleToClassCacheWithMode = {};
  1723.   function interpretTokenStyle(style, options) {
  1724.     if (!style || /^\s*$/.test(style)) { return null }
  1725.     var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  1726.     return cache[style] ||
  1727.       (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1728.   }
  1729.  
  1730.   // Render the DOM representation of the text of a line. Also builds
  1731.   // up a 'line map', which points at the DOM nodes that represent
  1732.   // specific stretches of text, and is used by the measuring code.
  1733.   // The returned object contains the DOM node, this map, and
  1734.   // information about line-wide styles that were set by the mode.
  1735.   function buildLineContent(cm, lineView) {
  1736.     // The padding-right forces the element to have a 'border', which
  1737.     // is needed on Webkit to be able to get line-level bounding
  1738.     // rectangles for it (in measureChar).
  1739.     var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  1740.     var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  1741.                    col: 0, pos: 0, cm: cm,
  1742.                    trailingSpace: false,
  1743.                    splitSpaces: cm.getOption("lineWrapping")};
  1744.     lineView.measure = {};
  1745.  
  1746.     // Iterate over the logical lines that make up this visual line.
  1747.     for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1748.       var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  1749.       builder.pos = 0;
  1750.       builder.addToken = buildToken;
  1751.       // Optionally wire in some hacks into the token-rendering
  1752.       // algorithm, to deal with browser quirks.
  1753.       if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  1754.         { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  1755.       builder.map = [];
  1756.       var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  1757.       insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  1758.       if (line.styleClasses) {
  1759.         if (line.styleClasses.bgClass)
  1760.           { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  1761.         if (line.styleClasses.textClass)
  1762.           { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  1763.       }
  1764.  
  1765.       // Ensure at least a single node is present, for measuring.
  1766.       if (builder.map.length == 0)
  1767.         { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  1768.  
  1769.       // Store the map and a cache object for the current logical line
  1770.       if (i == 0) {
  1771.         lineView.measure.map = builder.map;
  1772.         lineView.measure.cache = {};
  1773.       } else {
  1774.   (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1775.         ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  1776.       }
  1777.     }
  1778.  
  1779.     // See issue #2901
  1780.     if (webkit) {
  1781.       var last = builder.content.lastChild;
  1782.       if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1783.         { builder.content.className = "cm-tab-wrap-hack"; }
  1784.     }
  1785.  
  1786.     signal(cm, "renderLine", cm, lineView.line, builder.pre);
  1787.     if (builder.pre.className)
  1788.       { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  1789.  
  1790.     return builder
  1791.   }
  1792.  
  1793.   function defaultSpecialCharPlaceholder(ch) {
  1794.     var token = elt("span", "\u2022", "cm-invalidchar");
  1795.     token.title = "\\u" + ch.charCodeAt(0).toString(16);
  1796.     token.setAttribute("aria-label", token.title);
  1797.     return token
  1798.   }
  1799.  
  1800.   // Build up the DOM representation for a single token, and add it to
  1801.   // the line map. Takes care to render special characters separately.
  1802.   function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
  1803.     if (!text) { return }
  1804.     var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  1805.     var special = builder.cm.state.specialChars, mustWrap = false;
  1806.     var content;
  1807.     if (!special.test(text)) {
  1808.       builder.col += text.length;
  1809.       content = document.createTextNode(displayText);
  1810.       builder.map.push(builder.pos, builder.pos + text.length, content);
  1811.       if (ie && ie_version < 9) { mustWrap = true; }
  1812.       builder.pos += text.length;
  1813.     } else {
  1814.       content = document.createDocumentFragment();
  1815.       var pos = 0;
  1816.       while (true) {
  1817.         special.lastIndex = pos;
  1818.         var m = special.exec(text);
  1819.         var skipped = m ? m.index - pos : text.length - pos;
  1820.         if (skipped) {
  1821.           var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  1822.           if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  1823.           else { content.appendChild(txt); }
  1824.           builder.map.push(builder.pos, builder.pos + skipped, txt);
  1825.           builder.col += skipped;
  1826.           builder.pos += skipped;
  1827.         }
  1828.         if (!m) { break }
  1829.         pos += skipped + 1;
  1830.         var txt$1 = (void 0);
  1831.         if (m[0] == "\t") {
  1832.           var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  1833.           txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  1834.           txt$1.setAttribute("role", "presentation");
  1835.           txt$1.setAttribute("cm-text", "\t");
  1836.           builder.col += tabWidth;
  1837.         } else if (m[0] == "\r" || m[0] == "\n") {
  1838.           txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  1839.           txt$1.setAttribute("cm-text", m[0]);
  1840.           builder.col += 1;
  1841.         } else {
  1842.           txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  1843.           txt$1.setAttribute("cm-text", m[0]);
  1844.           if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  1845.           else { content.appendChild(txt$1); }
  1846.           builder.col += 1;
  1847.         }
  1848.         builder.map.push(builder.pos, builder.pos + 1, txt$1);
  1849.         builder.pos++;
  1850.       }
  1851.     }
  1852.     builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  1853.     if (style || startStyle || endStyle || mustWrap || css || attributes) {
  1854.       var fullStyle = style || "";
  1855.       if (startStyle) { fullStyle += startStyle; }
  1856.       if (endStyle) { fullStyle += endStyle; }
  1857.       var token = elt("span", [content], fullStyle, css);
  1858.       if (attributes) {
  1859.         for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
  1860.           { token.setAttribute(attr, attributes[attr]); } }
  1861.       }
  1862.       return builder.content.appendChild(token)
  1863.     }
  1864.     builder.content.appendChild(content);
  1865.   }
  1866.  
  1867.   // Change some spaces to NBSP to prevent the browser from collapsing
  1868.   // trailing spaces at the end of a line when rendering text (issue #1362).
  1869.   function splitSpaces(text, trailingBefore) {
  1870.     if (text.length > 1 && !/  /.test(text)) { return text }
  1871.     var spaceBefore = trailingBefore, result = "";
  1872.     for (var i = 0; i < text.length; i++) {
  1873.       var ch = text.charAt(i);
  1874.       if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1875.         { ch = "\u00a0"; }
  1876.       result += ch;
  1877.       spaceBefore = ch == " ";
  1878.     }
  1879.     return result
  1880.   }
  1881.  
  1882.   // Work around nonsense dimensions being reported for stretches of
  1883.   // right-to-left text.
  1884.   function buildTokenBadBidi(inner, order) {
  1885.     return function (builder, text, style, startStyle, endStyle, css, attributes) {
  1886.       style = style ? style + " cm-force-border" : "cm-force-border";
  1887.       var start = builder.pos, end = start + text.length;
  1888.       for (;;) {
  1889.         // Find the part that overlaps with the start of this text
  1890.         var part = (void 0);
  1891.         for (var i = 0; i < order.length; i++) {
  1892.           part = order[i];
  1893.           if (part.to > start && part.from <= start) { break }
  1894.         }
  1895.         if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
  1896.         inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
  1897.         startStyle = null;
  1898.         text = text.slice(part.to - start);
  1899.         start = part.to;
  1900.       }
  1901.     }
  1902.   }
  1903.  
  1904.   function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1905.     var widget = !ignoreWidget && marker.widgetNode;
  1906.     if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  1907.     if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1908.       if (!widget)
  1909.         { widget = builder.content.appendChild(document.createElement("span")); }
  1910.       widget.setAttribute("cm-marker", marker.id);
  1911.     }
  1912.     if (widget) {
  1913.       builder.cm.display.input.setUneditable(widget);
  1914.       builder.content.appendChild(widget);
  1915.     }
  1916.     builder.pos += size;
  1917.     builder.trailingSpace = false;
  1918.   }
  1919.  
  1920.   // Outputs a number of spans to make up a line, taking highlighting
  1921.   // and marked text into account.
  1922.   function insertLineContent(line, builder, styles) {
  1923.     var spans = line.markedSpans, allText = line.text, at = 0;
  1924.     if (!spans) {
  1925.       for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1926.         { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  1927.       return
  1928.     }
  1929.  
  1930.     var len = allText.length, pos = 0, i = 1, text = "", style, css;
  1931.     var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
  1932.     for (;;) {
  1933.       if (nextChange == pos) { // Update current marker set
  1934.         spanStyle = spanEndStyle = spanStartStyle = css = "";
  1935.         attributes = null;
  1936.         collapsed = null; nextChange = Infinity;
  1937.         var foundBookmarks = [], endStyles = (void 0);
  1938.         for (var j = 0; j < spans.length; ++j) {
  1939.           var sp = spans[j], m = sp.marker;
  1940.           if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1941.             foundBookmarks.push(m);
  1942.           } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1943.             if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1944.               nextChange = sp.to;
  1945.               spanEndStyle = "";
  1946.             }
  1947.             if (m.className) { spanStyle += " " + m.className; }
  1948.             if (m.css) { css = (css ? css + ";" : "") + m.css; }
  1949.             if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  1950.             if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  1951.             // support for the old title property
  1952.             // https://github.com/codemirror/CodeMirror/pull/5673
  1953.             if (m.title) { (attributes || (attributes = {})).title = m.title; }
  1954.             if (m.attributes) {
  1955.               for (var attr in m.attributes)
  1956.                 { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
  1957.             }
  1958.             if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1959.               { collapsed = sp; }
  1960.           } else if (sp.from > pos && nextChange > sp.from) {
  1961.             nextChange = sp.from;
  1962.           }
  1963.         }
  1964.         if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1965.           { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  1966.  
  1967.         if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1968.           { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  1969.         if (collapsed && (collapsed.from || 0) == pos) {
  1970.           buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1971.                              collapsed.marker, collapsed.from == null);
  1972.           if (collapsed.to == null) { return }
  1973.           if (collapsed.to == pos) { collapsed = false; }
  1974.         }
  1975.       }
  1976.       if (pos >= len) { break }
  1977.  
  1978.       var upto = Math.min(len, nextChange);
  1979.       while (true) {
  1980.         if (text) {
  1981.           var end = pos + text.length;
  1982.           if (!collapsed) {
  1983.             var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  1984.             builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1985.                              spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
  1986.           }
  1987.           if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1988.           pos = end;
  1989.           spanStartStyle = "";
  1990.         }
  1991.         text = allText.slice(at, at = styles[i++]);
  1992.         style = interpretTokenStyle(styles[i++], builder.cm.options);
  1993.       }
  1994.     }
  1995.   }
  1996.  
  1997.  
  1998.   // These objects are used to represent the visible (currently drawn)
  1999.   // part of the document. A LineView may correspond to multiple
  2000.   // logical lines, if those are connected by collapsed ranges.
  2001.   function LineView(doc, line, lineN) {
  2002.     // The starting line
  2003.     this.line = line;
  2004.     // Continuing lines, if any
  2005.     this.rest = visualLineContinued(line);
  2006.     // Number of logical lines in this visual line
  2007.     this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  2008.     this.node = this.text = null;
  2009.     this.hidden = lineIsHidden(doc, line);
  2010.   }
  2011.  
  2012.   // Create a range of LineView objects for the given lines.
  2013.   function buildViewArray(cm, from, to) {
  2014.     var array = [], nextPos;
  2015.     for (var pos = from; pos < to; pos = nextPos) {
  2016.       var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  2017.       nextPos = pos + view.size;
  2018.       array.push(view);
  2019.     }
  2020.     return array
  2021.   }
  2022.  
  2023.   var operationGroup = null;
  2024.  
  2025.   function pushOperation(op) {
  2026.     if (operationGroup) {
  2027.       operationGroup.ops.push(op);
  2028.     } else {
  2029.       op.ownsGroup = operationGroup = {
  2030.         ops: [op],
  2031.         delayedCallbacks: []
  2032.       };
  2033.     }
  2034.   }
  2035.  
  2036.   function fireCallbacksForOps(group) {
  2037.     // Calls delayed callbacks and cursorActivity handlers until no
  2038.     // new ones appear
  2039.     var callbacks = group.delayedCallbacks, i = 0;
  2040.     do {
  2041.       for (; i < callbacks.length; i++)
  2042.         { callbacks[i].call(null); }
  2043.       for (var j = 0; j < group.ops.length; j++) {
  2044.         var op = group.ops[j];
  2045.         if (op.cursorActivityHandlers)
  2046.           { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  2047.             { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  2048.       }
  2049.     } while (i < callbacks.length)
  2050.   }
  2051.  
  2052.   function finishOperation(op, endCb) {
  2053.     var group = op.ownsGroup;
  2054.     if (!group) { return }
  2055.  
  2056.     try { fireCallbacksForOps(group); }
  2057.     finally {
  2058.       operationGroup = null;
  2059.       endCb(group);
  2060.     }
  2061.   }
  2062.  
  2063.   var orphanDelayedCallbacks = null;
  2064.  
  2065.   // Often, we want to signal events at a point where we are in the
  2066.   // middle of some work, but don't want the handler to start calling
  2067.   // other methods on the editor, which might be in an inconsistent
  2068.   // state or simply not expect any other events to happen.
  2069.   // signalLater looks whether there are any handlers, and schedules
  2070.   // them to be executed when the last operation ends, or, if no
  2071.   // operation is active, when a timeout fires.
  2072.   function signalLater(emitter, type /*, values...*/) {
  2073.     var arr = getHandlers(emitter, type);
  2074.     if (!arr.length) { return }
  2075.     var args = Array.prototype.slice.call(arguments, 2), list;
  2076.     if (operationGroup) {
  2077.       list = operationGroup.delayedCallbacks;
  2078.     } else if (orphanDelayedCallbacks) {
  2079.       list = orphanDelayedCallbacks;
  2080.     } else {
  2081.       list = orphanDelayedCallbacks = [];
  2082.       setTimeout(fireOrphanDelayed, 0);
  2083.     }
  2084.     var loop = function ( i ) {
  2085.       list.push(function () { return arr[i].apply(null, args); });
  2086.     };
  2087.  
  2088.     for (var i = 0; i < arr.length; ++i)
  2089.       loop( i );
  2090.   }
  2091.  
  2092.   function fireOrphanDelayed() {
  2093.     var delayed = orphanDelayedCallbacks;
  2094.     orphanDelayedCallbacks = null;
  2095.     for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  2096.   }
  2097.  
  2098.   // When an aspect of a line changes, a string is added to
  2099.   // lineView.changes. This updates the relevant part of the line's
  2100.   // DOM structure.
  2101.   function updateLineForChanges(cm, lineView, lineN, dims) {
  2102.     for (var j = 0; j < lineView.changes.length; j++) {
  2103.       var type = lineView.changes[j];
  2104.       if (type == "text") { updateLineText(cm, lineView); }
  2105.       else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  2106.       else if (type == "class") { updateLineClasses(cm, lineView); }
  2107.       else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  2108.     }
  2109.     lineView.changes = null;
  2110.   }
  2111.  
  2112.   // Lines with gutter elements, widgets or a background class need to
  2113.   // be wrapped, and have the extra elements added to the wrapper div
  2114.   function ensureLineWrapped(lineView) {
  2115.     if (lineView.node == lineView.text) {
  2116.       lineView.node = elt("div", null, null, "position: relative");
  2117.       if (lineView.text.parentNode)
  2118.         { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  2119.       lineView.node.appendChild(lineView.text);
  2120.       if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  2121.     }
  2122.     return lineView.node
  2123.   }
  2124.  
  2125.   function updateLineBackground(cm, lineView) {
  2126.     var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  2127.     if (cls) { cls += " CodeMirror-linebackground"; }
  2128.     if (lineView.background) {
  2129.       if (cls) { lineView.background.className = cls; }
  2130.       else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  2131.     } else if (cls) {
  2132.       var wrap = ensureLineWrapped(lineView);
  2133.       lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  2134.       cm.display.input.setUneditable(lineView.background);
  2135.     }
  2136.   }
  2137.  
  2138.   // Wrapper around buildLineContent which will reuse the structure
  2139.   // in display.externalMeasured when possible.
  2140.   function getLineContent(cm, lineView) {
  2141.     var ext = cm.display.externalMeasured;
  2142.     if (ext && ext.line == lineView.line) {
  2143.       cm.display.externalMeasured = null;
  2144.       lineView.measure = ext.measure;
  2145.       return ext.built
  2146.     }
  2147.     return buildLineContent(cm, lineView)
  2148.   }
  2149.  
  2150.   // Redraw the line's text. Interacts with the background and text
  2151.   // classes because the mode may output tokens that influence these
  2152.   // classes.
  2153.   function updateLineText(cm, lineView) {
  2154.     var cls = lineView.text.className;
  2155.     var built = getLineContent(cm, lineView);
  2156.     if (lineView.text == lineView.node) { lineView.node = built.pre; }
  2157.     lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  2158.     lineView.text = built.pre;
  2159.     if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  2160.       lineView.bgClass = built.bgClass;
  2161.       lineView.textClass = built.textClass;
  2162.       updateLineClasses(cm, lineView);
  2163.     } else if (cls) {
  2164.       lineView.text.className = cls;
  2165.     }
  2166.   }
  2167.  
  2168.   function updateLineClasses(cm, lineView) {
  2169.     updateLineBackground(cm, lineView);
  2170.     if (lineView.line.wrapClass)
  2171.       { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  2172.     else if (lineView.node != lineView.text)
  2173.       { lineView.node.className = ""; }
  2174.     var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  2175.     lineView.text.className = textClass || "";
  2176.   }
  2177.  
  2178.   function updateLineGutter(cm, lineView, lineN, dims) {
  2179.     if (lineView.gutter) {
  2180.       lineView.node.removeChild(lineView.gutter);
  2181.       lineView.gutter = null;
  2182.     }
  2183.     if (lineView.gutterBackground) {
  2184.       lineView.node.removeChild(lineView.gutterBackground);
  2185.       lineView.gutterBackground = null;
  2186.     }
  2187.     if (lineView.line.gutterClass) {
  2188.       var wrap = ensureLineWrapped(lineView);
  2189.       lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  2190.                                       ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  2191.       cm.display.input.setUneditable(lineView.gutterBackground);
  2192.       wrap.insertBefore(lineView.gutterBackground, lineView.text);
  2193.     }
  2194.     var markers = lineView.line.gutterMarkers;
  2195.     if (cm.options.lineNumbers || markers) {
  2196.       var wrap$1 = ensureLineWrapped(lineView);
  2197.       var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  2198.       gutterWrap.setAttribute("aria-hidden", "true");
  2199.       cm.display.input.setUneditable(gutterWrap);
  2200.       wrap$1.insertBefore(gutterWrap, lineView.text);
  2201.       if (lineView.line.gutterClass)
  2202.         { gutterWrap.className += " " + lineView.line.gutterClass; }
  2203.       if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  2204.         { lineView.lineNumber = gutterWrap.appendChild(
  2205.           elt("div", lineNumberFor(cm.options, lineN),
  2206.               "CodeMirror-linenumber CodeMirror-gutter-elt",
  2207.               ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  2208.       if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
  2209.         var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
  2210.         if (found)
  2211.           { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2212.                                      ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  2213.       } }
  2214.     }
  2215.   }
  2216.  
  2217.   function updateLineWidgets(cm, lineView, dims) {
  2218.     if (lineView.alignable) { lineView.alignable = null; }
  2219.     var isWidget = classTest("CodeMirror-linewidget");
  2220.     for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  2221.       next = node.nextSibling;
  2222.       if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
  2223.     }
  2224.     insertLineWidgets(cm, lineView, dims);
  2225.   }
  2226.  
  2227.   // Build a line's DOM representation from scratch
  2228.   function buildLineElement(cm, lineView, lineN, dims) {
  2229.     var built = getLineContent(cm, lineView);
  2230.     lineView.text = lineView.node = built.pre;
  2231.     if (built.bgClass) { lineView.bgClass = built.bgClass; }
  2232.     if (built.textClass) { lineView.textClass = built.textClass; }
  2233.  
  2234.     updateLineClasses(cm, lineView);
  2235.     updateLineGutter(cm, lineView, lineN, dims);
  2236.     insertLineWidgets(cm, lineView, dims);
  2237.     return lineView.node
  2238.   }
  2239.  
  2240.   // A lineView may contain multiple logical lines (when merged by
  2241.   // collapsed spans). The widgets for all of them need to be drawn.
  2242.   function insertLineWidgets(cm, lineView, dims) {
  2243.     insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  2244.     if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2245.       { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  2246.   }
  2247.  
  2248.   function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2249.     if (!line.widgets) { return }
  2250.     var wrap = ensureLineWrapped(lineView);
  2251.     for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2252.       var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
  2253.       if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  2254.       positionLineWidget(widget, node, lineView, dims);
  2255.       cm.display.input.setUneditable(node);
  2256.       if (allowAbove && widget.above)
  2257.         { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  2258.       else
  2259.         { wrap.appendChild(node); }
  2260.       signalLater(widget, "redraw");
  2261.     }
  2262.   }
  2263.  
  2264.   function positionLineWidget(widget, node, lineView, dims) {
  2265.     if (widget.noHScroll) {
  2266.   (lineView.alignable || (lineView.alignable = [])).push(node);
  2267.       var width = dims.wrapperWidth;
  2268.       node.style.left = dims.fixedPos + "px";
  2269.       if (!widget.coverGutter) {
  2270.         width -= dims.gutterTotalWidth;
  2271.         node.style.paddingLeft = dims.gutterTotalWidth + "px";
  2272.       }
  2273.       node.style.width = width + "px";
  2274.     }
  2275.     if (widget.coverGutter) {
  2276.       node.style.zIndex = 5;
  2277.       node.style.position = "relative";
  2278.       if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  2279.     }
  2280.   }
  2281.  
  2282.   function widgetHeight(widget) {
  2283.     if (widget.height != null) { return widget.height }
  2284.     var cm = widget.doc.cm;
  2285.     if (!cm) { return 0 }
  2286.     if (!contains(document.body, widget.node)) {
  2287.       var parentStyle = "position: relative;";
  2288.       if (widget.coverGutter)
  2289.         { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  2290.       if (widget.noHScroll)
  2291.         { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  2292.       removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  2293.     }
  2294.     return widget.height = widget.node.parentNode.offsetHeight
  2295.   }
  2296.  
  2297.   // Return true when the given mouse event happened in a widget
  2298.   function eventInWidget(display, e) {
  2299.     for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2300.       if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2301.           (n.parentNode == display.sizer && n != display.mover))
  2302.         { return true }
  2303.     }
  2304.   }
  2305.  
  2306.   // POSITION MEASUREMENT
  2307.  
  2308.   function paddingTop(display) {return display.lineSpace.offsetTop}
  2309.   function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2310.   function paddingH(display) {
  2311.     if (display.cachedPaddingH) { return display.cachedPaddingH }
  2312.     var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
  2313.     var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2314.     var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2315.     if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  2316.     return data
  2317.   }
  2318.  
  2319.   function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2320.   function displayWidth(cm) {
  2321.     return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2322.   }
  2323.   function displayHeight(cm) {
  2324.     return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2325.   }
  2326.  
  2327.   // Ensure the lineView.wrapping.heights array is populated. This is
  2328.   // an array of bottom offsets for the lines that make up a drawn
  2329.   // line. When lineWrapping is on, there might be more than one
  2330.   // height.
  2331.   function ensureLineHeights(cm, lineView, rect) {
  2332.     var wrapping = cm.options.lineWrapping;
  2333.     var curWidth = wrapping && displayWidth(cm);
  2334.     if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2335.       var heights = lineView.measure.heights = [];
  2336.       if (wrapping) {
  2337.         lineView.measure.width = curWidth;
  2338.         var rects = lineView.text.firstChild.getClientRects();
  2339.         for (var i = 0; i < rects.length - 1; i++) {
  2340.           var cur = rects[i], next = rects[i + 1];
  2341.           if (Math.abs(cur.bottom - next.bottom) > 2)
  2342.             { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  2343.         }
  2344.       }
  2345.       heights.push(rect.bottom - rect.top);
  2346.     }
  2347.   }
  2348.  
  2349.   // Find a line map (mapping character offsets to text nodes) and a
  2350.   // measurement cache for the given line number. (A line view might
  2351.   // contain multiple lines when collapsed ranges are present.)
  2352.   function mapFromLineView(lineView, line, lineN) {
  2353.     if (lineView.line == line)
  2354.       { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2355.     if (lineView.rest) {
  2356.       for (var i = 0; i < lineView.rest.length; i++)
  2357.         { if (lineView.rest[i] == line)
  2358.           { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2359.       for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2360.         { if (lineNo(lineView.rest[i$1]) > lineN)
  2361.           { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2362.     }
  2363.   }
  2364.  
  2365.   // Render a line into the hidden node display.externalMeasured. Used
  2366.   // when measurement is needed for a line that's not in the viewport.
  2367.   function updateExternalMeasurement(cm, line) {
  2368.     line = visualLine(line);
  2369.     var lineN = lineNo(line);
  2370.     var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2371.     view.lineN = lineN;
  2372.     var built = view.built = buildLineContent(cm, view);
  2373.     view.text = built.pre;
  2374.     removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2375.     return view
  2376.   }
  2377.  
  2378.   // Get a {top, bottom, left, right} box (in line-local coordinates)
  2379.   // for a given character.
  2380.   function measureChar(cm, line, ch, bias) {
  2381.     return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2382.   }
  2383.  
  2384.   // Find a line view that corresponds to the given line number.
  2385.   function findViewForLine(cm, lineN) {
  2386.     if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2387.       { return cm.display.view[findViewIndex(cm, lineN)] }
  2388.     var ext = cm.display.externalMeasured;
  2389.     if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2390.       { return ext }
  2391.   }
  2392.  
  2393.   // Measurement can be split in two steps, the set-up work that
  2394.   // applies to the whole line, and the measurement of the actual
  2395.   // character. Functions like coordsChar, that need to do a lot of
  2396.   // measurements in a row, can thus ensure that the set-up work is
  2397.   // only done once.
  2398.   function prepareMeasureForLine(cm, line) {
  2399.     var lineN = lineNo(line);
  2400.     var view = findViewForLine(cm, lineN);
  2401.     if (view && !view.text) {
  2402.       view = null;
  2403.     } else if (view && view.changes) {
  2404.       updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2405.       cm.curOp.forceUpdate = true;
  2406.     }
  2407.     if (!view)
  2408.       { view = updateExternalMeasurement(cm, line); }
  2409.  
  2410.     var info = mapFromLineView(view, line, lineN);
  2411.     return {
  2412.       line: line, view: view, rect: null,
  2413.       map: info.map, cache: info.cache, before: info.before,
  2414.       hasHeights: false
  2415.     }
  2416.   }
  2417.  
  2418.   // Given a prepared measurement object, measures the position of an
  2419.   // actual character (or fetches it from the cache).
  2420.   function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2421.     if (prepared.before) { ch = -1; }
  2422.     var key = ch + (bias || ""), found;
  2423.     if (prepared.cache.hasOwnProperty(key)) {
  2424.       found = prepared.cache[key];
  2425.     } else {
  2426.       if (!prepared.rect)
  2427.         { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  2428.       if (!prepared.hasHeights) {
  2429.         ensureLineHeights(cm, prepared.view, prepared.rect);
  2430.         prepared.hasHeights = true;
  2431.       }
  2432.       found = measureCharInner(cm, prepared, ch, bias);
  2433.       if (!found.bogus) { prepared.cache[key] = found; }
  2434.     }
  2435.     return {left: found.left, right: found.right,
  2436.             top: varHeight ? found.rtop : found.top,
  2437.             bottom: varHeight ? found.rbottom : found.bottom}
  2438.   }
  2439.  
  2440.   var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2441.  
  2442.   function nodeAndOffsetInLineMap(map, ch, bias) {
  2443.     var node, start, end, collapse, mStart, mEnd;
  2444.     // First, search the line map for the text node corresponding to,
  2445.     // or closest to, the target character.
  2446.     for (var i = 0; i < map.length; i += 3) {
  2447.       mStart = map[i];
  2448.       mEnd = map[i + 1];
  2449.       if (ch < mStart) {
  2450.         start = 0; end = 1;
  2451.         collapse = "left";
  2452.       } else if (ch < mEnd) {
  2453.         start = ch - mStart;
  2454.         end = start + 1;
  2455.       } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2456.         end = mEnd - mStart;
  2457.         start = end - 1;
  2458.         if (ch >= mEnd) { collapse = "right"; }
  2459.       }
  2460.       if (start != null) {
  2461.         node = map[i + 2];
  2462.         if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2463.           { collapse = bias; }
  2464.         if (bias == "left" && start == 0)
  2465.           { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2466.             node = map[(i -= 3) + 2];
  2467.             collapse = "left";
  2468.           } }
  2469.         if (bias == "right" && start == mEnd - mStart)
  2470.           { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2471.             node = map[(i += 3) + 2];
  2472.             collapse = "right";
  2473.           } }
  2474.         break
  2475.       }
  2476.     }
  2477.     return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2478.   }
  2479.  
  2480.   function getUsefulRect(rects, bias) {
  2481.     var rect = nullRect;
  2482.     if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2483.       if ((rect = rects[i]).left != rect.right) { break }
  2484.     } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2485.       if ((rect = rects[i$1]).left != rect.right) { break }
  2486.     } }
  2487.     return rect
  2488.   }
  2489.  
  2490.   function measureCharInner(cm, prepared, ch, bias) {
  2491.     var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2492.     var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2493.  
  2494.     var rect;
  2495.     if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2496.       for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2497.         while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  2498.         while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  2499.         if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2500.           { rect = node.parentNode.getBoundingClientRect(); }
  2501.         else
  2502.           { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  2503.         if (rect.left || rect.right || start == 0) { break }
  2504.         end = start;
  2505.         start = start - 1;
  2506.         collapse = "right";
  2507.       }
  2508.       if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  2509.     } else { // If it is a widget, simply get the box for the whole widget.
  2510.       if (start > 0) { collapse = bias = "right"; }
  2511.       var rects;
  2512.       if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2513.         { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  2514.       else
  2515.         { rect = node.getBoundingClientRect(); }
  2516.     }
  2517.     if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2518.       var rSpan = node.parentNode.getClientRects()[0];
  2519.       if (rSpan)
  2520.         { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  2521.       else
  2522.         { rect = nullRect; }
  2523.     }
  2524.  
  2525.     var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2526.     var mid = (rtop + rbot) / 2;
  2527.     var heights = prepared.view.measure.heights;
  2528.     var i = 0;
  2529.     for (; i < heights.length - 1; i++)
  2530.       { if (mid < heights[i]) { break } }
  2531.     var top = i ? heights[i - 1] : 0, bot = heights[i];
  2532.     var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2533.                   right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2534.                   top: top, bottom: bot};
  2535.     if (!rect.left && !rect.right) { result.bogus = true; }
  2536.     if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2537.  
  2538.     return result
  2539.   }
  2540.  
  2541.   // Work around problem with bounding client rects on ranges being
  2542.   // returned incorrectly when zoomed on IE10 and below.
  2543.   function maybeUpdateRectForZooming(measure, rect) {
  2544.     if (!window.screen || screen.logicalXDPI == null ||
  2545.         screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2546.       { return rect }
  2547.     var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2548.     var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2549.     return {left: rect.left * scaleX, right: rect.right * scaleX,
  2550.             top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2551.   }
  2552.  
  2553.   function clearLineMeasurementCacheFor(lineView) {
  2554.     if (lineView.measure) {
  2555.       lineView.measure.cache = {};
  2556.       lineView.measure.heights = null;
  2557.       if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2558.         { lineView.measure.caches[i] = {}; } }
  2559.     }
  2560.   }
  2561.  
  2562.   function clearLineMeasurementCache(cm) {
  2563.     cm.display.externalMeasure = null;
  2564.     removeChildren(cm.display.lineMeasure);
  2565.     for (var i = 0; i < cm.display.view.length; i++)
  2566.       { clearLineMeasurementCacheFor(cm.display.view[i]); }
  2567.   }
  2568.  
  2569.   function clearCaches(cm) {
  2570.     clearLineMeasurementCache(cm);
  2571.     cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2572.     if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  2573.     cm.display.lineNumChars = null;
  2574.   }
  2575.  
  2576.   function pageScrollX() {
  2577.     // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  2578.     // which causes page_Offset and bounding client rects to use
  2579.     // different reference viewports and invalidate our calculations.
  2580.     if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  2581.     return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  2582.   }
  2583.   function pageScrollY() {
  2584.     if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  2585.     return window.pageYOffset || (document.documentElement || document.body).scrollTop
  2586.   }
  2587.  
  2588.   function widgetTopHeight(lineObj) {
  2589.     var ref = visualLine(lineObj);
  2590.     var widgets = ref.widgets;
  2591.     var height = 0;
  2592.     if (widgets) { for (var i = 0; i < widgets.length; ++i) { if (widgets[i].above)
  2593.       { height += widgetHeight(widgets[i]); } } }
  2594.     return height
  2595.   }
  2596.  
  2597.   // Converts a {top, bottom, left, right} box from line-local
  2598.   // coordinates into another coordinate system. Context may be one of
  2599.   // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2600.   // or "page".
  2601.   function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2602.     if (!includeWidgets) {
  2603.       var height = widgetTopHeight(lineObj);
  2604.       rect.top += height; rect.bottom += height;
  2605.     }
  2606.     if (context == "line") { return rect }
  2607.     if (!context) { context = "local"; }
  2608.     var yOff = heightAtLine(lineObj);
  2609.     if (context == "local") { yOff += paddingTop(cm.display); }
  2610.     else { yOff -= cm.display.viewOffset; }
  2611.     if (context == "page" || context == "window") {
  2612.       var lOff = cm.display.lineSpace.getBoundingClientRect();
  2613.       yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2614.       var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2615.       rect.left += xOff; rect.right += xOff;
  2616.     }
  2617.     rect.top += yOff; rect.bottom += yOff;
  2618.     return rect
  2619.   }
  2620.  
  2621.   // Coverts a box from "div" coords to another coordinate system.
  2622.   // Context may be "window", "page", "div", or "local"./null.
  2623.   function fromCoordSystem(cm, coords, context) {
  2624.     if (context == "div") { return coords }
  2625.     var left = coords.left, top = coords.top;
  2626.     // First move into "page" coordinate system
  2627.     if (context == "page") {
  2628.       left -= pageScrollX();
  2629.       top -= pageScrollY();
  2630.     } else if (context == "local" || !context) {
  2631.       var localBox = cm.display.sizer.getBoundingClientRect();
  2632.       left += localBox.left;
  2633.       top += localBox.top;
  2634.     }
  2635.  
  2636.     var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2637.     return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2638.   }
  2639.  
  2640.   function charCoords(cm, pos, context, lineObj, bias) {
  2641.     if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  2642.     return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2643.   }
  2644.  
  2645.   // Returns a box for a given cursor position, which may have an
  2646.   // 'other' property containing the position of the secondary cursor
  2647.   // on a bidi boundary.
  2648.   // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2649.   // and after `char - 1` in writing order of `char - 1`
  2650.   // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2651.   // and before `char` in writing order of `char`
  2652.   // Examples (upper-case letters are RTL, lower-case are LTR):
  2653.   //     Pos(0, 1, ...)
  2654.   //     before   after
  2655.   // ab     a|b     a|b
  2656.   // aB     a|B     aB|
  2657.   // Ab     |Ab     A|b
  2658.   // AB     B|A     B|A
  2659.   // Every position after the last character on a line is considered to stick
  2660.   // to the last character on the line.
  2661.   function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2662.     lineObj = lineObj || getLine(cm.doc, pos.line);
  2663.     if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2664.     function get(ch, right) {
  2665.       var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2666.       if (right) { m.left = m.right; } else { m.right = m.left; }
  2667.       return intoCoordSystem(cm, lineObj, m, context)
  2668.     }
  2669.     var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  2670.     if (ch >= lineObj.text.length) {
  2671.       ch = lineObj.text.length;
  2672.       sticky = "before";
  2673.     } else if (ch <= 0) {
  2674.       ch = 0;
  2675.       sticky = "after";
  2676.     }
  2677.     if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2678.  
  2679.     function getBidi(ch, partPos, invert) {
  2680.       var part = order[partPos], right = part.level == 1;
  2681.       return get(invert ? ch - 1 : ch, right != invert)
  2682.     }
  2683.     var partPos = getBidiPartAt(order, ch, sticky);
  2684.     var other = bidiOther;
  2685.     var val = getBidi(ch, partPos, sticky == "before");
  2686.     if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  2687.     return val
  2688.   }
  2689.  
  2690.   // Used to cheaply estimate the coordinates for a position. Used for
  2691.   // intermediate scroll updates.
  2692.   function estimateCoords(cm, pos) {
  2693.     var left = 0;
  2694.     pos = clipPos(cm.doc, pos);
  2695.     if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  2696.     var lineObj = getLine(cm.doc, pos.line);
  2697.     var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2698.     return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2699.   }
  2700.  
  2701.   // Positions returned by coordsChar contain some extra information.
  2702.   // xRel is the relative x position of the input coordinates compared
  2703.   // to the found position (so xRel > 0 means the coordinates are to
  2704.   // the right of the character position, for example). When outside
  2705.   // is true, that means the coordinates lie outside the line's
  2706.   // vertical range.
  2707.   function PosWithInfo(line, ch, sticky, outside, xRel) {
  2708.     var pos = Pos(line, ch, sticky);
  2709.     pos.xRel = xRel;
  2710.     if (outside) { pos.outside = outside; }
  2711.     return pos
  2712.   }
  2713.  
  2714.   // Compute the character position closest to the given coordinates.
  2715.   // Input must be lineSpace-local ("div" coordinate system).
  2716.   function coordsChar(cm, x, y) {
  2717.     var doc = cm.doc;
  2718.     y += cm.display.viewOffset;
  2719.     if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
  2720.     var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2721.     if (lineN > last)
  2722.       { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
  2723.     if (x < 0) { x = 0; }
  2724.  
  2725.     var lineObj = getLine(doc, lineN);
  2726.     for (;;) {
  2727.       var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2728.       var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
  2729.       if (!collapsed) { return found }
  2730.       var rangeEnd = collapsed.find(1);
  2731.       if (rangeEnd.line == lineN) { return rangeEnd }
  2732.       lineObj = getLine(doc, lineN = rangeEnd.line);
  2733.     }
  2734.   }
  2735.  
  2736.   function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2737.     y -= widgetTopHeight(lineObj);
  2738.     var end = lineObj.text.length;
  2739.     var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  2740.     end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  2741.     return {begin: begin, end: end}
  2742.   }
  2743.  
  2744.   function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2745.     if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2746.     var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  2747.     return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2748.   }
  2749.  
  2750.   // Returns true if the given side of a box is after the given
  2751.   // coordinates, in top-to-bottom, left-to-right order.
  2752.   function boxIsAfter(box, x, y, left) {
  2753.     return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  2754.   }
  2755.  
  2756.   function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2757.     // Move y into line-local coordinate space
  2758.     y -= heightAtLine(lineObj);
  2759.     var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2760.     // When directly calling `measureCharPrepared`, we have to adjust
  2761.     // for the widgets at this line.
  2762.     var widgetHeight = widgetTopHeight(lineObj);
  2763.     var begin = 0, end = lineObj.text.length, ltr = true;
  2764.  
  2765.     var order = getOrder(lineObj, cm.doc.direction);
  2766.     // If the line isn't plain left-to-right text, first figure out
  2767.     // which bidi section the coordinates fall into.
  2768.     if (order) {
  2769.       var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  2770.                    (cm, lineObj, lineNo, preparedMeasure, order, x, y);
  2771.       ltr = part.level != 1;
  2772.       // The awkward -1 offsets are needed because findFirst (called
  2773.       // on these below) will treat its first bound as inclusive,
  2774.       // second as exclusive, but we want to actually address the
  2775.       // characters in the part's range
  2776.       begin = ltr ? part.from : part.to - 1;
  2777.       end = ltr ? part.to : part.from - 1;
  2778.     }
  2779.  
  2780.     // A binary search to find the first character whose bounding box
  2781.     // starts after the coordinates. If we run across any whose box wrap
  2782.     // the coordinates, store that.
  2783.     var chAround = null, boxAround = null;
  2784.     var ch = findFirst(function (ch) {
  2785.       var box = measureCharPrepared(cm, preparedMeasure, ch);
  2786.       box.top += widgetHeight; box.bottom += widgetHeight;
  2787.       if (!boxIsAfter(box, x, y, false)) { return false }
  2788.       if (box.top <= y && box.left <= x) {
  2789.         chAround = ch;
  2790.         boxAround = box;
  2791.       }
  2792.       return true
  2793.     }, begin, end);
  2794.  
  2795.     var baseX, sticky, outside = false;
  2796.     // If a box around the coordinates was found, use that
  2797.     if (boxAround) {
  2798.       // Distinguish coordinates nearer to the left or right side of the box
  2799.       var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  2800.       ch = chAround + (atStart ? 0 : 1);
  2801.       sticky = atStart ? "after" : "before";
  2802.       baseX = atLeft ? boxAround.left : boxAround.right;
  2803.     } else {
  2804.       // (Adjust for extended bound, if necessary.)
  2805.       if (!ltr && (ch == end || ch == begin)) { ch++; }
  2806.       // To determine which side to associate with, get the box to the
  2807.       // left of the character and compare it's vertical position to the
  2808.       // coordinates
  2809.       sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  2810.         (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
  2811.         "after" : "before";
  2812.       // Now get accurate coordinates for this place, in order to get a
  2813.       // base X position
  2814.       var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
  2815.       baseX = coords.left;
  2816.       outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
  2817.     }
  2818.  
  2819.     ch = skipExtendingChars(lineObj.text, ch, 1);
  2820.     return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  2821.   }
  2822.  
  2823.   function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
  2824.     // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  2825.     // situation, we can take this ordering to correspond to the visual
  2826.     // ordering. This finds the first part whose end is after the given
  2827.     // coordinates.
  2828.     var index = findFirst(function (i) {
  2829.       var part = order[i], ltr = part.level != 1;
  2830.       return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
  2831.                                      "line", lineObj, preparedMeasure), x, y, true)
  2832.     }, 0, order.length - 1);
  2833.     var part = order[index];
  2834.     // If this isn't the first part, the part's start is also after
  2835.     // the coordinates, and the coordinates aren't on the same line as
  2836.     // that start, move one part back.
  2837.     if (index > 0) {
  2838.       var ltr = part.level != 1;
  2839.       var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
  2840.                                "line", lineObj, preparedMeasure);
  2841.       if (boxIsAfter(start, x, y, true) && start.top > y)
  2842.         { part = order[index - 1]; }
  2843.     }
  2844.     return part
  2845.   }
  2846.  
  2847.   function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  2848.     // In a wrapped line, rtl text on wrapping boundaries can do things
  2849.     // that don't correspond to the ordering in our `order` array at
  2850.     // all, so a binary search doesn't work, and we want to return a
  2851.     // part that only spans one line so that the binary search in
  2852.     // coordsCharInner is safe. As such, we first find the extent of the
  2853.     // wrapped line, and then do a flat search in which we discard any
  2854.     // spans that aren't on the line.
  2855.     var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  2856.     var begin = ref.begin;
  2857.     var end = ref.end;
  2858.     if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  2859.     var part = null, closestDist = null;
  2860.     for (var i = 0; i < order.length; i++) {
  2861.       var p = order[i];
  2862.       if (p.from >= end || p.to <= begin) { continue }
  2863.       var ltr = p.level != 1;
  2864.       var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  2865.       // Weigh against spans ending before this, so that they are only
  2866.       // picked if nothing ends after
  2867.       var dist = endX < x ? x - endX + 1e9 : endX - x;
  2868.       if (!part || closestDist > dist) {
  2869.         part = p;
  2870.         closestDist = dist;
  2871.       }
  2872.     }
  2873.     if (!part) { part = order[order.length - 1]; }
  2874.     // Clip the part to the wrapped line.
  2875.     if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  2876.     if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  2877.     return part
  2878.   }
  2879.  
  2880.   var measureText;
  2881.   // Compute the default text height.
  2882.   function textHeight(display) {
  2883.     if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2884.     if (measureText == null) {
  2885.       measureText = elt("pre", null, "CodeMirror-line-like");
  2886.       // Measure a bunch of lines, for browsers that compute
  2887.       // fractional heights.
  2888.       for (var i = 0; i < 49; ++i) {
  2889.         measureText.appendChild(document.createTextNode("x"));
  2890.         measureText.appendChild(elt("br"));
  2891.       }
  2892.       measureText.appendChild(document.createTextNode("x"));
  2893.     }
  2894.     removeChildrenAndAdd(display.measure, measureText);
  2895.     var height = measureText.offsetHeight / 50;
  2896.     if (height > 3) { display.cachedTextHeight = height; }
  2897.     removeChildren(display.measure);
  2898.     return height || 1
  2899.   }
  2900.  
  2901.   // Compute the default character width.
  2902.   function charWidth(display) {
  2903.     if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2904.     var anchor = elt("span", "xxxxxxxxxx");
  2905.     var pre = elt("pre", [anchor], "CodeMirror-line-like");
  2906.     removeChildrenAndAdd(display.measure, pre);
  2907.     var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2908.     if (width > 2) { display.cachedCharWidth = width; }
  2909.     return width || 10
  2910.   }
  2911.  
  2912.   // Do a bulk-read of the DOM positions and sizes needed to draw the
  2913.   // view, so that we don't interleave reading and writing to the DOM.
  2914.   function getDimensions(cm) {
  2915.     var d = cm.display, left = {}, width = {};
  2916.     var gutterLeft = d.gutters.clientLeft;
  2917.     for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2918.       var id = cm.display.gutterSpecs[i].className;
  2919.       left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
  2920.       width[id] = n.clientWidth;
  2921.     }
  2922.     return {fixedPos: compensateForHScroll(d),
  2923.             gutterTotalWidth: d.gutters.offsetWidth,
  2924.             gutterLeft: left,
  2925.             gutterWidth: width,
  2926.             wrapperWidth: d.wrapper.clientWidth}
  2927.   }
  2928.  
  2929.   // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2930.   // but using getBoundingClientRect to get a sub-pixel-accurate
  2931.   // result.
  2932.   function compensateForHScroll(display) {
  2933.     return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2934.   }
  2935.  
  2936.   // Returns a function that estimates the height of a line, to use as
  2937.   // first approximation until the line becomes visible (and is thus
  2938.   // properly measurable).
  2939.   function estimateHeight(cm) {
  2940.     var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  2941.     var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  2942.     return function (line) {
  2943.       if (lineIsHidden(cm.doc, line)) { return 0 }
  2944.  
  2945.       var widgetsHeight = 0;
  2946.       if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2947.         if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  2948.       } }
  2949.  
  2950.       if (wrapping)
  2951.         { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2952.       else
  2953.         { return widgetsHeight + th }
  2954.     }
  2955.   }
  2956.  
  2957.   function estimateLineHeights(cm) {
  2958.     var doc = cm.doc, est = estimateHeight(cm);
  2959.     doc.iter(function (line) {
  2960.       var estHeight = est(line);
  2961.       if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  2962.     });
  2963.   }
  2964.  
  2965.   // Given a mouse event, find the corresponding position. If liberal
  2966.   // is false, it checks whether a gutter or scrollbar was clicked,
  2967.   // and returns null if it was. forRect is used by rectangular
  2968.   // selections, and tries to estimate a character position even for
  2969.   // coordinates beyond the right of the text.
  2970.   function posFromMouse(cm, e, liberal, forRect) {
  2971.     var display = cm.display;
  2972.     if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2973.  
  2974.     var x, y, space = display.lineSpace.getBoundingClientRect();
  2975.     // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2976.     try { x = e.clientX - space.left; y = e.clientY - space.top; }
  2977.     catch (e$1) { return null }
  2978.     var coords = coordsChar(cm, x, y), line;
  2979.     if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2980.       var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  2981.       coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  2982.     }
  2983.     return coords
  2984.   }
  2985.  
  2986.   // Find the view element corresponding to a given line. Return null
  2987.   // when the line isn't visible.
  2988.   function findViewIndex(cm, n) {
  2989.     if (n >= cm.display.viewTo) { return null }
  2990.     n -= cm.display.viewFrom;
  2991.     if (n < 0) { return null }
  2992.     var view = cm.display.view;
  2993.     for (var i = 0; i < view.length; i++) {
  2994.       n -= view[i].size;
  2995.       if (n < 0) { return i }
  2996.     }
  2997.   }
  2998.  
  2999.   // Updates the display.view data structure for a given change to the
  3000.   // document. From and to are in pre-change coordinates. Lendiff is
  3001.   // the amount of lines added or subtracted by the change. This is
  3002.   // used for changes that span multiple lines, or change the way
  3003.   // lines are divided into visual lines. regLineChange (below)
  3004.   // registers single-line changes.
  3005.   function regChange(cm, from, to, lendiff) {
  3006.     if (from == null) { from = cm.doc.first; }
  3007.     if (to == null) { to = cm.doc.first + cm.doc.size; }
  3008.     if (!lendiff) { lendiff = 0; }
  3009.  
  3010.     var display = cm.display;
  3011.     if (lendiff && to < display.viewTo &&
  3012.         (display.updateLineNumbers == null || display.updateLineNumbers > from))
  3013.       { display.updateLineNumbers = from; }
  3014.  
  3015.     cm.curOp.viewChanged = true;
  3016.  
  3017.     if (from >= display.viewTo) { // Change after
  3018.       if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  3019.         { resetView(cm); }
  3020.     } else if (to <= display.viewFrom) { // Change before
  3021.       if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  3022.         resetView(cm);
  3023.       } else {
  3024.         display.viewFrom += lendiff;
  3025.         display.viewTo += lendiff;
  3026.       }
  3027.     } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  3028.       resetView(cm);
  3029.     } else if (from <= display.viewFrom) { // Top overlap
  3030.       var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  3031.       if (cut) {
  3032.         display.view = display.view.slice(cut.index);
  3033.         display.viewFrom = cut.lineN;
  3034.         display.viewTo += lendiff;
  3035.       } else {
  3036.         resetView(cm);
  3037.       }
  3038.     } else if (to >= display.viewTo) { // Bottom overlap
  3039.       var cut$1 = viewCuttingPoint(cm, from, from, -1);
  3040.       if (cut$1) {
  3041.         display.view = display.view.slice(0, cut$1.index);
  3042.         display.viewTo = cut$1.lineN;
  3043.       } else {
  3044.         resetView(cm);
  3045.       }
  3046.     } else { // Gap in the middle
  3047.       var cutTop = viewCuttingPoint(cm, from, from, -1);
  3048.       var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  3049.       if (cutTop && cutBot) {
  3050.         display.view = display.view.slice(0, cutTop.index)
  3051.           .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  3052.           .concat(display.view.slice(cutBot.index));
  3053.         display.viewTo += lendiff;
  3054.       } else {
  3055.         resetView(cm);
  3056.       }
  3057.     }
  3058.  
  3059.     var ext = display.externalMeasured;
  3060.     if (ext) {
  3061.       if (to < ext.lineN)
  3062.         { ext.lineN += lendiff; }
  3063.       else if (from < ext.lineN + ext.size)
  3064.         { display.externalMeasured = null; }
  3065.     }
  3066.   }
  3067.  
  3068.   // Register a change to a single line. Type must be one of "text",
  3069.   // "gutter", "class", "widget"
  3070.   function regLineChange(cm, line, type) {
  3071.     cm.curOp.viewChanged = true;
  3072.     var display = cm.display, ext = cm.display.externalMeasured;
  3073.     if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  3074.       { display.externalMeasured = null; }
  3075.  
  3076.     if (line < display.viewFrom || line >= display.viewTo) { return }
  3077.     var lineView = display.view[findViewIndex(cm, line)];
  3078.     if (lineView.node == null) { return }
  3079.     var arr = lineView.changes || (lineView.changes = []);
  3080.     if (indexOf(arr, type) == -1) { arr.push(type); }
  3081.   }
  3082.  
  3083.   // Clear the view.
  3084.   function resetView(cm) {
  3085.     cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  3086.     cm.display.view = [];
  3087.     cm.display.viewOffset = 0;
  3088.   }
  3089.  
  3090.   function viewCuttingPoint(cm, oldN, newN, dir) {
  3091.     var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  3092.     if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  3093.       { return {index: index, lineN: newN} }
  3094.     var n = cm.display.viewFrom;
  3095.     for (var i = 0; i < index; i++)
  3096.       { n += view[i].size; }
  3097.     if (n != oldN) {
  3098.       if (dir > 0) {
  3099.         if (index == view.length - 1) { return null }
  3100.         diff = (n + view[index].size) - oldN;
  3101.         index++;
  3102.       } else {
  3103.         diff = n - oldN;
  3104.       }
  3105.       oldN += diff; newN += diff;
  3106.     }
  3107.     while (visualLineNo(cm.doc, newN) != newN) {
  3108.       if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  3109.       newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  3110.       index += dir;
  3111.     }
  3112.     return {index: index, lineN: newN}
  3113.   }
  3114.  
  3115.   // Force the view to cover a given range, adding empty view element
  3116.   // or clipping off existing ones as needed.
  3117.   function adjustView(cm, from, to) {
  3118.     var display = cm.display, view = display.view;
  3119.     if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3120.       display.view = buildViewArray(cm, from, to);
  3121.       display.viewFrom = from;
  3122.     } else {
  3123.       if (display.viewFrom > from)
  3124.         { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  3125.       else if (display.viewFrom < from)
  3126.         { display.view = display.view.slice(findViewIndex(cm, from)); }
  3127.       display.viewFrom = from;
  3128.       if (display.viewTo < to)
  3129.         { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  3130.       else if (display.viewTo > to)
  3131.         { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  3132.     }
  3133.     display.viewTo = to;
  3134.   }
  3135.  
  3136.   // Count the number of lines in the view whose DOM representation is
  3137.   // out of date (or nonexistent).
  3138.   function countDirtyView(cm) {
  3139.     var view = cm.display.view, dirty = 0;
  3140.     for (var i = 0; i < view.length; i++) {
  3141.       var lineView = view[i];
  3142.       if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  3143.     }
  3144.     return dirty
  3145.   }
  3146.  
  3147.   function updateSelection(cm) {
  3148.     cm.display.input.showSelection(cm.display.input.prepareSelection());
  3149.   }
  3150.  
  3151.   function prepareSelection(cm, primary) {
  3152.     if ( primary === void 0 ) primary = true;
  3153.  
  3154.     var doc = cm.doc, result = {};
  3155.     var curFragment = result.cursors = document.createDocumentFragment();
  3156.     var selFragment = result.selection = document.createDocumentFragment();
  3157.  
  3158.     var customCursor = cm.options.$customCursor;
  3159.     if (customCursor) { primary = true; }
  3160.     for (var i = 0; i < doc.sel.ranges.length; i++) {
  3161.       if (!primary && i == doc.sel.primIndex) { continue }
  3162.       var range = doc.sel.ranges[i];
  3163.       if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
  3164.       var collapsed = range.empty();
  3165.       if (customCursor) {
  3166.         var head = customCursor(cm, range);
  3167.         if (head) { drawSelectionCursor(cm, head, curFragment); }
  3168.       } else if (collapsed || cm.options.showCursorWhenSelecting) {
  3169.         drawSelectionCursor(cm, range.head, curFragment);
  3170.       }
  3171.       if (!collapsed)
  3172.         { drawSelectionRange(cm, range, selFragment); }
  3173.     }
  3174.     return result
  3175.   }
  3176.  
  3177.   // Draws a cursor for the given range
  3178.   function drawSelectionCursor(cm, head, output) {
  3179.     var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  3180.  
  3181.     var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  3182.     cursor.style.left = pos.left + "px";
  3183.     cursor.style.top = pos.top + "px";
  3184.     cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  3185.  
  3186.     if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) {
  3187.       var charPos = charCoords(cm, head, "div", null, null);
  3188.       var width = charPos.right - charPos.left;
  3189.       cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px";
  3190.     }
  3191.  
  3192.     if (pos.other) {
  3193.       // Secondary cursor, shown when on a 'jump' in bi-directional text
  3194.       var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  3195.       otherCursor.style.display = "";
  3196.       otherCursor.style.left = pos.other.left + "px";
  3197.       otherCursor.style.top = pos.other.top + "px";
  3198.       otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  3199.     }
  3200.   }
  3201.  
  3202.   function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  3203.  
  3204.   // Draws the given range as a highlighted selection
  3205.   function drawSelectionRange(cm, range, output) {
  3206.     var display = cm.display, doc = cm.doc;
  3207.     var fragment = document.createDocumentFragment();
  3208.     var padding = paddingH(cm.display), leftSide = padding.left;
  3209.     var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  3210.     var docLTR = doc.direction == "ltr";
  3211.  
  3212.     function add(left, top, width, bottom) {
  3213.       if (top < 0) { top = 0; }
  3214.       top = Math.round(top);
  3215.       bottom = Math.round(bottom);
  3216.       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")));
  3217.     }
  3218.  
  3219.     function drawForLine(line, fromArg, toArg) {
  3220.       var lineObj = getLine(doc, line);
  3221.       var lineLen = lineObj.text.length;
  3222.       var start, end;
  3223.       function coords(ch, bias) {
  3224.         return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  3225.       }
  3226.  
  3227.       function wrapX(pos, dir, side) {
  3228.         var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  3229.         var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  3230.         var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  3231.         return coords(ch, prop)[prop]
  3232.       }
  3233.  
  3234.       var order = getOrder(lineObj, doc.direction);
  3235.       iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  3236.         var ltr = dir == "ltr";
  3237.         var fromPos = coords(from, ltr ? "left" : "right");
  3238.         var toPos = coords(to - 1, ltr ? "right" : "left");
  3239.  
  3240.         var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  3241.         var first = i == 0, last = !order || i == order.length - 1;
  3242.         if (toPos.top - fromPos.top <= 3) { // Single line
  3243.           var openLeft = (docLTR ? openStart : openEnd) && first;
  3244.           var openRight = (docLTR ? openEnd : openStart) && last;
  3245.           var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  3246.           var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  3247.           add(left, fromPos.top, right - left, fromPos.bottom);
  3248.         } else { // Multiple lines
  3249.           var topLeft, topRight, botLeft, botRight;
  3250.           if (ltr) {
  3251.             topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  3252.             topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  3253.             botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  3254.             botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  3255.           } else {
  3256.             topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  3257.             topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  3258.             botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  3259.             botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  3260.           }
  3261.           add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  3262.           if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  3263.           add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  3264.         }
  3265.  
  3266.         if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  3267.         if (cmpCoords(toPos, start) < 0) { start = toPos; }
  3268.         if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  3269.         if (cmpCoords(toPos, end) < 0) { end = toPos; }
  3270.       });
  3271.       return {start: start, end: end}
  3272.     }
  3273.  
  3274.     var sFrom = range.from(), sTo = range.to();
  3275.     if (sFrom.line == sTo.line) {
  3276.       drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  3277.     } else {
  3278.       var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  3279.       var singleVLine = visualLine(fromLine) == visualLine(toLine);
  3280.       var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  3281.       var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  3282.       if (singleVLine) {
  3283.         if (leftEnd.top < rightStart.top - 2) {
  3284.           add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  3285.           add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  3286.         } else {
  3287.           add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  3288.         }
  3289.       }
  3290.       if (leftEnd.bottom < rightStart.top)
  3291.         { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  3292.     }
  3293.  
  3294.     output.appendChild(fragment);
  3295.   }
  3296.  
  3297.   // Cursor-blinking
  3298.   function restartBlink(cm) {
  3299.     if (!cm.state.focused) { return }
  3300.     var display = cm.display;
  3301.     clearInterval(display.blinker);
  3302.     var on = true;
  3303.     display.cursorDiv.style.visibility = "";
  3304.     if (cm.options.cursorBlinkRate > 0)
  3305.       { display.blinker = setInterval(function () {
  3306.         if (!cm.hasFocus()) { onBlur(cm); }
  3307.         display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  3308.       }, cm.options.cursorBlinkRate); }
  3309.     else if (cm.options.cursorBlinkRate < 0)
  3310.       { display.cursorDiv.style.visibility = "hidden"; }
  3311.   }
  3312.  
  3313.   function ensureFocus(cm) {
  3314.     if (!cm.hasFocus()) {
  3315.       cm.display.input.focus();
  3316.       if (!cm.state.focused) { onFocus(cm); }
  3317.     }
  3318.   }
  3319.  
  3320.   function delayBlurEvent(cm) {
  3321.     cm.state.delayingBlurEvent = true;
  3322.     setTimeout(function () { if (cm.state.delayingBlurEvent) {
  3323.       cm.state.delayingBlurEvent = false;
  3324.       if (cm.state.focused) { onBlur(cm); }
  3325.     } }, 100);
  3326.   }
  3327.  
  3328.   function onFocus(cm, e) {
  3329.     if (cm.state.delayingBlurEvent && !cm.state.draggingText) { cm.state.delayingBlurEvent = false; }
  3330.  
  3331.     if (cm.options.readOnly == "nocursor") { return }
  3332.     if (!cm.state.focused) {
  3333.       signal(cm, "focus", cm, e);
  3334.       cm.state.focused = true;
  3335.       addClass(cm.display.wrapper, "CodeMirror-focused");
  3336.       // This test prevents this from firing when a context
  3337.       // menu is closed (since the input reset would kill the
  3338.       // select-all detection hack)
  3339.       if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3340.         cm.display.input.reset();
  3341.         if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  3342.       }
  3343.       cm.display.input.receivedFocus();
  3344.     }
  3345.     restartBlink(cm);
  3346.   }
  3347.   function onBlur(cm, e) {
  3348.     if (cm.state.delayingBlurEvent) { return }
  3349.  
  3350.     if (cm.state.focused) {
  3351.       signal(cm, "blur", cm, e);
  3352.       cm.state.focused = false;
  3353.       rmClass(cm.display.wrapper, "CodeMirror-focused");
  3354.     }
  3355.     clearInterval(cm.display.blinker);
  3356.     setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  3357.   }
  3358.  
  3359.   // Read the actual heights of the rendered lines, and update their
  3360.   // stored heights to match.
  3361.   function updateHeightsInViewport(cm) {
  3362.     var display = cm.display;
  3363.     var prevBottom = display.lineDiv.offsetTop;
  3364.     var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top);
  3365.     var oldHeight = display.lineDiv.getBoundingClientRect().top;
  3366.     var mustScroll = 0;
  3367.     for (var i = 0; i < display.view.length; i++) {
  3368.       var cur = display.view[i], wrapping = cm.options.lineWrapping;
  3369.       var height = (void 0), width = 0;
  3370.       if (cur.hidden) { continue }
  3371.       oldHeight += cur.line.height;
  3372.       if (ie && ie_version < 8) {
  3373.         var bot = cur.node.offsetTop + cur.node.offsetHeight;
  3374.         height = bot - prevBottom;
  3375.         prevBottom = bot;
  3376.       } else {
  3377.         var box = cur.node.getBoundingClientRect();
  3378.         height = box.bottom - box.top;
  3379.         // Check that lines don't extend past the right of the current
  3380.         // editor width
  3381.         if (!wrapping && cur.text.firstChild)
  3382.           { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
  3383.       }
  3384.       var diff = cur.line.height - height;
  3385.       if (diff > .005 || diff < -.005) {
  3386.         if (oldHeight < viewTop) { mustScroll -= diff; }
  3387.         updateLineHeight(cur.line, height);
  3388.         updateWidgetHeight(cur.line);
  3389.         if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  3390.           { updateWidgetHeight(cur.rest[j]); } }
  3391.       }
  3392.       if (width > cm.display.sizerWidth) {
  3393.         var chWidth = Math.ceil(width / charWidth(cm.display));
  3394.         if (chWidth > cm.display.maxLineLength) {
  3395.           cm.display.maxLineLength = chWidth;
  3396.           cm.display.maxLine = cur.line;
  3397.           cm.display.maxLineChanged = true;
  3398.         }
  3399.       }
  3400.     }
  3401.     if (Math.abs(mustScroll) > 2) { display.scroller.scrollTop += mustScroll; }
  3402.   }
  3403.  
  3404.   // Read and store the height of line widgets associated with the
  3405.   // given line.
  3406.   function updateWidgetHeight(line) {
  3407.     if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  3408.       var w = line.widgets[i], parent = w.node.parentNode;
  3409.       if (parent) { w.height = parent.offsetHeight; }
  3410.     } }
  3411.   }
  3412.  
  3413.   // Compute the lines that are visible in a given viewport (defaults
  3414.   // the the current scroll position). viewport may contain top,
  3415.   // height, and ensure (see op.scrollToPos) properties.
  3416.   function visibleLines(display, doc, viewport) {
  3417.     var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  3418.     top = Math.floor(top - paddingTop(display));
  3419.     var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  3420.  
  3421.     var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  3422.     // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  3423.     // forces those lines into the viewport (if possible).
  3424.     if (viewport && viewport.ensure) {
  3425.       var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  3426.       if (ensureFrom < from) {
  3427.         from = ensureFrom;
  3428.         to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  3429.       } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  3430.         from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  3431.         to = ensureTo;
  3432.       }
  3433.     }
  3434.     return {from: from, to: Math.max(to, from + 1)}
  3435.   }
  3436.  
  3437.   // SCROLLING THINGS INTO VIEW
  3438.  
  3439.   // If an editor sits on the top or bottom of the window, partially
  3440.   // scrolled out of view, this ensures that the cursor is visible.
  3441.   function maybeScrollWindow(cm, rect) {
  3442.     if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3443.  
  3444.     var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  3445.     if (rect.top + box.top < 0) { doScroll = true; }
  3446.     else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
  3447.     if (doScroll != null && !phantom) {
  3448.       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;"));
  3449.       cm.display.lineSpace.appendChild(scrollNode);
  3450.       scrollNode.scrollIntoView(doScroll);
  3451.       cm.display.lineSpace.removeChild(scrollNode);
  3452.     }
  3453.   }
  3454.  
  3455.   // Scroll a given position into view (immediately), verifying that
  3456.   // it actually became visible (as line heights are accurately
  3457.   // measured, the position of something may 'drift' during drawing).
  3458.   function scrollPosIntoView(cm, pos, end, margin) {
  3459.     if (margin == null) { margin = 0; }
  3460.     var rect;
  3461.     if (!cm.options.lineWrapping && pos == end) {
  3462.       // Set pos and end to the cursor positions around the character pos sticks to
  3463.       // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  3464.       // If pos == Pos(_, 0, "before"), pos and end are unchanged
  3465.       end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  3466.       pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  3467.     }
  3468.     for (var limit = 0; limit < 5; limit++) {
  3469.       var changed = false;
  3470.       var coords = cursorCoords(cm, pos);
  3471.       var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  3472.       rect = {left: Math.min(coords.left, endCoords.left),
  3473.               top: Math.min(coords.top, endCoords.top) - margin,
  3474.               right: Math.max(coords.left, endCoords.left),
  3475.               bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  3476.       var scrollPos = calculateScrollPos(cm, rect);
  3477.       var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  3478.       if (scrollPos.scrollTop != null) {
  3479.         updateScrollTop(cm, scrollPos.scrollTop);
  3480.         if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  3481.       }
  3482.       if (scrollPos.scrollLeft != null) {
  3483.         setScrollLeft(cm, scrollPos.scrollLeft);
  3484.         if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  3485.       }
  3486.       if (!changed) { break }
  3487.     }
  3488.     return rect
  3489.   }
  3490.  
  3491.   // Scroll a given set of coordinates into view (immediately).
  3492.   function scrollIntoView(cm, rect) {
  3493.     var scrollPos = calculateScrollPos(cm, rect);
  3494.     if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  3495.     if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  3496.   }
  3497.  
  3498.   // Calculate a new scroll position needed to scroll the given
  3499.   // rectangle into view. Returns an object with scrollTop and
  3500.   // scrollLeft properties. When these are undefined, the
  3501.   // vertical/horizontal position does not need to be adjusted.
  3502.   function calculateScrollPos(cm, rect) {
  3503.     var display = cm.display, snapMargin = textHeight(cm.display);
  3504.     if (rect.top < 0) { rect.top = 0; }
  3505.     var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  3506.     var screen = displayHeight(cm), result = {};
  3507.     if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  3508.     var docBottom = cm.doc.height + paddingVert(display);
  3509.     var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  3510.     if (rect.top < screentop) {
  3511.       result.scrollTop = atTop ? 0 : rect.top;
  3512.     } else if (rect.bottom > screentop + screen) {
  3513.       var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  3514.       if (newTop != screentop) { result.scrollTop = newTop; }
  3515.     }
  3516.  
  3517.     var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
  3518.     var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
  3519.     var screenw = displayWidth(cm) - display.gutters.offsetWidth;
  3520.     var tooWide = rect.right - rect.left > screenw;
  3521.     if (tooWide) { rect.right = rect.left + screenw; }
  3522.     if (rect.left < 10)
  3523.       { result.scrollLeft = 0; }
  3524.     else if (rect.left < screenleft)
  3525.       { result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); }
  3526.     else if (rect.right > screenw + screenleft - 3)
  3527.       { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  3528.     return result
  3529.   }
  3530.  
  3531.   // Store a relative adjustment to the scroll position in the current
  3532.   // operation (to be applied when the operation finishes).
  3533.   function addToScrollTop(cm, top) {
  3534.     if (top == null) { return }
  3535.     resolveScrollToPos(cm);
  3536.     cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  3537.   }
  3538.  
  3539.   // Make sure that at the end of the operation the current cursor is
  3540.   // shown.
  3541.   function ensureCursorVisible(cm) {
  3542.     resolveScrollToPos(cm);
  3543.     var cur = cm.getCursor();
  3544.     cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  3545.   }
  3546.  
  3547.   function scrollToCoords(cm, x, y) {
  3548.     if (x != null || y != null) { resolveScrollToPos(cm); }
  3549.     if (x != null) { cm.curOp.scrollLeft = x; }
  3550.     if (y != null) { cm.curOp.scrollTop = y; }
  3551.   }
  3552.  
  3553.   function scrollToRange(cm, range) {
  3554.     resolveScrollToPos(cm);
  3555.     cm.curOp.scrollToPos = range;
  3556.   }
  3557.  
  3558.   // When an operation has its scrollToPos property set, and another
  3559.   // scroll action is applied before the end of the operation, this
  3560.   // 'simulates' scrolling that position into view in a cheap way, so
  3561.   // that the effect of intermediate scroll commands is not ignored.
  3562.   function resolveScrollToPos(cm) {
  3563.     var range = cm.curOp.scrollToPos;
  3564.     if (range) {
  3565.       cm.curOp.scrollToPos = null;
  3566.       var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  3567.       scrollToCoordsRange(cm, from, to, range.margin);
  3568.     }
  3569.   }
  3570.  
  3571.   function scrollToCoordsRange(cm, from, to, margin) {
  3572.     var sPos = calculateScrollPos(cm, {
  3573.       left: Math.min(from.left, to.left),
  3574.       top: Math.min(from.top, to.top) - margin,
  3575.       right: Math.max(from.right, to.right),
  3576.       bottom: Math.max(from.bottom, to.bottom) + margin
  3577.     });
  3578.     scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  3579.   }
  3580.  
  3581.   // Sync the scrollable area and scrollbars, ensure the viewport
  3582.   // covers the visible area.
  3583.   function updateScrollTop(cm, val) {
  3584.     if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  3585.     if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  3586.     setScrollTop(cm, val, true);
  3587.     if (gecko) { updateDisplaySimple(cm); }
  3588.     startWorker(cm, 100);
  3589.   }
  3590.  
  3591.   function setScrollTop(cm, val, forceScroll) {
  3592.     val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
  3593.     if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  3594.     cm.doc.scrollTop = val;
  3595.     cm.display.scrollbars.setScrollTop(val);
  3596.     if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  3597.   }
  3598.  
  3599.   // Sync scroller and scrollbar, ensure the gutter elements are
  3600.   // aligned.
  3601.   function setScrollLeft(cm, val, isScroller, forceScroll) {
  3602.     val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
  3603.     if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  3604.     cm.doc.scrollLeft = val;
  3605.     alignHorizontally(cm);
  3606.     if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  3607.     cm.display.scrollbars.setScrollLeft(val);
  3608.   }
  3609.  
  3610.   // SCROLLBARS
  3611.  
  3612.   // Prepare DOM reads needed to update the scrollbars. Done in one
  3613.   // shot to minimize update/measure roundtrips.
  3614.   function measureForScrollbars(cm) {
  3615.     var d = cm.display, gutterW = d.gutters.offsetWidth;
  3616.     var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  3617.     return {
  3618.       clientHeight: d.scroller.clientHeight,
  3619.       viewHeight: d.wrapper.clientHeight,
  3620.       scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3621.       viewWidth: d.wrapper.clientWidth,
  3622.       barLeft: cm.options.fixedGutter ? gutterW : 0,
  3623.       docHeight: docH,
  3624.       scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3625.       nativeBarWidth: d.nativeBarWidth,
  3626.       gutterWidth: gutterW
  3627.     }
  3628.   }
  3629.  
  3630.   var NativeScrollbars = function(place, scroll, cm) {
  3631.     this.cm = cm;
  3632.     var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  3633.     var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  3634.     vert.tabIndex = horiz.tabIndex = -1;
  3635.     place(vert); place(horiz);
  3636.  
  3637.     on(vert, "scroll", function () {
  3638.       if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  3639.     });
  3640.     on(horiz, "scroll", function () {
  3641.       if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  3642.     });
  3643.  
  3644.     this.checkedZeroWidth = false;
  3645.     // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3646.     if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  3647.   };
  3648.  
  3649.   NativeScrollbars.prototype.update = function (measure) {
  3650.     var needsH = measure.scrollWidth > measure.clientWidth + 1;
  3651.     var needsV = measure.scrollHeight > measure.clientHeight + 1;
  3652.     var sWidth = measure.nativeBarWidth;
  3653.  
  3654.     if (needsV) {
  3655.       this.vert.style.display = "block";
  3656.       this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  3657.       var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  3658.       // A bug in IE8 can cause this value to be negative, so guard it.
  3659.       this.vert.firstChild.style.height =
  3660.         Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  3661.     } else {
  3662.       this.vert.scrollTop = 0;
  3663.       this.vert.style.display = "";
  3664.       this.vert.firstChild.style.height = "0";
  3665.     }
  3666.  
  3667.     if (needsH) {
  3668.       this.horiz.style.display = "block";
  3669.       this.horiz.style.right = needsV ? sWidth + "px" : "0";
  3670.       this.horiz.style.left = measure.barLeft + "px";
  3671.       var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  3672.       this.horiz.firstChild.style.width =
  3673.         Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  3674.     } else {
  3675.       this.horiz.style.display = "";
  3676.       this.horiz.firstChild.style.width = "0";
  3677.     }
  3678.  
  3679.     if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3680.       if (sWidth == 0) { this.zeroWidthHack(); }
  3681.       this.checkedZeroWidth = true;
  3682.     }
  3683.  
  3684.     return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3685.   };
  3686.  
  3687.   NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3688.     if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  3689.     if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  3690.   };
  3691.  
  3692.   NativeScrollbars.prototype.setScrollTop = function (pos) {
  3693.     if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  3694.     if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  3695.   };
  3696.  
  3697.   NativeScrollbars.prototype.zeroWidthHack = function () {
  3698.     var w = mac && !mac_geMountainLion ? "12px" : "18px";
  3699.     this.horiz.style.height = this.vert.style.width = w;
  3700.     this.horiz.style.visibility = this.vert.style.visibility = "hidden";
  3701.     this.disableHoriz = new Delayed;
  3702.     this.disableVert = new Delayed;
  3703.   };
  3704.  
  3705.   NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  3706.     bar.style.visibility = "";
  3707.     function maybeDisable() {
  3708.       // To find out whether the scrollbar is still visible, we
  3709.       // check whether the element under the pixel in the bottom
  3710.       // right corner of the scrollbar box is the scrollbar box
  3711.       // itself (when the bar is still visible) or its filler child
  3712.       // (when the bar is hidden). If it is still visible, we keep
  3713.       // it enabled, if it's hidden, we disable pointer events.
  3714.       var box = bar.getBoundingClientRect();
  3715.       var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  3716.           : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  3717.       if (elt != bar) { bar.style.visibility = "hidden"; }
  3718.       else { delay.set(1000, maybeDisable); }
  3719.     }
  3720.     delay.set(1000, maybeDisable);
  3721.   };
  3722.  
  3723.   NativeScrollbars.prototype.clear = function () {
  3724.     var parent = this.horiz.parentNode;
  3725.     parent.removeChild(this.horiz);
  3726.     parent.removeChild(this.vert);
  3727.   };
  3728.  
  3729.   var NullScrollbars = function () {};
  3730.  
  3731.   NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3732.   NullScrollbars.prototype.setScrollLeft = function () {};
  3733.   NullScrollbars.prototype.setScrollTop = function () {};
  3734.   NullScrollbars.prototype.clear = function () {};
  3735.  
  3736.   function updateScrollbars(cm, measure) {
  3737.     if (!measure) { measure = measureForScrollbars(cm); }
  3738.     var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  3739.     updateScrollbarsInner(cm, measure);
  3740.     for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3741.       if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3742.         { updateHeightsInViewport(cm); }
  3743.       updateScrollbarsInner(cm, measureForScrollbars(cm));
  3744.       startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  3745.     }
  3746.   }
  3747.  
  3748.   // Re-synchronize the fake scrollbars with the actual size of the
  3749.   // content.
  3750.   function updateScrollbarsInner(cm, measure) {
  3751.     var d = cm.display;
  3752.     var sizes = d.scrollbars.update(measure);
  3753.  
  3754.     d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  3755.     d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  3756.     d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  3757.  
  3758.     if (sizes.right && sizes.bottom) {
  3759.       d.scrollbarFiller.style.display = "block";
  3760.       d.scrollbarFiller.style.height = sizes.bottom + "px";
  3761.       d.scrollbarFiller.style.width = sizes.right + "px";
  3762.     } else { d.scrollbarFiller.style.display = ""; }
  3763.     if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3764.       d.gutterFiller.style.display = "block";
  3765.       d.gutterFiller.style.height = sizes.bottom + "px";
  3766.       d.gutterFiller.style.width = measure.gutterWidth + "px";
  3767.     } else { d.gutterFiller.style.display = ""; }
  3768.   }
  3769.  
  3770.   var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  3771.  
  3772.   function initScrollbars(cm) {
  3773.     if (cm.display.scrollbars) {
  3774.       cm.display.scrollbars.clear();
  3775.       if (cm.display.scrollbars.addClass)
  3776.         { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3777.     }
  3778.  
  3779.     cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3780.       cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  3781.       // Prevent clicks in the scrollbars from killing focus
  3782.       on(node, "mousedown", function () {
  3783.         if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  3784.       });
  3785.       node.setAttribute("cm-not-content", "true");
  3786.     }, function (pos, axis) {
  3787.       if (axis == "horizontal") { setScrollLeft(cm, pos); }
  3788.       else { updateScrollTop(cm, pos); }
  3789.     }, cm);
  3790.     if (cm.display.scrollbars.addClass)
  3791.       { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3792.   }
  3793.  
  3794.   // Operations are used to wrap a series of changes to the editor
  3795.   // state in such a way that each change won't have to update the
  3796.   // cursor and display (which would be awkward, slow, and
  3797.   // error-prone). Instead, display updates are batched and then all
  3798.   // combined and executed at once.
  3799.  
  3800.   var nextOpId = 0;
  3801.   // Start a new operation.
  3802.   function startOperation(cm) {
  3803.     cm.curOp = {
  3804.       cm: cm,
  3805.       viewChanged: false,      // Flag that indicates that lines might need to be redrawn
  3806.       startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3807.       forceUpdate: false,      // Used to force a redraw
  3808.       updateInput: 0,       // Whether to reset the input textarea
  3809.       typing: false,           // Whether this reset should be careful to leave existing text (for compositing)
  3810.       changeObjs: null,        // Accumulated changes, for firing change events
  3811.       cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3812.       cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3813.       selectionChanged: false, // Whether the selection needs to be redrawn
  3814.       updateMaxLine: false,    // Set when the widest line needs to be determined anew
  3815.       scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3816.       scrollToPos: null,       // Used to scroll to a specific position
  3817.       focus: false,
  3818.       id: ++nextOpId,          // Unique ID
  3819.       markArrays: null         // Used by addMarkedSpan
  3820.     };
  3821.     pushOperation(cm.curOp);
  3822.   }
  3823.  
  3824.   // Finish an operation, updating the display and signalling delayed events
  3825.   function endOperation(cm) {
  3826.     var op = cm.curOp;
  3827.     if (op) { finishOperation(op, function (group) {
  3828.       for (var i = 0; i < group.ops.length; i++)
  3829.         { group.ops[i].cm.curOp = null; }
  3830.       endOperations(group);
  3831.     }); }
  3832.   }
  3833.  
  3834.   // The DOM updates done when an operation finishes are batched so
  3835.   // that the minimum number of relayouts are required.
  3836.   function endOperations(group) {
  3837.     var ops = group.ops;
  3838.     for (var i = 0; i < ops.length; i++) // Read DOM
  3839.       { endOperation_R1(ops[i]); }
  3840.     for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3841.       { endOperation_W1(ops[i$1]); }
  3842.     for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3843.       { endOperation_R2(ops[i$2]); }
  3844.     for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3845.       { endOperation_W2(ops[i$3]); }
  3846.     for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3847.       { endOperation_finish(ops[i$4]); }
  3848.   }
  3849.  
  3850.   function endOperation_R1(op) {
  3851.     var cm = op.cm, display = cm.display;
  3852.     maybeClipScrollbars(cm);
  3853.     if (op.updateMaxLine) { findMaxLine(cm); }
  3854.  
  3855.     op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3856.       op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3857.                          op.scrollToPos.to.line >= display.viewTo) ||
  3858.       display.maxLineChanged && cm.options.lineWrapping;
  3859.     op.update = op.mustUpdate &&
  3860.       new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  3861.   }
  3862.  
  3863.   function endOperation_W1(op) {
  3864.     op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  3865.   }
  3866.  
  3867.   function endOperation_R2(op) {
  3868.     var cm = op.cm, display = cm.display;
  3869.     if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  3870.  
  3871.     op.barMeasure = measureForScrollbars(cm);
  3872.  
  3873.     // If the max line changed since it was last measured, measure it,
  3874.     // and ensure the document's width matches it.
  3875.     // updateDisplay_W2 will use these properties to do the actual resizing
  3876.     if (display.maxLineChanged && !cm.options.lineWrapping) {
  3877.       op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  3878.       cm.display.sizerWidth = op.adjustWidthTo;
  3879.       op.barMeasure.scrollWidth =
  3880.         Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  3881.       op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  3882.     }
  3883.  
  3884.     if (op.updatedDisplay || op.selectionChanged)
  3885.       { op.preparedSelection = display.input.prepareSelection(); }
  3886.   }
  3887.  
  3888.   function endOperation_W2(op) {
  3889.     var cm = op.cm;
  3890.  
  3891.     if (op.adjustWidthTo != null) {
  3892.       cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  3893.       if (op.maxScrollLeft < cm.doc.scrollLeft)
  3894.         { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  3895.       cm.display.maxLineChanged = false;
  3896.     }
  3897.  
  3898.     var takeFocus = op.focus && op.focus == activeElt();
  3899.     if (op.preparedSelection)
  3900.       { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  3901.     if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3902.       { updateScrollbars(cm, op.barMeasure); }
  3903.     if (op.updatedDisplay)
  3904.       { setDocumentHeight(cm, op.barMeasure); }
  3905.  
  3906.     if (op.selectionChanged) { restartBlink(cm); }
  3907.  
  3908.     if (cm.state.focused && op.updateInput)
  3909.       { cm.display.input.reset(op.typing); }
  3910.     if (takeFocus) { ensureFocus(op.cm); }
  3911.   }
  3912.  
  3913.   function endOperation_finish(op) {
  3914.     var cm = op.cm, display = cm.display, doc = cm.doc;
  3915.  
  3916.     if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  3917.  
  3918.     // Abort mouse wheel delta measurement, when scrolling explicitly
  3919.     if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3920.       { display.wheelStartX = display.wheelStartY = null; }
  3921.  
  3922.     // Propagate the scroll position to the actual DOM scroller
  3923.     if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  3924.  
  3925.     if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  3926.     // If we need to scroll a specific position into view, do so.
  3927.     if (op.scrollToPos) {
  3928.       var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3929.                                    clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  3930.       maybeScrollWindow(cm, rect);
  3931.     }
  3932.  
  3933.     // Fire events for markers that are hidden/unidden by editing or
  3934.     // undoing
  3935.     var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  3936.     if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3937.       { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  3938.     if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3939.       { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  3940.  
  3941.     if (display.wrapper.offsetHeight)
  3942.       { doc.scrollTop = cm.display.scroller.scrollTop; }
  3943.  
  3944.     // Fire change events, and delayed event handlers
  3945.     if (op.changeObjs)
  3946.       { signal(cm, "changes", cm, op.changeObjs); }
  3947.     if (op.update)
  3948.       { op.update.finish(); }
  3949.   }
  3950.  
  3951.   // Run the given function in an operation
  3952.   function runInOp(cm, f) {
  3953.     if (cm.curOp) { return f() }
  3954.     startOperation(cm);
  3955.     try { return f() }
  3956.     finally { endOperation(cm); }
  3957.   }
  3958.   // Wraps a function in an operation. Returns the wrapped function.
  3959.   function operation(cm, f) {
  3960.     return function() {
  3961.       if (cm.curOp) { return f.apply(cm, arguments) }
  3962.       startOperation(cm);
  3963.       try { return f.apply(cm, arguments) }
  3964.       finally { endOperation(cm); }
  3965.     }
  3966.   }
  3967.   // Used to add methods to editor and doc instances, wrapping them in
  3968.   // operations.
  3969.   function methodOp(f) {
  3970.     return function() {
  3971.       if (this.curOp) { return f.apply(this, arguments) }
  3972.       startOperation(this);
  3973.       try { return f.apply(this, arguments) }
  3974.       finally { endOperation(this); }
  3975.     }
  3976.   }
  3977.   function docMethodOp(f) {
  3978.     return function() {
  3979.       var cm = this.cm;
  3980.       if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3981.       startOperation(cm);
  3982.       try { return f.apply(this, arguments) }
  3983.       finally { endOperation(cm); }
  3984.     }
  3985.   }
  3986.  
  3987.   // HIGHLIGHT WORKER
  3988.  
  3989.   function startWorker(cm, time) {
  3990.     if (cm.doc.highlightFrontier < cm.display.viewTo)
  3991.       { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  3992.   }
  3993.  
  3994.   function highlightWorker(cm) {
  3995.     var doc = cm.doc;
  3996.     if (doc.highlightFrontier >= cm.display.viewTo) { return }
  3997.     var end = +new Date + cm.options.workTime;
  3998.     var context = getContextBefore(cm, doc.highlightFrontier);
  3999.     var changedLines = [];
  4000.  
  4001.     doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  4002.       if (context.line >= cm.display.viewFrom) { // Visible
  4003.         var oldStyles = line.styles;
  4004.         var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  4005.         var highlighted = highlightLine(cm, line, context, true);
  4006.         if (resetState) { context.state = resetState; }
  4007.         line.styles = highlighted.styles;
  4008.         var oldCls = line.styleClasses, newCls = highlighted.classes;
  4009.         if (newCls) { line.styleClasses = newCls; }
  4010.         else if (oldCls) { line.styleClasses = null; }
  4011.         var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  4012.           oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  4013.         for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  4014.         if (ischange) { changedLines.push(context.line); }
  4015.         line.stateAfter = context.save();
  4016.         context.nextLine();
  4017.       } else {
  4018.         if (line.text.length <= cm.options.maxHighlightLength)
  4019.           { processLine(cm, line.text, context); }
  4020.         line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  4021.         context.nextLine();
  4022.       }
  4023.       if (+new Date > end) {
  4024.         startWorker(cm, cm.options.workDelay);
  4025.         return true
  4026.       }
  4027.     });
  4028.     doc.highlightFrontier = context.line;
  4029.     doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  4030.     if (changedLines.length) { runInOp(cm, function () {
  4031.       for (var i = 0; i < changedLines.length; i++)
  4032.         { regLineChange(cm, changedLines[i], "text"); }
  4033.     }); }
  4034.   }
  4035.  
  4036.   // DISPLAY DRAWING
  4037.  
  4038.   var DisplayUpdate = function(cm, viewport, force) {
  4039.     var display = cm.display;
  4040.  
  4041.     this.viewport = viewport;
  4042.     // Store some values that we'll need later (but don't want to force a relayout for)
  4043.     this.visible = visibleLines(display, cm.doc, viewport);
  4044.     this.editorIsHidden = !display.wrapper.offsetWidth;
  4045.     this.wrapperHeight = display.wrapper.clientHeight;
  4046.     this.wrapperWidth = display.wrapper.clientWidth;
  4047.     this.oldDisplayWidth = displayWidth(cm);
  4048.     this.force = force;
  4049.     this.dims = getDimensions(cm);
  4050.     this.events = [];
  4051.   };
  4052.  
  4053.   DisplayUpdate.prototype.signal = function (emitter, type) {
  4054.     if (hasHandler(emitter, type))
  4055.       { this.events.push(arguments); }
  4056.   };
  4057.   DisplayUpdate.prototype.finish = function () {
  4058.     for (var i = 0; i < this.events.length; i++)
  4059.       { signal.apply(null, this.events[i]); }
  4060.   };
  4061.  
  4062.   function maybeClipScrollbars(cm) {
  4063.     var display = cm.display;
  4064.     if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  4065.       display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  4066.       display.heightForcer.style.height = scrollGap(cm) + "px";
  4067.       display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  4068.       display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  4069.       display.scrollbarsClipped = true;
  4070.     }
  4071.   }
  4072.  
  4073.   function selectionSnapshot(cm) {
  4074.     if (cm.hasFocus()) { return null }
  4075.     var active = activeElt();
  4076.     if (!active || !contains(cm.display.lineDiv, active)) { return null }
  4077.     var result = {activeElt: active};
  4078.     if (window.getSelection) {
  4079.       var sel = window.getSelection();
  4080.       if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  4081.         result.anchorNode = sel.anchorNode;
  4082.         result.anchorOffset = sel.anchorOffset;
  4083.         result.focusNode = sel.focusNode;
  4084.         result.focusOffset = sel.focusOffset;
  4085.       }
  4086.     }
  4087.     return result
  4088.   }
  4089.  
  4090.   function restoreSelection(snapshot) {
  4091.     if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  4092.     snapshot.activeElt.focus();
  4093.     if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
  4094.         snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  4095.       var sel = window.getSelection(), range = document.createRange();
  4096.       range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  4097.       range.collapse(false);
  4098.       sel.removeAllRanges();
  4099.       sel.addRange(range);
  4100.       sel.extend(snapshot.focusNode, snapshot.focusOffset);
  4101.     }
  4102.   }
  4103.  
  4104.   // Does the actual updating of the line display. Bails out
  4105.   // (returning false) when there is nothing to be done and forced is
  4106.   // false.
  4107.   function updateDisplayIfNeeded(cm, update) {
  4108.     var display = cm.display, doc = cm.doc;
  4109.  
  4110.     if (update.editorIsHidden) {
  4111.       resetView(cm);
  4112.       return false
  4113.     }
  4114.  
  4115.     // Bail out if the visible area is already rendered and nothing changed.
  4116.     if (!update.force &&
  4117.         update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  4118.         (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  4119.         display.renderedView == display.view && countDirtyView(cm) == 0)
  4120.       { return false }
  4121.  
  4122.     if (maybeUpdateLineNumberWidth(cm)) {
  4123.       resetView(cm);
  4124.       update.dims = getDimensions(cm);
  4125.     }
  4126.  
  4127.     // Compute a suitable new viewport (from & to)
  4128.     var end = doc.first + doc.size;
  4129.     var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  4130.     var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  4131.     if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  4132.     if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  4133.     if (sawCollapsedSpans) {
  4134.       from = visualLineNo(cm.doc, from);
  4135.       to = visualLineEndNo(cm.doc, to);
  4136.     }
  4137.  
  4138.     var different = from != display.viewFrom || to != display.viewTo ||
  4139.       display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  4140.     adjustView(cm, from, to);
  4141.  
  4142.     display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  4143.     // Position the mover div to align with the current scroll position
  4144.     cm.display.mover.style.top = display.viewOffset + "px";
  4145.  
  4146.     var toUpdate = countDirtyView(cm);
  4147.     if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  4148.         (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  4149.       { return false }
  4150.  
  4151.     // For big changes, we hide the enclosing element during the
  4152.     // update, since that speeds up the operations on most browsers.
  4153.     var selSnapshot = selectionSnapshot(cm);
  4154.     if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  4155.     patchDisplay(cm, display.updateLineNumbers, update.dims);
  4156.     if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  4157.     display.renderedView = display.view;
  4158.     // There might have been a widget with a focused element that got
  4159.     // hidden or updated, if so re-focus it.
  4160.     restoreSelection(selSnapshot);
  4161.  
  4162.     // Prevent selection and cursors from interfering with the scroll
  4163.     // width and height.
  4164.     removeChildren(display.cursorDiv);
  4165.     removeChildren(display.selectionDiv);
  4166.     display.gutters.style.height = display.sizer.style.minHeight = 0;
  4167.  
  4168.     if (different) {
  4169.       display.lastWrapHeight = update.wrapperHeight;
  4170.       display.lastWrapWidth = update.wrapperWidth;
  4171.       startWorker(cm, 400);
  4172.     }
  4173.  
  4174.     display.updateLineNumbers = null;
  4175.  
  4176.     return true
  4177.   }
  4178.  
  4179.   function postUpdateDisplay(cm, update) {
  4180.     var viewport = update.viewport;
  4181.  
  4182.     for (var first = true;; first = false) {
  4183.       if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  4184.         // Clip forced viewport to actual scrollable area.
  4185.         if (viewport && viewport.top != null)
  4186.           { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  4187.         // Updated line heights might result in the drawn area not
  4188.         // actually covering the viewport. Keep looping until it does.
  4189.         update.visible = visibleLines(cm.display, cm.doc, viewport);
  4190.         if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  4191.           { break }
  4192.       } else if (first) {
  4193.         update.visible = visibleLines(cm.display, cm.doc, viewport);
  4194.       }
  4195.       if (!updateDisplayIfNeeded(cm, update)) { break }
  4196.       updateHeightsInViewport(cm);
  4197.       var barMeasure = measureForScrollbars(cm);
  4198.       updateSelection(cm);
  4199.       updateScrollbars(cm, barMeasure);
  4200.       setDocumentHeight(cm, barMeasure);
  4201.       update.force = false;
  4202.     }
  4203.  
  4204.     update.signal(cm, "update", cm);
  4205.     if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  4206.       update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  4207.       cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  4208.     }
  4209.   }
  4210.  
  4211.   function updateDisplaySimple(cm, viewport) {
  4212.     var update = new DisplayUpdate(cm, viewport);
  4213.     if (updateDisplayIfNeeded(cm, update)) {
  4214.       updateHeightsInViewport(cm);
  4215.       postUpdateDisplay(cm, update);
  4216.       var barMeasure = measureForScrollbars(cm);
  4217.       updateSelection(cm);
  4218.       updateScrollbars(cm, barMeasure);
  4219.       setDocumentHeight(cm, barMeasure);
  4220.       update.finish();
  4221.     }
  4222.   }
  4223.  
  4224.   // Sync the actual display DOM structure with display.view, removing
  4225.   // nodes for lines that are no longer in view, and creating the ones
  4226.   // that are not there yet, and updating the ones that are out of
  4227.   // date.
  4228.   function patchDisplay(cm, updateNumbersFrom, dims) {
  4229.     var display = cm.display, lineNumbers = cm.options.lineNumbers;
  4230.     var container = display.lineDiv, cur = container.firstChild;
  4231.  
  4232.     function rm(node) {
  4233.       var next = node.nextSibling;
  4234.       // Works around a throw-scroll bug in OS X Webkit
  4235.       if (webkit && mac && cm.display.currentWheelTarget == node)
  4236.         { node.style.display = "none"; }
  4237.       else
  4238.         { node.parentNode.removeChild(node); }
  4239.       return next
  4240.     }
  4241.  
  4242.     var view = display.view, lineN = display.viewFrom;
  4243.     // Loop over the elements in the view, syncing cur (the DOM nodes
  4244.     // in display.lineDiv) with the view as we go.
  4245.     for (var i = 0; i < view.length; i++) {
  4246.       var lineView = view[i];
  4247.       if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  4248.         var node = buildLineElement(cm, lineView, lineN, dims);
  4249.         container.insertBefore(node, cur);
  4250.       } else { // Already drawn
  4251.         while (cur != lineView.node) { cur = rm(cur); }
  4252.         var updateNumber = lineNumbers && updateNumbersFrom != null &&
  4253.           updateNumbersFrom <= lineN && lineView.lineNumber;
  4254.         if (lineView.changes) {
  4255.           if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  4256.           updateLineForChanges(cm, lineView, lineN, dims);
  4257.         }
  4258.         if (updateNumber) {
  4259.           removeChildren(lineView.lineNumber);
  4260.           lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  4261.         }
  4262.         cur = lineView.node.nextSibling;
  4263.       }
  4264.       lineN += lineView.size;
  4265.     }
  4266.     while (cur) { cur = rm(cur); }
  4267.   }
  4268.  
  4269.   function updateGutterSpace(display) {
  4270.     var width = display.gutters.offsetWidth;
  4271.     display.sizer.style.marginLeft = width + "px";
  4272.     // Send an event to consumers responding to changes in gutter width.
  4273.     signalLater(display, "gutterChanged", display);
  4274.   }
  4275.  
  4276.   function setDocumentHeight(cm, measure) {
  4277.     cm.display.sizer.style.minHeight = measure.docHeight + "px";
  4278.     cm.display.heightForcer.style.top = measure.docHeight + "px";
  4279.     cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  4280.   }
  4281.  
  4282.   // Re-align line numbers and gutter marks to compensate for
  4283.   // horizontal scrolling.
  4284.   function alignHorizontally(cm) {
  4285.     var display = cm.display, view = display.view;
  4286.     if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  4287.     var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  4288.     var gutterW = display.gutters.offsetWidth, left = comp + "px";
  4289.     for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  4290.       if (cm.options.fixedGutter) {
  4291.         if (view[i].gutter)
  4292.           { view[i].gutter.style.left = left; }
  4293.         if (view[i].gutterBackground)
  4294.           { view[i].gutterBackground.style.left = left; }
  4295.       }
  4296.       var align = view[i].alignable;
  4297.       if (align) { for (var j = 0; j < align.length; j++)
  4298.         { align[j].style.left = left; } }
  4299.     } }
  4300.     if (cm.options.fixedGutter)
  4301.       { display.gutters.style.left = (comp + gutterW) + "px"; }
  4302.   }
  4303.  
  4304.   // Used to ensure that the line number gutter is still the right
  4305.   // size for the current document size. Returns true when an update
  4306.   // is needed.
  4307.   function maybeUpdateLineNumberWidth(cm) {
  4308.     if (!cm.options.lineNumbers) { return false }
  4309.     var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  4310.     if (last.length != display.lineNumChars) {
  4311.       var test = display.measure.appendChild(elt("div", [elt("div", last)],
  4312.                                                  "CodeMirror-linenumber CodeMirror-gutter-elt"));
  4313.       var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  4314.       display.lineGutter.style.width = "";
  4315.       display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  4316.       display.lineNumWidth = display.lineNumInnerWidth + padding;
  4317.       display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  4318.       display.lineGutter.style.width = display.lineNumWidth + "px";
  4319.       updateGutterSpace(cm.display);
  4320.       return true
  4321.     }
  4322.     return false
  4323.   }
  4324.  
  4325.   function getGutters(gutters, lineNumbers) {
  4326.     var result = [], sawLineNumbers = false;
  4327.     for (var i = 0; i < gutters.length; i++) {
  4328.       var name = gutters[i], style = null;
  4329.       if (typeof name != "string") { style = name.style; name = name.className; }
  4330.       if (name == "CodeMirror-linenumbers") {
  4331.         if (!lineNumbers) { continue }
  4332.         else { sawLineNumbers = true; }
  4333.       }
  4334.       result.push({className: name, style: style});
  4335.     }
  4336.     if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
  4337.     return result
  4338.   }
  4339.  
  4340.   // Rebuild the gutter elements, ensure the margin to the left of the
  4341.   // code matches their width.
  4342.   function renderGutters(display) {
  4343.     var gutters = display.gutters, specs = display.gutterSpecs;
  4344.     removeChildren(gutters);
  4345.     display.lineGutter = null;
  4346.     for (var i = 0; i < specs.length; ++i) {
  4347.       var ref = specs[i];
  4348.       var className = ref.className;
  4349.       var style = ref.style;
  4350.       var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
  4351.       if (style) { gElt.style.cssText = style; }
  4352.       if (className == "CodeMirror-linenumbers") {
  4353.         display.lineGutter = gElt;
  4354.         gElt.style.width = (display.lineNumWidth || 1) + "px";
  4355.       }
  4356.     }
  4357.     gutters.style.display = specs.length ? "" : "none";
  4358.     updateGutterSpace(display);
  4359.   }
  4360.  
  4361.   function updateGutters(cm) {
  4362.     renderGutters(cm.display);
  4363.     regChange(cm);
  4364.     alignHorizontally(cm);
  4365.   }
  4366.  
  4367.   // The display handles the DOM integration, both for input reading
  4368.   // and content drawing. It holds references to DOM nodes and
  4369.   // display-related state.
  4370.  
  4371.   function Display(place, doc, input, options) {
  4372.     var d = this;
  4373.     this.input = input;
  4374.  
  4375.     // Covers bottom-right square when both scrollbars are present.
  4376.     d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  4377.     d.scrollbarFiller.setAttribute("cm-not-content", "true");
  4378.     // Covers bottom of gutter when coverGutterNextToScrollbar is on
  4379.     // and h scrollbar is present.
  4380.     d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  4381.     d.gutterFiller.setAttribute("cm-not-content", "true");
  4382.     // Will contain the actual code, positioned to cover the viewport.
  4383.     d.lineDiv = eltP("div", null, "CodeMirror-code");
  4384.     // Elements are added to these to represent selection and cursors.
  4385.     d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  4386.     d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  4387.     // A visibility: hidden element used to find the size of things.
  4388.     d.measure = elt("div", null, "CodeMirror-measure");
  4389.     // When lines outside of the viewport are measured, they are drawn in this.
  4390.     d.lineMeasure = elt("div", null, "CodeMirror-measure");
  4391.     // Wraps everything that needs to exist inside the vertically-padded coordinate system
  4392.     d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  4393.                       null, "position: relative; outline: none");
  4394.     var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  4395.     // Moved around its parent to cover visible view.
  4396.     d.mover = elt("div", [lines], null, "position: relative");
  4397.     // Set to the height of the document, allowing scrolling.
  4398.     d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  4399.     d.sizerWidth = null;
  4400.     // Behavior of elts with overflow: auto and padding is
  4401.     // inconsistent across browsers. This is used to ensure the
  4402.     // scrollable area is big enough.
  4403.     d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  4404.     // Will contain the gutters, if any.
  4405.     d.gutters = elt("div", null, "CodeMirror-gutters");
  4406.     d.lineGutter = null;
  4407.     // Actual scrollable element.
  4408.     d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  4409.     d.scroller.setAttribute("tabIndex", "-1");
  4410.     // The element in which the editor lives.
  4411.     d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  4412.  
  4413.     // This attribute is respected by automatic translation systems such as Google Translate,
  4414.     // and may also be respected by tools used by human translators.
  4415.     d.wrapper.setAttribute('translate', 'no');
  4416.  
  4417.     // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  4418.     if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  4419.     if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  4420.  
  4421.     if (place) {
  4422.       if (place.appendChild) { place.appendChild(d.wrapper); }
  4423.       else { place(d.wrapper); }
  4424.     }
  4425.  
  4426.     // Current rendered range (may be bigger than the view window).
  4427.     d.viewFrom = d.viewTo = doc.first;
  4428.     d.reportedViewFrom = d.reportedViewTo = doc.first;
  4429.     // Information about the rendered lines.
  4430.     d.view = [];
  4431.     d.renderedView = null;
  4432.     // Holds info about a single rendered line when it was rendered
  4433.     // for measurement, while not in view.
  4434.     d.externalMeasured = null;
  4435.     // Empty space (in pixels) above the view
  4436.     d.viewOffset = 0;
  4437.     d.lastWrapHeight = d.lastWrapWidth = 0;
  4438.     d.updateLineNumbers = null;
  4439.  
  4440.     d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  4441.     d.scrollbarsClipped = false;
  4442.  
  4443.     // Used to only resize the line number gutter when necessary (when
  4444.     // the amount of lines crosses a boundary that makes its width change)
  4445.     d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  4446.     // Set to true when a non-horizontal-scrolling line widget is
  4447.     // added. As an optimization, line widget aligning is skipped when
  4448.     // this is false.
  4449.     d.alignWidgets = false;
  4450.  
  4451.     d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  4452.  
  4453.     // Tracks the maximum line length so that the horizontal scrollbar
  4454.     // can be kept static when scrolling.
  4455.     d.maxLine = null;
  4456.     d.maxLineLength = 0;
  4457.     d.maxLineChanged = false;
  4458.  
  4459.     // Used for measuring wheel scrolling granularity
  4460.     d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  4461.  
  4462.     // True when shift is held down.
  4463.     d.shift = false;
  4464.  
  4465.     // Used to track whether anything happened since the context menu
  4466.     // was opened.
  4467.     d.selForContextMenu = null;
  4468.  
  4469.     d.activeTouch = null;
  4470.  
  4471.     d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
  4472.     renderGutters(d);
  4473.  
  4474.     input.init(d);
  4475.   }
  4476.  
  4477.   // Since the delta values reported on mouse wheel events are
  4478.   // unstandardized between browsers and even browser versions, and
  4479.   // generally horribly unpredictable, this code starts by measuring
  4480.   // the scroll effect that the first few mouse wheel events have,
  4481.   // and, from that, detects the way it can convert deltas to pixel
  4482.   // offsets afterwards.
  4483.   //
  4484.   // The reason we want to know the amount a wheel event will scroll
  4485.   // is that it gives us a chance to update the display before the
  4486.   // actual scrolling happens, reducing flickering.
  4487.  
  4488.   var wheelSamples = 0, wheelPixelsPerUnit = null;
  4489.   // Fill in a browser-detected starting value on browsers where we
  4490.   // know one. These don't have to be accurate -- the result of them
  4491.   // being wrong would just be a slight flicker on the first wheel
  4492.   // scroll (if it is large enough).
  4493.   if (ie) { wheelPixelsPerUnit = -.53; }
  4494.   else if (gecko) { wheelPixelsPerUnit = 15; }
  4495.   else if (chrome) { wheelPixelsPerUnit = -.7; }
  4496.   else if (safari) { wheelPixelsPerUnit = -1/3; }
  4497.  
  4498.   function wheelEventDelta(e) {
  4499.     var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  4500.     if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  4501.     if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  4502.     else if (dy == null) { dy = e.wheelDelta; }
  4503.     return {x: dx, y: dy}
  4504.   }
  4505.   function wheelEventPixels(e) {
  4506.     var delta = wheelEventDelta(e);
  4507.     delta.x *= wheelPixelsPerUnit;
  4508.     delta.y *= wheelPixelsPerUnit;
  4509.     return delta
  4510.   }
  4511.  
  4512.   function onScrollWheel(cm, e) {
  4513.     // On Chrome 102, viewport updates somehow stop wheel-based
  4514.     // scrolling. Turning off pointer events during the scroll seems
  4515.     // to avoid the issue.
  4516.     if (chrome && chrome_version >= 102) {
  4517.       if (cm.display.chromeScrollHack == null) { cm.display.sizer.style.pointerEvents = "none"; }
  4518.       else { clearTimeout(cm.display.chromeScrollHack); }
  4519.       cm.display.chromeScrollHack = setTimeout(function () {
  4520.         cm.display.chromeScrollHack = null;
  4521.         cm.display.sizer.style.pointerEvents = "";
  4522.       }, 100);
  4523.     }
  4524.     var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  4525.     var pixelsPerUnit = wheelPixelsPerUnit;
  4526.     if (e.deltaMode === 0) {
  4527.       dx = e.deltaX;
  4528.       dy = e.deltaY;
  4529.       pixelsPerUnit = 1;
  4530.     }
  4531.  
  4532.     var display = cm.display, scroll = display.scroller;
  4533.     // Quit if there's nothing to scroll here
  4534.     var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  4535.     var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  4536.     if (!(dx && canScrollX || dy && canScrollY)) { return }
  4537.  
  4538.     // Webkit browsers on OS X abort momentum scrolls when the target
  4539.     // of the scroll event is removed from the scrollable element.
  4540.     // This hack (see related code in patchDisplay) makes sure the
  4541.     // element is kept around.
  4542.     if (dy && mac && webkit) {
  4543.       outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  4544.         for (var i = 0; i < view.length; i++) {
  4545.           if (view[i].node == cur) {
  4546.             cm.display.currentWheelTarget = cur;
  4547.             break outer
  4548.           }
  4549.         }
  4550.       }
  4551.     }
  4552.  
  4553.     // On some browsers, horizontal scrolling will cause redraws to
  4554.     // happen before the gutter has been realigned, causing it to
  4555.     // wriggle around in a most unseemly way. When we have an
  4556.     // estimated pixels/delta value, we just handle horizontal
  4557.     // scrolling entirely here. It'll be slightly off from native, but
  4558.     // better than glitching out.
  4559.     if (dx && !gecko && !presto && pixelsPerUnit != null) {
  4560.       if (dy && canScrollY)
  4561.         { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); }
  4562.       setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit));
  4563.       // Only prevent default scrolling if vertical scrolling is
  4564.       // actually possible. Otherwise, it causes vertical scroll
  4565.       // jitter on OSX trackpads when deltaX is small and deltaY
  4566.       // is large (issue #3579)
  4567.       if (!dy || (dy && canScrollY))
  4568.         { e_preventDefault(e); }
  4569.       display.wheelStartX = null; // Abort measurement, if in progress
  4570.       return
  4571.     }
  4572.  
  4573.     // 'Project' the visible viewport to cover the area that is being
  4574.     // scrolled into view (if we know enough to estimate it).
  4575.     if (dy && pixelsPerUnit != null) {
  4576.       var pixels = dy * pixelsPerUnit;
  4577.       var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  4578.       if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  4579.       else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  4580.       updateDisplaySimple(cm, {top: top, bottom: bot});
  4581.     }
  4582.  
  4583.     if (wheelSamples < 20 && e.deltaMode !== 0) {
  4584.       if (display.wheelStartX == null) {
  4585.         display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  4586.         display.wheelDX = dx; display.wheelDY = dy;
  4587.         setTimeout(function () {
  4588.           if (display.wheelStartX == null) { return }
  4589.           var movedX = scroll.scrollLeft - display.wheelStartX;
  4590.           var movedY = scroll.scrollTop - display.wheelStartY;
  4591.           var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  4592.             (movedX && display.wheelDX && movedX / display.wheelDX);
  4593.           display.wheelStartX = display.wheelStartY = null;
  4594.           if (!sample) { return }
  4595.           wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  4596.           ++wheelSamples;
  4597.         }, 200);
  4598.       } else {
  4599.         display.wheelDX += dx; display.wheelDY += dy;
  4600.       }
  4601.     }
  4602.   }
  4603.  
  4604.   // Selection objects are immutable. A new one is created every time
  4605.   // the selection changes. A selection is one or more non-overlapping
  4606.   // (and non-touching) ranges, sorted, and an integer that indicates
  4607.   // which one is the primary selection (the one that's scrolled into
  4608.   // view, that getCursor returns, etc).
  4609.   var Selection = function(ranges, primIndex) {
  4610.     this.ranges = ranges;
  4611.     this.primIndex = primIndex;
  4612.   };
  4613.  
  4614.   Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  4615.  
  4616.   Selection.prototype.equals = function (other) {
  4617.     if (other == this) { return true }
  4618.     if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  4619.     for (var i = 0; i < this.ranges.length; i++) {
  4620.       var here = this.ranges[i], there = other.ranges[i];
  4621.       if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  4622.     }
  4623.     return true
  4624.   };
  4625.  
  4626.   Selection.prototype.deepCopy = function () {
  4627.     var out = [];
  4628.     for (var i = 0; i < this.ranges.length; i++)
  4629.       { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
  4630.     return new Selection(out, this.primIndex)
  4631.   };
  4632.  
  4633.   Selection.prototype.somethingSelected = function () {
  4634.     for (var i = 0; i < this.ranges.length; i++)
  4635.       { if (!this.ranges[i].empty()) { return true } }
  4636.     return false
  4637.   };
  4638.  
  4639.   Selection.prototype.contains = function (pos, end) {
  4640.     if (!end) { end = pos; }
  4641.     for (var i = 0; i < this.ranges.length; i++) {
  4642.       var range = this.ranges[i];
  4643.       if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  4644.         { return i }
  4645.     }
  4646.     return -1
  4647.   };
  4648.  
  4649.   var Range = function(anchor, head) {
  4650.     this.anchor = anchor; this.head = head;
  4651.   };
  4652.  
  4653.   Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  4654.   Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  4655.   Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  4656.  
  4657.   // Take an unsorted, potentially overlapping set of ranges, and
  4658.   // build a selection out of it. 'Consumes' ranges array (modifying
  4659.   // it).
  4660.   function normalizeSelection(cm, ranges, primIndex) {
  4661.     var mayTouch = cm && cm.options.selectionsMayTouch;
  4662.     var prim = ranges[primIndex];
  4663.     ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  4664.     primIndex = indexOf(ranges, prim);
  4665.     for (var i = 1; i < ranges.length; i++) {
  4666.       var cur = ranges[i], prev = ranges[i - 1];
  4667.       var diff = cmp(prev.to(), cur.from());
  4668.       if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
  4669.         var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  4670.         var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  4671.         if (i <= primIndex) { --primIndex; }
  4672.         ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  4673.       }
  4674.     }
  4675.     return new Selection(ranges, primIndex)
  4676.   }
  4677.  
  4678.   function simpleSelection(anchor, head) {
  4679.     return new Selection([new Range(anchor, head || anchor)], 0)
  4680.   }
  4681.  
  4682.   // Compute the position of the end of a change (its 'to' property
  4683.   // refers to the pre-change end).
  4684.   function changeEnd(change) {
  4685.     if (!change.text) { return change.to }
  4686.     return Pos(change.from.line + change.text.length - 1,
  4687.                lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  4688.   }
  4689.  
  4690.   // Adjust a position to refer to the post-change position of the
  4691.   // same text, or the end of the change if the change covers it.
  4692.   function adjustForChange(pos, change) {
  4693.     if (cmp(pos, change.from) < 0) { return pos }
  4694.     if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  4695.  
  4696.     var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  4697.     if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  4698.     return Pos(line, ch)
  4699.   }
  4700.  
  4701.   function computeSelAfterChange(doc, change) {
  4702.     var out = [];
  4703.     for (var i = 0; i < doc.sel.ranges.length; i++) {
  4704.       var range = doc.sel.ranges[i];
  4705.       out.push(new Range(adjustForChange(range.anchor, change),
  4706.                          adjustForChange(range.head, change)));
  4707.     }
  4708.     return normalizeSelection(doc.cm, out, doc.sel.primIndex)
  4709.   }
  4710.  
  4711.   function offsetPos(pos, old, nw) {
  4712.     if (pos.line == old.line)
  4713.       { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4714.     else
  4715.       { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4716.   }
  4717.  
  4718.   // Used by replaceSelections to allow moving the selection to the
  4719.   // start or around the replaced test. Hint may be "start" or "around".
  4720.   function computeReplacedSel(doc, changes, hint) {
  4721.     var out = [];
  4722.     var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  4723.     for (var i = 0; i < changes.length; i++) {
  4724.       var change = changes[i];
  4725.       var from = offsetPos(change.from, oldPrev, newPrev);
  4726.       var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  4727.       oldPrev = change.to;
  4728.       newPrev = to;
  4729.       if (hint == "around") {
  4730.         var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  4731.         out[i] = new Range(inv ? to : from, inv ? from : to);
  4732.       } else {
  4733.         out[i] = new Range(from, from);
  4734.       }
  4735.     }
  4736.     return new Selection(out, doc.sel.primIndex)
  4737.   }
  4738.  
  4739.   // Used to get the editor into a consistent state again when options change.
  4740.  
  4741.   function loadMode(cm) {
  4742.     cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  4743.     resetModeState(cm);
  4744.   }
  4745.  
  4746.   function resetModeState(cm) {
  4747.     cm.doc.iter(function (line) {
  4748.       if (line.stateAfter) { line.stateAfter = null; }
  4749.       if (line.styles) { line.styles = null; }
  4750.     });
  4751.     cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  4752.     startWorker(cm, 100);
  4753.     cm.state.modeGen++;
  4754.     if (cm.curOp) { regChange(cm); }
  4755.   }
  4756.  
  4757.   // DOCUMENT DATA STRUCTURE
  4758.  
  4759.   // By default, updates that start and end at the beginning of a line
  4760.   // are treated specially, in order to make the association of line
  4761.   // widgets and marker elements with the text behave more intuitive.
  4762.   function isWholeLineUpdate(doc, change) {
  4763.     return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4764.       (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4765.   }
  4766.  
  4767.   // Perform a change on the document data structure.
  4768.   function updateDoc(doc, change, markedSpans, estimateHeight) {
  4769.     function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  4770.     function update(line, text, spans) {
  4771.       updateLine(line, text, spans, estimateHeight);
  4772.       signalLater(line, "change", line, change);
  4773.     }
  4774.     function linesFor(start, end) {
  4775.       var result = [];
  4776.       for (var i = start; i < end; ++i)
  4777.         { result.push(new Line(text[i], spansFor(i), estimateHeight)); }
  4778.       return result
  4779.     }
  4780.  
  4781.     var from = change.from, to = change.to, text = change.text;
  4782.     var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  4783.     var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  4784.  
  4785.     // Adjust the line structure
  4786.     if (change.full) {
  4787.       doc.insert(0, linesFor(0, text.length));
  4788.       doc.remove(text.length, doc.size - text.length);
  4789.     } else if (isWholeLineUpdate(doc, change)) {
  4790.       // This is a whole-line replace. Treated specially to make
  4791.       // sure line objects move the way they are supposed to.
  4792.       var added = linesFor(0, text.length - 1);
  4793.       update(lastLine, lastLine.text, lastSpans);
  4794.       if (nlines) { doc.remove(from.line, nlines); }
  4795.       if (added.length) { doc.insert(from.line, added); }
  4796.     } else if (firstLine == lastLine) {
  4797.       if (text.length == 1) {
  4798.         update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  4799.       } else {
  4800.         var added$1 = linesFor(1, text.length - 1);
  4801.         added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  4802.         update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4803.         doc.insert(from.line + 1, added$1);
  4804.       }
  4805.     } else if (text.length == 1) {
  4806.       update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  4807.       doc.remove(from.line + 1, nlines);
  4808.     } else {
  4809.       update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4810.       update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  4811.       var added$2 = linesFor(1, text.length - 1);
  4812.       if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  4813.       doc.insert(from.line + 1, added$2);
  4814.     }
  4815.  
  4816.     signalLater(doc, "change", doc, change);
  4817.   }
  4818.  
  4819.   // Call f for all linked documents.
  4820.   function linkedDocs(doc, f, sharedHistOnly) {
  4821.     function propagate(doc, skip, sharedHist) {
  4822.       if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4823.         var rel = doc.linked[i];
  4824.         if (rel.doc == skip) { continue }
  4825.         var shared = sharedHist && rel.sharedHist;
  4826.         if (sharedHistOnly && !shared) { continue }
  4827.         f(rel.doc, shared);
  4828.         propagate(rel.doc, doc, shared);
  4829.       } }
  4830.     }
  4831.     propagate(doc, null, true);
  4832.   }
  4833.  
  4834.   // Attach a document to an editor.
  4835.   function attachDoc(cm, doc) {
  4836.     if (doc.cm) { throw new Error("This document is already in use.") }
  4837.     cm.doc = doc;
  4838.     doc.cm = cm;
  4839.     estimateLineHeights(cm);
  4840.     loadMode(cm);
  4841.     setDirectionClass(cm);
  4842.     cm.options.direction = doc.direction;
  4843.     if (!cm.options.lineWrapping) { findMaxLine(cm); }
  4844.     cm.options.mode = doc.modeOption;
  4845.     regChange(cm);
  4846.   }
  4847.  
  4848.   function setDirectionClass(cm) {
  4849.   (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  4850.   }
  4851.  
  4852.   function directionChanged(cm) {
  4853.     runInOp(cm, function () {
  4854.       setDirectionClass(cm);
  4855.       regChange(cm);
  4856.     });
  4857.   }
  4858.  
  4859.   function History(prev) {
  4860.     // Arrays of change events and selections. Doing something adds an
  4861.     // event to done and clears undo. Undoing moves events from done
  4862.     // to undone, redoing moves them in the other direction.
  4863.     this.done = []; this.undone = [];
  4864.     this.undoDepth = prev ? prev.undoDepth : Infinity;
  4865.     // Used to track when changes can be merged into a single undo
  4866.     // event
  4867.     this.lastModTime = this.lastSelTime = 0;
  4868.     this.lastOp = this.lastSelOp = null;
  4869.     this.lastOrigin = this.lastSelOrigin = null;
  4870.     // Used by the isClean() method
  4871.     this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1;
  4872.   }
  4873.  
  4874.   // Create a history change event from an updateDoc-style change
  4875.   // object.
  4876.   function historyChangeFromChange(doc, change) {
  4877.     var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  4878.     attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  4879.     linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  4880.     return histChange
  4881.   }
  4882.  
  4883.   // Pop all selection events off the end of a history array. Stop at
  4884.   // a change event.
  4885.   function clearSelectionEvents(array) {
  4886.     while (array.length) {
  4887.       var last = lst(array);
  4888.       if (last.ranges) { array.pop(); }
  4889.       else { break }
  4890.     }
  4891.   }
  4892.  
  4893.   // Find the top change event in the history. Pop off selection
  4894.   // events that are in the way.
  4895.   function lastChangeEvent(hist, force) {
  4896.     if (force) {
  4897.       clearSelectionEvents(hist.done);
  4898.       return lst(hist.done)
  4899.     } else if (hist.done.length && !lst(hist.done).ranges) {
  4900.       return lst(hist.done)
  4901.     } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4902.       hist.done.pop();
  4903.       return lst(hist.done)
  4904.     }
  4905.   }
  4906.  
  4907.   // Register a change in the history. Merges changes that are within
  4908.   // a single operation, or are close together with an origin that
  4909.   // allows merging (starting with "+") into a single event.
  4910.   function addChangeToHistory(doc, change, selAfter, opId) {
  4911.     var hist = doc.history;
  4912.     hist.undone.length = 0;
  4913.     var time = +new Date, cur;
  4914.     var last;
  4915.  
  4916.     if ((hist.lastOp == opId ||
  4917.          hist.lastOrigin == change.origin && change.origin &&
  4918.          ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
  4919.           change.origin.charAt(0) == "*")) &&
  4920.         (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4921.       // Merge this change into the last event
  4922.       last = lst(cur.changes);
  4923.       if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4924.         // Optimized case for simple insertion -- don't want to add
  4925.         // new changesets for every character typed
  4926.         last.to = changeEnd(change);
  4927.       } else {
  4928.         // Add new sub-event
  4929.         cur.changes.push(historyChangeFromChange(doc, change));
  4930.       }
  4931.     } else {
  4932.       // Can not be merged, start a new event.
  4933.       var before = lst(hist.done);
  4934.       if (!before || !before.ranges)
  4935.         { pushSelectionToHistory(doc.sel, hist.done); }
  4936.       cur = {changes: [historyChangeFromChange(doc, change)],
  4937.              generation: hist.generation};
  4938.       hist.done.push(cur);
  4939.       while (hist.done.length > hist.undoDepth) {
  4940.         hist.done.shift();
  4941.         if (!hist.done[0].ranges) { hist.done.shift(); }
  4942.       }
  4943.     }
  4944.     hist.done.push(selAfter);
  4945.     hist.generation = ++hist.maxGeneration;
  4946.     hist.lastModTime = hist.lastSelTime = time;
  4947.     hist.lastOp = hist.lastSelOp = opId;
  4948.     hist.lastOrigin = hist.lastSelOrigin = change.origin;
  4949.  
  4950.     if (!last) { signal(doc, "historyAdded"); }
  4951.   }
  4952.  
  4953.   function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4954.     var ch = origin.charAt(0);
  4955.     return ch == "*" ||
  4956.       ch == "+" &&
  4957.       prev.ranges.length == sel.ranges.length &&
  4958.       prev.somethingSelected() == sel.somethingSelected() &&
  4959.       new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4960.   }
  4961.  
  4962.   // Called whenever the selection changes, sets the new selection as
  4963.   // the pending selection in the history, and pushes the old pending
  4964.   // selection into the 'done' array when it was significantly
  4965.   // different (in number of selected ranges, emptiness, or time).
  4966.   function addSelectionToHistory(doc, sel, opId, options) {
  4967.     var hist = doc.history, origin = options && options.origin;
  4968.  
  4969.     // A new event is started when the previous origin does not match
  4970.     // the current, or the origins don't allow matching. Origins
  4971.     // starting with * are always merged, those starting with + are
  4972.     // merged when similar and close together in time.
  4973.     if (opId == hist.lastSelOp ||
  4974.         (origin && hist.lastSelOrigin == origin &&
  4975.          (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4976.           selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4977.       { hist.done[hist.done.length - 1] = sel; }
  4978.     else
  4979.       { pushSelectionToHistory(sel, hist.done); }
  4980.  
  4981.     hist.lastSelTime = +new Date;
  4982.     hist.lastSelOrigin = origin;
  4983.     hist.lastSelOp = opId;
  4984.     if (options && options.clearRedo !== false)
  4985.       { clearSelectionEvents(hist.undone); }
  4986.   }
  4987.  
  4988.   function pushSelectionToHistory(sel, dest) {
  4989.     var top = lst(dest);
  4990.     if (!(top && top.ranges && top.equals(sel)))
  4991.       { dest.push(sel); }
  4992.   }
  4993.  
  4994.   // Used to store marked span information in the history.
  4995.   function attachLocalSpans(doc, change, from, to) {
  4996.     var existing = change["spans_" + doc.id], n = 0;
  4997.     doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4998.       if (line.markedSpans)
  4999.         { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  5000.       ++n;
  5001.     });
  5002.   }
  5003.  
  5004.   // When un/re-doing restores text containing marked spans, those
  5005.   // that have been explicitly cleared should not be restored.
  5006.   function removeClearedSpans(spans) {
  5007.     if (!spans) { return null }
  5008.     var out;
  5009.     for (var i = 0; i < spans.length; ++i) {
  5010.       if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  5011.       else if (out) { out.push(spans[i]); }
  5012.     }
  5013.     return !out ? spans : out.length ? out : null
  5014.   }
  5015.  
  5016.   // Retrieve and filter the old marked spans stored in a change event.
  5017.   function getOldSpans(doc, change) {
  5018.     var found = change["spans_" + doc.id];
  5019.     if (!found) { return null }
  5020.     var nw = [];
  5021.     for (var i = 0; i < change.text.length; ++i)
  5022.       { nw.push(removeClearedSpans(found[i])); }
  5023.     return nw
  5024.   }
  5025.  
  5026.   // Used for un/re-doing changes from the history. Combines the
  5027.   // result of computing the existing spans with the set of spans that
  5028.   // existed in the history (so that deleting around a span and then
  5029.   // undoing brings back the span).
  5030.   function mergeOldSpans(doc, change) {
  5031.     var old = getOldSpans(doc, change);
  5032.     var stretched = stretchSpansOverChange(doc, change);
  5033.     if (!old) { return stretched }
  5034.     if (!stretched) { return old }
  5035.  
  5036.     for (var i = 0; i < old.length; ++i) {
  5037.       var oldCur = old[i], stretchCur = stretched[i];
  5038.       if (oldCur && stretchCur) {
  5039.         spans: for (var j = 0; j < stretchCur.length; ++j) {
  5040.           var span = stretchCur[j];
  5041.           for (var k = 0; k < oldCur.length; ++k)
  5042.             { if (oldCur[k].marker == span.marker) { continue spans } }
  5043.           oldCur.push(span);
  5044.         }
  5045.       } else if (stretchCur) {
  5046.         old[i] = stretchCur;
  5047.       }
  5048.     }
  5049.     return old
  5050.   }
  5051.  
  5052.   // Used both to provide a JSON-safe object in .getHistory, and, when
  5053.   // detaching a document, to split the history in two
  5054.   function copyHistoryArray(events, newGroup, instantiateSel) {
  5055.     var copy = [];
  5056.     for (var i = 0; i < events.length; ++i) {
  5057.       var event = events[i];
  5058.       if (event.ranges) {
  5059.         copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  5060.         continue
  5061.       }
  5062.       var changes = event.changes, newChanges = [];
  5063.       copy.push({changes: newChanges});
  5064.       for (var j = 0; j < changes.length; ++j) {
  5065.         var change = changes[j], m = (void 0);
  5066.         newChanges.push({from: change.from, to: change.to, text: change.text});
  5067.         if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  5068.           if (indexOf(newGroup, Number(m[1])) > -1) {
  5069.             lst(newChanges)[prop] = change[prop];
  5070.             delete change[prop];
  5071.           }
  5072.         } } }
  5073.       }
  5074.     }
  5075.     return copy
  5076.   }
  5077.  
  5078.   // The 'scroll' parameter given to many of these indicated whether
  5079.   // the new cursor position should be scrolled into view after
  5080.   // modifying the selection.
  5081.  
  5082.   // If shift is held or the extend flag is set, extends a range to
  5083.   // include a given position (and optionally a second position).
  5084.   // Otherwise, simply returns the range between the given positions.
  5085.   // Used for cursor motion and such.
  5086.   function extendRange(range, head, other, extend) {
  5087.     if (extend) {
  5088.       var anchor = range.anchor;
  5089.       if (other) {
  5090.         var posBefore = cmp(head, anchor) < 0;
  5091.         if (posBefore != (cmp(other, anchor) < 0)) {
  5092.           anchor = head;
  5093.           head = other;
  5094.         } else if (posBefore != (cmp(head, other) < 0)) {
  5095.           head = other;
  5096.         }
  5097.       }
  5098.       return new Range(anchor, head)
  5099.     } else {
  5100.       return new Range(other || head, head)
  5101.     }
  5102.   }
  5103.  
  5104.   // Extend the primary selection range, discard the rest.
  5105.   function extendSelection(doc, head, other, options, extend) {
  5106.     if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  5107.     setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  5108.   }
  5109.  
  5110.   // Extend all selections (pos is an array of selections with length
  5111.   // equal the number of selections)
  5112.   function extendSelections(doc, heads, options) {
  5113.     var out = [];
  5114.     var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  5115.     for (var i = 0; i < doc.sel.ranges.length; i++)
  5116.       { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  5117.     var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
  5118.     setSelection(doc, newSel, options);
  5119.   }
  5120.  
  5121.   // Updates a single range in the selection.
  5122.   function replaceOneSelection(doc, i, range, options) {
  5123.     var ranges = doc.sel.ranges.slice(0);
  5124.     ranges[i] = range;
  5125.     setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
  5126.   }
  5127.  
  5128.   // Reset the selection to a single range.
  5129.   function setSimpleSelection(doc, anchor, head, options) {
  5130.     setSelection(doc, simpleSelection(anchor, head), options);
  5131.   }
  5132.  
  5133.   // Give beforeSelectionChange handlers a change to influence a
  5134.   // selection update.
  5135.   function filterSelectionChange(doc, sel, options) {
  5136.     var obj = {
  5137.       ranges: sel.ranges,
  5138.       update: function(ranges) {
  5139.         this.ranges = [];
  5140.         for (var i = 0; i < ranges.length; i++)
  5141.           { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  5142.                                      clipPos(doc, ranges[i].head)); }
  5143.       },
  5144.       origin: options && options.origin
  5145.     };
  5146.     signal(doc, "beforeSelectionChange", doc, obj);
  5147.     if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  5148.     if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
  5149.     else { return sel }
  5150.   }
  5151.  
  5152.   function setSelectionReplaceHistory(doc, sel, options) {
  5153.     var done = doc.history.done, last = lst(done);
  5154.     if (last && last.ranges) {
  5155.       done[done.length - 1] = sel;
  5156.       setSelectionNoUndo(doc, sel, options);
  5157.     } else {
  5158.       setSelection(doc, sel, options);
  5159.     }
  5160.   }
  5161.  
  5162.   // Set a new selection.
  5163.   function setSelection(doc, sel, options) {
  5164.     setSelectionNoUndo(doc, sel, options);
  5165.     addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  5166.   }
  5167.  
  5168.   function setSelectionNoUndo(doc, sel, options) {
  5169.     if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  5170.       { sel = filterSelectionChange(doc, sel, options); }
  5171.  
  5172.     var bias = options && options.bias ||
  5173.       (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  5174.     setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  5175.  
  5176.     if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor")
  5177.       { ensureCursorVisible(doc.cm); }
  5178.   }
  5179.  
  5180.   function setSelectionInner(doc, sel) {
  5181.     if (sel.equals(doc.sel)) { return }
  5182.  
  5183.     doc.sel = sel;
  5184.  
  5185.     if (doc.cm) {
  5186.       doc.cm.curOp.updateInput = 1;
  5187.       doc.cm.curOp.selectionChanged = true;
  5188.       signalCursorActivity(doc.cm);
  5189.     }
  5190.     signalLater(doc, "cursorActivity", doc);
  5191.   }
  5192.  
  5193.   // Verify that the selection does not partially select any atomic
  5194.   // marked ranges.
  5195.   function reCheckSelection(doc) {
  5196.     setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  5197.   }
  5198.  
  5199.   // Return a selection that does not partially select any atomic
  5200.   // ranges.
  5201.   function skipAtomicInSelection(doc, sel, bias, mayClear) {
  5202.     var out;
  5203.     for (var i = 0; i < sel.ranges.length; i++) {
  5204.       var range = sel.ranges[i];
  5205.       var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  5206.       var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  5207.       var newHead = range.head == range.anchor ? newAnchor : skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  5208.       if (out || newAnchor != range.anchor || newHead != range.head) {
  5209.         if (!out) { out = sel.ranges.slice(0, i); }
  5210.         out[i] = new Range(newAnchor, newHead);
  5211.       }
  5212.     }
  5213.     return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
  5214.   }
  5215.  
  5216.   function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  5217.     var line = getLine(doc, pos.line);
  5218.     if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  5219.       var sp = line.markedSpans[i], m = sp.marker;
  5220.  
  5221.       // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
  5222.       // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
  5223.       // is with selectLeft/Right
  5224.       var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
  5225.       var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
  5226.  
  5227.       if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  5228.           (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  5229.         if (mayClear) {
  5230.           signal(m, "beforeCursorEnter");
  5231.           if (m.explicitlyCleared) {
  5232.             if (!line.markedSpans) { break }
  5233.             else {--i; continue}
  5234.           }
  5235.         }
  5236.         if (!m.atomic) { continue }
  5237.  
  5238.         if (oldPos) {
  5239.           var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  5240.           if (dir < 0 ? preventCursorRight : preventCursorLeft)
  5241.             { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  5242.           if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  5243.             { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  5244.         }
  5245.  
  5246.         var far = m.find(dir < 0 ? -1 : 1);
  5247.         if (dir < 0 ? preventCursorLeft : preventCursorRight)
  5248.           { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  5249.         return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  5250.       }
  5251.     } }
  5252.     return pos
  5253.   }
  5254.  
  5255.   // Ensure a given position is not inside an atomic range.
  5256.   function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  5257.     var dir = bias || 1;
  5258.     var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  5259.         (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  5260.         skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  5261.         (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  5262.     if (!found) {
  5263.       doc.cantEdit = true;
  5264.       return Pos(doc.first, 0)
  5265.     }
  5266.     return found
  5267.   }
  5268.  
  5269.   function movePos(doc, pos, dir, line) {
  5270.     if (dir < 0 && pos.ch == 0) {
  5271.       if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  5272.       else { return null }
  5273.     } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  5274.       if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  5275.       else { return null }
  5276.     } else {
  5277.       return new Pos(pos.line, pos.ch + dir)
  5278.     }
  5279.   }
  5280.  
  5281.   function selectAll(cm) {
  5282.     cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  5283.   }
  5284.  
  5285.   // UPDATING
  5286.  
  5287.   // Allow "beforeChange" event handlers to influence a change
  5288.   function filterChange(doc, change, update) {
  5289.     var obj = {
  5290.       canceled: false,
  5291.       from: change.from,
  5292.       to: change.to,
  5293.       text: change.text,
  5294.       origin: change.origin,
  5295.       cancel: function () { return obj.canceled = true; }
  5296.     };
  5297.     if (update) { obj.update = function (from, to, text, origin) {
  5298.       if (from) { obj.from = clipPos(doc, from); }
  5299.       if (to) { obj.to = clipPos(doc, to); }
  5300.       if (text) { obj.text = text; }
  5301.       if (origin !== undefined) { obj.origin = origin; }
  5302.     }; }
  5303.     signal(doc, "beforeChange", doc, obj);
  5304.     if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  5305.  
  5306.     if (obj.canceled) {
  5307.       if (doc.cm) { doc.cm.curOp.updateInput = 2; }
  5308.       return null
  5309.     }
  5310.     return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  5311.   }
  5312.  
  5313.   // Apply a change to a document, and add it to the document's
  5314.   // history, and propagating it to all linked documents.
  5315.   function makeChange(doc, change, ignoreReadOnly) {
  5316.     if (doc.cm) {
  5317.       if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  5318.       if (doc.cm.state.suppressEdits) { return }
  5319.     }
  5320.  
  5321.     if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  5322.       change = filterChange(doc, change, true);
  5323.       if (!change) { return }
  5324.     }
  5325.  
  5326.     // Possibly split or suppress the update based on the presence
  5327.     // of read-only spans in its range.
  5328.     var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  5329.     if (split) {
  5330.       for (var i = split.length - 1; i >= 0; --i)
  5331.         { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  5332.     } else {
  5333.       makeChangeInner(doc, change);
  5334.     }
  5335.   }
  5336.  
  5337.   function makeChangeInner(doc, change) {
  5338.     if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  5339.     var selAfter = computeSelAfterChange(doc, change);
  5340.     addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  5341.  
  5342.     makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  5343.     var rebased = [];
  5344.  
  5345.     linkedDocs(doc, function (doc, sharedHist) {
  5346.       if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  5347.         rebaseHist(doc.history, change);
  5348.         rebased.push(doc.history);
  5349.       }
  5350.       makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  5351.     });
  5352.   }
  5353.  
  5354.   // Revert a change stored in a document's history.
  5355.   function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  5356.     var suppress = doc.cm && doc.cm.state.suppressEdits;
  5357.     if (suppress && !allowSelectionOnly) { return }
  5358.  
  5359.     var hist = doc.history, event, selAfter = doc.sel;
  5360.     var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  5361.  
  5362.     // Verify that there is a useable event (so that ctrl-z won't
  5363.     // needlessly clear selection events)
  5364.     var i = 0;
  5365.     for (; i < source.length; i++) {
  5366.       event = source[i];
  5367.       if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  5368.         { break }
  5369.     }
  5370.     if (i == source.length) { return }
  5371.     hist.lastOrigin = hist.lastSelOrigin = null;
  5372.  
  5373.     for (;;) {
  5374.       event = source.pop();
  5375.       if (event.ranges) {
  5376.         pushSelectionToHistory(event, dest);
  5377.         if (allowSelectionOnly && !event.equals(doc.sel)) {
  5378.           setSelection(doc, event, {clearRedo: false});
  5379.           return
  5380.         }
  5381.         selAfter = event;
  5382.       } else if (suppress) {
  5383.         source.push(event);
  5384.         return
  5385.       } else { break }
  5386.     }
  5387.  
  5388.     // Build up a reverse change object to add to the opposite history
  5389.     // stack (redo when undoing, and vice versa).
  5390.     var antiChanges = [];
  5391.     pushSelectionToHistory(selAfter, dest);
  5392.     dest.push({changes: antiChanges, generation: hist.generation});
  5393.     hist.generation = event.generation || ++hist.maxGeneration;
  5394.  
  5395.     var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  5396.  
  5397.     var loop = function ( i ) {
  5398.       var change = event.changes[i];
  5399.       change.origin = type;
  5400.       if (filter && !filterChange(doc, change, false)) {
  5401.         source.length = 0;
  5402.         return {}
  5403.       }
  5404.  
  5405.       antiChanges.push(historyChangeFromChange(doc, change));
  5406.  
  5407.       var after = i ? computeSelAfterChange(doc, change) : lst(source);
  5408.       makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  5409.       if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  5410.       var rebased = [];
  5411.  
  5412.       // Propagate to the linked documents
  5413.       linkedDocs(doc, function (doc, sharedHist) {
  5414.         if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  5415.           rebaseHist(doc.history, change);
  5416.           rebased.push(doc.history);
  5417.         }
  5418.         makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  5419.       });
  5420.     };
  5421.  
  5422.     for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  5423.       var returned = loop( i$1 );
  5424.  
  5425.       if ( returned ) return returned.v;
  5426.     }
  5427.   }
  5428.  
  5429.   // Sub-views need their line numbers shifted when text is added
  5430.   // above or below them in the parent document.
  5431.   function shiftDoc(doc, distance) {
  5432.     if (distance == 0) { return }
  5433.     doc.first += distance;
  5434.     doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  5435.       Pos(range.anchor.line + distance, range.anchor.ch),
  5436.       Pos(range.head.line + distance, range.head.ch)
  5437.     ); }), doc.sel.primIndex);
  5438.     if (doc.cm) {
  5439.       regChange(doc.cm, doc.first, doc.first - distance, distance);
  5440.       for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  5441.         { regLineChange(doc.cm, l, "gutter"); }
  5442.     }
  5443.   }
  5444.  
  5445.   // More lower-level change function, handling only a single document
  5446.   // (not linked ones).
  5447.   function makeChangeSingleDoc(doc, change, selAfter, spans) {
  5448.     if (doc.cm && !doc.cm.curOp)
  5449.       { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  5450.  
  5451.     if (change.to.line < doc.first) {
  5452.       shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  5453.       return
  5454.     }
  5455.     if (change.from.line > doc.lastLine()) { return }
  5456.  
  5457.     // Clip the change to the size of this doc
  5458.     if (change.from.line < doc.first) {
  5459.       var shift = change.text.length - 1 - (doc.first - change.from.line);
  5460.       shiftDoc(doc, shift);
  5461.       change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  5462.                 text: [lst(change.text)], origin: change.origin};
  5463.     }
  5464.     var last = doc.lastLine();
  5465.     if (change.to.line > last) {
  5466.       change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  5467.                 text: [change.text[0]], origin: change.origin};
  5468.     }
  5469.  
  5470.     change.removed = getBetween(doc, change.from, change.to);
  5471.  
  5472.     if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  5473.     if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  5474.     else { updateDoc(doc, change, spans); }
  5475.     setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  5476.  
  5477.     if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
  5478.       { doc.cantEdit = false; }
  5479.   }
  5480.  
  5481.   // Handle the interaction of a change to a document with the editor
  5482.   // that this document is part of.
  5483.   function makeChangeSingleDocInEditor(cm, change, spans) {
  5484.     var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  5485.  
  5486.     var recomputeMaxLength = false, checkWidthStart = from.line;
  5487.     if (!cm.options.lineWrapping) {
  5488.       checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  5489.       doc.iter(checkWidthStart, to.line + 1, function (line) {
  5490.         if (line == display.maxLine) {
  5491.           recomputeMaxLength = true;
  5492.           return true
  5493.         }
  5494.       });
  5495.     }
  5496.  
  5497.     if (doc.sel.contains(change.from, change.to) > -1)
  5498.       { signalCursorActivity(cm); }
  5499.  
  5500.     updateDoc(doc, change, spans, estimateHeight(cm));
  5501.  
  5502.     if (!cm.options.lineWrapping) {
  5503.       doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  5504.         var len = lineLength(line);
  5505.         if (len > display.maxLineLength) {
  5506.           display.maxLine = line;
  5507.           display.maxLineLength = len;
  5508.           display.maxLineChanged = true;
  5509.           recomputeMaxLength = false;
  5510.         }
  5511.       });
  5512.       if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  5513.     }
  5514.  
  5515.     retreatFrontier(doc, from.line);
  5516.     startWorker(cm, 400);
  5517.  
  5518.     var lendiff = change.text.length - (to.line - from.line) - 1;
  5519.     // Remember that these lines changed, for updating the display
  5520.     if (change.full)
  5521.       { regChange(cm); }
  5522.     else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  5523.       { regLineChange(cm, from.line, "text"); }
  5524.     else
  5525.       { regChange(cm, from.line, to.line + 1, lendiff); }
  5526.  
  5527.     var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  5528.     if (changeHandler || changesHandler) {
  5529.       var obj = {
  5530.         from: from, to: to,
  5531.         text: change.text,
  5532.         removed: change.removed,
  5533.         origin: change.origin
  5534.       };
  5535.       if (changeHandler) { signalLater(cm, "change", cm, obj); }
  5536.       if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  5537.     }
  5538.     cm.display.selForContextMenu = null;
  5539.   }
  5540.  
  5541.   function replaceRange(doc, code, from, to, origin) {
  5542.     var assign;
  5543.  
  5544.     if (!to) { to = from; }
  5545.     if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
  5546.     if (typeof code == "string") { code = doc.splitLines(code); }
  5547.     makeChange(doc, {from: from, to: to, text: code, origin: origin});
  5548.   }
  5549.  
  5550.   // Rebasing/resetting history to deal with externally-sourced changes
  5551.  
  5552.   function rebaseHistSelSingle(pos, from, to, diff) {
  5553.     if (to < pos.line) {
  5554.       pos.line += diff;
  5555.     } else if (from < pos.line) {
  5556.       pos.line = from;
  5557.       pos.ch = 0;
  5558.     }
  5559.   }
  5560.  
  5561.   // Tries to rebase an array of history events given a change in the
  5562.   // document. If the change touches the same lines as the event, the
  5563.   // event, and everything 'behind' it, is discarded. If the change is
  5564.   // before the event, the event's positions are updated. Uses a
  5565.   // copy-on-write scheme for the positions, to avoid having to
  5566.   // reallocate them all on every rebase, but also avoid problems with
  5567.   // shared position objects being unsafely updated.
  5568.   function rebaseHistArray(array, from, to, diff) {
  5569.     for (var i = 0; i < array.length; ++i) {
  5570.       var sub = array[i], ok = true;
  5571.       if (sub.ranges) {
  5572.         if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  5573.         for (var j = 0; j < sub.ranges.length; j++) {
  5574.           rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  5575.           rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  5576.         }
  5577.         continue
  5578.       }
  5579.       for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  5580.         var cur = sub.changes[j$1];
  5581.         if (to < cur.from.line) {
  5582.           cur.from = Pos(cur.from.line + diff, cur.from.ch);
  5583.           cur.to = Pos(cur.to.line + diff, cur.to.ch);
  5584.         } else if (from <= cur.to.line) {
  5585.           ok = false;
  5586.           break
  5587.         }
  5588.       }
  5589.       if (!ok) {
  5590.         array.splice(0, i + 1);
  5591.         i = 0;
  5592.       }
  5593.     }
  5594.   }
  5595.  
  5596.   function rebaseHist(hist, change) {
  5597.     var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  5598.     rebaseHistArray(hist.done, from, to, diff);
  5599.     rebaseHistArray(hist.undone, from, to, diff);
  5600.   }
  5601.  
  5602.   // Utility for applying a change to a line by handle or number,
  5603.   // returning the number and optionally registering the line as
  5604.   // changed.
  5605.   function changeLine(doc, handle, changeType, op) {
  5606.     var no = handle, line = handle;
  5607.     if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  5608.     else { no = lineNo(handle); }
  5609.     if (no == null) { return null }
  5610.     if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  5611.     return line
  5612.   }
  5613.  
  5614.   // The document is represented as a BTree consisting of leaves, with
  5615.   // chunk of lines in them, and branches, with up to ten leaves or
  5616.   // other branch nodes below them. The top node is always a branch
  5617.   // node, and is the document object itself (meaning it has
  5618.   // additional methods and properties).
  5619.   //
  5620.   // All nodes have parent links. The tree is used both to go from
  5621.   // line numbers to line objects, and to go from objects to numbers.
  5622.   // It also indexes by height, and is used to convert between height
  5623.   // and line object, and to find the total height of the document.
  5624.   //
  5625.   // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  5626.  
  5627.   function LeafChunk(lines) {
  5628.     this.lines = lines;
  5629.     this.parent = null;
  5630.     var height = 0;
  5631.     for (var i = 0; i < lines.length; ++i) {
  5632.       lines[i].parent = this;
  5633.       height += lines[i].height;
  5634.     }
  5635.     this.height = height;
  5636.   }
  5637.  
  5638.   LeafChunk.prototype = {
  5639.     chunkSize: function() { return this.lines.length },
  5640.  
  5641.     // Remove the n lines at offset 'at'.
  5642.     removeInner: function(at, n) {
  5643.       for (var i = at, e = at + n; i < e; ++i) {
  5644.         var line = this.lines[i];
  5645.         this.height -= line.height;
  5646.         cleanUpLine(line);
  5647.         signalLater(line, "delete");
  5648.       }
  5649.       this.lines.splice(at, n);
  5650.     },
  5651.  
  5652.     // Helper used to collapse a small branch into a single leaf.
  5653.     collapse: function(lines) {
  5654.       lines.push.apply(lines, this.lines);
  5655.     },
  5656.  
  5657.     // Insert the given array of lines at offset 'at', count them as
  5658.     // having the given height.
  5659.     insertInner: function(at, lines, height) {
  5660.       this.height += height;
  5661.       this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  5662.       for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
  5663.     },
  5664.  
  5665.     // Used to iterate over a part of the tree.
  5666.     iterN: function(at, n, op) {
  5667.       for (var e = at + n; at < e; ++at)
  5668.         { if (op(this.lines[at])) { return true } }
  5669.     }
  5670.   };
  5671.  
  5672.   function BranchChunk(children) {
  5673.     this.children = children;
  5674.     var size = 0, height = 0;
  5675.     for (var i = 0; i < children.length; ++i) {
  5676.       var ch = children[i];
  5677.       size += ch.chunkSize(); height += ch.height;
  5678.       ch.parent = this;
  5679.     }
  5680.     this.size = size;
  5681.     this.height = height;
  5682.     this.parent = null;
  5683.   }
  5684.  
  5685.   BranchChunk.prototype = {
  5686.     chunkSize: function() { return this.size },
  5687.  
  5688.     removeInner: function(at, n) {
  5689.       this.size -= n;
  5690.       for (var i = 0; i < this.children.length; ++i) {
  5691.         var child = this.children[i], sz = child.chunkSize();
  5692.         if (at < sz) {
  5693.           var rm = Math.min(n, sz - at), oldHeight = child.height;
  5694.           child.removeInner(at, rm);
  5695.           this.height -= oldHeight - child.height;
  5696.           if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  5697.           if ((n -= rm) == 0) { break }
  5698.           at = 0;
  5699.         } else { at -= sz; }
  5700.       }
  5701.       // If the result is smaller than 25 lines, ensure that it is a
  5702.       // single leaf node.
  5703.       if (this.size - n < 25 &&
  5704.           (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  5705.         var lines = [];
  5706.         this.collapse(lines);
  5707.         this.children = [new LeafChunk(lines)];
  5708.         this.children[0].parent = this;
  5709.       }
  5710.     },
  5711.  
  5712.     collapse: function(lines) {
  5713.       for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
  5714.     },
  5715.  
  5716.     insertInner: function(at, lines, height) {
  5717.       this.size += lines.length;
  5718.       this.height += height;
  5719.       for (var i = 0; i < this.children.length; ++i) {
  5720.         var child = this.children[i], sz = child.chunkSize();
  5721.         if (at <= sz) {
  5722.           child.insertInner(at, lines, height);
  5723.           if (child.lines && child.lines.length > 50) {
  5724.             // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  5725.             // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  5726.             var remaining = child.lines.length % 25 + 25;
  5727.             for (var pos = remaining; pos < child.lines.length;) {
  5728.               var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  5729.               child.height -= leaf.height;
  5730.               this.children.splice(++i, 0, leaf);
  5731.               leaf.parent = this;
  5732.             }
  5733.             child.lines = child.lines.slice(0, remaining);
  5734.             this.maybeSpill();
  5735.           }
  5736.           break
  5737.         }
  5738.         at -= sz;
  5739.       }
  5740.     },
  5741.  
  5742.     // When a node has grown, check whether it should be split.
  5743.     maybeSpill: function() {
  5744.       if (this.children.length <= 10) { return }
  5745.       var me = this;
  5746.       do {
  5747.         var spilled = me.children.splice(me.children.length - 5, 5);
  5748.         var sibling = new BranchChunk(spilled);
  5749.         if (!me.parent) { // Become the parent node
  5750.           var copy = new BranchChunk(me.children);
  5751.           copy.parent = me;
  5752.           me.children = [copy, sibling];
  5753.           me = copy;
  5754.        } else {
  5755.           me.size -= sibling.size;
  5756.           me.height -= sibling.height;
  5757.           var myIndex = indexOf(me.parent.children, me);
  5758.           me.parent.children.splice(myIndex + 1, 0, sibling);
  5759.         }
  5760.         sibling.parent = me.parent;
  5761.       } while (me.children.length > 10)
  5762.       me.parent.maybeSpill();
  5763.     },
  5764.  
  5765.     iterN: function(at, n, op) {
  5766.       for (var i = 0; i < this.children.length; ++i) {
  5767.         var child = this.children[i], sz = child.chunkSize();
  5768.         if (at < sz) {
  5769.           var used = Math.min(n, sz - at);
  5770.           if (child.iterN(at, used, op)) { return true }
  5771.           if ((n -= used) == 0) { break }
  5772.           at = 0;
  5773.         } else { at -= sz; }
  5774.       }
  5775.     }
  5776.   };
  5777.  
  5778.   // Line widgets are block elements displayed above or below a line.
  5779.  
  5780.   var LineWidget = function(doc, node, options) {
  5781.     if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  5782.       { this[opt] = options[opt]; } } }
  5783.     this.doc = doc;
  5784.     this.node = node;
  5785.   };
  5786.  
  5787.   LineWidget.prototype.clear = function () {
  5788.     var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  5789.     if (no == null || !ws) { return }
  5790.     for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
  5791.     if (!ws.length) { line.widgets = null; }
  5792.     var height = widgetHeight(this);
  5793.     updateLineHeight(line, Math.max(0, line.height - height));
  5794.     if (cm) {
  5795.       runInOp(cm, function () {
  5796.         adjustScrollWhenAboveVisible(cm, line, -height);
  5797.         regLineChange(cm, no, "widget");
  5798.       });
  5799.       signalLater(cm, "lineWidgetCleared", cm, this, no);
  5800.     }
  5801.   };
  5802.  
  5803.   LineWidget.prototype.changed = function () {
  5804.       var this$1 = this;
  5805.  
  5806.     var oldH = this.height, cm = this.doc.cm, line = this.line;
  5807.     this.height = null;
  5808.     var diff = widgetHeight(this) - oldH;
  5809.     if (!diff) { return }
  5810.     if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
  5811.     if (cm) {
  5812.       runInOp(cm, function () {
  5813.         cm.curOp.forceUpdate = true;
  5814.         adjustScrollWhenAboveVisible(cm, line, diff);
  5815.         signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  5816.       });
  5817.     }
  5818.   };
  5819.   eventMixin(LineWidget);
  5820.  
  5821.   function adjustScrollWhenAboveVisible(cm, line, diff) {
  5822.     if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5823.       { addToScrollTop(cm, diff); }
  5824.   }
  5825.  
  5826.   function addLineWidget(doc, handle, node, options) {
  5827.     var widget = new LineWidget(doc, node, options);
  5828.     var cm = doc.cm;
  5829.     if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  5830.     changeLine(doc, handle, "widget", function (line) {
  5831.       var widgets = line.widgets || (line.widgets = []);
  5832.       if (widget.insertAt == null) { widgets.push(widget); }
  5833.       else { widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); }
  5834.       widget.line = line;
  5835.       if (cm && !lineIsHidden(doc, line)) {
  5836.         var aboveVisible = heightAtLine(line) < doc.scrollTop;
  5837.         updateLineHeight(line, line.height + widgetHeight(widget));
  5838.         if (aboveVisible) { addToScrollTop(cm, widget.height); }
  5839.         cm.curOp.forceUpdate = true;
  5840.       }
  5841.       return true
  5842.     });
  5843.     if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
  5844.     return widget
  5845.   }
  5846.  
  5847.   // TEXTMARKERS
  5848.  
  5849.   // Created with markText and setBookmark methods. A TextMarker is a
  5850.   // handle that can be used to clear or find a marked position in the
  5851.   // document. Line objects hold arrays (markedSpans) containing
  5852.   // {from, to, marker} object pointing to such marker objects, and
  5853.   // indicating that such a marker is present on that line. Multiple
  5854.   // lines may point to the same marker when it spans across lines.
  5855.   // The spans will have null for their from/to properties when the
  5856.   // marker continues beyond the start/end of the line. Markers have
  5857.   // links back to the lines they currently touch.
  5858.  
  5859.   // Collapsed markers have unique ids, in order to be able to order
  5860.   // them, which is needed for uniquely determining an outer marker
  5861.   // when they overlap (they may nest, but not partially overlap).
  5862.   var nextMarkerId = 0;
  5863.  
  5864.   var TextMarker = function(doc, type) {
  5865.     this.lines = [];
  5866.     this.type = type;
  5867.     this.doc = doc;
  5868.     this.id = ++nextMarkerId;
  5869.   };
  5870.  
  5871.   // Clear the marker.
  5872.   TextMarker.prototype.clear = function () {
  5873.     if (this.explicitlyCleared) { return }
  5874.     var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5875.     if (withOp) { startOperation(cm); }
  5876.     if (hasHandler(this, "clear")) {
  5877.       var found = this.find();
  5878.       if (found) { signalLater(this, "clear", found.from, found.to); }
  5879.     }
  5880.     var min = null, max = null;
  5881.     for (var i = 0; i < this.lines.length; ++i) {
  5882.       var line = this.lines[i];
  5883.       var span = getMarkedSpanFor(line.markedSpans, this);
  5884.       if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  5885.       else if (cm) {
  5886.         if (span.to != null) { max = lineNo(line); }
  5887.         if (span.from != null) { min = lineNo(line); }
  5888.       }
  5889.       line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5890.       if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  5891.         { updateLineHeight(line, textHeight(cm.display)); }
  5892.     }
  5893.     if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5894.       var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
  5895.       if (len > cm.display.maxLineLength) {
  5896.         cm.display.maxLine = visual;
  5897.         cm.display.maxLineLength = len;
  5898.         cm.display.maxLineChanged = true;
  5899.       }
  5900.     } }
  5901.  
  5902.     if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  5903.     this.lines.length = 0;
  5904.     this.explicitlyCleared = true;
  5905.     if (this.atomic && this.doc.cantEdit) {
  5906.       this.doc.cantEdit = false;
  5907.       if (cm) { reCheckSelection(cm.doc); }
  5908.     }
  5909.     if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  5910.     if (withOp) { endOperation(cm); }
  5911.     if (this.parent) { this.parent.clear(); }
  5912.   };
  5913.  
  5914.   // Find the position of the marker in the document. Returns a {from,
  5915.   // to} object by default. Side can be passed to get a specific side
  5916.   // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5917.   // Pos objects returned contain a line object, rather than a line
  5918.   // number (used to prevent looking up the same line twice).
  5919.   TextMarker.prototype.find = function (side, lineObj) {
  5920.     if (side == null && this.type == "bookmark") { side = 1; }
  5921.     var from, to;
  5922.     for (var i = 0; i < this.lines.length; ++i) {
  5923.       var line = this.lines[i];
  5924.       var span = getMarkedSpanFor(line.markedSpans, this);
  5925.       if (span.from != null) {
  5926.         from = Pos(lineObj ? line : lineNo(line), span.from);
  5927.         if (side == -1) { return from }
  5928.       }
  5929.       if (span.to != null) {
  5930.         to = Pos(lineObj ? line : lineNo(line), span.to);
  5931.         if (side == 1) { return to }
  5932.       }
  5933.     }
  5934.     return from && {from: from, to: to}
  5935.   };
  5936.  
  5937.   // Signals that the marker's widget changed, and surrounding layout
  5938.   // should be recomputed.
  5939.   TextMarker.prototype.changed = function () {
  5940.       var this$1 = this;
  5941.  
  5942.     var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5943.     if (!pos || !cm) { return }
  5944.     runInOp(cm, function () {
  5945.       var line = pos.line, lineN = lineNo(pos.line);
  5946.       var view = findViewForLine(cm, lineN);
  5947.       if (view) {
  5948.         clearLineMeasurementCacheFor(view);
  5949.         cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5950.       }
  5951.       cm.curOp.updateMaxLine = true;
  5952.       if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5953.         var oldHeight = widget.height;
  5954.         widget.height = null;
  5955.         var dHeight = widgetHeight(widget) - oldHeight;
  5956.         if (dHeight)
  5957.           { updateLineHeight(line, line.height + dHeight); }
  5958.       }
  5959.       signalLater(cm, "markerChanged", cm, this$1);
  5960.     });
  5961.   };
  5962.  
  5963.   TextMarker.prototype.attachLine = function (line) {
  5964.     if (!this.lines.length && this.doc.cm) {
  5965.       var op = this.doc.cm.curOp;
  5966.       if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5967.         { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  5968.     }
  5969.     this.lines.push(line);
  5970.   };
  5971.  
  5972.   TextMarker.prototype.detachLine = function (line) {
  5973.     this.lines.splice(indexOf(this.lines, line), 1);
  5974.     if (!this.lines.length && this.doc.cm) {
  5975.       var op = this.doc.cm.curOp
  5976.       ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5977.     }
  5978.   };
  5979.   eventMixin(TextMarker);
  5980.  
  5981.   // Create a marker, wire it up to the right lines, and
  5982.   function markText(doc, from, to, options, type) {
  5983.     // Shared markers (across linked documents) are handled separately
  5984.     // (markTextShared will call out to this again, once per
  5985.     // document).
  5986.     if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5987.     // Ensure we are in an operation.
  5988.     if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5989.  
  5990.     var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5991.     if (options) { copyObj(options, marker, false); }
  5992.     // Don't connect empty markers unless clearWhenEmpty is false
  5993.     if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5994.       { return marker }
  5995.     if (marker.replacedWith) {
  5996.       // Showing up as a widget implies collapsed (widget replaces text)
  5997.       marker.collapsed = true;
  5998.       marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  5999.       if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  6000.       if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  6001.     }
  6002.     if (marker.collapsed) {
  6003.       if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  6004.           from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  6005.         { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  6006.       seeCollapsedSpans();
  6007.     }
  6008.  
  6009.     if (marker.addToHistory)
  6010.       { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  6011.  
  6012.     var curLine = from.line, cm = doc.cm, updateMaxLine;
  6013.     doc.iter(curLine, to.line + 1, function (line) {
  6014.       if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  6015.         { updateMaxLine = true; }
  6016.       if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  6017.       addMarkedSpan(line, new MarkedSpan(marker,
  6018.                                          curLine == from.line ? from.ch : null,
  6019.                                          curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp);
  6020.       ++curLine;
  6021.     });
  6022.     // lineIsHidden depends on the presence of the spans, so needs a second pass
  6023.     if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  6024.       if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  6025.     }); }
  6026.  
  6027.     if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  6028.  
  6029.     if (marker.readOnly) {
  6030.       seeReadOnlySpans();
  6031.       if (doc.history.done.length || doc.history.undone.length)
  6032.         { doc.clearHistory(); }
  6033.     }
  6034.     if (marker.collapsed) {
  6035.       marker.id = ++nextMarkerId;
  6036.       marker.atomic = true;
  6037.     }
  6038.     if (cm) {
  6039.       // Sync editor state
  6040.       if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  6041.       if (marker.collapsed)
  6042.         { regChange(cm, from.line, to.line + 1); }
  6043.       else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
  6044.                marker.attributes || marker.title)
  6045.         { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  6046.       if (marker.atomic) { reCheckSelection(cm.doc); }
  6047.       signalLater(cm, "markerAdded", cm, marker);
  6048.     }
  6049.     return marker
  6050.   }
  6051.  
  6052.   // SHARED TEXTMARKERS
  6053.  
  6054.   // A shared marker spans multiple linked documents. It is
  6055.   // implemented as a meta-marker-object controlling multiple normal
  6056.   // markers.
  6057.   var SharedTextMarker = function(markers, primary) {
  6058.     this.markers = markers;
  6059.     this.primary = primary;
  6060.     for (var i = 0; i < markers.length; ++i)
  6061.       { markers[i].parent = this; }
  6062.   };
  6063.  
  6064.   SharedTextMarker.prototype.clear = function () {
  6065.     if (this.explicitlyCleared) { return }
  6066.     this.explicitlyCleared = true;
  6067.     for (var i = 0; i < this.markers.length; ++i)
  6068.       { this.markers[i].clear(); }
  6069.     signalLater(this, "clear");
  6070.   };
  6071.  
  6072.   SharedTextMarker.prototype.find = function (side, lineObj) {
  6073.     return this.primary.find(side, lineObj)
  6074.   };
  6075.   eventMixin(SharedTextMarker);
  6076.  
  6077.   function markTextShared(doc, from, to, options, type) {
  6078.     options = copyObj(options);
  6079.     options.shared = false;
  6080.     var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  6081.     var widget = options.widgetNode;
  6082.     linkedDocs(doc, function (doc) {
  6083.       if (widget) { options.widgetNode = widget.cloneNode(true); }
  6084.       markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  6085.       for (var i = 0; i < doc.linked.length; ++i)
  6086.         { if (doc.linked[i].isParent) { return } }
  6087.       primary = lst(markers);
  6088.     });
  6089.     return new SharedTextMarker(markers, primary)
  6090.   }
  6091.  
  6092.   function findSharedMarkers(doc) {
  6093.     return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  6094.   }
  6095.  
  6096.   function copySharedMarkers(doc, markers) {
  6097.     for (var i = 0; i < markers.length; i++) {
  6098.       var marker = markers[i], pos = marker.find();
  6099.       var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  6100.       if (cmp(mFrom, mTo)) {
  6101.         var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  6102.         marker.markers.push(subMark);
  6103.         subMark.parent = marker;
  6104.       }
  6105.     }
  6106.   }
  6107.  
  6108.   function detachSharedMarkers(markers) {
  6109.     var loop = function ( i ) {
  6110.       var marker = markers[i], linked = [marker.primary.doc];
  6111.       linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  6112.       for (var j = 0; j < marker.markers.length; j++) {
  6113.         var subMarker = marker.markers[j];
  6114.         if (indexOf(linked, subMarker.doc) == -1) {
  6115.           subMarker.parent = null;
  6116.           marker.markers.splice(j--, 1);
  6117.         }
  6118.       }
  6119.     };
  6120.  
  6121.     for (var i = 0; i < markers.length; i++) loop( i );
  6122.   }
  6123.  
  6124.   var nextDocId = 0;
  6125.   var Doc = function(text, mode, firstLine, lineSep, direction) {
  6126.     if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  6127.     if (firstLine == null) { firstLine = 0; }
  6128.  
  6129.     BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  6130.     this.first = firstLine;
  6131.     this.scrollTop = this.scrollLeft = 0;
  6132.     this.cantEdit = false;
  6133.     this.cleanGeneration = 1;
  6134.     this.modeFrontier = this.highlightFrontier = firstLine;
  6135.     var start = Pos(firstLine, 0);
  6136.     this.sel = simpleSelection(start);
  6137.     this.history = new History(null);
  6138.     this.id = ++nextDocId;
  6139.     this.modeOption = mode;
  6140.     this.lineSep = lineSep;
  6141.     this.direction = (direction == "rtl") ? "rtl" : "ltr";
  6142.     this.extend = false;
  6143.  
  6144.     if (typeof text == "string") { text = this.splitLines(text); }
  6145.     updateDoc(this, {from: start, to: start, text: text});
  6146.     setSelection(this, simpleSelection(start), sel_dontScroll);
  6147.   };
  6148.  
  6149.   Doc.prototype = createObj(BranchChunk.prototype, {
  6150.     constructor: Doc,
  6151.     // Iterate over the document. Supports two forms -- with only one
  6152.     // argument, it calls that for each line in the document. With
  6153.     // three, it iterates over the range given by the first two (with
  6154.     // the second being non-inclusive).
  6155.     iter: function(from, to, op) {
  6156.       if (op) { this.iterN(from - this.first, to - from, op); }
  6157.       else { this.iterN(this.first, this.first + this.size, from); }
  6158.     },
  6159.  
  6160.     // Non-public interface for adding and removing lines.
  6161.     insert: function(at, lines) {
  6162.       var height = 0;
  6163.       for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  6164.       this.insertInner(at - this.first, lines, height);
  6165.     },
  6166.     remove: function(at, n) { this.removeInner(at - this.first, n); },
  6167.  
  6168.     // From here, the methods are part of the public interface. Most
  6169.     // are also available from CodeMirror (editor) instances.
  6170.  
  6171.     getValue: function(lineSep) {
  6172.       var lines = getLines(this, this.first, this.first + this.size);
  6173.       if (lineSep === false) { return lines }
  6174.       return lines.join(lineSep || this.lineSeparator())
  6175.     },
  6176.     setValue: docMethodOp(function(code) {
  6177.       var top = Pos(this.first, 0), last = this.first + this.size - 1;
  6178.       makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  6179.                         text: this.splitLines(code), origin: "setValue", full: true}, true);
  6180.       if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  6181.       setSelection(this, simpleSelection(top), sel_dontScroll);
  6182.     }),
  6183.     replaceRange: function(code, from, to, origin) {
  6184.       from = clipPos(this, from);
  6185.       to = to ? clipPos(this, to) : from;
  6186.       replaceRange(this, code, from, to, origin);
  6187.     },
  6188.     getRange: function(from, to, lineSep) {
  6189.       var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  6190.       if (lineSep === false) { return lines }
  6191.       if (lineSep === '') { return lines.join('') }
  6192.       return lines.join(lineSep || this.lineSeparator())
  6193.     },
  6194.  
  6195.     getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  6196.  
  6197.     getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  6198.     getLineNumber: function(line) {return lineNo(line)},
  6199.  
  6200.     getLineHandleVisualStart: function(line) {
  6201.       if (typeof line == "number") { line = getLine(this, line); }
  6202.       return visualLine(line)
  6203.     },
  6204.  
  6205.     lineCount: function() {return this.size},
  6206.     firstLine: function() {return this.first},
  6207.     lastLine: function() {return this.first + this.size - 1},
  6208.  
  6209.     clipPos: function(pos) {return clipPos(this, pos)},
  6210.  
  6211.     getCursor: function(start) {
  6212.       var range = this.sel.primary(), pos;
  6213.       if (start == null || start == "head") { pos = range.head; }
  6214.       else if (start == "anchor") { pos = range.anchor; }
  6215.       else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
  6216.       else { pos = range.from(); }
  6217.       return pos
  6218.     },
  6219.     listSelections: function() { return this.sel.ranges },
  6220.     somethingSelected: function() {return this.sel.somethingSelected()},
  6221.  
  6222.     setCursor: docMethodOp(function(line, ch, options) {
  6223.       setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  6224.     }),
  6225.     setSelection: docMethodOp(function(anchor, head, options) {
  6226.       setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  6227.     }),
  6228.     extendSelection: docMethodOp(function(head, other, options) {
  6229.       extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  6230.     }),
  6231.     extendSelections: docMethodOp(function(heads, options) {
  6232.       extendSelections(this, clipPosArray(this, heads), options);
  6233.     }),
  6234.     extendSelectionsBy: docMethodOp(function(f, options) {
  6235.       var heads = map(this.sel.ranges, f);
  6236.       extendSelections(this, clipPosArray(this, heads), options);
  6237.     }),
  6238.     setSelections: docMethodOp(function(ranges, primary, options) {
  6239.       if (!ranges.length) { return }
  6240.       var out = [];
  6241.       for (var i = 0; i < ranges.length; i++)
  6242.         { out[i] = new Range(clipPos(this, ranges[i].anchor),
  6243.                            clipPos(this, ranges[i].head || ranges[i].anchor)); }
  6244.       if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  6245.       setSelection(this, normalizeSelection(this.cm, out, primary), options);
  6246.     }),
  6247.     addSelection: docMethodOp(function(anchor, head, options) {
  6248.       var ranges = this.sel.ranges.slice(0);
  6249.       ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  6250.       setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
  6251.     }),
  6252.  
  6253.     getSelection: function(lineSep) {
  6254.       var ranges = this.sel.ranges, lines;
  6255.       for (var i = 0; i < ranges.length; i++) {
  6256.         var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6257.         lines = lines ? lines.concat(sel) : sel;
  6258.       }
  6259.       if (lineSep === false) { return lines }
  6260.       else { return lines.join(lineSep || this.lineSeparator()) }
  6261.     },
  6262.     getSelections: function(lineSep) {
  6263.       var parts = [], ranges = this.sel.ranges;
  6264.       for (var i = 0; i < ranges.length; i++) {
  6265.         var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6266.         if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
  6267.         parts[i] = sel;
  6268.       }
  6269.       return parts
  6270.     },
  6271.     replaceSelection: function(code, collapse, origin) {
  6272.       var dup = [];
  6273.       for (var i = 0; i < this.sel.ranges.length; i++)
  6274.         { dup[i] = code; }
  6275.       this.replaceSelections(dup, collapse, origin || "+input");
  6276.     },
  6277.     replaceSelections: docMethodOp(function(code, collapse, origin) {
  6278.       var changes = [], sel = this.sel;
  6279.       for (var i = 0; i < sel.ranges.length; i++) {
  6280.         var range = sel.ranges[i];
  6281.         changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  6282.       }
  6283.       var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  6284.       for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  6285.         { makeChange(this, changes[i$1]); }
  6286.       if (newSel) { setSelectionReplaceHistory(this, newSel); }
  6287.       else if (this.cm) { ensureCursorVisible(this.cm); }
  6288.     }),
  6289.     undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  6290.     redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  6291.     undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  6292.     redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  6293.  
  6294.     setExtending: function(val) {this.extend = val;},
  6295.     getExtending: function() {return this.extend},
  6296.  
  6297.     historySize: function() {
  6298.       var hist = this.history, done = 0, undone = 0;
  6299.       for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  6300.       for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  6301.       return {undo: done, redo: undone}
  6302.     },
  6303.     clearHistory: function() {
  6304.       var this$1 = this;
  6305.  
  6306.       this.history = new History(this.history);
  6307.       linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
  6308.     },
  6309.  
  6310.     markClean: function() {
  6311.       this.cleanGeneration = this.changeGeneration(true);
  6312.     },
  6313.     changeGeneration: function(forceSplit) {
  6314.       if (forceSplit)
  6315.         { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  6316.       return this.history.generation
  6317.     },
  6318.     isClean: function (gen) {
  6319.       return this.history.generation == (gen || this.cleanGeneration)
  6320.     },
  6321.  
  6322.     getHistory: function() {
  6323.       return {done: copyHistoryArray(this.history.done),
  6324.               undone: copyHistoryArray(this.history.undone)}
  6325.     },
  6326.     setHistory: function(histData) {
  6327.       var hist = this.history = new History(this.history);
  6328.       hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  6329.       hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  6330.     },
  6331.  
  6332.     setGutterMarker: docMethodOp(function(line, gutterID, value) {
  6333.       return changeLine(this, line, "gutter", function (line) {
  6334.         var markers = line.gutterMarkers || (line.gutterMarkers = {});
  6335.         markers[gutterID] = value;
  6336.         if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  6337.         return true
  6338.       })
  6339.     }),
  6340.  
  6341.     clearGutter: docMethodOp(function(gutterID) {
  6342.       var this$1 = this;
  6343.  
  6344.       this.iter(function (line) {
  6345.         if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  6346.           changeLine(this$1, line, "gutter", function () {
  6347.             line.gutterMarkers[gutterID] = null;
  6348.             if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  6349.             return true
  6350.           });
  6351.         }
  6352.       });
  6353.     }),
  6354.  
  6355.     lineInfo: function(line) {
  6356.       var n;
  6357.       if (typeof line == "number") {
  6358.         if (!isLine(this, line)) { return null }
  6359.         n = line;
  6360.         line = getLine(this, line);
  6361.         if (!line) { return null }
  6362.       } else {
  6363.         n = lineNo(line);
  6364.         if (n == null) { return null }
  6365.       }
  6366.       return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  6367.               textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  6368.               widgets: line.widgets}
  6369.     },
  6370.  
  6371.     addLineClass: docMethodOp(function(handle, where, cls) {
  6372.       return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  6373.         var prop = where == "text" ? "textClass"
  6374.                  : where == "background" ? "bgClass"
  6375.                  : where == "gutter" ? "gutterClass" : "wrapClass";
  6376.         if (!line[prop]) { line[prop] = cls; }
  6377.         else if (classTest(cls).test(line[prop])) { return false }
  6378.         else { line[prop] += " " + cls; }
  6379.         return true
  6380.       })
  6381.     }),
  6382.     removeLineClass: docMethodOp(function(handle, where, cls) {
  6383.       return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  6384.         var prop = where == "text" ? "textClass"
  6385.                  : where == "background" ? "bgClass"
  6386.                  : where == "gutter" ? "gutterClass" : "wrapClass";
  6387.         var cur = line[prop];
  6388.         if (!cur) { return false }
  6389.         else if (cls == null) { line[prop] = null; }
  6390.         else {
  6391.           var found = cur.match(classTest(cls));
  6392.           if (!found) { return false }
  6393.           var end = found.index + found[0].length;
  6394.           line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  6395.         }
  6396.         return true
  6397.       })
  6398.     }),
  6399.  
  6400.     addLineWidget: docMethodOp(function(handle, node, options) {
  6401.       return addLineWidget(this, handle, node, options)
  6402.     }),
  6403.     removeLineWidget: function(widget) { widget.clear(); },
  6404.  
  6405.     markText: function(from, to, options) {
  6406.       return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  6407.     },
  6408.     setBookmark: function(pos, options) {
  6409.       var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  6410.                       insertLeft: options && options.insertLeft,
  6411.                       clearWhenEmpty: false, shared: options && options.shared,
  6412.                       handleMouseEvents: options && options.handleMouseEvents};
  6413.       pos = clipPos(this, pos);
  6414.       return markText(this, pos, pos, realOpts, "bookmark")
  6415.     },
  6416.     findMarksAt: function(pos) {
  6417.       pos = clipPos(this, pos);
  6418.       var markers = [], spans = getLine(this, pos.line).markedSpans;
  6419.       if (spans) { for (var i = 0; i < spans.length; ++i) {
  6420.         var span = spans[i];
  6421.         if ((span.from == null || span.from <= pos.ch) &&
  6422.             (span.to == null || span.to >= pos.ch))
  6423.           { markers.push(span.marker.parent || span.marker); }
  6424.       } }
  6425.       return markers
  6426.     },
  6427.     findMarks: function(from, to, filter) {
  6428.       from = clipPos(this, from); to = clipPos(this, to);
  6429.       var found = [], lineNo = from.line;
  6430.       this.iter(from.line, to.line + 1, function (line) {
  6431.         var spans = line.markedSpans;
  6432.         if (spans) { for (var i = 0; i < spans.length; i++) {
  6433.           var span = spans[i];
  6434.           if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  6435.                 span.from == null && lineNo != from.line ||
  6436.                 span.from != null && lineNo == to.line && span.from >= to.ch) &&
  6437.               (!filter || filter(span.marker)))
  6438.             { found.push(span.marker.parent || span.marker); }
  6439.         } }
  6440.         ++lineNo;
  6441.       });
  6442.       return found
  6443.     },
  6444.     getAllMarks: function() {
  6445.       var markers = [];
  6446.       this.iter(function (line) {
  6447.         var sps = line.markedSpans;
  6448.         if (sps) { for (var i = 0; i < sps.length; ++i)
  6449.           { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  6450.       });
  6451.       return markers
  6452.     },
  6453.  
  6454.     posFromIndex: function(off) {
  6455.       var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  6456.       this.iter(function (line) {
  6457.         var sz = line.text.length + sepSize;
  6458.         if (sz > off) { ch = off; return true }
  6459.         off -= sz;
  6460.         ++lineNo;
  6461.       });
  6462.       return clipPos(this, Pos(lineNo, ch))
  6463.     },
  6464.     indexFromPos: function (coords) {
  6465.       coords = clipPos(this, coords);
  6466.       var index = coords.ch;
  6467.       if (coords.line < this.first || coords.ch < 0) { return 0 }
  6468.       var sepSize = this.lineSeparator().length;
  6469.       this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  6470.         index += line.text.length + sepSize;
  6471.       });
  6472.       return index
  6473.     },
  6474.  
  6475.     copy: function(copyHistory) {
  6476.       var doc = new Doc(getLines(this, this.first, this.first + this.size),
  6477.                         this.modeOption, this.first, this.lineSep, this.direction);
  6478.       doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  6479.       doc.sel = this.sel;
  6480.       doc.extend = false;
  6481.       if (copyHistory) {
  6482.         doc.history.undoDepth = this.history.undoDepth;
  6483.         doc.setHistory(this.getHistory());
  6484.       }
  6485.       return doc
  6486.     },
  6487.  
  6488.     linkedDoc: function(options) {
  6489.       if (!options) { options = {}; }
  6490.       var from = this.first, to = this.first + this.size;
  6491.       if (options.from != null && options.from > from) { from = options.from; }
  6492.       if (options.to != null && options.to < to) { to = options.to; }
  6493.       var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  6494.       if (options.sharedHist) { copy.history = this.history
  6495.       ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  6496.       copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  6497.       copySharedMarkers(copy, findSharedMarkers(this));
  6498.       return copy
  6499.     },
  6500.     unlinkDoc: function(other) {
  6501.       if (other instanceof CodeMirror) { other = other.doc; }
  6502.       if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  6503.         var link = this.linked[i];
  6504.         if (link.doc != other) { continue }
  6505.         this.linked.splice(i, 1);
  6506.         other.unlinkDoc(this);
  6507.         detachSharedMarkers(findSharedMarkers(this));
  6508.         break
  6509.       } }
  6510.       // If the histories were shared, split them again
  6511.       if (other.history == this.history) {
  6512.         var splitIds = [other.id];
  6513.         linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  6514.         other.history = new History(null);
  6515.         other.history.done = copyHistoryArray(this.history.done, splitIds);
  6516.         other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  6517.       }
  6518.     },
  6519.     iterLinkedDocs: function(f) {linkedDocs(this, f);},
  6520.  
  6521.     getMode: function() {return this.mode},
  6522.     getEditor: function() {return this.cm},
  6523.  
  6524.     splitLines: function(str) {
  6525.       if (this.lineSep) { return str.split(this.lineSep) }
  6526.       return splitLinesAuto(str)
  6527.     },
  6528.     lineSeparator: function() { return this.lineSep || "\n" },
  6529.  
  6530.     setDirection: docMethodOp(function (dir) {
  6531.       if (dir != "rtl") { dir = "ltr"; }
  6532.       if (dir == this.direction) { return }
  6533.       this.direction = dir;
  6534.       this.iter(function (line) { return line.order = null; });
  6535.       if (this.cm) { directionChanged(this.cm); }
  6536.     })
  6537.   });
  6538.  
  6539.   // Public alias.
  6540.   Doc.prototype.eachLine = Doc.prototype.iter;
  6541.  
  6542.   // Kludge to work around strange IE behavior where it'll sometimes
  6543.   // re-fire a series of drag-related events right after the drop (#1551)
  6544.   var lastDrop = 0;
  6545.  
  6546.   function onDrop(e) {
  6547.     var cm = this;
  6548.     clearDragCursor(cm);
  6549.     if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  6550.       { return }
  6551.     e_preventDefault(e);
  6552.     if (ie) { lastDrop = +new Date; }
  6553.     var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  6554.     if (!pos || cm.isReadOnly()) { return }
  6555.     // Might be a file drop, in which case we simply extract the text
  6556.     // and insert it.
  6557.     if (files && files.length && window.FileReader && window.File) {
  6558.       var n = files.length, text = Array(n), read = 0;
  6559.       var markAsReadAndPasteIfAllFilesAreRead = function () {
  6560.         if (++read == n) {
  6561.           operation(cm, function () {
  6562.             pos = clipPos(cm.doc, pos);
  6563.             var change = {from: pos, to: pos,
  6564.                           text: cm.doc.splitLines(
  6565.                               text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
  6566.                           origin: "paste"};
  6567.             makeChange(cm.doc, change);
  6568.             setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
  6569.           })();
  6570.         }
  6571.       };
  6572.       var readTextFromFile = function (file, i) {
  6573.         if (cm.options.allowDropFileTypes &&
  6574.             indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
  6575.           markAsReadAndPasteIfAllFilesAreRead();
  6576.           return
  6577.         }
  6578.         var reader = new FileReader;
  6579.         reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
  6580.         reader.onload = function () {
  6581.           var content = reader.result;
  6582.           if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
  6583.             markAsReadAndPasteIfAllFilesAreRead();
  6584.             return
  6585.           }
  6586.           text[i] = content;
  6587.           markAsReadAndPasteIfAllFilesAreRead();
  6588.         };
  6589.         reader.readAsText(file);
  6590.       };
  6591.       for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
  6592.     } else { // Normal drop
  6593.       // Don't do a replace if the drop happened inside of the selected text.
  6594.       if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  6595.         cm.state.draggingText(e);
  6596.         // Ensure the editor is re-focused
  6597.         setTimeout(function () { return cm.display.input.focus(); }, 20);
  6598.         return
  6599.       }
  6600.       try {
  6601.         var text$1 = e.dataTransfer.getData("Text");
  6602.         if (text$1) {
  6603.           var selected;
  6604.           if (cm.state.draggingText && !cm.state.draggingText.copy)
  6605.             { selected = cm.listSelections(); }
  6606.           setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  6607.           if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  6608.             { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  6609.           cm.replaceSelection(text$1, "around", "paste");
  6610.           cm.display.input.focus();
  6611.         }
  6612.       }
  6613.       catch(e$1){}
  6614.     }
  6615.   }
  6616.  
  6617.   function onDragStart(cm, e) {
  6618.     if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  6619.     if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  6620.  
  6621.     e.dataTransfer.setData("Text", cm.getSelection());
  6622.     e.dataTransfer.effectAllowed = "copyMove";
  6623.  
  6624.     // Use dummy image instead of default browsers image.
  6625.     // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  6626.     if (e.dataTransfer.setDragImage && !safari) {
  6627.       var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  6628.       img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  6629.       if (presto) {
  6630.         img.width = img.height = 1;
  6631.         cm.display.wrapper.appendChild(img);
  6632.         // Force a relayout, or Opera won't use our image for some obscure reason
  6633.         img._top = img.offsetTop;
  6634.       }
  6635.       e.dataTransfer.setDragImage(img, 0, 0);
  6636.       if (presto) { img.parentNode.removeChild(img); }
  6637.     }
  6638.   }
  6639.  
  6640.   function onDragOver(cm, e) {
  6641.     var pos = posFromMouse(cm, e);
  6642.     if (!pos) { return }
  6643.     var frag = document.createDocumentFragment();
  6644.     drawSelectionCursor(cm, pos, frag);
  6645.     if (!cm.display.dragCursor) {
  6646.       cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  6647.       cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  6648.     }
  6649.     removeChildrenAndAdd(cm.display.dragCursor, frag);
  6650.   }
  6651.  
  6652.   function clearDragCursor(cm) {
  6653.     if (cm.display.dragCursor) {
  6654.       cm.display.lineSpace.removeChild(cm.display.dragCursor);
  6655.       cm.display.dragCursor = null;
  6656.     }
  6657.   }
  6658.  
  6659.   // These must be handled carefully, because naively registering a
  6660.   // handler for each editor will cause the editors to never be
  6661.   // garbage collected.
  6662.  
  6663.   function forEachCodeMirror(f) {
  6664.     if (!document.getElementsByClassName) { return }
  6665.     var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
  6666.     for (var i = 0; i < byClass.length; i++) {
  6667.       var cm = byClass[i].CodeMirror;
  6668.       if (cm) { editors.push(cm); }
  6669.     }
  6670.     if (editors.length) { editors[0].operation(function () {
  6671.       for (var i = 0; i < editors.length; i++) { f(editors[i]); }
  6672.     }); }
  6673.   }
  6674.  
  6675.   var globalsRegistered = false;
  6676.   function ensureGlobalHandlers() {
  6677.     if (globalsRegistered) { return }
  6678.     registerGlobalHandlers();
  6679.     globalsRegistered = true;
  6680.   }
  6681.   function registerGlobalHandlers() {
  6682.     // When the window resizes, we need to refresh active editors.
  6683.     var resizeTimer;
  6684.     on(window, "resize", function () {
  6685.       if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  6686.         resizeTimer = null;
  6687.         forEachCodeMirror(onResize);
  6688.       }, 100); }
  6689.     });
  6690.     // When the window loses focus, we want to show the editor as blurred
  6691.     on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  6692.   }
  6693.   // Called when the window resizes
  6694.   function onResize(cm) {
  6695.     var d = cm.display;
  6696.     // Might be a text scaling operation, clear size caches.
  6697.     d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  6698.     d.scrollbarsClipped = false;
  6699.     cm.setSize();
  6700.   }
  6701.  
  6702.   var keyNames = {
  6703.     3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  6704.     19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  6705.     36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  6706.     46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  6707.     106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
  6708.     173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  6709.     221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  6710.     63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  6711.   };
  6712.  
  6713.   // Number keys
  6714.   for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  6715.   // Alphabetic keys
  6716.   for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  6717.   // Function keys
  6718.   for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  6719.  
  6720.   var keyMap = {};
  6721.  
  6722.   keyMap.basic = {
  6723.     "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  6724.     "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  6725.     "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  6726.     "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  6727.     "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  6728.     "Esc": "singleSelection"
  6729.   };
  6730.   // Note that the save and find-related commands aren't defined by
  6731.   // default. User code or addons can define them. Unknown commands
  6732.   // are simply ignored.
  6733.   keyMap.pcDefault = {
  6734.     "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  6735.     "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  6736.     "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  6737.     "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  6738.     "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  6739.     "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  6740.     "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  6741.     "fallthrough": "basic"
  6742.   };
  6743.   // Very basic readline/emacs-style bindings, which are standard on Mac.
  6744.   keyMap.emacsy = {
  6745.     "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  6746.     "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp",
  6747.     "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine",
  6748.     "Ctrl-T": "transposeChars", "Ctrl-O": "openLine"
  6749.   };
  6750.   keyMap.macDefault = {
  6751.     "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  6752.     "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  6753.     "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  6754.     "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  6755.     "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  6756.     "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  6757.     "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  6758.     "fallthrough": ["basic", "emacsy"]
  6759.   };
  6760.   keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  6761.  
  6762.   // KEYMAP DISPATCH
  6763.  
  6764.   function normalizeKeyName(name) {
  6765.     var parts = name.split(/-(?!$)/);
  6766.     name = parts[parts.length - 1];
  6767.     var alt, ctrl, shift, cmd;
  6768.     for (var i = 0; i < parts.length - 1; i++) {
  6769.       var mod = parts[i];
  6770.       if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  6771.       else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  6772.       else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  6773.       else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  6774.       else { throw new Error("Unrecognized modifier name: " + mod) }
  6775.     }
  6776.     if (alt) { name = "Alt-" + name; }
  6777.     if (ctrl) { name = "Ctrl-" + name; }
  6778.     if (cmd) { name = "Cmd-" + name; }
  6779.     if (shift) { name = "Shift-" + name; }
  6780.     return name
  6781.   }
  6782.  
  6783.   // This is a kludge to keep keymaps mostly working as raw objects
  6784.   // (backwards compatibility) while at the same time support features
  6785.   // like normalization and multi-stroke key bindings. It compiles a
  6786.   // new normalized keymap, and then updates the old object to reflect
  6787.   // this.
  6788.   function normalizeKeyMap(keymap) {
  6789.     var copy = {};
  6790.     for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  6791.       var value = keymap[keyname];
  6792.       if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  6793.       if (value == "...") { delete keymap[keyname]; continue }
  6794.  
  6795.       var keys = map(keyname.split(" "), normalizeKeyName);
  6796.       for (var i = 0; i < keys.length; i++) {
  6797.         var val = (void 0), name = (void 0);
  6798.         if (i == keys.length - 1) {
  6799.           name = keys.join(" ");
  6800.           val = value;
  6801.         } else {
  6802.           name = keys.slice(0, i + 1).join(" ");
  6803.           val = "...";
  6804.         }
  6805.         var prev = copy[name];
  6806.         if (!prev) { copy[name] = val; }
  6807.         else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  6808.       }
  6809.       delete keymap[keyname];
  6810.     } }
  6811.     for (var prop in copy) { keymap[prop] = copy[prop]; }
  6812.     return keymap
  6813.   }
  6814.  
  6815.   function lookupKey(key, map, handle, context) {
  6816.     map = getKeyMap(map);
  6817.     var found = map.call ? map.call(key, context) : map[key];
  6818.     if (found === false) { return "nothing" }
  6819.     if (found === "...") { return "multi" }
  6820.     if (found != null && handle(found)) { return "handled" }
  6821.  
  6822.     if (map.fallthrough) {
  6823.       if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  6824.         { return lookupKey(key, map.fallthrough, handle, context) }
  6825.       for (var i = 0; i < map.fallthrough.length; i++) {
  6826.         var result = lookupKey(key, map.fallthrough[i], handle, context);
  6827.         if (result) { return result }
  6828.       }
  6829.     }
  6830.   }
  6831.  
  6832.   // Modifier key presses don't count as 'real' key presses for the
  6833.   // purpose of keymap fallthrough.
  6834.   function isModifierKey(value) {
  6835.     var name = typeof value == "string" ? value : keyNames[value.keyCode];
  6836.     return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  6837.   }
  6838.  
  6839.   function addModifierNames(name, event, noShift) {
  6840.     var base = name;
  6841.     if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  6842.     if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  6843.     if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; }
  6844.     if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  6845.     return name
  6846.   }
  6847.  
  6848.   // Look up the name of a key as indicated by an event object.
  6849.   function keyName(event, noShift) {
  6850.     if (presto && event.keyCode == 34 && event["char"]) { return false }
  6851.     var name = keyNames[event.keyCode];
  6852.     if (name == null || event.altGraphKey) { return false }
  6853.     // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  6854.     // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  6855.     if (event.keyCode == 3 && event.code) { name = event.code; }
  6856.     return addModifierNames(name, event, noShift)
  6857.   }
  6858.  
  6859.   function getKeyMap(val) {
  6860.     return typeof val == "string" ? keyMap[val] : val
  6861.   }
  6862.  
  6863.   // Helper for deleting text near the selection(s), used to implement
  6864.   // backspace, delete, and similar functionality.
  6865.   function deleteNearSelection(cm, compute) {
  6866.     var ranges = cm.doc.sel.ranges, kill = [];
  6867.     // Build up a set of ranges to kill first, merging overlapping
  6868.     // ranges.
  6869.     for (var i = 0; i < ranges.length; i++) {
  6870.       var toKill = compute(ranges[i]);
  6871.       while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6872.         var replaced = kill.pop();
  6873.         if (cmp(replaced.from, toKill.from) < 0) {
  6874.           toKill.from = replaced.from;
  6875.           break
  6876.         }
  6877.       }
  6878.       kill.push(toKill);
  6879.     }
  6880.     // Next, remove those actual ranges.
  6881.     runInOp(cm, function () {
  6882.       for (var i = kill.length - 1; i >= 0; i--)
  6883.         { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  6884.       ensureCursorVisible(cm);
  6885.     });
  6886.   }
  6887.  
  6888.   function moveCharLogically(line, ch, dir) {
  6889.     var target = skipExtendingChars(line.text, ch + dir, dir);
  6890.     return target < 0 || target > line.text.length ? null : target
  6891.   }
  6892.  
  6893.   function moveLogically(line, start, dir) {
  6894.     var ch = moveCharLogically(line, start.ch, dir);
  6895.     return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  6896.   }
  6897.  
  6898.   function endOfLine(visually, cm, lineObj, lineNo, dir) {
  6899.     if (visually) {
  6900.       if (cm.doc.direction == "rtl") { dir = -dir; }
  6901.       var order = getOrder(lineObj, cm.doc.direction);
  6902.       if (order) {
  6903.         var part = dir < 0 ? lst(order) : order[0];
  6904.         var moveInStorageOrder = (dir < 0) == (part.level == 1);
  6905.         var sticky = moveInStorageOrder ? "after" : "before";
  6906.         var ch;
  6907.         // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  6908.         // it could be that the last bidi part is not on the last visual line,
  6909.         // since visual lines contain content order-consecutive chunks.
  6910.         // Thus, in rtl, we are looking for the first (content-order) character
  6911.         // in the rtl chunk that is on the last line (that is, the same line
  6912.         // as the last (content-order) character).
  6913.         if (part.level > 0 || cm.doc.direction == "rtl") {
  6914.           var prep = prepareMeasureForLine(cm, lineObj);
  6915.           ch = dir < 0 ? lineObj.text.length - 1 : 0;
  6916.           var targetTop = measureCharPrepared(cm, prep, ch).top;
  6917.           ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  6918.           if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  6919.         } else { ch = dir < 0 ? part.to : part.from; }
  6920.         return new Pos(lineNo, ch, sticky)
  6921.       }
  6922.     }
  6923.     return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  6924.   }
  6925.  
  6926.   function moveVisually(cm, line, start, dir) {
  6927.     var bidi = getOrder(line, cm.doc.direction);
  6928.     if (!bidi) { return moveLogically(line, start, dir) }
  6929.     if (start.ch >= line.text.length) {
  6930.       start.ch = line.text.length;
  6931.       start.sticky = "before";
  6932.     } else if (start.ch <= 0) {
  6933.       start.ch = 0;
  6934.       start.sticky = "after";
  6935.     }
  6936.     var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  6937.     if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  6938.       // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  6939.       // nothing interesting happens.
  6940.       return moveLogically(line, start, dir)
  6941.     }
  6942.  
  6943.     var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  6944.     var prep;
  6945.     var getWrappedLineExtent = function (ch) {
  6946.       if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  6947.       prep = prep || prepareMeasureForLine(cm, line);
  6948.       return wrappedLineExtentChar(cm, line, prep, ch)
  6949.     };
  6950.     var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  6951.  
  6952.     if (cm.doc.direction == "rtl" || part.level == 1) {
  6953.       var moveInStorageOrder = (part.level == 1) == (dir < 0);
  6954.       var ch = mv(start, moveInStorageOrder ? 1 : -1);
  6955.       if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  6956.         // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  6957.         var sticky = moveInStorageOrder ? "before" : "after";
  6958.         return new Pos(start.line, ch, sticky)
  6959.       }
  6960.     }
  6961.  
  6962.     // Case 3: Could not move within this bidi part in this visual line, so leave
  6963.     // the current bidi part
  6964.  
  6965.     var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  6966.       var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  6967.         ? new Pos(start.line, mv(ch, 1), "before")
  6968.         : new Pos(start.line, ch, "after"); };
  6969.  
  6970.       for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  6971.         var part = bidi[partPos];
  6972.         var moveInStorageOrder = (dir > 0) == (part.level != 1);
  6973.         var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  6974.         if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  6975.         ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  6976.         if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  6977.       }
  6978.     };
  6979.  
  6980.     // Case 3a: Look for other bidi parts on the same visual line
  6981.     var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  6982.     if (res) { return res }
  6983.  
  6984.     // Case 3b: Look for other bidi parts on the next visual line
  6985.     var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  6986.     if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  6987.       res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  6988.       if (res) { return res }
  6989.     }
  6990.  
  6991.     // Case 4: Nowhere to move
  6992.     return null
  6993.   }
  6994.  
  6995.   // Commands are parameter-less actions that can be performed on an
  6996.   // editor, mostly used for keybindings.
  6997.   var commands = {
  6998.     selectAll: selectAll,
  6999.     singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  7000.     killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  7001.       if (range.empty()) {
  7002.         var len = getLine(cm.doc, range.head.line).text.length;
  7003.         if (range.head.ch == len && range.head.line < cm.lastLine())
  7004.           { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  7005.         else
  7006.           { return {from: range.head, to: Pos(range.head.line, len)} }
  7007.       } else {
  7008.         return {from: range.from(), to: range.to()}
  7009.       }
  7010.     }); },
  7011.     deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  7012.       from: Pos(range.from().line, 0),
  7013.       to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  7014.     }); }); },
  7015.     delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  7016.       from: Pos(range.from().line, 0), to: range.from()
  7017.     }); }); },
  7018.     delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  7019.       var top = cm.charCoords(range.head, "div").top + 5;
  7020.       var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  7021.       return {from: leftPos, to: range.from()}
  7022.     }); },
  7023.     delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  7024.       var top = cm.charCoords(range.head, "div").top + 5;
  7025.       var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  7026.       return {from: range.from(), to: rightPos }
  7027.     }); },
  7028.     undo: function (cm) { return cm.undo(); },
  7029.     redo: function (cm) { return cm.redo(); },
  7030.     undoSelection: function (cm) { return cm.undoSelection(); },
  7031.     redoSelection: function (cm) { return cm.redoSelection(); },
  7032.     goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  7033.     goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  7034.     goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  7035.       {origin: "+move", bias: 1}
  7036.     ); },
  7037.     goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  7038.       {origin: "+move", bias: 1}
  7039.     ); },
  7040.     goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  7041.       {origin: "+move", bias: -1}
  7042.     ); },
  7043.     goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  7044.       var top = cm.cursorCoords(range.head, "div").top + 5;
  7045.       return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  7046.     }, sel_move); },
  7047.     goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  7048.       var top = cm.cursorCoords(range.head, "div").top + 5;
  7049.       return cm.coordsChar({left: 0, top: top}, "div")
  7050.     }, sel_move); },
  7051.     goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  7052.       var top = cm.cursorCoords(range.head, "div").top + 5;
  7053.       var pos = cm.coordsChar({left: 0, top: top}, "div");
  7054.       if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  7055.       return pos
  7056.     }, sel_move); },
  7057.     goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  7058.     goLineDown: function (cm) { return cm.moveV(1, "line"); },
  7059.     goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  7060.     goPageDown: function (cm) { return cm.moveV(1, "page"); },
  7061.     goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  7062.     goCharRight: function (cm) { return cm.moveH(1, "char"); },
  7063.     goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  7064.     goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  7065.     goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  7066.     goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  7067.     goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  7068.     goWordRight: function (cm) { return cm.moveH(1, "word"); },
  7069.     delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); },
  7070.     delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  7071.     delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  7072.     delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  7073.     delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  7074.     delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  7075.     indentAuto: function (cm) { return cm.indentSelection("smart"); },
  7076.     indentMore: function (cm) { return cm.indentSelection("add"); },
  7077.     indentLess: function (cm) { return cm.indentSelection("subtract"); },
  7078.     insertTab: function (cm) { return cm.replaceSelection("\t"); },
  7079.     insertSoftTab: function (cm) {
  7080.       var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  7081.       for (var i = 0; i < ranges.length; i++) {
  7082.         var pos = ranges[i].from();
  7083.         var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  7084.         spaces.push(spaceStr(tabSize - col % tabSize));
  7085.       }
  7086.       cm.replaceSelections(spaces);
  7087.     },
  7088.     defaultTab: function (cm) {
  7089.       if (cm.somethingSelected()) { cm.indentSelection("add"); }
  7090.       else { cm.execCommand("insertTab"); }
  7091.     },
  7092.     // Swap the two chars left and right of each selection's head.
  7093.     // Move cursor behind the two swapped characters afterwards.
  7094.     //
  7095.     // Doesn't consider line feeds a character.
  7096.     // Doesn't scan more than one line above to find a character.
  7097.     // Doesn't do anything on an empty line.
  7098.     // Doesn't do anything with non-empty selections.
  7099.     transposeChars: function (cm) { return runInOp(cm, function () {
  7100.       var ranges = cm.listSelections(), newSel = [];
  7101.       for (var i = 0; i < ranges.length; i++) {
  7102.         if (!ranges[i].empty()) { continue }
  7103.         var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  7104.         if (line) {
  7105.           if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  7106.           if (cur.ch > 0) {
  7107.             cur = new Pos(cur.line, cur.ch + 1);
  7108.             cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  7109.                             Pos(cur.line, cur.ch - 2), cur, "+transpose");
  7110.           } else if (cur.line > cm.doc.first) {
  7111.             var prev = getLine(cm.doc, cur.line - 1).text;
  7112.             if (prev) {
  7113.               cur = new Pos(cur.line, 1);
  7114.               cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  7115.                               prev.charAt(prev.length - 1),
  7116.                               Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  7117.             }
  7118.           }
  7119.         }
  7120.         newSel.push(new Range(cur, cur));
  7121.       }
  7122.       cm.setSelections(newSel);
  7123.     }); },
  7124.     newlineAndIndent: function (cm) { return runInOp(cm, function () {
  7125.       var sels = cm.listSelections();
  7126.       for (var i = sels.length - 1; i >= 0; i--)
  7127.         { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  7128.       sels = cm.listSelections();
  7129.       for (var i$1 = 0; i$1 < sels.length; i$1++)
  7130.         { cm.indentLine(sels[i$1].from().line, null, true); }
  7131.       ensureCursorVisible(cm);
  7132.     }); },
  7133.     openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  7134.     toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  7135.   };
  7136.  
  7137.  
  7138.   function lineStart(cm, lineN) {
  7139.     var line = getLine(cm.doc, lineN);
  7140.     var visual = visualLine(line);
  7141.     if (visual != line) { lineN = lineNo(visual); }
  7142.     return endOfLine(true, cm, visual, lineN, 1)
  7143.   }
  7144.   function lineEnd(cm, lineN) {
  7145.     var line = getLine(cm.doc, lineN);
  7146.     var visual = visualLineEnd(line);
  7147.     if (visual != line) { lineN = lineNo(visual); }
  7148.     return endOfLine(true, cm, line, lineN, -1)
  7149.   }
  7150.   function lineStartSmart(cm, pos) {
  7151.     var start = lineStart(cm, pos.line);
  7152.     var line = getLine(cm.doc, start.line);
  7153.     var order = getOrder(line, cm.doc.direction);
  7154.     if (!order || order[0].level == 0) {
  7155.       var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
  7156.       var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  7157.       return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  7158.     }
  7159.     return start
  7160.   }
  7161.  
  7162.   // Run a handler that was bound to a key.
  7163.   function doHandleBinding(cm, bound, dropShift) {
  7164.     if (typeof bound == "string") {
  7165.       bound = commands[bound];
  7166.       if (!bound) { return false }
  7167.     }
  7168.     // Ensure previous input has been read, so that the handler sees a
  7169.     // consistent view of the document
  7170.     cm.display.input.ensurePolled();
  7171.     var prevShift = cm.display.shift, done = false;
  7172.     try {
  7173.       if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  7174.       if (dropShift) { cm.display.shift = false; }
  7175.       done = bound(cm) != Pass;
  7176.     } finally {
  7177.       cm.display.shift = prevShift;
  7178.       cm.state.suppressEdits = false;
  7179.     }
  7180.     return done
  7181.   }
  7182.  
  7183.   function lookupKeyForEditor(cm, name, handle) {
  7184.     for (var i = 0; i < cm.state.keyMaps.length; i++) {
  7185.       var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  7186.       if (result) { return result }
  7187.     }
  7188.     return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  7189.       || lookupKey(name, cm.options.keyMap, handle, cm)
  7190.   }
  7191.  
  7192.   // Note that, despite the name, this function is also used to check
  7193.   // for bound mouse clicks.
  7194.  
  7195.   var stopSeq = new Delayed;
  7196.  
  7197.   function dispatchKey(cm, name, e, handle) {
  7198.     var seq = cm.state.keySeq;
  7199.     if (seq) {
  7200.       if (isModifierKey(name)) { return "handled" }
  7201.       if (/\'$/.test(name))
  7202.         { cm.state.keySeq = null; }
  7203.       else
  7204.         { stopSeq.set(50, function () {
  7205.           if (cm.state.keySeq == seq) {
  7206.             cm.state.keySeq = null;
  7207.             cm.display.input.reset();
  7208.           }
  7209.         }); }
  7210.       if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  7211.     }
  7212.     return dispatchKeyInner(cm, name, e, handle)
  7213.   }
  7214.  
  7215.   function dispatchKeyInner(cm, name, e, handle) {
  7216.     var result = lookupKeyForEditor(cm, name, handle);
  7217.  
  7218.     if (result == "multi")
  7219.       { cm.state.keySeq = name; }
  7220.     if (result == "handled")
  7221.       { signalLater(cm, "keyHandled", cm, name, e); }
  7222.  
  7223.     if (result == "handled" || result == "multi") {
  7224.       e_preventDefault(e);
  7225.       restartBlink(cm);
  7226.     }
  7227.  
  7228.     return !!result
  7229.   }
  7230.  
  7231.   // Handle a key from the keydown event.
  7232.   function handleKeyBinding(cm, e) {
  7233.     var name = keyName(e, true);
  7234.     if (!name) { return false }
  7235.  
  7236.     if (e.shiftKey && !cm.state.keySeq) {
  7237.       // First try to resolve full name (including 'Shift-'). Failing
  7238.       // that, see if there is a cursor-motion command (starting with
  7239.       // 'go') bound to the keyname without 'Shift-'.
  7240.       return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  7241.           || dispatchKey(cm, name, e, function (b) {
  7242.                if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  7243.                  { return doHandleBinding(cm, b) }
  7244.              })
  7245.     } else {
  7246.       return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  7247.     }
  7248.   }
  7249.  
  7250.   // Handle a key from the keypress event
  7251.   function handleCharBinding(cm, e, ch) {
  7252.     return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  7253.   }
  7254.  
  7255.   var lastStoppedKey = null;
  7256.   function onKeyDown(e) {
  7257.     var cm = this;
  7258.     if (e.target && e.target != cm.display.input.getField()) { return }
  7259.     cm.curOp.focus = activeElt();
  7260.     if (signalDOMEvent(cm, e)) { return }
  7261.     // IE does strange things with escape.
  7262.     if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  7263.     var code = e.keyCode;
  7264.     cm.display.shift = code == 16 || e.shiftKey;
  7265.     var handled = handleKeyBinding(cm, e);
  7266.     if (presto) {
  7267.       lastStoppedKey = handled ? code : null;
  7268.       // Opera has no cut event... we try to at least catch the key combo
  7269.       if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  7270.         { cm.replaceSelection("", null, "cut"); }
  7271.     }
  7272.     if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
  7273.       { document.execCommand("cut"); }
  7274.  
  7275.     // Turn mouse into crosshair when Alt is held on Mac.
  7276.     if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  7277.       { showCrossHair(cm); }
  7278.   }
  7279.  
  7280.   function showCrossHair(cm) {
  7281.     var lineDiv = cm.display.lineDiv;
  7282.     addClass(lineDiv, "CodeMirror-crosshair");
  7283.  
  7284.     function up(e) {
  7285.       if (e.keyCode == 18 || !e.altKey) {
  7286.         rmClass(lineDiv, "CodeMirror-crosshair");
  7287.         off(document, "keyup", up);
  7288.         off(document, "mouseover", up);
  7289.       }
  7290.     }
  7291.     on(document, "keyup", up);
  7292.     on(document, "mouseover", up);
  7293.   }
  7294.  
  7295.   function onKeyUp(e) {
  7296.     if (e.keyCode == 16) { this.doc.sel.shift = false; }
  7297.     signalDOMEvent(this, e);
  7298.   }
  7299.  
  7300.   function onKeyPress(e) {
  7301.     var cm = this;
  7302.     if (e.target && e.target != cm.display.input.getField()) { return }
  7303.     if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  7304.     var keyCode = e.keyCode, charCode = e.charCode;
  7305.     if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  7306.     if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  7307.     var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  7308.     // Some browsers fire keypress events for backspace
  7309.     if (ch == "\x08") { return }
  7310.     if (handleCharBinding(cm, e, ch)) { return }
  7311.     cm.display.input.onKeyPress(e);
  7312.   }
  7313.  
  7314.   var DOUBLECLICK_DELAY = 400;
  7315.  
  7316.   var PastClick = function(time, pos, button) {
  7317.     this.time = time;
  7318.     this.pos = pos;
  7319.     this.button = button;
  7320.   };
  7321.  
  7322.   PastClick.prototype.compare = function (time, pos, button) {
  7323.     return this.time + DOUBLECLICK_DELAY > time &&
  7324.       cmp(pos, this.pos) == 0 && button == this.button
  7325.   };
  7326.  
  7327.   var lastClick, lastDoubleClick;
  7328.   function clickRepeat(pos, button) {
  7329.     var now = +new Date;
  7330.     if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  7331.       lastClick = lastDoubleClick = null;
  7332.       return "triple"
  7333.     } else if (lastClick && lastClick.compare(now, pos, button)) {
  7334.       lastDoubleClick = new PastClick(now, pos, button);
  7335.       lastClick = null;
  7336.       return "double"
  7337.     } else {
  7338.       lastClick = new PastClick(now, pos, button);
  7339.       lastDoubleClick = null;
  7340.       return "single"
  7341.     }
  7342.   }
  7343.  
  7344.   // A mouse down can be a single click, double click, triple click,
  7345.   // start of selection drag, start of text drag, new cursor
  7346.   // (ctrl-click), rectangle drag (alt-drag), or xwin
  7347.   // middle-click-paste. Or it might be a click on something we should
  7348.   // not interfere with, such as a scrollbar or widget.
  7349.   function onMouseDown(e) {
  7350.     var cm = this, display = cm.display;
  7351.     if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  7352.     display.input.ensurePolled();
  7353.     display.shift = e.shiftKey;
  7354.  
  7355.     if (eventInWidget(display, e)) {
  7356.       if (!webkit) {
  7357.         // Briefly turn off draggability, to allow widgets to do
  7358.         // normal dragging things.
  7359.         display.scroller.draggable = false;
  7360.         setTimeout(function () { return display.scroller.draggable = true; }, 100);
  7361.       }
  7362.       return
  7363.     }
  7364.     if (clickInGutter(cm, e)) { return }
  7365.     var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  7366.     window.focus();
  7367.  
  7368.     // #3261: make sure, that we're not starting a second selection
  7369.     if (button == 1 && cm.state.selectingText)
  7370.       { cm.state.selectingText(e); }
  7371.  
  7372.     if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  7373.  
  7374.     if (button == 1) {
  7375.       if (pos) { leftButtonDown(cm, pos, repeat, e); }
  7376.       else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  7377.     } else if (button == 2) {
  7378.       if (pos) { extendSelection(cm.doc, pos); }
  7379.       setTimeout(function () { return display.input.focus(); }, 20);
  7380.     } else if (button == 3) {
  7381.       if (captureRightClick) { cm.display.input.onContextMenu(e); }
  7382.       else { delayBlurEvent(cm); }
  7383.     }
  7384.   }
  7385.  
  7386.   function handleMappedButton(cm, button, pos, repeat, event) {
  7387.     var name = "Click";
  7388.     if (repeat == "double") { name = "Double" + name; }
  7389.     else if (repeat == "triple") { name = "Triple" + name; }
  7390.     name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  7391.  
  7392.     return dispatchKey(cm,  addModifierNames(name, event), event, function (bound) {
  7393.       if (typeof bound == "string") { bound = commands[bound]; }
  7394.       if (!bound) { return false }
  7395.       var done = false;
  7396.       try {
  7397.         if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  7398.         done = bound(cm, pos) != Pass;
  7399.       } finally {
  7400.         cm.state.suppressEdits = false;
  7401.       }
  7402.       return done
  7403.     })
  7404.   }
  7405.  
  7406.   function configureMouse(cm, repeat, event) {
  7407.     var option = cm.getOption("configureMouse");
  7408.     var value = option ? option(cm, repeat, event) : {};
  7409.     if (value.unit == null) {
  7410.       var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  7411.       value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  7412.     }
  7413.     if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  7414.     if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  7415.     if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  7416.     return value
  7417.   }
  7418.  
  7419.   function leftButtonDown(cm, pos, repeat, event) {
  7420.     if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  7421.     else { cm.curOp.focus = activeElt(); }
  7422.  
  7423.     var behavior = configureMouse(cm, repeat, event);
  7424.  
  7425.     var sel = cm.doc.sel, contained;
  7426.     if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  7427.         repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  7428.         (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  7429.         (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  7430.       { leftButtonStartDrag(cm, event, pos, behavior); }
  7431.     else
  7432.       { leftButtonSelect(cm, event, pos, behavior); }
  7433.   }
  7434.  
  7435.   // Start a text drag. When it ends, see if any dragging actually
  7436.   // happen, and treat as a click if it didn't.
  7437.   function leftButtonStartDrag(cm, event, pos, behavior) {
  7438.     var display = cm.display, moved = false;
  7439.     var dragEnd = operation(cm, function (e) {
  7440.       if (webkit) { display.scroller.draggable = false; }
  7441.       cm.state.draggingText = false;
  7442.       if (cm.state.delayingBlurEvent) {
  7443.         if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; }
  7444.         else { delayBlurEvent(cm); }
  7445.       }
  7446.       off(display.wrapper.ownerDocument, "mouseup", dragEnd);
  7447.       off(display.wrapper.ownerDocument, "mousemove", mouseMove);
  7448.       off(display.scroller, "dragstart", dragStart);
  7449.       off(display.scroller, "drop", dragEnd);
  7450.       if (!moved) {
  7451.         e_preventDefault(e);
  7452.         if (!behavior.addNew)
  7453.           { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  7454.         // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  7455.         if ((webkit && !safari) || ie && ie_version == 9)
  7456.           { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
  7457.         else
  7458.           { display.input.focus(); }
  7459.       }
  7460.     });
  7461.     var mouseMove = function(e2) {
  7462.       moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  7463.     };
  7464.     var dragStart = function () { return moved = true; };
  7465.     // Let the drag handler handle this.
  7466.     if (webkit) { display.scroller.draggable = true; }
  7467.     cm.state.draggingText = dragEnd;
  7468.     dragEnd.copy = !behavior.moveOnDrag;
  7469.     on(display.wrapper.ownerDocument, "mouseup", dragEnd);
  7470.     on(display.wrapper.ownerDocument, "mousemove", mouseMove);
  7471.     on(display.scroller, "dragstart", dragStart);
  7472.     on(display.scroller, "drop", dragEnd);
  7473.  
  7474.     cm.state.delayingBlurEvent = true;
  7475.     setTimeout(function () { return display.input.focus(); }, 20);
  7476.     // IE's approach to draggable
  7477.     if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  7478.   }
  7479.  
  7480.   function rangeForUnit(cm, pos, unit) {
  7481.     if (unit == "char") { return new Range(pos, pos) }
  7482.     if (unit == "word") { return cm.findWordAt(pos) }
  7483.     if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  7484.     var result = unit(cm, pos);
  7485.     return new Range(result.from, result.to)
  7486.   }
  7487.  
  7488.   // Normal selection, as opposed to text dragging.
  7489.   function leftButtonSelect(cm, event, start, behavior) {
  7490.     if (ie) { delayBlurEvent(cm); }
  7491.     var display = cm.display, doc = cm.doc;
  7492.     e_preventDefault(event);
  7493.  
  7494.     var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  7495.     if (behavior.addNew && !behavior.extend) {
  7496.       ourIndex = doc.sel.contains(start);
  7497.       if (ourIndex > -1)
  7498.         { ourRange = ranges[ourIndex]; }
  7499.       else
  7500.         { ourRange = new Range(start, start); }
  7501.     } else {
  7502.       ourRange = doc.sel.primary();
  7503.       ourIndex = doc.sel.primIndex;
  7504.     }
  7505.  
  7506.     if (behavior.unit == "rectangle") {
  7507.       if (!behavior.addNew) { ourRange = new Range(start, start); }
  7508.       start = posFromMouse(cm, event, true, true);
  7509.       ourIndex = -1;
  7510.     } else {
  7511.       var range = rangeForUnit(cm, start, behavior.unit);
  7512.       if (behavior.extend)
  7513.         { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
  7514.       else
  7515.         { ourRange = range; }
  7516.     }
  7517.  
  7518.     if (!behavior.addNew) {
  7519.       ourIndex = 0;
  7520.       setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  7521.       startSel = doc.sel;
  7522.     } else if (ourIndex == -1) {
  7523.       ourIndex = ranges.length;
  7524.       setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
  7525.                    {scroll: false, origin: "*mouse"});
  7526.     } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  7527.       setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  7528.                    {scroll: false, origin: "*mouse"});
  7529.       startSel = doc.sel;
  7530.     } else {
  7531.       replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  7532.     }
  7533.  
  7534.     var lastPos = start;
  7535.     function extendTo(pos) {
  7536.       if (cmp(lastPos, pos) == 0) { return }
  7537.       lastPos = pos;
  7538.  
  7539.       if (behavior.unit == "rectangle") {
  7540.         var ranges = [], tabSize = cm.options.tabSize;
  7541.         var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  7542.         var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  7543.         var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  7544.         for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  7545.              line <= end; line++) {
  7546.           var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  7547.           if (left == right)
  7548.             { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  7549.           else if (text.length > leftPos)
  7550.             { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  7551.         }
  7552.         if (!ranges.length) { ranges.push(new Range(start, start)); }
  7553.         setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  7554.                      {origin: "*mouse", scroll: false});
  7555.         cm.scrollIntoView(pos);
  7556.       } else {
  7557.         var oldRange = ourRange;
  7558.         var range = rangeForUnit(cm, pos, behavior.unit);
  7559.         var anchor = oldRange.anchor, head;
  7560.         if (cmp(range.anchor, anchor) > 0) {
  7561.           head = range.head;
  7562.           anchor = minPos(oldRange.from(), range.anchor);
  7563.         } else {
  7564.           head = range.anchor;
  7565.           anchor = maxPos(oldRange.to(), range.head);
  7566.         }
  7567.         var ranges$1 = startSel.ranges.slice(0);
  7568.         ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
  7569.         setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
  7570.       }
  7571.     }
  7572.  
  7573.     var editorSize = display.wrapper.getBoundingClientRect();
  7574.     // Used to ensure timeout re-tries don't fire when another extend
  7575.     // happened in the meantime (clearTimeout isn't reliable -- at
  7576.     // least on Chrome, the timeouts still happen even when cleared,
  7577.     // if the clear happens after their scheduled firing time).
  7578.     var counter = 0;
  7579.  
  7580.     function extend(e) {
  7581.       var curCount = ++counter;
  7582.       var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  7583.       if (!cur) { return }
  7584.       if (cmp(cur, lastPos) != 0) {
  7585.         cm.curOp.focus = activeElt();
  7586.         extendTo(cur);
  7587.         var visible = visibleLines(display, doc);
  7588.         if (cur.line >= visible.to || cur.line < visible.from)
  7589.           { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  7590.       } else {
  7591.         var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  7592.         if (outside) { setTimeout(operation(cm, function () {
  7593.           if (counter != curCount) { return }
  7594.           display.scroller.scrollTop += outside;
  7595.           extend(e);
  7596.         }), 50); }
  7597.       }
  7598.     }
  7599.  
  7600.     function done(e) {
  7601.       cm.state.selectingText = false;
  7602.       counter = Infinity;
  7603.       // If e is null or undefined we interpret this as someone trying
  7604.       // to explicitly cancel the selection rather than the user
  7605.       // letting go of the mouse button.
  7606.       if (e) {
  7607.         e_preventDefault(e);
  7608.         display.input.focus();
  7609.       }
  7610.       off(display.wrapper.ownerDocument, "mousemove", move);
  7611.       off(display.wrapper.ownerDocument, "mouseup", up);
  7612.       doc.history.lastSelOrigin = null;
  7613.     }
  7614.  
  7615.     var move = operation(cm, function (e) {
  7616.       if (e.buttons === 0 || !e_button(e)) { done(e); }
  7617.       else { extend(e); }
  7618.     });
  7619.     var up = operation(cm, done);
  7620.     cm.state.selectingText = up;
  7621.     on(display.wrapper.ownerDocument, "mousemove", move);
  7622.     on(display.wrapper.ownerDocument, "mouseup", up);
  7623.   }
  7624.  
  7625.   // Used when mouse-selecting to adjust the anchor to the proper side
  7626.   // of a bidi jump depending on the visual position of the head.
  7627.   function bidiSimplify(cm, range) {
  7628.     var anchor = range.anchor;
  7629.     var head = range.head;
  7630.     var anchorLine = getLine(cm.doc, anchor.line);
  7631.     if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
  7632.     var order = getOrder(anchorLine);
  7633.     if (!order) { return range }
  7634.     var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  7635.     if (part.from != anchor.ch && part.to != anchor.ch) { return range }
  7636.     var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  7637.     if (boundary == 0 || boundary == order.length) { return range }
  7638.  
  7639.     // Compute the relative visual position of the head compared to the
  7640.     // anchor (<0 is to the left, >0 to the right)
  7641.     var leftSide;
  7642.     if (head.line != anchor.line) {
  7643.       leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  7644.     } else {
  7645.       var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  7646.       var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  7647.       if (headIndex == boundary - 1 || headIndex == boundary)
  7648.         { leftSide = dir < 0; }
  7649.       else
  7650.         { leftSide = dir > 0; }
  7651.     }
  7652.  
  7653.     var usePart = order[boundary + (leftSide ? -1 : 0)];
  7654.     var from = leftSide == (usePart.level == 1);
  7655.     var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  7656.     return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  7657.   }
  7658.  
  7659.  
  7660.   // Determines whether an event happened in the gutter, and fires the
  7661.   // handlers for the corresponding event.
  7662.   function gutterEvent(cm, e, type, prevent) {
  7663.     var mX, mY;
  7664.     if (e.touches) {
  7665.       mX = e.touches[0].clientX;
  7666.       mY = e.touches[0].clientY;
  7667.     } else {
  7668.       try { mX = e.clientX; mY = e.clientY; }
  7669.       catch(e$1) { return false }
  7670.     }
  7671.     if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  7672.     if (prevent) { e_preventDefault(e); }
  7673.  
  7674.     var display = cm.display;
  7675.     var lineBox = display.lineDiv.getBoundingClientRect();
  7676.  
  7677.     if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  7678.     mY -= lineBox.top - display.viewOffset;
  7679.  
  7680.     for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
  7681.       var g = display.gutters.childNodes[i];
  7682.       if (g && g.getBoundingClientRect().right >= mX) {
  7683.         var line = lineAtHeight(cm.doc, mY);
  7684.         var gutter = cm.display.gutterSpecs[i];
  7685.         signal(cm, type, cm, line, gutter.className, e);
  7686.         return e_defaultPrevented(e)
  7687.       }
  7688.     }
  7689.   }
  7690.  
  7691.   function clickInGutter(cm, e) {
  7692.     return gutterEvent(cm, e, "gutterClick", true)
  7693.   }
  7694.  
  7695.   // CONTEXT MENU HANDLING
  7696.  
  7697.   // To make the context menu work, we need to briefly unhide the
  7698.   // textarea (making it as unobtrusive as possible) to let the
  7699.   // right-click take effect on it.
  7700.   function onContextMenu(cm, e) {
  7701.     if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  7702.     if (signalDOMEvent(cm, e, "contextmenu")) { return }
  7703.     if (!captureRightClick) { cm.display.input.onContextMenu(e); }
  7704.   }
  7705.  
  7706.   function contextMenuInGutter(cm, e) {
  7707.     if (!hasHandler(cm, "gutterContextMenu")) { return false }
  7708.     return gutterEvent(cm, e, "gutterContextMenu", false)
  7709.   }
  7710.  
  7711.   function themeChanged(cm) {
  7712.     cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  7713.       cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  7714.     clearCaches(cm);
  7715.   }
  7716.  
  7717.   var Init = {toString: function(){return "CodeMirror.Init"}};
  7718.  
  7719.   var defaults = {};
  7720.   var optionHandlers = {};
  7721.  
  7722.   function defineOptions(CodeMirror) {
  7723.     var optionHandlers = CodeMirror.optionHandlers;
  7724.  
  7725.     function option(name, deflt, handle, notOnInit) {
  7726.       CodeMirror.defaults[name] = deflt;
  7727.       if (handle) { optionHandlers[name] =
  7728.         notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  7729.     }
  7730.  
  7731.     CodeMirror.defineOption = option;
  7732.  
  7733.     // Passed to option handlers when there is no old value.
  7734.     CodeMirror.Init = Init;
  7735.  
  7736.     // These two are, on init, called from the constructor because they
  7737.     // have to be initialized before the editor can start at all.
  7738.     option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  7739.     option("mode", null, function (cm, val) {
  7740.       cm.doc.modeOption = val;
  7741.       loadMode(cm);
  7742.     }, true);
  7743.  
  7744.     option("indentUnit", 2, loadMode, true);
  7745.     option("indentWithTabs", false);
  7746.     option("smartIndent", true);
  7747.     option("tabSize", 4, function (cm) {
  7748.       resetModeState(cm);
  7749.       clearCaches(cm);
  7750.       regChange(cm);
  7751.     }, true);
  7752.  
  7753.     option("lineSeparator", null, function (cm, val) {
  7754.       cm.doc.lineSep = val;
  7755.       if (!val) { return }
  7756.       var newBreaks = [], lineNo = cm.doc.first;
  7757.       cm.doc.iter(function (line) {
  7758.         for (var pos = 0;;) {
  7759.           var found = line.text.indexOf(val, pos);
  7760.           if (found == -1) { break }
  7761.           pos = found + val.length;
  7762.           newBreaks.push(Pos(lineNo, found));
  7763.         }
  7764.         lineNo++;
  7765.       });
  7766.       for (var i = newBreaks.length - 1; i >= 0; i--)
  7767.         { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  7768.     });
  7769.     option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
  7770.       cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  7771.       if (old != Init) { cm.refresh(); }
  7772.     });
  7773.     option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  7774.     option("electricChars", true);
  7775.     option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  7776.       throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  7777.     }, true);
  7778.     option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  7779.     option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
  7780.     option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
  7781.     option("rtlMoveVisually", !windows);
  7782.     option("wholeLineUpdateBefore", true);
  7783.  
  7784.     option("theme", "default", function (cm) {
  7785.       themeChanged(cm);
  7786.       updateGutters(cm);
  7787.     }, true);
  7788.     option("keyMap", "default", function (cm, val, old) {
  7789.       var next = getKeyMap(val);
  7790.       var prev = old != Init && getKeyMap(old);
  7791.       if (prev && prev.detach) { prev.detach(cm, next); }
  7792.       if (next.attach) { next.attach(cm, prev || null); }
  7793.     });
  7794.     option("extraKeys", null);
  7795.     option("configureMouse", null);
  7796.  
  7797.     option("lineWrapping", false, wrappingChanged, true);
  7798.     option("gutters", [], function (cm, val) {
  7799.       cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
  7800.       updateGutters(cm);
  7801.     }, true);
  7802.     option("fixedGutter", true, function (cm, val) {
  7803.       cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  7804.       cm.refresh();
  7805.     }, true);
  7806.     option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  7807.     option("scrollbarStyle", "native", function (cm) {
  7808.       initScrollbars(cm);
  7809.       updateScrollbars(cm);
  7810.       cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  7811.       cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  7812.     }, true);
  7813.     option("lineNumbers", false, function (cm, val) {
  7814.       cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
  7815.       updateGutters(cm);
  7816.     }, true);
  7817.     option("firstLineNumber", 1, updateGutters, true);
  7818.     option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
  7819.     option("showCursorWhenSelecting", false, updateSelection, true);
  7820.  
  7821.     option("resetSelectionOnContextMenu", true);
  7822.     option("lineWiseCopyCut", true);
  7823.     option("pasteLinesPerSelection", true);
  7824.     option("selectionsMayTouch", false);
  7825.  
  7826.     option("readOnly", false, function (cm, val) {
  7827.       if (val == "nocursor") {
  7828.         onBlur(cm);
  7829.         cm.display.input.blur();
  7830.       }
  7831.       cm.display.input.readOnlyChanged(val);
  7832.     });
  7833.  
  7834.     option("screenReaderLabel", null, function (cm, val) {
  7835.       val = (val === '') ? null : val;
  7836.       cm.display.input.screenReaderLabelChanged(val);
  7837.     });
  7838.  
  7839.     option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  7840.     option("dragDrop", true, dragDropChanged);
  7841.     option("allowDropFileTypes", null);
  7842.  
  7843.     option("cursorBlinkRate", 530);
  7844.     option("cursorScrollMargin", 0);
  7845.     option("cursorHeight", 1, updateSelection, true);
  7846.     option("singleCursorHeightPerLine", true, updateSelection, true);
  7847.     option("workTime", 100);
  7848.     option("workDelay", 100);
  7849.     option("flattenSpans", true, resetModeState, true);
  7850.     option("addModeClass", false, resetModeState, true);
  7851.     option("pollInterval", 100);
  7852.     option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  7853.     option("historyEventDelay", 1250);
  7854.     option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  7855.     option("maxHighlightLength", 10000, resetModeState, true);
  7856.     option("moveInputWithCursor", true, function (cm, val) {
  7857.       if (!val) { cm.display.input.resetPosition(); }
  7858.     });
  7859.  
  7860.     option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  7861.     option("autofocus", null);
  7862.     option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  7863.     option("phrases", null);
  7864.   }
  7865.  
  7866.   function dragDropChanged(cm, value, old) {
  7867.     var wasOn = old && old != Init;
  7868.     if (!value != !wasOn) {
  7869.       var funcs = cm.display.dragFunctions;
  7870.       var toggle = value ? on : off;
  7871.       toggle(cm.display.scroller, "dragstart", funcs.start);
  7872.       toggle(cm.display.scroller, "dragenter", funcs.enter);
  7873.       toggle(cm.display.scroller, "dragover", funcs.over);
  7874.       toggle(cm.display.scroller, "dragleave", funcs.leave);
  7875.       toggle(cm.display.scroller, "drop", funcs.drop);
  7876.     }
  7877.   }
  7878.  
  7879.   function wrappingChanged(cm) {
  7880.     if (cm.options.lineWrapping) {
  7881.       addClass(cm.display.wrapper, "CodeMirror-wrap");
  7882.       cm.display.sizer.style.minWidth = "";
  7883.       cm.display.sizerWidth = null;
  7884.     } else {
  7885.       rmClass(cm.display.wrapper, "CodeMirror-wrap");
  7886.       findMaxLine(cm);
  7887.     }
  7888.     estimateLineHeights(cm);
  7889.     regChange(cm);
  7890.     clearCaches(cm);
  7891.     setTimeout(function () { return updateScrollbars(cm); }, 100);
  7892.   }
  7893.  
  7894.   // A CodeMirror instance represents an editor. This is the object
  7895.   // that user code is usually dealing with.
  7896.  
  7897.   function CodeMirror(place, options) {
  7898.     var this$1 = this;
  7899.  
  7900.     if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  7901.  
  7902.     this.options = options = options ? copyObj(options) : {};
  7903.     // Determine effective options based on given values and defaults.
  7904.     copyObj(defaults, options, false);
  7905.  
  7906.     var doc = options.value;
  7907.     if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  7908.     else if (options.mode) { doc.modeOption = options.mode; }
  7909.     this.doc = doc;
  7910.  
  7911.     var input = new CodeMirror.inputStyles[options.inputStyle](this);
  7912.     var display = this.display = new Display(place, doc, input, options);
  7913.     display.wrapper.CodeMirror = this;
  7914.     themeChanged(this);
  7915.     if (options.lineWrapping)
  7916.       { this.display.wrapper.className += " CodeMirror-wrap"; }
  7917.     initScrollbars(this);
  7918.  
  7919.     this.state = {
  7920.       keyMaps: [],  // stores maps added by addKeyMap
  7921.       overlays: [], // highlighting overlays, as added by addOverlay
  7922.       modeGen: 0,   // bumped when mode/overlay changes, used to invalidate highlighting info
  7923.       overwrite: false,
  7924.       delayingBlurEvent: false,
  7925.       focused: false,
  7926.       suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  7927.       pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
  7928.       selectingText: false,
  7929.       draggingText: false,
  7930.       highlight: new Delayed(), // stores highlight worker timeout
  7931.       keySeq: null,  // Unfinished key sequence
  7932.       specialChars: null
  7933.     };
  7934.  
  7935.     if (options.autofocus && !mobile) { display.input.focus(); }
  7936.  
  7937.     // Override magic textarea content restore that IE sometimes does
  7938.     // on our hidden textarea on reload
  7939.     if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  7940.  
  7941.     registerEventHandlers(this);
  7942.     ensureGlobalHandlers();
  7943.  
  7944.     startOperation(this);
  7945.     this.curOp.forceUpdate = true;
  7946.     attachDoc(this, doc);
  7947.  
  7948.     if ((options.autofocus && !mobile) || this.hasFocus())
  7949.       { setTimeout(function () {
  7950.         if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
  7951.       }, 20); }
  7952.     else
  7953.       { onBlur(this); }
  7954.  
  7955.     for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  7956.       { optionHandlers[opt](this, options[opt], Init); } }
  7957.     maybeUpdateLineNumberWidth(this);
  7958.     if (options.finishInit) { options.finishInit(this); }
  7959.     for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
  7960.     endOperation(this);
  7961.     // Suppress optimizelegibility in Webkit, since it breaks text
  7962.     // measuring on line wrapping boundaries.
  7963.     if (webkit && options.lineWrapping &&
  7964.         getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  7965.       { display.lineDiv.style.textRendering = "auto"; }
  7966.   }
  7967.  
  7968.   // The default configuration options.
  7969.   CodeMirror.defaults = defaults;
  7970.   // Functions to run when options are changed.
  7971.   CodeMirror.optionHandlers = optionHandlers;
  7972.  
  7973.   // Attach the necessary event handlers when initializing the editor
  7974.   function registerEventHandlers(cm) {
  7975.     var d = cm.display;
  7976.     on(d.scroller, "mousedown", operation(cm, onMouseDown));
  7977.     // Older IE's will not fire a second mousedown for a double click
  7978.     if (ie && ie_version < 11)
  7979.       { on(d.scroller, "dblclick", operation(cm, function (e) {
  7980.         if (signalDOMEvent(cm, e)) { return }
  7981.         var pos = posFromMouse(cm, e);
  7982.         if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  7983.         e_preventDefault(e);
  7984.         var word = cm.findWordAt(pos);
  7985.         extendSelection(cm.doc, word.anchor, word.head);
  7986.       })); }
  7987.     else
  7988.       { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  7989.     // Some browsers fire contextmenu *after* opening the menu, at
  7990.     // which point we can't mess with it anymore. Context menu is
  7991.     // handled in onMouseDown for these browsers.
  7992.     on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
  7993.     on(d.input.getField(), "contextmenu", function (e) {
  7994.       if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
  7995.     });
  7996.  
  7997.     // Used to suppress mouse event handling when a touch happens
  7998.     var touchFinished, prevTouch = {end: 0};
  7999.     function finishTouch() {
  8000.       if (d.activeTouch) {
  8001.         touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  8002.         prevTouch = d.activeTouch;
  8003.         prevTouch.end = +new Date;
  8004.       }
  8005.     }
  8006.     function isMouseLikeTouchEvent(e) {
  8007.       if (e.touches.length != 1) { return false }
  8008.       var touch = e.touches[0];
  8009.       return touch.radiusX <= 1 && touch.radiusY <= 1
  8010.     }
  8011.     function farAway(touch, other) {
  8012.       if (other.left == null) { return true }
  8013.       var dx = other.left - touch.left, dy = other.top - touch.top;
  8014.       return dx * dx + dy * dy > 20 * 20
  8015.     }
  8016.     on(d.scroller, "touchstart", function (e) {
  8017.       if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  8018.         d.input.ensurePolled();
  8019.         clearTimeout(touchFinished);
  8020.         var now = +new Date;
  8021.         d.activeTouch = {start: now, moved: false,
  8022.                          prev: now - prevTouch.end <= 300 ? prevTouch : null};
  8023.         if (e.touches.length == 1) {
  8024.           d.activeTouch.left = e.touches[0].pageX;
  8025.           d.activeTouch.top = e.touches[0].pageY;
  8026.         }
  8027.       }
  8028.     });
  8029.     on(d.scroller, "touchmove", function () {
  8030.       if (d.activeTouch) { d.activeTouch.moved = true; }
  8031.     });
  8032.     on(d.scroller, "touchend", function (e) {
  8033.       var touch = d.activeTouch;
  8034.       if (touch && !eventInWidget(d, e) && touch.left != null &&
  8035.           !touch.moved && new Date - touch.start < 300) {
  8036.         var pos = cm.coordsChar(d.activeTouch, "page"), range;
  8037.         if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  8038.           { range = new Range(pos, pos); }
  8039.         else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  8040.           { range = cm.findWordAt(pos); }
  8041.         else // Triple tap
  8042.           { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  8043.         cm.setSelection(range.anchor, range.head);
  8044.         cm.focus();
  8045.         e_preventDefault(e);
  8046.       }
  8047.       finishTouch();
  8048.     });
  8049.     on(d.scroller, "touchcancel", finishTouch);
  8050.  
  8051.     // Sync scrolling between fake scrollbars and real scrollable
  8052.     // area, ensure viewport is updated when scrolling.
  8053.     on(d.scroller, "scroll", function () {
  8054.       if (d.scroller.clientHeight) {
  8055.         updateScrollTop(cm, d.scroller.scrollTop);
  8056.         setScrollLeft(cm, d.scroller.scrollLeft, true);
  8057.         signal(cm, "scroll", cm);
  8058.       }
  8059.     });
  8060.  
  8061.     // Listen to wheel events in order to try and update the viewport on time.
  8062.     on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  8063.     on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  8064.  
  8065.     // Prevent wrapper from ever scrolling
  8066.     on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  8067.  
  8068.     d.dragFunctions = {
  8069.       enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  8070.       over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  8071.       start: function (e) { return onDragStart(cm, e); },
  8072.       drop: operation(cm, onDrop),
  8073.       leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  8074.     };
  8075.  
  8076.     var inp = d.input.getField();
  8077.     on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  8078.     on(inp, "keydown", operation(cm, onKeyDown));
  8079.     on(inp, "keypress", operation(cm, onKeyPress));
  8080.     on(inp, "focus", function (e) { return onFocus(cm, e); });
  8081.     on(inp, "blur", function (e) { return onBlur(cm, e); });
  8082.   }
  8083.  
  8084.   var initHooks = [];
  8085.   CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
  8086.  
  8087.   // Indent the given line. The how parameter can be "smart",
  8088.   // "add"/null, "subtract", or "prev". When aggressive is false
  8089.   // (typically set to true for forced single-line indents), empty
  8090.   // lines are not indented, and places where the mode returns Pass
  8091.   // are left alone.
  8092.   function indentLine(cm, n, how, aggressive) {
  8093.     var doc = cm.doc, state;
  8094.     if (how == null) { how = "add"; }
  8095.     if (how == "smart") {
  8096.       // Fall back to "prev" when the mode doesn't have an indentation
  8097.       // method.
  8098.       if (!doc.mode.indent) { how = "prev"; }
  8099.       else { state = getContextBefore(cm, n).state; }
  8100.     }
  8101.  
  8102.     var tabSize = cm.options.tabSize;
  8103.     var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  8104.     if (line.stateAfter) { line.stateAfter = null; }
  8105.     var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  8106.     if (!aggressive && !/\S/.test(line.text)) {
  8107.       indentation = 0;
  8108.       how = "not";
  8109.     } else if (how == "smart") {
  8110.       indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  8111.       if (indentation == Pass || indentation > 150) {
  8112.         if (!aggressive) { return }
  8113.         how = "prev";
  8114.       }
  8115.     }
  8116.     if (how == "prev") {
  8117.       if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  8118.       else { indentation = 0; }
  8119.     } else if (how == "add") {
  8120.       indentation = curSpace + cm.options.indentUnit;
  8121.     } else if (how == "subtract") {
  8122.       indentation = curSpace - cm.options.indentUnit;
  8123.     } else if (typeof how == "number") {
  8124.       indentation = curSpace + how;
  8125.     }
  8126.     indentation = Math.max(0, indentation);
  8127.  
  8128.     var indentString = "", pos = 0;
  8129.     if (cm.options.indentWithTabs)
  8130.       { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  8131.     if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  8132.  
  8133.     if (indentString != curSpaceString) {
  8134.       replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  8135.       line.stateAfter = null;
  8136.       return true
  8137.     } else {
  8138.       // Ensure that, if the cursor was in the whitespace at the start
  8139.       // of the line, it is moved to the end of that space.
  8140.       for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  8141.         var range = doc.sel.ranges[i$1];
  8142.         if (range.head.line == n && range.head.ch < curSpaceString.length) {
  8143.           var pos$1 = Pos(n, curSpaceString.length);
  8144.           replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  8145.           break
  8146.         }
  8147.       }
  8148.     }
  8149.   }
  8150.  
  8151.   // This will be set to a {lineWise: bool, text: [string]} object, so
  8152.   // that, when pasting, we know what kind of selections the copied
  8153.   // text was made out of.
  8154.   var lastCopied = null;
  8155.  
  8156.   function setLastCopied(newLastCopied) {
  8157.     lastCopied = newLastCopied;
  8158.   }
  8159.  
  8160.   function applyTextInput(cm, inserted, deleted, sel, origin) {
  8161.     var doc = cm.doc;
  8162.     cm.display.shift = false;
  8163.     if (!sel) { sel = doc.sel; }
  8164.  
  8165.     var recent = +new Date - 200;
  8166.     var paste = origin == "paste" || cm.state.pasteIncoming > recent;
  8167.     var textLines = splitLinesAuto(inserted), multiPaste = null;
  8168.     // When pasting N lines into N selections, insert one line per selection
  8169.     if (paste && sel.ranges.length > 1) {
  8170.       if (lastCopied && lastCopied.text.join("\n") == inserted) {
  8171.         if (sel.ranges.length % lastCopied.text.length == 0) {
  8172.           multiPaste = [];
  8173.           for (var i = 0; i < lastCopied.text.length; i++)
  8174.             { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  8175.         }
  8176.       } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  8177.         multiPaste = map(textLines, function (l) { return [l]; });
  8178.       }
  8179.     }
  8180.  
  8181.     var updateInput = cm.curOp.updateInput;
  8182.     // Normal behavior is to insert the new text into every selection
  8183.     for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  8184.       var range = sel.ranges[i$1];
  8185.       var from = range.from(), to = range.to();
  8186.       if (range.empty()) {
  8187.         if (deleted && deleted > 0) // Handle deletion
  8188.           { from = Pos(from.line, from.ch - deleted); }
  8189.         else if (cm.state.overwrite && !paste) // Handle overwrite
  8190.           { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  8191.         else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
  8192.           { from = to = Pos(from.line, 0); }
  8193.       }
  8194.       var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  8195.                          origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
  8196.       makeChange(cm.doc, changeEvent);
  8197.       signalLater(cm, "inputRead", cm, changeEvent);
  8198.     }
  8199.     if (inserted && !paste)
  8200.       { triggerElectric(cm, inserted); }
  8201.  
  8202.     ensureCursorVisible(cm);
  8203.     if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
  8204.     cm.curOp.typing = true;
  8205.     cm.state.pasteIncoming = cm.state.cutIncoming = -1;
  8206.   }
  8207.  
  8208.   function handlePaste(e, cm) {
  8209.     var pasted = e.clipboardData && e.clipboardData.getData("Text");
  8210.     if (pasted) {
  8211.       e.preventDefault();
  8212.       if (!cm.isReadOnly() && !cm.options.disableInput && cm.hasFocus())
  8213.         { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  8214.       return true
  8215.     }
  8216.   }
  8217.  
  8218.   function triggerElectric(cm, inserted) {
  8219.     // When an 'electric' character is inserted, immediately trigger a reindent
  8220.     if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  8221.     var sel = cm.doc.sel;
  8222.  
  8223.     for (var i = sel.ranges.length - 1; i >= 0; i--) {
  8224.       var range = sel.ranges[i];
  8225.       if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
  8226.       var mode = cm.getModeAt(range.head);
  8227.       var indented = false;
  8228.       if (mode.electricChars) {
  8229.         for (var j = 0; j < mode.electricChars.length; j++)
  8230.           { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  8231.             indented = indentLine(cm, range.head.line, "smart");
  8232.             break
  8233.           } }
  8234.       } else if (mode.electricInput) {
  8235.         if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  8236.           { indented = indentLine(cm, range.head.line, "smart"); }
  8237.       }
  8238.       if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
  8239.     }
  8240.   }
  8241.  
  8242.   function copyableRanges(cm) {
  8243.     var text = [], ranges = [];
  8244.     for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  8245.       var line = cm.doc.sel.ranges[i].head.line;
  8246.       var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  8247.       ranges.push(lineRange);
  8248.       text.push(cm.getRange(lineRange.anchor, lineRange.head));
  8249.     }
  8250.     return {text: text, ranges: ranges}
  8251.   }
  8252.  
  8253.   function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
  8254.     field.setAttribute("autocorrect", autocorrect ? "" : "off");
  8255.     field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
  8256.     field.setAttribute("spellcheck", !!spellcheck);
  8257.   }
  8258.  
  8259.   function hiddenTextarea() {
  8260.     var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none");
  8261.     var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  8262.     // The textarea is kept positioned near the cursor to prevent the
  8263.     // fact that it'll be scrolled into view on input from scrolling
  8264.     // our fake cursor out of view. On webkit, when wrap=off, paste is
  8265.     // very slow. So make the area wide instead.
  8266.     if (webkit) { te.style.width = "1000px"; }
  8267.     else { te.setAttribute("wrap", "off"); }
  8268.     // If border: 0; -- iOS fails to open keyboard (issue #1287)
  8269.     if (ios) { te.style.border = "1px solid black"; }
  8270.     disableBrowserMagic(te);
  8271.     return div
  8272.   }
  8273.  
  8274.   // The publicly visible API. Note that methodOp(f) means
  8275.   // 'wrap f in an operation, performed on its `this` parameter'.
  8276.  
  8277.   // This is not the complete set of editor methods. Most of the
  8278.   // methods defined on the Doc type are also injected into
  8279.   // CodeMirror.prototype, for backwards compatibility and
  8280.   // convenience.
  8281.  
  8282.   function addEditorMethods(CodeMirror) {
  8283.     var optionHandlers = CodeMirror.optionHandlers;
  8284.  
  8285.     var helpers = CodeMirror.helpers = {};
  8286.  
  8287.     CodeMirror.prototype = {
  8288.       constructor: CodeMirror,
  8289.       focus: function(){window.focus(); this.display.input.focus();},
  8290.  
  8291.       setOption: function(option, value) {
  8292.         var options = this.options, old = options[option];
  8293.         if (options[option] == value && option != "mode") { return }
  8294.         options[option] = value;
  8295.         if (optionHandlers.hasOwnProperty(option))
  8296.           { operation(this, optionHandlers[option])(this, value, old); }
  8297.         signal(this, "optionChange", this, option);
  8298.       },
  8299.  
  8300.       getOption: function(option) {return this.options[option]},
  8301.       getDoc: function() {return this.doc},
  8302.  
  8303.       addKeyMap: function(map, bottom) {
  8304.         this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  8305.       },
  8306.       removeKeyMap: function(map) {
  8307.         var maps = this.state.keyMaps;
  8308.         for (var i = 0; i < maps.length; ++i)
  8309.           { if (maps[i] == map || maps[i].name == map) {
  8310.             maps.splice(i, 1);
  8311.             return true
  8312.           } }
  8313.       },
  8314.  
  8315.       addOverlay: methodOp(function(spec, options) {
  8316.         var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  8317.         if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  8318.         insertSorted(this.state.overlays,
  8319.                      {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  8320.                       priority: (options && options.priority) || 0},
  8321.                      function (overlay) { return overlay.priority; });
  8322.         this.state.modeGen++;
  8323.         regChange(this);
  8324.       }),
  8325.       removeOverlay: methodOp(function(spec) {
  8326.         var overlays = this.state.overlays;
  8327.         for (var i = 0; i < overlays.length; ++i) {
  8328.           var cur = overlays[i].modeSpec;
  8329.           if (cur == spec || typeof spec == "string" && cur.name == spec) {
  8330.             overlays.splice(i, 1);
  8331.             this.state.modeGen++;
  8332.             regChange(this);
  8333.             return
  8334.           }
  8335.         }
  8336.       }),
  8337.  
  8338.       indentLine: methodOp(function(n, dir, aggressive) {
  8339.         if (typeof dir != "string" && typeof dir != "number") {
  8340.           if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  8341.           else { dir = dir ? "add" : "subtract"; }
  8342.         }
  8343.         if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  8344.       }),
  8345.       indentSelection: methodOp(function(how) {
  8346.         var ranges = this.doc.sel.ranges, end = -1;
  8347.         for (var i = 0; i < ranges.length; i++) {
  8348.           var range = ranges[i];
  8349.           if (!range.empty()) {
  8350.             var from = range.from(), to = range.to();
  8351.             var start = Math.max(end, from.line);
  8352.             end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  8353.             for (var j = start; j < end; ++j)
  8354.               { indentLine(this, j, how); }
  8355.             var newRanges = this.doc.sel.ranges;
  8356.             if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  8357.               { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  8358.           } else if (range.head.line > end) {
  8359.             indentLine(this, range.head.line, how, true);
  8360.             end = range.head.line;
  8361.             if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
  8362.           }
  8363.         }
  8364.       }),
  8365.  
  8366.       // Fetch the parser token for a given character. Useful for hacks
  8367.       // that want to inspect the mode state (say, for completion).
  8368.       getTokenAt: function(pos, precise) {
  8369.         return takeToken(this, pos, precise)
  8370.       },
  8371.  
  8372.       getLineTokens: function(line, precise) {
  8373.         return takeToken(this, Pos(line), precise, true)
  8374.       },
  8375.  
  8376.       getTokenTypeAt: function(pos) {
  8377.         pos = clipPos(this.doc, pos);
  8378.         var styles = getLineStyles(this, getLine(this.doc, pos.line));
  8379.         var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  8380.         var type;
  8381.         if (ch == 0) { type = styles[2]; }
  8382.         else { for (;;) {
  8383.           var mid = (before + after) >> 1;
  8384.           if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  8385.           else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  8386.           else { type = styles[mid * 2 + 2]; break }
  8387.         } }
  8388.         var cut = type ? type.indexOf("overlay ") : -1;
  8389.         return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  8390.       },
  8391.  
  8392.       getModeAt: function(pos) {
  8393.         var mode = this.doc.mode;
  8394.         if (!mode.innerMode) { return mode }
  8395.         return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  8396.       },
  8397.  
  8398.       getHelper: function(pos, type) {
  8399.         return this.getHelpers(pos, type)[0]
  8400.       },
  8401.  
  8402.       getHelpers: function(pos, type) {
  8403.         var found = [];
  8404.         if (!helpers.hasOwnProperty(type)) { return found }
  8405.         var help = helpers[type], mode = this.getModeAt(pos);
  8406.         if (typeof mode[type] == "string") {
  8407.           if (help[mode[type]]) { found.push(help[mode[type]]); }
  8408.         } else if (mode[type]) {
  8409.           for (var i = 0; i < mode[type].length; i++) {
  8410.             var val = help[mode[type][i]];
  8411.             if (val) { found.push(val); }
  8412.           }
  8413.         } else if (mode.helperType && help[mode.helperType]) {
  8414.           found.push(help[mode.helperType]);
  8415.         } else if (help[mode.name]) {
  8416.           found.push(help[mode.name]);
  8417.         }
  8418.         for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  8419.           var cur = help._global[i$1];
  8420.           if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  8421.             { found.push(cur.val); }
  8422.         }
  8423.         return found
  8424.       },
  8425.  
  8426.       getStateAfter: function(line, precise) {
  8427.         var doc = this.doc;
  8428.         line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  8429.         return getContextBefore(this, line + 1, precise).state
  8430.       },
  8431.  
  8432.       cursorCoords: function(start, mode) {
  8433.         var pos, range = this.doc.sel.primary();
  8434.         if (start == null) { pos = range.head; }
  8435.         else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  8436.         else { pos = start ? range.from() : range.to(); }
  8437.         return cursorCoords(this, pos, mode || "page")
  8438.       },
  8439.  
  8440.       charCoords: function(pos, mode) {
  8441.         return charCoords(this, clipPos(this.doc, pos), mode || "page")
  8442.       },
  8443.  
  8444.       coordsChar: function(coords, mode) {
  8445.         coords = fromCoordSystem(this, coords, mode || "page");
  8446.         return coordsChar(this, coords.left, coords.top)
  8447.       },
  8448.  
  8449.       lineAtHeight: function(height, mode) {
  8450.         height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  8451.         return lineAtHeight(this.doc, height + this.display.viewOffset)
  8452.       },
  8453.       heightAtLine: function(line, mode, includeWidgets) {
  8454.         var end = false, lineObj;
  8455.         if (typeof line == "number") {
  8456.           var last = this.doc.first + this.doc.size - 1;
  8457.           if (line < this.doc.first) { line = this.doc.first; }
  8458.           else if (line > last) { line = last; end = true; }
  8459.           lineObj = getLine(this.doc, line);
  8460.         } else {
  8461.           lineObj = line;
  8462.         }
  8463.         return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  8464.           (end ? this.doc.height - heightAtLine(lineObj) : 0)
  8465.       },
  8466.  
  8467.       defaultTextHeight: function() { return textHeight(this.display) },
  8468.       defaultCharWidth: function() { return charWidth(this.display) },
  8469.  
  8470.       getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  8471.  
  8472.       addWidget: function(pos, node, scroll, vert, horiz) {
  8473.         var display = this.display;
  8474.         pos = cursorCoords(this, clipPos(this.doc, pos));
  8475.         var top = pos.bottom, left = pos.left;
  8476.         node.style.position = "absolute";
  8477.         node.setAttribute("cm-ignore-events", "true");
  8478.         this.display.input.setUneditable(node);
  8479.         display.sizer.appendChild(node);
  8480.         if (vert == "over") {
  8481.           top = pos.top;
  8482.         } else if (vert == "above" || vert == "near") {
  8483.           var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  8484.           hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  8485.           // Default to positioning above (if specified and possible); otherwise default to positioning below
  8486.           if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  8487.             { top = pos.top - node.offsetHeight; }
  8488.           else if (pos.bottom + node.offsetHeight <= vspace)
  8489.             { top = pos.bottom; }
  8490.           if (left + node.offsetWidth > hspace)
  8491.             { left = hspace - node.offsetWidth; }
  8492.         }
  8493.         node.style.top = top + "px";
  8494.         node.style.left = node.style.right = "";
  8495.         if (horiz == "right") {
  8496.           left = display.sizer.clientWidth - node.offsetWidth;
  8497.           node.style.right = "0px";
  8498.         } else {
  8499.           if (horiz == "left") { left = 0; }
  8500.           else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  8501.           node.style.left = left + "px";
  8502.         }
  8503.         if (scroll)
  8504.           { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  8505.       },
  8506.  
  8507.       triggerOnKeyDown: methodOp(onKeyDown),
  8508.       triggerOnKeyPress: methodOp(onKeyPress),
  8509.       triggerOnKeyUp: onKeyUp,
  8510.       triggerOnMouseDown: methodOp(onMouseDown),
  8511.  
  8512.       execCommand: function(cmd) {
  8513.         if (commands.hasOwnProperty(cmd))
  8514.           { return commands[cmd].call(null, this) }
  8515.       },
  8516.  
  8517.       triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  8518.  
  8519.       findPosH: function(from, amount, unit, visually) {
  8520.         var dir = 1;
  8521.         if (amount < 0) { dir = -1; amount = -amount; }
  8522.         var cur = clipPos(this.doc, from);
  8523.         for (var i = 0; i < amount; ++i) {
  8524.           cur = findPosH(this.doc, cur, dir, unit, visually);
  8525.           if (cur.hitSide) { break }
  8526.         }
  8527.         return cur
  8528.       },
  8529.  
  8530.       moveH: methodOp(function(dir, unit) {
  8531.         var this$1 = this;
  8532.  
  8533.         this.extendSelectionsBy(function (range) {
  8534.           if (this$1.display.shift || this$1.doc.extend || range.empty())
  8535.             { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
  8536.           else
  8537.             { return dir < 0 ? range.from() : range.to() }
  8538.         }, sel_move);
  8539.       }),
  8540.  
  8541.       deleteH: methodOp(function(dir, unit) {
  8542.         var sel = this.doc.sel, doc = this.doc;
  8543.         if (sel.somethingSelected())
  8544.           { doc.replaceSelection("", null, "+delete"); }
  8545.         else
  8546.           { deleteNearSelection(this, function (range) {
  8547.             var other = findPosH(doc, range.head, dir, unit, false);
  8548.             return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
  8549.           }); }
  8550.       }),
  8551.  
  8552.       findPosV: function(from, amount, unit, goalColumn) {
  8553.         var dir = 1, x = goalColumn;
  8554.         if (amount < 0) { dir = -1; amount = -amount; }
  8555.         var cur = clipPos(this.doc, from);
  8556.         for (var i = 0; i < amount; ++i) {
  8557.           var coords = cursorCoords(this, cur, "div");
  8558.           if (x == null) { x = coords.left; }
  8559.           else { coords.left = x; }
  8560.           cur = findPosV(this, coords, dir, unit);
  8561.           if (cur.hitSide) { break }
  8562.         }
  8563.         return cur
  8564.       },
  8565.  
  8566.       moveV: methodOp(function(dir, unit) {
  8567.         var this$1 = this;
  8568.  
  8569.         var doc = this.doc, goals = [];
  8570.         var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  8571.         doc.extendSelectionsBy(function (range) {
  8572.           if (collapse)
  8573.             { return dir < 0 ? range.from() : range.to() }
  8574.           var headPos = cursorCoords(this$1, range.head, "div");
  8575.           if (range.goalColumn != null) { headPos.left = range.goalColumn; }
  8576.           goals.push(headPos.left);
  8577.           var pos = findPosV(this$1, headPos, dir, unit);
  8578.           if (unit == "page" && range == doc.sel.primary())
  8579.             { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  8580.           return pos
  8581.         }, sel_move);
  8582.         if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  8583.           { doc.sel.ranges[i].goalColumn = goals[i]; } }
  8584.       }),
  8585.  
  8586.       // Find the word at the given position (as returned by coordsChar).
  8587.       findWordAt: function(pos) {
  8588.         var doc = this.doc, line = getLine(doc, pos.line).text;
  8589.         var start = pos.ch, end = pos.ch;
  8590.         if (line) {
  8591.           var helper = this.getHelper(pos, "wordChars");
  8592.           if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  8593.           var startChar = line.charAt(start);
  8594.           var check = isWordChar(startChar, helper)
  8595.             ? function (ch) { return isWordChar(ch, helper); }
  8596.             : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  8597.             : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  8598.           while (start > 0 && check(line.charAt(start - 1))) { --start; }
  8599.           while (end < line.length && check(line.charAt(end))) { ++end; }
  8600.         }
  8601.         return new Range(Pos(pos.line, start), Pos(pos.line, end))
  8602.       },
  8603.  
  8604.       toggleOverwrite: function(value) {
  8605.         if (value != null && value == this.state.overwrite) { return }
  8606.         if (this.state.overwrite = !this.state.overwrite)
  8607.           { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  8608.         else
  8609.           { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  8610.  
  8611.         signal(this, "overwriteToggle", this, this.state.overwrite);
  8612.       },
  8613.       hasFocus: function() { return this.display.input.getField() == activeElt() },
  8614.       isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  8615.  
  8616.       scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  8617.       getScrollInfo: function() {
  8618.         var scroller = this.display.scroller;
  8619.         return {left: scroller.scrollLeft, top: scroller.scrollTop,
  8620.                 height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  8621.                 width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  8622.                 clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  8623.       },
  8624.  
  8625.       scrollIntoView: methodOp(function(range, margin) {
  8626.         if (range == null) {
  8627.           range = {from: this.doc.sel.primary().head, to: null};
  8628.           if (margin == null) { margin = this.options.cursorScrollMargin; }
  8629.         } else if (typeof range == "number") {
  8630.           range = {from: Pos(range, 0), to: null};
  8631.         } else if (range.from == null) {
  8632.           range = {from: range, to: null};
  8633.         }
  8634.         if (!range.to) { range.to = range.from; }
  8635.         range.margin = margin || 0;
  8636.  
  8637.         if (range.from.line != null) {
  8638.           scrollToRange(this, range);
  8639.         } else {
  8640.           scrollToCoordsRange(this, range.from, range.to, range.margin);
  8641.         }
  8642.       }),
  8643.  
  8644.       setSize: methodOp(function(width, height) {
  8645.         var this$1 = this;
  8646.  
  8647.         var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  8648.         if (width != null) { this.display.wrapper.style.width = interpret(width); }
  8649.         if (height != null) { this.display.wrapper.style.height = interpret(height); }
  8650.         if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  8651.         var lineNo = this.display.viewFrom;
  8652.         this.doc.iter(lineNo, this.display.viewTo, function (line) {
  8653.           if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  8654.             { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
  8655.           ++lineNo;
  8656.         });
  8657.         this.curOp.forceUpdate = true;
  8658.         signal(this, "refresh", this);
  8659.       }),
  8660.  
  8661.       operation: function(f){return runInOp(this, f)},
  8662.       startOperation: function(){return startOperation(this)},
  8663.       endOperation: function(){return endOperation(this)},
  8664.  
  8665.       refresh: methodOp(function() {
  8666.         var oldHeight = this.display.cachedTextHeight;
  8667.         regChange(this);
  8668.         this.curOp.forceUpdate = true;
  8669.         clearCaches(this);
  8670.         scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  8671.         updateGutterSpace(this.display);
  8672.         if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
  8673.           { estimateLineHeights(this); }
  8674.         signal(this, "refresh", this);
  8675.       }),
  8676.  
  8677.       swapDoc: methodOp(function(doc) {
  8678.         var old = this.doc;
  8679.         old.cm = null;
  8680.         // Cancel the current text selection if any (#5821)
  8681.         if (this.state.selectingText) { this.state.selectingText(); }
  8682.         attachDoc(this, doc);
  8683.         clearCaches(this);
  8684.         this.display.input.reset();
  8685.         scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  8686.         this.curOp.forceScroll = true;
  8687.         signalLater(this, "swapDoc", this, old);
  8688.         return old
  8689.       }),
  8690.  
  8691.       phrase: function(phraseText) {
  8692.         var phrases = this.options.phrases;
  8693.         return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
  8694.       },
  8695.  
  8696.       getInputField: function(){return this.display.input.getField()},
  8697.       getWrapperElement: function(){return this.display.wrapper},
  8698.       getScrollerElement: function(){return this.display.scroller},
  8699.       getGutterElement: function(){return this.display.gutters}
  8700.     };
  8701.     eventMixin(CodeMirror);
  8702.  
  8703.     CodeMirror.registerHelper = function(type, name, value) {
  8704.       if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  8705.       helpers[type][name] = value;
  8706.     };
  8707.     CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  8708.       CodeMirror.registerHelper(type, name, value);
  8709.       helpers[type]._global.push({pred: predicate, val: value});
  8710.     };
  8711.   }
  8712.  
  8713.   // Used for horizontal relative motion. Dir is -1 or 1 (left or
  8714.   // right), unit can be "codepoint", "char", "column" (like char, but
  8715.   // doesn't cross line boundaries), "word" (across next word), or
  8716.   // "group" (to the start of next group of word or
  8717.   // non-word-non-whitespace chars). The visually param controls
  8718.   // whether, in right-to-left text, direction 1 means to move towards
  8719.   // the next index in the string, or towards the character to the right
  8720.   // of the current position. The resulting position will have a
  8721.   // hitSide=true property if it reached the end of the document.
  8722.   function findPosH(doc, pos, dir, unit, visually) {
  8723.     var oldPos = pos;
  8724.     var origDir = dir;
  8725.     var lineObj = getLine(doc, pos.line);
  8726.     var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
  8727.     function findNextLine() {
  8728.       var l = pos.line + lineDir;
  8729.       if (l < doc.first || l >= doc.first + doc.size) { return false }
  8730.       pos = new Pos(l, pos.ch, pos.sticky);
  8731.       return lineObj = getLine(doc, l)
  8732.     }
  8733.     function moveOnce(boundToLine) {
  8734.       var next;
  8735.       if (unit == "codepoint") {
  8736.         var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1));
  8737.         if (isNaN(ch)) {
  8738.           next = null;
  8739.         } else {
  8740.           var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF;
  8741.           next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
  8742.         }
  8743.       } else if (visually) {
  8744.         next = moveVisually(doc.cm, lineObj, pos, dir);
  8745.       } else {
  8746.         next = moveLogically(lineObj, pos, dir);
  8747.       }
  8748.       if (next == null) {
  8749.         if (!boundToLine && findNextLine())
  8750.           { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
  8751.         else
  8752.           { return false }
  8753.       } else {
  8754.         pos = next;
  8755.       }
  8756.       return true
  8757.     }
  8758.  
  8759.     if (unit == "char" || unit == "codepoint") {
  8760.       moveOnce();
  8761.     } else if (unit == "column") {
  8762.       moveOnce(true);
  8763.     } else if (unit == "word" || unit == "group") {
  8764.       var sawType = null, group = unit == "group";
  8765.       var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  8766.       for (var first = true;; first = false) {
  8767.         if (dir < 0 && !moveOnce(!first)) { break }
  8768.         var cur = lineObj.text.charAt(pos.ch) || "\n";
  8769.         var type = isWordChar(cur, helper) ? "w"
  8770.           : group && cur == "\n" ? "n"
  8771.           : !group || /\s/.test(cur) ? null
  8772.           : "p";
  8773.         if (group && !first && !type) { type = "s"; }
  8774.         if (sawType && sawType != type) {
  8775.           if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  8776.           break
  8777.         }
  8778.  
  8779.         if (type) { sawType = type; }
  8780.         if (dir > 0 && !moveOnce(!first)) { break }
  8781.       }
  8782.     }
  8783.     var result = skipAtomic(doc, pos, oldPos, origDir, true);
  8784.     if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  8785.     return result
  8786.   }
  8787.  
  8788.   // For relative vertical movement. Dir may be -1 or 1. Unit can be
  8789.   // "page" or "line". The resulting position will have a hitSide=true
  8790.   // property if it reached the end of the document.
  8791.   function findPosV(cm, pos, dir, unit) {
  8792.     var doc = cm.doc, x = pos.left, y;
  8793.     if (unit == "page") {
  8794.       var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  8795.       var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  8796.       y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  8797.  
  8798.     } else if (unit == "line") {
  8799.       y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  8800.     }
  8801.     var target;
  8802.     for (;;) {
  8803.       target = coordsChar(cm, x, y);
  8804.       if (!target.outside) { break }
  8805.       if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  8806.       y += dir * 5;
  8807.     }
  8808.     return target
  8809.   }
  8810.  
  8811.   // CONTENTEDITABLE INPUT STYLE
  8812.  
  8813.   var ContentEditableInput = function(cm) {
  8814.     this.cm = cm;
  8815.     this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  8816.     this.polling = new Delayed();
  8817.     this.composing = null;
  8818.     this.gracePeriod = false;
  8819.     this.readDOMTimeout = null;
  8820.   };
  8821.  
  8822.   ContentEditableInput.prototype.init = function (display) {
  8823.       var this$1 = this;
  8824.  
  8825.     var input = this, cm = input.cm;
  8826.     var div = input.div = display.lineDiv;
  8827.     div.contentEditable = true;
  8828.     disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
  8829.  
  8830.     function belongsToInput(e) {
  8831.       for (var t = e.target; t; t = t.parentNode) {
  8832.         if (t == div) { return true }
  8833.         if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
  8834.       }
  8835.       return false
  8836.     }
  8837.  
  8838.     on(div, "paste", function (e) {
  8839.       if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8840.       // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  8841.       if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  8842.     });
  8843.  
  8844.     on(div, "compositionstart", function (e) {
  8845.       this$1.composing = {data: e.data, done: false};
  8846.     });
  8847.     on(div, "compositionupdate", function (e) {
  8848.       if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  8849.     });
  8850.     on(div, "compositionend", function (e) {
  8851.       if (this$1.composing) {
  8852.         if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  8853.         this$1.composing.done = true;
  8854.       }
  8855.     });
  8856.  
  8857.     on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  8858.  
  8859.     on(div, "input", function () {
  8860.       if (!this$1.composing) { this$1.readFromDOMSoon(); }
  8861.     });
  8862.  
  8863.     function onCopyCut(e) {
  8864.       if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
  8865.       if (cm.somethingSelected()) {
  8866.         setLastCopied({lineWise: false, text: cm.getSelections()});
  8867.         if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  8868.       } else if (!cm.options.lineWiseCopyCut) {
  8869.         return
  8870.       } else {
  8871.         var ranges = copyableRanges(cm);
  8872.         setLastCopied({lineWise: true, text: ranges.text});
  8873.         if (e.type == "cut") {
  8874.           cm.operation(function () {
  8875.             cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  8876.             cm.replaceSelection("", null, "cut");
  8877.           });
  8878.         }
  8879.       }
  8880.       if (e.clipboardData) {
  8881.         e.clipboardData.clearData();
  8882.         var content = lastCopied.text.join("\n");
  8883.         // iOS exposes the clipboard API, but seems to discard content inserted into it
  8884.         e.clipboardData.setData("Text", content);
  8885.         if (e.clipboardData.getData("Text") == content) {
  8886.           e.preventDefault();
  8887.           return
  8888.         }
  8889.       }
  8890.       // Old-fashioned briefly-focus-a-textarea hack
  8891.       var kludge = hiddenTextarea(), te = kludge.firstChild;
  8892.       cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  8893.       te.value = lastCopied.text.join("\n");
  8894.       var hadFocus = activeElt();
  8895.       selectInput(te);
  8896.       setTimeout(function () {
  8897.         cm.display.lineSpace.removeChild(kludge);
  8898.         hadFocus.focus();
  8899.         if (hadFocus == div) { input.showPrimarySelection(); }
  8900.       }, 50);
  8901.     }
  8902.     on(div, "copy", onCopyCut);
  8903.     on(div, "cut", onCopyCut);
  8904.   };
  8905.  
  8906.   ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
  8907.     // Label for screenreaders, accessibility
  8908.     if(label) {
  8909.       this.div.setAttribute('aria-label', label);
  8910.     } else {
  8911.       this.div.removeAttribute('aria-label');
  8912.     }
  8913.   };
  8914.  
  8915.   ContentEditableInput.prototype.prepareSelection = function () {
  8916.     var result = prepareSelection(this.cm, false);
  8917.     result.focus = activeElt() == this.div;
  8918.     return result
  8919.   };
  8920.  
  8921.   ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  8922.     if (!info || !this.cm.display.view.length) { return }
  8923.     if (info.focus || takeFocus) { this.showPrimarySelection(); }
  8924.     this.showMultipleSelections(info);
  8925.   };
  8926.  
  8927.   ContentEditableInput.prototype.getSelection = function () {
  8928.     return this.cm.display.wrapper.ownerDocument.getSelection()
  8929.   };
  8930.  
  8931.   ContentEditableInput.prototype.showPrimarySelection = function () {
  8932.     var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  8933.     var from = prim.from(), to = prim.to();
  8934.  
  8935.     if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  8936.       sel.removeAllRanges();
  8937.       return
  8938.     }
  8939.  
  8940.     var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8941.     var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  8942.     if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  8943.         cmp(minPos(curAnchor, curFocus), from) == 0 &&
  8944.         cmp(maxPos(curAnchor, curFocus), to) == 0)
  8945.       { return }
  8946.  
  8947.     var view = cm.display.view;
  8948.     var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  8949.         {node: view[0].measure.map[2], offset: 0};
  8950.     var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  8951.     if (!end) {
  8952.       var measure = view[view.length - 1].measure;
  8953.       var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  8954.       end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  8955.     }
  8956.  
  8957.     if (!start || !end) {
  8958.       sel.removeAllRanges();
  8959.       return
  8960.     }
  8961.  
  8962.     var old = sel.rangeCount && sel.getRangeAt(0), rng;
  8963.     try { rng = range(start.node, start.offset, end.offset, end.node); }
  8964.     catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  8965.     if (rng) {
  8966.       if (!gecko && cm.state.focused) {
  8967.         sel.collapse(start.node, start.offset);
  8968.         if (!rng.collapsed) {
  8969.           sel.removeAllRanges();
  8970.           sel.addRange(rng);
  8971.         }
  8972.       } else {
  8973.         sel.removeAllRanges();
  8974.         sel.addRange(rng);
  8975.       }
  8976.       if (old && sel.anchorNode == null) { sel.addRange(old); }
  8977.       else if (gecko) { this.startGracePeriod(); }
  8978.     }
  8979.     this.rememberSelection();
  8980.   };
  8981.  
  8982.   ContentEditableInput.prototype.startGracePeriod = function () {
  8983.       var this$1 = this;
  8984.  
  8985.     clearTimeout(this.gracePeriod);
  8986.     this.gracePeriod = setTimeout(function () {
  8987.       this$1.gracePeriod = false;
  8988.       if (this$1.selectionChanged())
  8989.         { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  8990.     }, 20);
  8991.   };
  8992.  
  8993.   ContentEditableInput.prototype.showMultipleSelections = function (info) {
  8994.     removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  8995.     removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  8996.   };
  8997.  
  8998.   ContentEditableInput.prototype.rememberSelection = function () {
  8999.     var sel = this.getSelection();
  9000.     this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  9001.     this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  9002.   };
  9003.  
  9004.   ContentEditableInput.prototype.selectionInEditor = function () {
  9005.     var sel = this.getSelection();
  9006.     if (!sel.rangeCount) { return false }
  9007.     var node = sel.getRangeAt(0).commonAncestorContainer;
  9008.     return contains(this.div, node)
  9009.   };
  9010.  
  9011.   ContentEditableInput.prototype.focus = function () {
  9012.     if (this.cm.options.readOnly != "nocursor") {
  9013.       if (!this.selectionInEditor() || activeElt() != this.div)
  9014.         { this.showSelection(this.prepareSelection(), true); }
  9015.       this.div.focus();
  9016.     }
  9017.   };
  9018.   ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  9019.   ContentEditableInput.prototype.getField = function () { return this.div };
  9020.  
  9021.   ContentEditableInput.prototype.supportsTouch = function () { return true };
  9022.  
  9023.   ContentEditableInput.prototype.receivedFocus = function () {
  9024.       var this$1 = this;
  9025.  
  9026.     var input = this;
  9027.     if (this.selectionInEditor())
  9028.       { setTimeout(function () { return this$1.pollSelection(); }, 20); }
  9029.     else
  9030.       { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  9031.  
  9032.     function poll() {
  9033.       if (input.cm.state.focused) {
  9034.         input.pollSelection();
  9035.         input.polling.set(input.cm.options.pollInterval, poll);
  9036.       }
  9037.     }
  9038.     this.polling.set(this.cm.options.pollInterval, poll);
  9039.   };
  9040.  
  9041.   ContentEditableInput.prototype.selectionChanged = function () {
  9042.     var sel = this.getSelection();
  9043.     return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  9044.       sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  9045.   };
  9046.  
  9047.   ContentEditableInput.prototype.pollSelection = function () {
  9048.     if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  9049.     var sel = this.getSelection(), cm = this.cm;
  9050.     // On Android Chrome (version 56, at least), backspacing into an
  9051.     // uneditable block element will put the cursor in that element,
  9052.     // and then, because it's not editable, hide the virtual keyboard.
  9053.     // Because Android doesn't allow us to actually detect backspace
  9054.     // presses in a sane way, this code checks for when that happens
  9055.     // and simulates a backspace press in this case.
  9056.     if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
  9057.       this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  9058.       this.blur();
  9059.       this.focus();
  9060.       return
  9061.     }
  9062.     if (this.composing) { return }
  9063.     this.rememberSelection();
  9064.     var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  9065.     var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  9066.     if (anchor && head) { runInOp(cm, function () {
  9067.       setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  9068.       if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  9069.     }); }
  9070.   };
  9071.  
  9072.   ContentEditableInput.prototype.pollContent = function () {
  9073.     if (this.readDOMTimeout != null) {
  9074.       clearTimeout(this.readDOMTimeout);
  9075.       this.readDOMTimeout = null;
  9076.     }
  9077.  
  9078.     var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  9079.     var from = sel.from(), to = sel.to();
  9080.     if (from.ch == 0 && from.line > cm.firstLine())
  9081.       { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  9082.     if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  9083.       { to = Pos(to.line + 1, 0); }
  9084.     if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  9085.  
  9086.     var fromIndex, fromLine, fromNode;
  9087.     if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  9088.       fromLine = lineNo(display.view[0].line);
  9089.       fromNode = display.view[0].node;
  9090.     } else {
  9091.       fromLine = lineNo(display.view[fromIndex].line);
  9092.       fromNode = display.view[fromIndex - 1].node.nextSibling;
  9093.     }
  9094.     var toIndex = findViewIndex(cm, to.line);
  9095.     var toLine, toNode;
  9096.     if (toIndex == display.view.length - 1) {
  9097.       toLine = display.viewTo - 1;
  9098.       toNode = display.lineDiv.lastChild;
  9099.     } else {
  9100.       toLine = lineNo(display.view[toIndex + 1].line) - 1;
  9101.       toNode = display.view[toIndex + 1].node.previousSibling;
  9102.     }
  9103.  
  9104.     if (!fromNode) { return false }
  9105.     var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  9106.     var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  9107.     while (newText.length > 1 && oldText.length > 1) {
  9108.       if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  9109.       else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  9110.       else { break }
  9111.     }
  9112.  
  9113.     var cutFront = 0, cutEnd = 0;
  9114.     var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  9115.     while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  9116.       { ++cutFront; }
  9117.     var newBot = lst(newText), oldBot = lst(oldText);
  9118.     var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  9119.                              oldBot.length - (oldText.length == 1 ? cutFront : 0));
  9120.     while (cutEnd < maxCutEnd &&
  9121.            newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  9122.       { ++cutEnd; }
  9123.     // Try to move start of change to start of selection if ambiguous
  9124.     if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  9125.       while (cutFront && cutFront > from.ch &&
  9126.              newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  9127.         cutFront--;
  9128.         cutEnd++;
  9129.       }
  9130.     }
  9131.  
  9132.     newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  9133.     newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  9134.  
  9135.     var chFrom = Pos(fromLine, cutFront);
  9136.     var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  9137.     if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  9138.       replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  9139.       return true
  9140.     }
  9141.   };
  9142.  
  9143.   ContentEditableInput.prototype.ensurePolled = function () {
  9144.     this.forceCompositionEnd();
  9145.   };
  9146.   ContentEditableInput.prototype.reset = function () {
  9147.     this.forceCompositionEnd();
  9148.   };
  9149.   ContentEditableInput.prototype.forceCompositionEnd = function () {
  9150.     if (!this.composing) { return }
  9151.     clearTimeout(this.readDOMTimeout);
  9152.     this.composing = null;
  9153.     this.updateFromDOM();
  9154.     this.div.blur();
  9155.     this.div.focus();
  9156.   };
  9157.   ContentEditableInput.prototype.readFromDOMSoon = function () {
  9158.       var this$1 = this;
  9159.  
  9160.     if (this.readDOMTimeout != null) { return }
  9161.     this.readDOMTimeout = setTimeout(function () {
  9162.       this$1.readDOMTimeout = null;
  9163.       if (this$1.composing) {
  9164.         if (this$1.composing.done) { this$1.composing = null; }
  9165.         else { return }
  9166.       }
  9167.       this$1.updateFromDOM();
  9168.     }, 80);
  9169.   };
  9170.  
  9171.   ContentEditableInput.prototype.updateFromDOM = function () {
  9172.       var this$1 = this;
  9173.  
  9174.     if (this.cm.isReadOnly() || !this.pollContent())
  9175.       { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  9176.   };
  9177.  
  9178.   ContentEditableInput.prototype.setUneditable = function (node) {
  9179.     node.contentEditable = "false";
  9180.   };
  9181.  
  9182.   ContentEditableInput.prototype.onKeyPress = function (e) {
  9183.     if (e.charCode == 0 || this.composing) { return }
  9184.     e.preventDefault();
  9185.     if (!this.cm.isReadOnly())
  9186.       { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  9187.   };
  9188.  
  9189.   ContentEditableInput.prototype.readOnlyChanged = function (val) {
  9190.     this.div.contentEditable = String(val != "nocursor");
  9191.   };
  9192.  
  9193.   ContentEditableInput.prototype.onContextMenu = function () {};
  9194.   ContentEditableInput.prototype.resetPosition = function () {};
  9195.  
  9196.   ContentEditableInput.prototype.needsContentAttribute = true;
  9197.  
  9198.   function posToDOM(cm, pos) {
  9199.     var view = findViewForLine(cm, pos.line);
  9200.     if (!view || view.hidden) { return null }
  9201.     var line = getLine(cm.doc, pos.line);
  9202.     var info = mapFromLineView(view, line, pos.line);
  9203.  
  9204.     var order = getOrder(line, cm.doc.direction), side = "left";
  9205.     if (order) {
  9206.       var partPos = getBidiPartAt(order, pos.ch);
  9207.       side = partPos % 2 ? "right" : "left";
  9208.     }
  9209.     var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  9210.     result.offset = result.collapse == "right" ? result.end : result.start;
  9211.     return result
  9212.   }
  9213.  
  9214.   function isInGutter(node) {
  9215.     for (var scan = node; scan; scan = scan.parentNode)
  9216.       { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  9217.     return false
  9218.   }
  9219.  
  9220.   function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  9221.  
  9222.   function domTextBetween(cm, from, to, fromLine, toLine) {
  9223.     var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
  9224.     function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  9225.     function close() {
  9226.       if (closing) {
  9227.         text += lineSep;
  9228.         if (extraLinebreak) { text += lineSep; }
  9229.         closing = extraLinebreak = false;
  9230.       }
  9231.     }
  9232.     function addText(str) {
  9233.       if (str) {
  9234.         close();
  9235.         text += str;
  9236.       }
  9237.     }
  9238.     function walk(node) {
  9239.       if (node.nodeType == 1) {
  9240.         var cmText = node.getAttribute("cm-text");
  9241.         if (cmText) {
  9242.           addText(cmText);
  9243.           return
  9244.         }
  9245.         var markerID = node.getAttribute("cm-marker"), range;
  9246.         if (markerID) {
  9247.           var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  9248.           if (found.length && (range = found[0].find(0)))
  9249.             { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
  9250.           return
  9251.         }
  9252.         if (node.getAttribute("contenteditable") == "false") { return }
  9253.         var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
  9254.         if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
  9255.  
  9256.         if (isBlock) { close(); }
  9257.         for (var i = 0; i < node.childNodes.length; i++)
  9258.           { walk(node.childNodes[i]); }
  9259.  
  9260.         if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
  9261.         if (isBlock) { closing = true; }
  9262.       } else if (node.nodeType == 3) {
  9263.         addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
  9264.       }
  9265.     }
  9266.     for (;;) {
  9267.       walk(from);
  9268.       if (from == to) { break }
  9269.       from = from.nextSibling;
  9270.       extraLinebreak = false;
  9271.     }
  9272.     return text
  9273.   }
  9274.  
  9275.   function domToPos(cm, node, offset) {
  9276.     var lineNode;
  9277.     if (node == cm.display.lineDiv) {
  9278.       lineNode = cm.display.lineDiv.childNodes[offset];
  9279.       if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  9280.       node = null; offset = 0;
  9281.     } else {
  9282.       for (lineNode = node;; lineNode = lineNode.parentNode) {
  9283.         if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  9284.         if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  9285.       }
  9286.     }
  9287.     for (var i = 0; i < cm.display.view.length; i++) {
  9288.       var lineView = cm.display.view[i];
  9289.       if (lineView.node == lineNode)
  9290.         { return locateNodeInLineView(lineView, node, offset) }
  9291.     }
  9292.   }
  9293.  
  9294.   function locateNodeInLineView(lineView, node, offset) {
  9295.     var wrapper = lineView.text.firstChild, bad = false;
  9296.     if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  9297.     if (node == wrapper) {
  9298.       bad = true;
  9299.       node = wrapper.childNodes[offset];
  9300.       offset = 0;
  9301.       if (!node) {
  9302.         var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  9303.         return badPos(Pos(lineNo(line), line.text.length), bad)
  9304.       }
  9305.     }
  9306.  
  9307.     var textNode = node.nodeType == 3 ? node : null, topNode = node;
  9308.     if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  9309.       textNode = node.firstChild;
  9310.       if (offset) { offset = textNode.nodeValue.length; }
  9311.     }
  9312.     while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  9313.     var measure = lineView.measure, maps = measure.maps;
  9314.  
  9315.     function find(textNode, topNode, offset) {
  9316.       for (var i = -1; i < (maps ? maps.length : 0); i++) {
  9317.         var map = i < 0 ? measure.map : maps[i];
  9318.         for (var j = 0; j < map.length; j += 3) {
  9319.           var curNode = map[j + 2];
  9320.           if (curNode == textNode || curNode == topNode) {
  9321.             var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  9322.             var ch = map[j] + offset;
  9323.             if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
  9324.             return Pos(line, ch)
  9325.           }
  9326.         }
  9327.       }
  9328.     }
  9329.     var found = find(textNode, topNode, offset);
  9330.     if (found) { return badPos(found, bad) }
  9331.  
  9332.     // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  9333.     for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  9334.       found = find(after, after.firstChild, 0);
  9335.       if (found)
  9336.         { return badPos(Pos(found.line, found.ch - dist), bad) }
  9337.       else
  9338.         { dist += after.textContent.length; }
  9339.     }
  9340.     for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  9341.       found = find(before, before.firstChild, -1);
  9342.       if (found)
  9343.         { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  9344.       else
  9345.         { dist$1 += before.textContent.length; }
  9346.     }
  9347.   }
  9348.  
  9349.   // TEXTAREA INPUT STYLE
  9350.  
  9351.   var TextareaInput = function(cm) {
  9352.     this.cm = cm;
  9353.     // See input.poll and input.reset
  9354.     this.prevInput = "";
  9355.  
  9356.     // Flag that indicates whether we expect input to appear real soon
  9357.     // now (after some event like 'keypress' or 'input') and are
  9358.     // polling intensively.
  9359.     this.pollingFast = false;
  9360.     // Self-resetting timeout for the poller
  9361.     this.polling = new Delayed();
  9362.     // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  9363.     this.hasSelection = false;
  9364.     this.composing = null;
  9365.   };
  9366.  
  9367.   TextareaInput.prototype.init = function (display) {
  9368.       var this$1 = this;
  9369.  
  9370.     var input = this, cm = this.cm;
  9371.     this.createField(display);
  9372.     var te = this.textarea;
  9373.  
  9374.     display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
  9375.  
  9376.     // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  9377.     if (ios) { te.style.width = "0px"; }
  9378.  
  9379.     on(te, "input", function () {
  9380.       if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  9381.       input.poll();
  9382.     });
  9383.  
  9384.     on(te, "paste", function (e) {
  9385.       if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  9386.  
  9387.       cm.state.pasteIncoming = +new Date;
  9388.       input.fastPoll();
  9389.     });
  9390.  
  9391.     function prepareCopyCut(e) {
  9392.       if (signalDOMEvent(cm, e)) { return }
  9393.       if (cm.somethingSelected()) {
  9394.         setLastCopied({lineWise: false, text: cm.getSelections()});
  9395.       } else if (!cm.options.lineWiseCopyCut) {
  9396.         return
  9397.       } else {
  9398.         var ranges = copyableRanges(cm);
  9399.         setLastCopied({lineWise: true, text: ranges.text});
  9400.         if (e.type == "cut") {
  9401.           cm.setSelections(ranges.ranges, null, sel_dontScroll);
  9402.         } else {
  9403.           input.prevInput = "";
  9404.           te.value = ranges.text.join("\n");
  9405.           selectInput(te);
  9406.         }
  9407.       }
  9408.       if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
  9409.     }
  9410.     on(te, "cut", prepareCopyCut);
  9411.     on(te, "copy", prepareCopyCut);
  9412.  
  9413.     on(display.scroller, "paste", function (e) {
  9414.       if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  9415.       if (!te.dispatchEvent) {
  9416.         cm.state.pasteIncoming = +new Date;
  9417.         input.focus();
  9418.         return
  9419.       }
  9420.  
  9421.       // Pass the `paste` event to the textarea so it's handled by its event listener.
  9422.       var event = new Event("paste");
  9423.       event.clipboardData = e.clipboardData;
  9424.       te.dispatchEvent(event);
  9425.     });
  9426.  
  9427.     // Prevent normal selection in the editor (we handle our own)
  9428.     on(display.lineSpace, "selectstart", function (e) {
  9429.       if (!eventInWidget(display, e)) { e_preventDefault(e); }
  9430.     });
  9431.  
  9432.     on(te, "compositionstart", function () {
  9433.       var start = cm.getCursor("from");
  9434.       if (input.composing) { input.composing.range.clear(); }
  9435.       input.composing = {
  9436.         start: start,
  9437.         range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  9438.       };
  9439.     });
  9440.     on(te, "compositionend", function () {
  9441.       if (input.composing) {
  9442.         input.poll();
  9443.         input.composing.range.clear();
  9444.         input.composing = null;
  9445.       }
  9446.     });
  9447.   };
  9448.  
  9449.   TextareaInput.prototype.createField = function (_display) {
  9450.     // Wraps and hides input textarea
  9451.     this.wrapper = hiddenTextarea();
  9452.     // The semihidden textarea that is focused when the editor is
  9453.     // focused, and receives input.
  9454.     this.textarea = this.wrapper.firstChild;
  9455.   };
  9456.  
  9457.   TextareaInput.prototype.screenReaderLabelChanged = function (label) {
  9458.     // Label for screenreaders, accessibility
  9459.     if(label) {
  9460.       this.textarea.setAttribute('aria-label', label);
  9461.     } else {
  9462.       this.textarea.removeAttribute('aria-label');
  9463.     }
  9464.   };
  9465.  
  9466.   TextareaInput.prototype.prepareSelection = function () {
  9467.     // Redraw the selection and/or cursor
  9468.     var cm = this.cm, display = cm.display, doc = cm.doc;
  9469.     var result = prepareSelection(cm);
  9470.  
  9471.     // Move the hidden textarea near the cursor to prevent scrolling artifacts
  9472.     if (cm.options.moveInputWithCursor) {
  9473.       var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  9474.       var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  9475.       result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  9476.                                           headPos.top + lineOff.top - wrapOff.top));
  9477.       result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  9478.                                            headPos.left + lineOff.left - wrapOff.left));
  9479.     }
  9480.  
  9481.     return result
  9482.   };
  9483.  
  9484.   TextareaInput.prototype.showSelection = function (drawn) {
  9485.     var cm = this.cm, display = cm.display;
  9486.     removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  9487.     removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  9488.     if (drawn.teTop != null) {
  9489.       this.wrapper.style.top = drawn.teTop + "px";
  9490.       this.wrapper.style.left = drawn.teLeft + "px";
  9491.     }
  9492.   };
  9493.  
  9494.   // Reset the input to correspond to the selection (or to be empty,
  9495.   // when not typing and nothing is selected)
  9496.   TextareaInput.prototype.reset = function (typing) {
  9497.     if (this.contextMenuPending || this.composing) { return }
  9498.     var cm = this.cm;
  9499.     if (cm.somethingSelected()) {
  9500.       this.prevInput = "";
  9501.       var content = cm.getSelection();
  9502.       this.textarea.value = content;
  9503.       if (cm.state.focused) { selectInput(this.textarea); }
  9504.       if (ie && ie_version >= 9) { this.hasSelection = content; }
  9505.     } else if (!typing) {
  9506.       this.prevInput = this.textarea.value = "";
  9507.       if (ie && ie_version >= 9) { this.hasSelection = null; }
  9508.     }
  9509.   };
  9510.  
  9511.   TextareaInput.prototype.getField = function () { return this.textarea };
  9512.  
  9513.   TextareaInput.prototype.supportsTouch = function () { return false };
  9514.  
  9515.   TextareaInput.prototype.focus = function () {
  9516.     if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  9517.       try { this.textarea.focus(); }
  9518.       catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  9519.     }
  9520.   };
  9521.  
  9522.   TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  9523.  
  9524.   TextareaInput.prototype.resetPosition = function () {
  9525.     this.wrapper.style.top = this.wrapper.style.left = 0;
  9526.   };
  9527.  
  9528.   TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  9529.  
  9530.   // Poll for input changes, using the normal rate of polling. This
  9531.   // runs as long as the editor is focused.
  9532.   TextareaInput.prototype.slowPoll = function () {
  9533.       var this$1 = this;
  9534.  
  9535.     if (this.pollingFast) { return }
  9536.     this.polling.set(this.cm.options.pollInterval, function () {
  9537.       this$1.poll();
  9538.       if (this$1.cm.state.focused) { this$1.slowPoll(); }
  9539.     });
  9540.   };
  9541.  
  9542.   // When an event has just come in that is likely to add or change
  9543.   // something in the input textarea, we poll faster, to ensure that
  9544.   // the change appears on the screen quickly.
  9545.   TextareaInput.prototype.fastPoll = function () {
  9546.     var missed = false, input = this;
  9547.     input.pollingFast = true;
  9548.     function p() {
  9549.       var changed = input.poll();
  9550.       if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  9551.       else {input.pollingFast = false; input.slowPoll();}
  9552.     }
  9553.     input.polling.set(20, p);
  9554.   };
  9555.  
  9556.   // Read input from the textarea, and update the document to match.
  9557.   // When something is selected, it is present in the textarea, and
  9558.   // selected (unless it is huge, in which case a placeholder is
  9559.   // used). When nothing is selected, the cursor sits after previously
  9560.   // seen text (can be empty), which is stored in prevInput (we must
  9561.   // not reset the textarea when typing, because that breaks IME).
  9562.   TextareaInput.prototype.poll = function () {
  9563.       var this$1 = this;
  9564.  
  9565.     var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  9566.     // Since this is called a *lot*, try to bail out as cheaply as
  9567.     // possible when it is clear that nothing happened. hasSelection
  9568.     // will be the case when there is a lot of text in the textarea,
  9569.     // in which case reading its value would be expensive.
  9570.     if (this.contextMenuPending || !cm.state.focused ||
  9571.         (hasSelection(input) && !prevInput && !this.composing) ||
  9572.         cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  9573.       { return false }
  9574.  
  9575.     var text = input.value;
  9576.     // If nothing changed, bail.
  9577.     if (text == prevInput && !cm.somethingSelected()) { return false }
  9578.     // Work around nonsensical selection resetting in IE9/10, and
  9579.     // inexplicable appearance of private area unicode characters on
  9580.     // some key combos in Mac (#2689).
  9581.     if (ie && ie_version >= 9 && this.hasSelection === text ||
  9582.         mac && /[\uf700-\uf7ff]/.test(text)) {
  9583.       cm.display.input.reset();
  9584.       return false
  9585.     }
  9586.  
  9587.     if (cm.doc.sel == cm.display.selForContextMenu) {
  9588.       var first = text.charCodeAt(0);
  9589.       if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  9590.       if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  9591.     }
  9592.     // Find the part of the input that is actually new
  9593.     var same = 0, l = Math.min(prevInput.length, text.length);
  9594.     while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  9595.  
  9596.     runInOp(cm, function () {
  9597.       applyTextInput(cm, text.slice(same), prevInput.length - same,
  9598.                      null, this$1.composing ? "*compose" : null);
  9599.  
  9600.       // Don't leave long text in the textarea, since it makes further polling slow
  9601.       if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  9602.       else { this$1.prevInput = text; }
  9603.  
  9604.       if (this$1.composing) {
  9605.         this$1.composing.range.clear();
  9606.         this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  9607.                                            {className: "CodeMirror-composing"});
  9608.       }
  9609.     });
  9610.     return true
  9611.   };
  9612.  
  9613.   TextareaInput.prototype.ensurePolled = function () {
  9614.     if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  9615.   };
  9616.  
  9617.   TextareaInput.prototype.onKeyPress = function () {
  9618.     if (ie && ie_version >= 9) { this.hasSelection = null; }
  9619.     this.fastPoll();
  9620.   };
  9621.  
  9622.   TextareaInput.prototype.onContextMenu = function (e) {
  9623.     var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  9624.     if (input.contextMenuPending) { input.contextMenuPending(); }
  9625.     var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  9626.     if (!pos || presto) { return } // Opera is difficult.
  9627.  
  9628.     // Reset the current text selection only if the click is done outside of the selection
  9629.     // and 'resetSelectionOnContextMenu' option is true.
  9630.     var reset = cm.options.resetSelectionOnContextMenu;
  9631.     if (reset && cm.doc.sel.contains(pos) == -1)
  9632.       { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  9633.  
  9634.     var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  9635.     var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
  9636.     input.wrapper.style.cssText = "position: static";
  9637.     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);";
  9638.     var oldScrollY;
  9639.     if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
  9640.     display.input.focus();
  9641.     if (webkit) { window.scrollTo(null, oldScrollY); }
  9642.     display.input.reset();
  9643.     // Adds "Select all" to context menu in FF
  9644.     if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  9645.     input.contextMenuPending = rehide;
  9646.     display.selForContextMenu = cm.doc.sel;
  9647.     clearTimeout(display.detectingSelectAll);
  9648.  
  9649.     // Select-all will be greyed out if there's nothing to select, so
  9650.     // this adds a zero-width space so that we can later check whether
  9651.     // it got selected.
  9652.     function prepareSelectAllHack() {
  9653.       if (te.selectionStart != null) {
  9654.         var selected = cm.somethingSelected();
  9655.         var extval = "\u200b" + (selected ? te.value : "");
  9656.         te.value = "\u21da"; // Used to catch context-menu undo
  9657.         te.value = extval;
  9658.         input.prevInput = selected ? "" : "\u200b";
  9659.         te.selectionStart = 1; te.selectionEnd = extval.length;
  9660.         // Re-set this, in case some other handler touched the
  9661.         // selection in the meantime.
  9662.         display.selForContextMenu = cm.doc.sel;
  9663.       }
  9664.     }
  9665.     function rehide() {
  9666.       if (input.contextMenuPending != rehide) { return }
  9667.       input.contextMenuPending = false;
  9668.       input.wrapper.style.cssText = oldWrapperCSS;
  9669.       te.style.cssText = oldCSS;
  9670.       if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  9671.  
  9672.       // Try to detect the user choosing select-all
  9673.       if (te.selectionStart != null) {
  9674.         if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  9675.         var i = 0, poll = function () {
  9676.           if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  9677.               te.selectionEnd > 0 && input.prevInput == "\u200b") {
  9678.             operation(cm, selectAll)(cm);
  9679.           } else if (i++ < 10) {
  9680.             display.detectingSelectAll = setTimeout(poll, 500);
  9681.           } else {
  9682.             display.selForContextMenu = null;
  9683.             display.input.reset();
  9684.           }
  9685.         };
  9686.         display.detectingSelectAll = setTimeout(poll, 200);
  9687.       }
  9688.     }
  9689.  
  9690.     if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  9691.     if (captureRightClick) {
  9692.       e_stop(e);
  9693.       var mouseup = function () {
  9694.         off(window, "mouseup", mouseup);
  9695.         setTimeout(rehide, 20);
  9696.       };
  9697.       on(window, "mouseup", mouseup);
  9698.     } else {
  9699.       setTimeout(rehide, 50);
  9700.     }
  9701.   };
  9702.  
  9703.   TextareaInput.prototype.readOnlyChanged = function (val) {
  9704.     if (!val) { this.reset(); }
  9705.     this.textarea.disabled = val == "nocursor";
  9706.     this.textarea.readOnly = !!val;
  9707.   };
  9708.  
  9709.   TextareaInput.prototype.setUneditable = function () {};
  9710.  
  9711.   TextareaInput.prototype.needsContentAttribute = false;
  9712.  
  9713.   function fromTextArea(textarea, options) {
  9714.     options = options ? copyObj(options) : {};
  9715.     options.value = textarea.value;
  9716.     if (!options.tabindex && textarea.tabIndex)
  9717.       { options.tabindex = textarea.tabIndex; }
  9718.     if (!options.placeholder && textarea.placeholder)
  9719.       { options.placeholder = textarea.placeholder; }
  9720.     // Set autofocus to true if this textarea is focused, or if it has
  9721.     // autofocus and no other element is focused.
  9722.     if (options.autofocus == null) {
  9723.       var hasFocus = activeElt();
  9724.       options.autofocus = hasFocus == textarea ||
  9725.         textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  9726.     }
  9727.  
  9728.     function save() {textarea.value = cm.getValue();}
  9729.  
  9730.     var realSubmit;
  9731.     if (textarea.form) {
  9732.       on(textarea.form, "submit", save);
  9733.       // Deplorable hack to make the submit method do the right thing.
  9734.       if (!options.leaveSubmitMethodAlone) {
  9735.         var form = textarea.form;
  9736.         realSubmit = form.submit;
  9737.         try {
  9738.           var wrappedSubmit = form.submit = function () {
  9739.             save();
  9740.             form.submit = realSubmit;
  9741.             form.submit();
  9742.             form.submit = wrappedSubmit;
  9743.           };
  9744.         } catch(e) {}
  9745.       }
  9746.     }
  9747.  
  9748.     options.finishInit = function (cm) {
  9749.       cm.save = save;
  9750.       cm.getTextArea = function () { return textarea; };
  9751.       cm.toTextArea = function () {
  9752.         cm.toTextArea = isNaN; // Prevent this from being ran twice
  9753.         save();
  9754.         textarea.parentNode.removeChild(cm.getWrapperElement());
  9755.         textarea.style.display = "";
  9756.         if (textarea.form) {
  9757.           off(textarea.form, "submit", save);
  9758.           if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
  9759.             { textarea.form.submit = realSubmit; }
  9760.         }
  9761.       };
  9762.     };
  9763.  
  9764.     textarea.style.display = "none";
  9765.     var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  9766.       options);
  9767.     return cm
  9768.   }
  9769.  
  9770.   function addLegacyProps(CodeMirror) {
  9771.     CodeMirror.off = off;
  9772.     CodeMirror.on = on;
  9773.     CodeMirror.wheelEventPixels = wheelEventPixels;
  9774.     CodeMirror.Doc = Doc;
  9775.     CodeMirror.splitLines = splitLinesAuto;
  9776.     CodeMirror.countColumn = countColumn;
  9777.     CodeMirror.findColumn = findColumn;
  9778.     CodeMirror.isWordChar = isWordCharBasic;
  9779.     CodeMirror.Pass = Pass;
  9780.     CodeMirror.signal = signal;
  9781.     CodeMirror.Line = Line;
  9782.     CodeMirror.changeEnd = changeEnd;
  9783.     CodeMirror.scrollbarModel = scrollbarModel;
  9784.     CodeMirror.Pos = Pos;
  9785.     CodeMirror.cmpPos = cmp;
  9786.     CodeMirror.modes = modes;
  9787.     CodeMirror.mimeModes = mimeModes;
  9788.     CodeMirror.resolveMode = resolveMode;
  9789.     CodeMirror.getMode = getMode;
  9790.     CodeMirror.modeExtensions = modeExtensions;
  9791.     CodeMirror.extendMode = extendMode;
  9792.     CodeMirror.copyState = copyState;
  9793.     CodeMirror.startState = startState;
  9794.     CodeMirror.innerMode = innerMode;
  9795.     CodeMirror.commands = commands;
  9796.     CodeMirror.keyMap = keyMap;
  9797.     CodeMirror.keyName = keyName;
  9798.     CodeMirror.isModifierKey = isModifierKey;
  9799.     CodeMirror.lookupKey = lookupKey;
  9800.     CodeMirror.normalizeKeyMap = normalizeKeyMap;
  9801.     CodeMirror.StringStream = StringStream;
  9802.     CodeMirror.SharedTextMarker = SharedTextMarker;
  9803.     CodeMirror.TextMarker = TextMarker;
  9804.     CodeMirror.LineWidget = LineWidget;
  9805.     CodeMirror.e_preventDefault = e_preventDefault;
  9806.     CodeMirror.e_stopPropagation = e_stopPropagation;
  9807.     CodeMirror.e_stop = e_stop;
  9808.     CodeMirror.addClass = addClass;
  9809.     CodeMirror.contains = contains;
  9810.     CodeMirror.rmClass = rmClass;
  9811.     CodeMirror.keyNames = keyNames;
  9812.   }
  9813.  
  9814.   // EDITOR CONSTRUCTOR
  9815.  
  9816.   defineOptions(CodeMirror);
  9817.  
  9818.   addEditorMethods(CodeMirror);
  9819.  
  9820.   // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  9821.   var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  9822.   for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  9823.     { CodeMirror.prototype[prop] = (function(method) {
  9824.       return function() {return method.apply(this.doc, arguments)}
  9825.     })(Doc.prototype[prop]); } }
  9826.  
  9827.   eventMixin(Doc);
  9828.   CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  9829.  
  9830.   // Extra arguments are stored as the mode's dependencies, which is
  9831.   // used by (legacy) mechanisms like loadmode.js to automatically
  9832.   // load a mode. (Preferred mechanism is the require/define calls.)
  9833.   CodeMirror.defineMode = function(name/*, mode, …*/) {
  9834.     if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
  9835.     defineMode.apply(this, arguments);
  9836.   };
  9837.  
  9838.   CodeMirror.defineMIME = defineMIME;
  9839.  
  9840.   // Minimal default mode.
  9841.   CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  9842.   CodeMirror.defineMIME("text/plain", "null");
  9843.  
  9844.   // EXTENSIONS
  9845.  
  9846.   CodeMirror.defineExtension = function (name, func) {
  9847.     CodeMirror.prototype[name] = func;
  9848.   };
  9849.   CodeMirror.defineDocExtension = function (name, func) {
  9850.     Doc.prototype[name] = func;
  9851.   };
  9852.  
  9853.   CodeMirror.fromTextArea = fromTextArea;
  9854.  
  9855.   addLegacyProps(CodeMirror);
  9856.  
  9857.   CodeMirror.version = "5.65.6";
  9858.  
  9859.   return CodeMirror;
  9860.  
  9861. })));
  9862.