Bug 1381689 - Upgrade to CodeMirror 5.27.4. r=bgrins
authorGabriel Luong <gabriel.luong@gmail.com>
Wed, 19 Jul 2017 16:37:58 -0400
changeset 418636 718e6989c87212cee3b2eb445f9f9982e23e2c39
parent 418635 d3a0d05602dd3bd32394807ea13d0d3482be853e
child 418637 7066bee0381d62764ba8fc55aa4270eb5a241b20
push id7566
push usermtabara@mozilla.com
push dateWed, 02 Aug 2017 08:25:16 +0000
treeherdermozilla-beta@86913f512c3c [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersbgrins
bugs1381689
milestone56.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1381689 - Upgrade to CodeMirror 5.27.4. r=bgrins
devtools/client/sourceeditor/codemirror/README
devtools/client/sourceeditor/codemirror/addon/comment/comment.js
devtools/client/sourceeditor/codemirror/addon/edit/closebrackets.js
devtools/client/sourceeditor/codemirror/addon/edit/continuelist.js
devtools/client/sourceeditor/codemirror/addon/edit/matchbrackets.js
devtools/client/sourceeditor/codemirror/addon/fold/indent-fold.js
devtools/client/sourceeditor/codemirror/addon/fold/xml-fold.js
devtools/client/sourceeditor/codemirror/addon/hint/show-hint.js
devtools/client/sourceeditor/codemirror/addon/search/match-highlighter.js
devtools/client/sourceeditor/codemirror/addon/search/search.js
devtools/client/sourceeditor/codemirror/addon/search/searchcursor.js
devtools/client/sourceeditor/codemirror/addon/selection/active-line.js
devtools/client/sourceeditor/codemirror/addon/selection/mark-selection.js
devtools/client/sourceeditor/codemirror/codemirror.bundle.js
devtools/client/sourceeditor/codemirror/keymap/emacs.js
devtools/client/sourceeditor/codemirror/keymap/sublime.js
devtools/client/sourceeditor/codemirror/keymap/vim.js
devtools/client/sourceeditor/codemirror/lib/codemirror.css
devtools/client/sourceeditor/codemirror/lib/codemirror.js
devtools/client/sourceeditor/codemirror/mode/clike/clike.js
devtools/client/sourceeditor/codemirror/mode/css/css.js
devtools/client/sourceeditor/codemirror/mode/elm/elm.js
devtools/client/sourceeditor/codemirror/mode/htmlmixed/htmlmixed.js
devtools/client/sourceeditor/codemirror/mode/javascript/javascript.js
devtools/client/sourceeditor/test/codemirror/comment_test.js
devtools/client/sourceeditor/test/codemirror/doc_test.js
devtools/client/sourceeditor/test/codemirror/driver.js
devtools/client/sourceeditor/test/codemirror/emacs_test.js
devtools/client/sourceeditor/test/codemirror/mode/javascript/test.js
devtools/client/sourceeditor/test/codemirror/mode_test.js
devtools/client/sourceeditor/test/codemirror/multi_test.js
devtools/client/sourceeditor/test/codemirror/search_test.js
devtools/client/sourceeditor/test/codemirror/sublime_test.js
devtools/client/sourceeditor/test/codemirror/test.js
devtools/client/sourceeditor/test/codemirror/vim_test.js
--- a/devtools/client/sourceeditor/codemirror/README
+++ b/devtools/client/sourceeditor/codemirror/README
@@ -1,21 +1,21 @@
 This is the CodeMirror editor packaged for the Mozilla Project. CodeMirror
 is a JavaScript component that provides a code editor in the browser. When
 a mode is available for the language you are coding in, it will color your
 code, and optionally help with indentation.
 
 # Upgrade
 
-Currently used version is 5.16.0. To upgrade: download a new version of
+Currently used version is 5.27.4. To upgrade: download a new version of
 CodeMirror from the project's page [1] and replace all JavaScript and
 CSS files inside the codemirror directory [2].
 
 Then to recreate codemirror.bundle.js:
- > cd devtools/client
+ > cd devtools/client/sourceeditor
  > npm install
  > webpack
 
 To confirm the functionality run mochitests for the following components:
 
  * sourceeditor
  * scratchpad
  * debugger
--- a/devtools/client/sourceeditor/codemirror/addon/comment/comment.js
+++ b/devtools/client/sourceeditor/codemirror/addon/comment/comment.js
@@ -41,22 +41,27 @@
       } else {
         cm.lineComment(from, to, options);
       }
     }
   });
 
   // Rough heuristic to try and detect lines that are part of multi-line string
   function probablyInsideString(cm, pos, line) {
-    return /\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line, 0))) && !/^[\'\"`]/.test(line)
+    return /\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line, 0))) && !/^[\'\"\`]/.test(line)
+  }
+
+  function getMode(cm, pos) {
+    var mode = cm.getMode()
+    return mode.useInnerComments === false || !mode.innerMode ? mode : cm.getModeAt(pos)
   }
 
   CodeMirror.defineExtension("lineComment", function(from, to, options) {
     if (!options) options = noOptions;
-    var self = this, mode = self.getModeAt(from);
+    var self = this, mode = getMode(self, from);
     var firstLine = self.getLine(from.line);
     if (firstLine == null || probablyInsideString(self, from, firstLine)) return;
 
     var commentString = options.lineComment || mode.lineComment;
     if (!commentString) {
       if (options.blockCommentStart || mode.blockCommentStart) {
         options.fullLines = true;
         self.blockComment(from, to, options);
@@ -90,24 +95,25 @@
             self.replaceRange(commentString + pad, Pos(i, 0));
         }
       }
     });
   });
 
   CodeMirror.defineExtension("blockComment", function(from, to, options) {
     if (!options) options = noOptions;
-    var self = this, mode = self.getModeAt(from);
+    var self = this, mode = getMode(self, from);
     var startString = options.blockCommentStart || mode.blockCommentStart;
     var endString = options.blockCommentEnd || mode.blockCommentEnd;
     if (!startString || !endString) {
       if ((options.lineComment || mode.lineComment) && options.fullLines != false)
         self.lineComment(from, to, options);
       return;
     }
+    if (/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line, 0)))) return
 
     var end = Math.min(to.line, self.lastLine());
     if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end;
 
     var pad = options.padding == null ? " " : options.padding;
     if (from.line > end) return;
 
     self.operation(function() {
@@ -123,29 +129,29 @@
         self.replaceRange(endString, to);
         self.replaceRange(startString, from);
       }
     });
   });
 
   CodeMirror.defineExtension("uncomment", function(from, to, options) {
     if (!options) options = noOptions;
-    var self = this, mode = self.getModeAt(from);
+    var self = this, mode = getMode(self, from);
     var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self.lastLine()), start = Math.min(from.line, end);
 
     // Try finding line comments
     var lineString = options.lineComment || mode.lineComment, lines = [];
     var pad = options.padding == null ? " " : options.padding, didSomething;
     lineComment: {
       if (!lineString) break lineComment;
       for (var i = start; i <= end; ++i) {
         var line = self.getLine(i);
         var found = line.indexOf(lineString);
         if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1;
-        if (found == -1 && (i != end || i == start) && nonWS.test(line)) break lineComment;
+        if (found == -1 && nonWS.test(line)) break lineComment;
         if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment;
         lines.push(line);
       }
       self.operation(function() {
         for (var i = start; i <= end; ++i) {
           var line = lines[i - start];
           var pos = line.indexOf(lineString), endPos = pos + lineString.length;
           if (pos < 0) continue;
@@ -157,25 +163,29 @@
       if (didSomething) return true;
     }
 
     // Try block comments
     var startString = options.blockCommentStart || mode.blockCommentStart;
     var endString = options.blockCommentEnd || mode.blockCommentEnd;
     if (!startString || !endString) return false;
     var lead = options.blockCommentLead || mode.blockCommentLead;
-    var startLine = self.getLine(start), endLine = end == start ? startLine : self.getLine(end);
-    var open = startLine.indexOf(startString), close = endLine.lastIndexOf(endString);
+    var startLine = self.getLine(start), open = startLine.indexOf(startString)
+    if (open == -1) return false
+    var endLine = end == start ? startLine : self.getLine(end)
+    var close = endLine.indexOf(endString, end == start ? open + startString.length : 0);
     if (close == -1 && start != end) {
       endLine = self.getLine(--end);
-      close = endLine.lastIndexOf(endString);
+      close = endLine.indexOf(endString);
     }
-    if (open == -1 || close == -1 ||
-        !/comment/.test(self.getTokenTypeAt(Pos(start, open + 1))) ||
-        !/comment/.test(self.getTokenTypeAt(Pos(end, close + 1))))
+    var insideStart = Pos(start, open + 1), insideEnd = Pos(end, close + 1)
+    if (close == -1 ||
+        !/comment/.test(self.getTokenTypeAt(insideStart)) ||
+        !/comment/.test(self.getTokenTypeAt(insideEnd)) ||
+        self.getRange(insideStart, insideEnd, "\n").indexOf(endString) > -1)
       return false;
 
     // Avoid killing block comments completely outside the selection.
     // Positions of the last startString before the start of the selection, and the first endString after it.
     var lastStart = startLine.lastIndexOf(startString, from.ch);
     var firstEnd = lastStart == -1 ? -1 : startLine.slice(0, from.ch).indexOf(endString, lastStart + startString.length);
     if (lastStart != -1 && firstEnd != -1 && firstEnd + endString.length != from.ch) return false;
     // Positions of the first endString after the end of the selection, and the last startString before it.
--- a/devtools/client/sourceeditor/codemirror/addon/edit/closebrackets.js
+++ b/devtools/client/sourceeditor/codemirror/addon/edit/closebrackets.js
@@ -40,17 +40,17 @@
     keyMap["'" + bind.charAt(i) + "'"] = handler(bind.charAt(i));
 
   function handler(ch) {
     return function(cm) { return handleChar(cm, ch); };
   }
 
   function getConfig(cm) {
     var deflt = cm.state.closeBrackets;
-    if (!deflt) return null;
+    if (!deflt || deflt.override) return deflt;
     var mode = cm.getModeAt(cm.getCursor());
     return mode.closeBrackets || deflt;
   }
 
   function handleBackspace(cm) {
     var conf = getConfig(cm);
     if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
 
@@ -111,17 +111,19 @@
 
     var type;
     for (var i = 0; i < ranges.length; i++) {
       var range = ranges[i], cur = range.head, curType;
       var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
       if (opening && !range.empty()) {
         curType = "surround";
       } else if ((identical || !opening) && next == ch) {
-        if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
+        if (identical && stringStartsAfter(cm, cur))
+          curType = "both";
+        else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
           curType = "skipThree";
         else
           curType = "skip";
       } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 &&
                  cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch &&
                  (cur.ch <= 2 || cm.getRange(Pos(cur.line, cur.ch - 3), Pos(cur.line, cur.ch - 2)) != ch)) {
         curType = "addFour";
       } else if (identical) {
@@ -178,18 +180,23 @@
   }
 
   // Project the token type that will exists after the given char is
   // typed, and use it to determine whether it would cause the start
   // of a string token.
   function enteringString(cm, pos, ch) {
     var line = cm.getLine(pos.line);
     var token = cm.getTokenAt(pos);
-    if (/\bstring2?\b/.test(token.type)) return false;
+    if (/\bstring2?\b/.test(token.type) || stringStartsAfter(cm, pos)) return false;
     var stream = new CodeMirror.StringStream(line.slice(0, pos.ch) + ch + line.slice(pos.ch), 4);
     stream.pos = stream.start = token.start;
     for (;;) {
       var type1 = cm.getMode().token(stream, token.state);
       if (stream.pos >= pos.ch + 1) return /\bstring2?\b/.test(type1);
       stream.start = stream.pos;
     }
   }
+
+  function stringStartsAfter(cm, pos) {
+    var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1))
+    return /\bstring/.test(token.type) && token.start == pos.ch
+  }
 });
--- a/devtools/client/sourceeditor/codemirror/addon/edit/continuelist.js
+++ b/devtools/client/sourceeditor/codemirror/addon/edit/continuelist.js
@@ -6,18 +6,18 @@
     mod(require("../../lib/codemirror"));
   else if (typeof define == "function" && define.amd) // AMD
     define(["../../lib/codemirror"], mod);
   else // Plain browser env
     mod(CodeMirror);
 })(function(CodeMirror) {
   "use strict";
 
-  var listRE = /^(\s*)(>[> ]*|[*+-]\s|(\d+)([.)]))(\s*)/,
-      emptyListRE = /^(\s*)(>[> ]*|[*+-]|(\d+)[.)])(\s*)$/,
+  var listRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]\s|[*+-]\s|(\d+)([.)]))(\s*)/,
+      emptyListRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]|[*+-]|(\d+)[.)])(\s*)$/,
       unorderedListRE = /[*+-]\s/;
 
   CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
     if (cm.getOption("disableInput")) return CodeMirror.Pass;
     var ranges = cm.listSelections(), replacements = [];
     for (var i = 0; i < ranges.length; i++) {
       var pos = ranges[i].head;
       var eolState = cm.getStateAfter(pos.line);
@@ -25,26 +25,26 @@
       var inQuote = eolState.quote !== 0;
 
       var line = cm.getLine(pos.line), match = listRE.exec(line);
       if (!ranges[i].empty() || (!inList && !inQuote) || !match) {
         cm.execCommand("newlineAndIndent");
         return;
       }
       if (emptyListRE.test(line)) {
-        cm.replaceRange("", {
+        if (!/>\s*$/.test(line)) cm.replaceRange("", {
           line: pos.line, ch: 0
         }, {
           line: pos.line, ch: pos.ch + 1
         });
         replacements[i] = "\n";
       } else {
         var indent = match[1], after = match[5];
         var bullet = unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0
-          ? match[2]
+          ? match[2].replace("x", " ")
           : (parseInt(match[3], 10) + 1) + match[4];
 
         replacements[i] = "\n" + indent + bullet + after;
       }
     }
 
     cm.replaceSelections(replacements);
   };
--- a/devtools/client/sourceeditor/codemirror/addon/edit/matchbrackets.js
+++ b/devtools/client/sourceeditor/codemirror/addon/edit/matchbrackets.js
@@ -11,22 +11,31 @@
 })(function(CodeMirror) {
   var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
     (document.documentMode == null || document.documentMode < 8);
 
   var Pos = CodeMirror.Pos;
 
   var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
 
-  function findMatchingBracket(cm, where, strict, config) {
+  function findMatchingBracket(cm, where, config) {
     var line = cm.getLineHandle(where.line), pos = where.ch - 1;
-    var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
+    var afterCursor = config && config.afterCursor
+    if (afterCursor == null)
+      afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className)
+
+    // A cursor is defined as between two characters, but in in vim command mode
+    // (i.e. not insert mode), the cursor is visually represented as a
+    // highlighted box on top of the 2nd character. Otherwise, we allow matches
+    // from before or after the cursor.
+    var match = (!afterCursor && pos >= 0 && matching[line.text.charAt(pos)]) ||
+        matching[line.text.charAt(++pos)];
     if (!match) return null;
     var dir = match.charAt(1) == ">" ? 1 : -1;
-    if (strict && (dir > 0) != (pos == where.ch)) return null;
+    if (config && config.strict && (dir > 0) != (pos == where.ch)) return null;
     var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));
 
     var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);
     if (found == null) return null;
     return {from: Pos(where.line, pos), to: found && found.pos,
             match: found && found.ch == match.charAt(0), forward: dir > 0};
   }
 
@@ -64,17 +73,17 @@
     return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
   }
 
   function matchBrackets(cm, autoclear, config) {
     // Disable brace matching in long lines, since it'll cause hugely slow updates
     var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
     var marks = [], ranges = cm.listSelections();
     for (var i = 0; i < ranges.length; i++) {
-      var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, false, config);
+      var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config);
       if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {
         var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
         marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));
         if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
           marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));
       }
     }
 
@@ -97,24 +106,35 @@
   function doMatchBrackets(cm) {
     cm.operation(function() {
       if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
       currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
     });
   }
 
   CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
-    if (old && old != CodeMirror.Init)
+    if (old && old != CodeMirror.Init) {
       cm.off("cursorActivity", doMatchBrackets);
+      if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
+    }
     if (val) {
       cm.state.matchBrackets = typeof val == "object" ? val : {};
       cm.on("cursorActivity", doMatchBrackets);
     }
   });
 
   CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
-  CodeMirror.defineExtension("findMatchingBracket", function(pos, strict, config){
-    return findMatchingBracket(this, pos, strict, config);
+  CodeMirror.defineExtension("findMatchingBracket", function(pos, config, oldConfig){
+    // Backwards-compatibility kludge
+    if (oldConfig || typeof config == "boolean") {
+      if (!oldConfig) {
+        config = config ? {strict: true} : null
+      } else {
+        oldConfig.strict = config
+        config = oldConfig
+      }
+    }
+    return findMatchingBracket(this, pos, config)
   });
   CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
     return scanForBracket(this, pos, dir, style, config);
   });
 });
--- a/devtools/client/sourceeditor/codemirror/addon/fold/indent-fold.js
+++ b/devtools/client/sourceeditor/codemirror/addon/fold/indent-fold.js
@@ -6,39 +6,43 @@
     mod(require("../../lib/codemirror"));
   else if (typeof define == "function" && define.amd) // AMD
     define(["../../lib/codemirror"], mod);
   else // Plain browser env
     mod(CodeMirror);
 })(function(CodeMirror) {
 "use strict";
 
+function lineIndent(cm, lineNo) {
+  var text = cm.getLine(lineNo)
+  var spaceTo = text.search(/\S/)
+  if (spaceTo == -1 || /\bcomment\b/.test(cm.getTokenTypeAt(CodeMirror.Pos(lineNo, spaceTo + 1))))
+    return -1
+  return CodeMirror.countColumn(text, null, cm.getOption("tabSize"))
+}
+
 CodeMirror.registerHelper("fold", "indent", function(cm, start) {
-  var tabSize = cm.getOption("tabSize"), firstLine = cm.getLine(start.line);
-  if (!/\S/.test(firstLine)) return;
-  var getIndent = function(line) {
-    return CodeMirror.countColumn(line, null, tabSize);
-  };
-  var myIndent = getIndent(firstLine);
-  var lastLineInFold = null;
+  var myIndent = lineIndent(cm, start.line)
+  if (myIndent < 0) return
+  var lastLineInFold = null
+
   // Go through lines until we find a line that definitely doesn't belong in
   // the block we're folding, or to the end.
   for (var i = start.line + 1, end = cm.lastLine(); i <= end; ++i) {
-    var curLine = cm.getLine(i);
-    var curIndent = getIndent(curLine);
-    if (curIndent > myIndent) {
+    var indent = lineIndent(cm, i)
+    if (indent == -1) {
+    } else if (indent > myIndent) {
       // Lines with a greater indent are considered part of the block.
       lastLineInFold = i;
-    } else if (!/\S/.test(curLine)) {
-      // Empty lines might be breaks within the block we're trying to fold.
     } else {
-      // A non-empty line at an indent equal to or less than ours marks the
-      // start of another block.
+      // If this line has non-space, non-comment content, and is
+      // indented less or equal to the start line, it is the start of
+      // another block.
       break;
     }
   }
   if (lastLineInFold) return {
-    from: CodeMirror.Pos(start.line, firstLine.length),
+    from: CodeMirror.Pos(start.line, cm.getLine(start.line).length),
     to: CodeMirror.Pos(lastLineInFold, cm.getLine(lastLineInFold).length)
   };
 });
 
 });
--- a/devtools/client/sourceeditor/codemirror/addon/fold/xml-fold.js
+++ b/devtools/client/sourceeditor/codemirror/addon/fold/xml-fold.js
@@ -16,18 +16,18 @@
 
   var nameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
   var nameChar = nameStartChar + "\-\:\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
   var xmlTagStart = new RegExp("<(/?)([" + nameStartChar + "][" + nameChar + "]*)", "g");
 
   function Iter(cm, line, ch, range) {
     this.line = line; this.ch = ch;
     this.cm = cm; this.text = cm.getLine(line);
-    this.min = range ? range.from : cm.firstLine();
-    this.max = range ? range.to - 1 : cm.lastLine();
+    this.min = range ? Math.max(range.from, cm.firstLine()) : cm.firstLine();
+    this.max = range ? Math.min(range.to - 1, cm.lastLine()) : cm.lastLine();
   }
 
   function tagAt(iter, ch) {
     var type = iter.cm.getTokenTypeAt(Pos(iter.line, ch));
     return type && /\btag\b/.test(type);
   }
 
   function nextLine(iter) {
@@ -158,20 +158,20 @@
     if (start[1]) { // closing tag
       return {open: findMatchingOpen(iter, start[2]), close: here, at: "close"};
     } else { // opening tag
       iter = new Iter(cm, to.line, to.ch, range);
       return {open: here, close: findMatchingClose(iter, start[2]), at: "open"};
     }
   };
 
-  CodeMirror.findEnclosingTag = function(cm, pos, range) {
+  CodeMirror.findEnclosingTag = function(cm, pos, range, tag) {
     var iter = new Iter(cm, pos.line, pos.ch, range);
     for (;;) {
-      var open = findMatchingOpen(iter);
+      var open = findMatchingOpen(iter, tag);
       if (!open) break;
       var forward = new Iter(cm, pos.line, pos.ch, range);
       var close = findMatchingClose(forward, open.tag);
       if (close) return {open: open, close: close};
     }
   };
 
   // Used by addon/edit/closetag.js
--- a/devtools/client/sourceeditor/codemirror/addon/hint/show-hint.js
+++ b/devtools/client/sourceeditor/codemirror/addon/hint/show-hint.js
@@ -225,16 +225,18 @@
     hints.style.left = left + "px";
     hints.style.top = top + "px";
     // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
     var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
     var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
     (completion.options.container || document.body).appendChild(hints);
     var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH;
     var scrolls = hints.scrollHeight > hints.clientHeight + 1
+    var startScroll = cm.getScrollInfo();
+
     if (overlapY > 0) {
       var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
       if (curTop - height > 0) { // Fits above cursor
         hints.style.top = (top = pos.top - height) + "px";
         below = false;
       } else if (height > winH) {
         hints.style.height = (winH - 5) + "px";
         hints.style.top = (top = pos.bottom - box.top) + "px";
@@ -268,17 +270,16 @@
     }));
 
     if (completion.options.closeOnUnfocus) {
       var closingOnBlur;
       cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
       cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
     }
 
-    var startScroll = cm.getScrollInfo();
     cm.on("scroll", this.onScroll = function() {
       var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
       var newTop = top + startScroll.top - curScroll.top;
       var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop);
       if (!below) point += hints.offsetHeight;
       if (point <= editor.top || point >= editor.bottom) return completion.close();
       hints.style.top = newTop + "px";
       hints.style.left = (left + startScroll.left - curScroll.left) + "px";
--- a/devtools/client/sourceeditor/codemirror/addon/search/match-highlighter.js
+++ b/devtools/client/sourceeditor/codemirror/addon/search/match-highlighter.js
@@ -40,44 +40,63 @@
   }
 
   function State(options) {
     this.options = {}
     for (var name in defaults)
       this.options[name] = (options && options.hasOwnProperty(name) ? options : defaults)[name]
     this.overlay = this.timeout = null;
     this.matchesonscroll = null;
+    this.active = false;
   }
 
   CodeMirror.defineOption("highlightSelectionMatches", false, function(cm, val, old) {
     if (old && old != CodeMirror.Init) {
       removeOverlay(cm);
       clearTimeout(cm.state.matchHighlighter.timeout);
       cm.state.matchHighlighter = null;
       cm.off("cursorActivity", cursorActivity);
+      cm.off("focus", onFocus)
     }
     if (val) {
-      cm.state.matchHighlighter = new State(val);
-      highlightMatches(cm);
+      var state = cm.state.matchHighlighter = new State(val);
+      if (cm.hasFocus()) {
+        state.active = true
+        highlightMatches(cm)
+      } else {
+        cm.on("focus", onFocus)
+      }
       cm.on("cursorActivity", cursorActivity);
     }
   });
 
   function cursorActivity(cm) {
     var state = cm.state.matchHighlighter;
+    if (state.active || cm.hasFocus()) scheduleHighlight(cm, state)
+  }
+
+  function onFocus(cm) {
+    var state = cm.state.matchHighlighter
+    if (!state.active) {
+      state.active = true
+      scheduleHighlight(cm, state)
+    }
+  }
+
+  function scheduleHighlight(cm, state) {
     clearTimeout(state.timeout);
     state.timeout = setTimeout(function() {highlightMatches(cm);}, state.options.delay);
   }
 
   function addOverlay(cm, query, hasBoundary, style) {
     var state = cm.state.matchHighlighter;
     cm.addOverlay(state.overlay = makeOverlay(query, hasBoundary, style));
     if (state.options.annotateScrollbar && cm.showMatchesOnScrollbar) {
       var searchFor = hasBoundary ? new RegExp("\\b" + query + "\\b") : query;
-      state.matchesonscroll = cm.showMatchesOnScrollbar(searchFor, true,
+      state.matchesonscroll = cm.showMatchesOnScrollbar(searchFor, false,
         {className: "CodeMirror-selection-highlight-scrollbar"});
     }
   }
 
   function removeOverlay(cm) {
     var state = cm.state.matchHighlighter;
     if (state.overlay) {
       cm.removeOverlay(state.overlay);
--- a/devtools/client/sourceeditor/codemirror/addon/search/search.js
+++ b/devtools/client/sourceeditor/codemirror/addon/search/search.js
@@ -49,25 +49,26 @@
   }
 
   function queryCaseInsensitive(query) {
     return typeof query == "string" && query == query.toLowerCase();
   }
 
   function getSearchCursor(cm, query, pos) {
     // Heuristic: if the query string is all lowercase, do a case insensitive search.
-    return cm.getSearchCursor(query, pos, queryCaseInsensitive(query));
+    return cm.getSearchCursor(query, pos, {caseFold: queryCaseInsensitive(query), multiline: true});
   }
 
-  function persistentDialog(cm, text, deflt, f) {
-    cm.openDialog(text, f, {
+  function persistentDialog(cm, text, deflt, onEnter, onKeyDown) {
+    cm.openDialog(text, onEnter, {
       value: deflt,
       selectValueOnOpen: true,
       closeOnEnter: false,
-      onClose: function() { clearSearch(cm); }
+      onClose: function() { clearSearch(cm); },
+      onKeyDown: onKeyDown
     });
   }
 
   function dialog(cm, text, shortText, deflt, f) {
     if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true});
     else f(prompt(shortText, deflt));
   }
 
@@ -106,17 +107,17 @@
     state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query));
     cm.addOverlay(state.overlay);
     if (cm.showMatchesOnScrollbar) {
       if (state.annotate) { state.annotate.clear(); state.annotate = null; }
       state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query));
     }
   }
 
-  function doSearch(cm, rev, persistent) {
+  function doSearch(cm, rev, persistent, immediate) {
     if (!queryDialog) {
       let doc = cm.getWrapperElement().ownerDocument;
       let inp = doc.createElement("input");
 
       inp.type = "search";
       inp.placeholder = cm.l10n("findCmd.promptMessage");
       inp.style.marginInlineStart = "1em";
       inp.style.marginInlineEnd = "1em";
@@ -128,32 +129,50 @@
       queryDialog.style.display = "flex";
     }
 
     var state = getSearchState(cm);
     if (state.query) return findNext(cm, rev);
     var q = cm.getSelection() || state.lastQuery;
     if (persistent && cm.openDialog) {
       var hiding = null
-      persistentDialog(cm, queryDialog, q, function(query, event) {
+      var searchNext = function(query, event) {
         CodeMirror.e_stop(event);
         if (!query) return;
         if (query != state.queryText) {
           startSearch(cm, state, query);
           state.posFrom = state.posTo = cm.getCursor();
         }
         if (hiding) hiding.style.opacity = 1
         findNext(cm, event.shiftKey, function(_, to) {
           var dialog
           if (to.line < 3 && document.querySelector &&
               (dialog = cm.display.wrapper.querySelector(".CodeMirror-dialog")) &&
               dialog.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top)
             (hiding = dialog).style.opacity = .4
         })
+      };
+      persistentDialog(cm, queryDialog, q, searchNext, function(event, query) {
+        var keyName = CodeMirror.keyName(event)
+        var cmd = CodeMirror.keyMap[cm.getOption("keyMap")][keyName]
+        if (!cmd) cmd = cm.getOption('extraKeys')[keyName]
+        if (cmd == "findNext" || cmd == "findPrev" ||
+          cmd == "findPersistentNext" || cmd == "findPersistentPrev") {
+          CodeMirror.e_stop(event);
+          startSearch(cm, getSearchState(cm), query);
+          cm.execCommand(cmd);
+        } else if (cmd == "find" || cmd == "findPersistent") {
+          CodeMirror.e_stop(event);
+          searchNext(query, event);
+        }
       });
+      if (immediate && q) {
+        startSearch(cm, state, q);
+        findNext(cm, rev);
+      }
     } else {
       dialog(cm, queryDialog, "Search for:", q, function(query) {
         if (query && !state.query) cm.operation(function() {
           startSearch(cm, state, query);
           state.posFrom = state.posTo = cm.getCursor();
           findNext(cm, rev);
         });
       });
@@ -179,34 +198,34 @@
     if (!state.query) return;
     state.query = state.queryText = null;
     cm.removeOverlay(state.overlay);
     if (state.annotate) { state.annotate.clear(); state.annotate = null; }
   });}
 
   var replaceQueryDialog =
     ' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">(Use /re/ syntax for regexp search)</span>';
-  var replacementQueryDialog = 'With: <input type="text" style="width: 10em" class="CodeMirror-search-field"/>';
-  var doReplaceConfirm = "Replace? <button>Yes</button> <button>No</button> <button>All</button> <button>Stop</button>";
+  var replacementQueryDialog = '<span class="CodeMirror-search-label">With:</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/>';
+  var doReplaceConfirm = '<span class="CodeMirror-search-label">Replace?</span> <button>Yes</button> <button>No</button> <button>All</button> <button>Stop</button>';
 
   function replaceAll(cm, query, text) {
     cm.operation(function() {
       for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
         if (typeof query != "string") {
           var match = cm.getRange(cursor.from(), cursor.to()).match(query);
           cursor.replace(text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
         } else cursor.replace(text);
       }
     });
   }
 
   function replace(cm, all) {
     if (cm.getOption("readOnly")) return;
     var query = cm.getSelection() || getSearchState(cm).lastQuery;
-    var dialogText = all ? "Replace all:" : "Replace:"
+    var dialogText = '<span class="CodeMirror-search-label">' + (all ? 'Replace all:' : 'Replace:') + '</span>';
     dialog(cm, dialogText + replaceQueryDialog, dialogText, query, function(query) {
       if (!query) return;
       query = parseQuery(query);
       dialog(cm, replacementQueryDialog, "Replace with:", "", function(text) {
         text = parseString(text)
         if (all) {
           replaceAll(cm, query, text)
         } else {
@@ -233,14 +252,16 @@
           advance();
         }
       });
     });
   }
 
   CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
   CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);};
+  CodeMirror.commands.findPersistentNext = function(cm) {doSearch(cm, false, true, true);};
+  CodeMirror.commands.findPersistentPrev = function(cm) {doSearch(cm, true, true, true);};
   CodeMirror.commands.findNext = doSearch;
   CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
   CodeMirror.commands.clearSearch = clearSearch;
   CodeMirror.commands.replace = replace;
   CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
 });
--- a/devtools/client/sourceeditor/codemirror/addon/search/searchcursor.js
+++ b/devtools/client/sourceeditor/codemirror/addon/search/searchcursor.js
@@ -1,189 +1,287 @@
 // CodeMirror, copyright (c) by Marijn Haverbeke and others
 // Distributed under an MIT license: http://codemirror.net/LICENSE
 
 (function(mod) {
   if (typeof exports == "object" && typeof module == "object") // CommonJS
-    mod(require("../../lib/codemirror"));
+    mod(require("../../lib/codemirror"))
   else if (typeof define == "function" && define.amd) // AMD
-    define(["../../lib/codemirror"], mod);
+    define(["../../lib/codemirror"], mod)
   else // Plain browser env
-    mod(CodeMirror);
+    mod(CodeMirror)
 })(function(CodeMirror) {
-  "use strict";
-  var Pos = CodeMirror.Pos;
+  "use strict"
+  var Pos = CodeMirror.Pos
+
+  function regexpFlags(regexp) {
+    var flags = regexp.flags
+    return flags != null ? flags : (regexp.ignoreCase ? "i" : "")
+      + (regexp.global ? "g" : "")
+      + (regexp.multiline ? "m" : "")
+  }
+
+  function ensureGlobal(regexp) {
+    return regexp.global ? regexp : new RegExp(regexp.source, regexpFlags(regexp) + "g")
+  }
 
-  function SearchCursor(doc, query, pos, caseFold) {
-    this.atOccurrence = false; this.doc = doc;
-    if (caseFold == null && typeof query == "string") caseFold = false;
+  function maybeMultiline(regexp) {
+    return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source)
+  }
 
-    pos = pos ? doc.clipPos(pos) : Pos(0, 0);
-    this.pos = {from: pos, to: pos};
+  function searchRegexpForward(doc, regexp, start) {
+    regexp = ensureGlobal(regexp)
+    for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) {
+      regexp.lastIndex = ch
+      var string = doc.getLine(line), match = regexp.exec(string)
+      if (match)
+        return {from: Pos(line, match.index),
+                to: Pos(line, match.index + match[0].length),
+                match: match}
+    }
+  }
+
+  function searchRegexpForwardMultiline(doc, regexp, start) {
+    if (!maybeMultiline(regexp)) return searchRegexpForward(doc, regexp, start)
 
-    // The matches method is filled in based on the type of query.
-    // It takes a position and a direction, and returns an object
-    // describing the next occurrence of the query, or null if no
-    // more matches were found.
-    if (typeof query != "string") { // Regexp match
-      if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "ig" : "g");
-      this.matches = function(reverse, pos) {
-        if (reverse) {
-          query.lastIndex = 0;
-          var line = doc.getLine(pos.line).slice(0, pos.ch), cutOff = 0, match, start;
-          for (;;) {
-            query.lastIndex = cutOff;
-            var newMatch = query.exec(line);
-            if (!newMatch) break;
-            match = newMatch;
-            start = match.index;
-            cutOff = match.index + (match[0].length || 1);
-            if (cutOff == line.length) break;
-          }
-          var matchLen = (match && match[0].length) || 0;
-          if (!matchLen) {
-            if (start == 0 && line.length == 0) {match = undefined;}
-            else if (start != doc.getLine(pos.line).length) {
-              matchLen++;
-            }
-          }
-        } else {
-          query.lastIndex = pos.ch;
-          var line = doc.getLine(pos.line), match = query.exec(line);
-          var matchLen = (match && match[0].length) || 0;
-          var start = match && match.index;
-          if (start + matchLen != line.length && !matchLen) matchLen = 1;
-        }
-        if (match && matchLen)
-          return {from: Pos(pos.line, start),
-                  to: Pos(pos.line, start + matchLen),
-                  match: match};
-      };
-    } else { // String query
-      var origQuery = query;
-      if (caseFold) query = query.toLowerCase();
-      var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
-      var target = query.split("\n");
-      // Different methods for single-line and multi-line queries
-      if (target.length == 1) {
-        if (!query.length) {
-          // Empty string would match anything and never progress, so
-          // we define it to match nothing instead.
-          this.matches = function() {};
-        } else {
-          this.matches = function(reverse, pos) {
-            if (reverse) {
-              var orig = doc.getLine(pos.line).slice(0, pos.ch), line = fold(orig);
-              var match = line.lastIndexOf(query);
-              if (match > -1) {
-                match = adjustPos(orig, line, match);
-                return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)};
-              }
-             } else {
-               var orig = doc.getLine(pos.line).slice(pos.ch), line = fold(orig);
-               var match = line.indexOf(query);
-               if (match > -1) {
-                 match = adjustPos(orig, line, match) + pos.ch;
-                 return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)};
-               }
-            }
-          };
-        }
-      } else {
-        var origTarget = origQuery.split("\n");
-        this.matches = function(reverse, pos) {
-          var last = target.length - 1;
-          if (reverse) {
-            if (pos.line - (target.length - 1) < doc.firstLine()) return;
-            if (fold(doc.getLine(pos.line).slice(0, origTarget[last].length)) != target[target.length - 1]) return;
-            var to = Pos(pos.line, origTarget[last].length);
-            for (var ln = pos.line - 1, i = last - 1; i >= 1; --i, --ln)
-              if (target[i] != fold(doc.getLine(ln))) return;
-            var line = doc.getLine(ln), cut = line.length - origTarget[0].length;
-            if (fold(line.slice(cut)) != target[0]) return;
-            return {from: Pos(ln, cut), to: to};
-          } else {
-            if (pos.line + (target.length - 1) > doc.lastLine()) return;
-            var line = doc.getLine(pos.line), cut = line.length - origTarget[0].length;
-            if (fold(line.slice(cut)) != target[0]) return;
-            var from = Pos(pos.line, cut);
-            for (var ln = pos.line + 1, i = 1; i < last; ++i, ++ln)
-              if (target[i] != fold(doc.getLine(ln))) return;
-            if (fold(doc.getLine(ln).slice(0, origTarget[last].length)) != target[last]) return;
-            return {from: from, to: Pos(ln, origTarget[last].length)};
-          }
-        };
+    regexp = ensureGlobal(regexp)
+    var string, chunk = 1
+    for (var line = start.line, last = doc.lastLine(); line <= last;) {
+      // This grows the search buffer in exponentially-sized chunks
+      // between matches, so that nearby matches are fast and don't
+      // require concatenating the whole document (in case we're
+      // searching for something that has tons of matches), but at the
+      // same time, the amount of retries is limited.
+      for (var i = 0; i < chunk; i++) {
+        var curLine = doc.getLine(line++)
+        string = string == null ? curLine : string + "\n" + curLine
+      }
+      chunk = chunk * 2
+      regexp.lastIndex = start.ch
+      var match = regexp.exec(string)
+      if (match) {
+        var before = string.slice(0, match.index).split("\n"), inside = match[0].split("\n")
+        var startLine = start.line + before.length - 1, startCh = before[before.length - 1].length
+        return {from: Pos(startLine, startCh),
+                to: Pos(startLine + inside.length - 1,
+                        inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length),
+                match: match}
+      }
+    }
+  }
+
+  function lastMatchIn(string, regexp) {
+    var cutOff = 0, match
+    for (;;) {
+      regexp.lastIndex = cutOff
+      var newMatch = regexp.exec(string)
+      if (!newMatch) return match
+      match = newMatch
+      cutOff = match.index + (match[0].length || 1)
+      if (cutOff == string.length) return match
+    }
+  }
+
+  function searchRegexpBackward(doc, regexp, start) {
+    regexp = ensureGlobal(regexp)
+    for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) {
+      var string = doc.getLine(line)
+      if (ch > -1) string = string.slice(0, ch)
+      var match = lastMatchIn(string, regexp)
+      if (match)
+        return {from: Pos(line, match.index),
+                to: Pos(line, match.index + match[0].length),
+                match: match}
+    }
+  }
+
+  function searchRegexpBackwardMultiline(doc, regexp, start) {
+    regexp = ensureGlobal(regexp)
+    var string, chunk = 1
+    for (var line = start.line, first = doc.firstLine(); line >= first;) {
+      for (var i = 0; i < chunk; i++) {
+        var curLine = doc.getLine(line--)
+        string = string == null ? curLine.slice(0, start.ch) : curLine + "\n" + string
+      }
+      chunk *= 2
+
+      var match = lastMatchIn(string, regexp)
+      if (match) {
+        var before = string.slice(0, match.index).split("\n"), inside = match[0].split("\n")
+        var startLine = line + before.length, startCh = before[before.length - 1].length
+        return {from: Pos(startLine, startCh),
+                to: Pos(startLine + inside.length - 1,
+                        inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length),
+                match: match}
       }
     }
   }
 
+  var doFold, noFold
+  if (String.prototype.normalize) {
+    doFold = function(str) { return str.normalize("NFD").toLowerCase() }
+    noFold = function(str) { return str.normalize("NFD") }
+  } else {
+    doFold = function(str) { return str.toLowerCase() }
+    noFold = function(str) { return str }
+  }
+
+  // Maps a position in a case-folded line back to a position in the original line
+  // (compensating for codepoints increasing in number during folding)
+  function adjustPos(orig, folded, pos, foldFunc) {
+    if (orig.length == folded.length) return pos
+    for (var pos1 = Math.min(pos, orig.length);;) {
+      var len1 = foldFunc(orig.slice(0, pos1)).length
+      if (len1 < pos) ++pos1
+      else if (len1 > pos) --pos1
+      else return pos1
+    }
+  }
+
+  function searchStringForward(doc, query, start, caseFold) {
+    // Empty string would match anything and never progress, so we
+    // define it to match nothing instead.
+    if (!query.length) return null
+    var fold = caseFold ? doFold : noFold
+    var lines = fold(query).split(/\r|\n\r?/)
+
+    search: for (var line = start.line, ch = start.ch, last = doc.lastLine() + 1 - lines.length; line <= last; line++, ch = 0) {
+      var orig = doc.getLine(line).slice(ch), string = fold(orig)
+      if (lines.length == 1) {
+        var found = string.indexOf(lines[0])
+        if (found == -1) continue search
+        var start = adjustPos(orig, string, found, fold) + ch
+        return {from: Pos(line, adjustPos(orig, string, found, fold) + ch),
+                to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold) + ch)}
+      } else {
+        var cutFrom = string.length - lines[0].length
+        if (string.slice(cutFrom) != lines[0]) continue search
+        for (var i = 1; i < lines.length - 1; i++)
+          if (fold(doc.getLine(line + i)) != lines[i]) continue search
+        var end = doc.getLine(line + lines.length - 1), endString = fold(end), lastLine = lines[lines.length - 1]
+        if (end.slice(0, lastLine.length) != lastLine) continue search
+        return {from: Pos(line, adjustPos(orig, string, cutFrom, fold) + ch),
+                to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold))}
+      }
+    }
+  }
+
+  function searchStringBackward(doc, query, start, caseFold) {
+    if (!query.length) return null
+    var fold = caseFold ? doFold : noFold
+    var lines = fold(query).split(/\r|\n\r?/)
+
+    search: for (var line = start.line, ch = start.ch, first = doc.firstLine() - 1 + lines.length; line >= first; line--, ch = -1) {
+      var orig = doc.getLine(line)
+      if (ch > -1) orig = orig.slice(0, ch)
+      var string = fold(orig)
+      if (lines.length == 1) {
+        var found = string.lastIndexOf(lines[0])
+        if (found == -1) continue search
+        return {from: Pos(line, adjustPos(orig, string, found, fold)),
+                to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold))}
+      } else {
+        var lastLine = lines[lines.length - 1]
+        if (string.slice(0, lastLine.length) != lastLine) continue search
+        for (var i = 1, start = line - lines.length + 1; i < lines.length - 1; i++)
+          if (fold(doc.getLine(start + i)) != lines[i]) continue search
+        var top = doc.getLine(line + 1 - lines.length), topString = fold(top)
+        if (topString.slice(topString.length - lines[0].length) != lines[0]) continue search
+        return {from: Pos(line + 1 - lines.length, adjustPos(top, topString, top.length - lines[0].length, fold)),
+                to: Pos(line, adjustPos(orig, string, lastLine.length, fold))}
+      }
+    }
+  }
+
+  function SearchCursor(doc, query, pos, options) {
+    this.atOccurrence = false
+    this.doc = doc
+    pos = pos ? doc.clipPos(pos) : Pos(0, 0)
+    this.pos = {from: pos, to: pos}
+
+    var caseFold
+    if (typeof options == "object") {
+      caseFold = options.caseFold
+    } else { // Backwards compat for when caseFold was the 4th argument
+      caseFold = options
+      options = null
+    }
+
+    if (typeof query == "string") {
+      if (caseFold == null) caseFold = false
+      this.matches = function(reverse, pos) {
+        return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos, caseFold)
+      }
+    } else {
+      query = ensureGlobal(query)
+      if (!options || options.multiline !== false)
+        this.matches = function(reverse, pos) {
+          return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos)
+        }
+      else
+        this.matches = function(reverse, pos) {
+          return (reverse ? searchRegexpBackward : searchRegexpForward)(doc, query, pos)
+        }
+    }
+  }
+
   SearchCursor.prototype = {
-    findNext: function() {return this.find(false);},
-    findPrevious: function() {return this.find(true);},
+    findNext: function() {return this.find(false)},
+    findPrevious: function() {return this.find(true)},
 
     find: function(reverse) {
-      var self = this, pos = this.doc.clipPos(reverse ? this.pos.from : this.pos.to);
-      function savePosAndFail(line) {
-        var pos = Pos(line, 0);
-        self.pos = {from: pos, to: pos};
-        self.atOccurrence = false;
-        return false;
+      var result = this.matches(reverse, this.doc.clipPos(reverse ? this.pos.from : this.pos.to))
+
+      // Implements weird auto-growing behavior on null-matches for
+      // backwards-compatiblity with the vim code (unfortunately)
+      while (result && CodeMirror.cmpPos(result.from, result.to) == 0) {
+        if (reverse) {
+          if (result.from.ch) result.from = Pos(result.from.line, result.from.ch - 1)
+          else if (result.from.line == this.doc.firstLine()) result = null
+          else result = this.matches(reverse, this.doc.clipPos(Pos(result.from.line - 1)))
+        } else {
+          if (result.to.ch < this.doc.getLine(result.to.line).length) result.to = Pos(result.to.line, result.to.ch + 1)
+          else if (result.to.line == this.doc.lastLine()) result = null
+          else result = this.matches(reverse, Pos(result.to.line + 1, 0))
+        }
       }
 
-      for (;;) {
-        if (this.pos = this.matches(reverse, pos)) {
-          this.atOccurrence = true;
-          return this.pos.match || true;
-        }
-        if (reverse) {
-          if (!pos.line) return savePosAndFail(0);
-          pos = Pos(pos.line-1, this.doc.getLine(pos.line-1).length);
-        }
-        else {
-          var maxLine = this.doc.lineCount();
-          if (pos.line == maxLine - 1) return savePosAndFail(maxLine);
-          pos = Pos(pos.line + 1, 0);
-        }
+      if (result) {
+        this.pos = result
+        this.atOccurrence = true
+        return this.pos.match || true
+      } else {
+        var end = Pos(reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, 0)
+        this.pos = {from: end, to: end}
+        return this.atOccurrence = false
       }
     },
 
-    from: function() {if (this.atOccurrence) return this.pos.from;},
-    to: function() {if (this.atOccurrence) return this.pos.to;},
+    from: function() {if (this.atOccurrence) return this.pos.from},
+    to: function() {if (this.atOccurrence) return this.pos.to},
 
     replace: function(newText, origin) {
-      if (!this.atOccurrence) return;
-      var lines = CodeMirror.splitLines(newText);
-      this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin);
+      if (!this.atOccurrence) return
+      var lines = CodeMirror.splitLines(newText)
+      this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin)
       this.pos.to = Pos(this.pos.from.line + lines.length - 1,
-                        lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0));
-    }
-  };
-
-  // Maps a position in a case-folded line back to a position in the original line
-  // (compensating for codepoints increasing in number during folding)
-  function adjustPos(orig, folded, pos) {
-    if (orig.length == folded.length) return pos;
-    for (var pos1 = Math.min(pos, orig.length);;) {
-      var len1 = orig.slice(0, pos1).toLowerCase().length;
-      if (len1 < pos) ++pos1;
-      else if (len1 > pos) --pos1;
-      else return pos1;
+                        lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0))
     }
   }
 
   CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
-    return new SearchCursor(this.doc, query, pos, caseFold);
-  });
+    return new SearchCursor(this.doc, query, pos, caseFold)
+  })
   CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
-    return new SearchCursor(this, query, pos, caseFold);
-  });
+    return new SearchCursor(this, query, pos, caseFold)
+  })
 
   CodeMirror.defineExtension("selectMatches", function(query, caseFold) {
-    var ranges = [];
-    var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold);
+    var ranges = []
+    var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold)
     while (cur.findNext()) {
-      if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break;
-      ranges.push({anchor: cur.from(), head: cur.to()});
+      if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break
+      ranges.push({anchor: cur.from(), head: cur.to()})
     }
     if (ranges.length)
-      this.setSelections(ranges, 0);
-  });
+      this.setSelections(ranges, 0)
+  })
 });
--- a/devtools/client/sourceeditor/codemirror/addon/selection/active-line.js
+++ b/devtools/client/sourceeditor/codemirror/addon/selection/active-line.js
@@ -1,40 +1,36 @@
 // CodeMirror, copyright (c) by Marijn Haverbeke and others
 // Distributed under an MIT license: http://codemirror.net/LICENSE
 
-// Because sometimes you need to style the cursor's line.
-//
-// Adds an option 'styleActiveLine' which, when enabled, gives the
-// active line's wrapping <div> the CSS class "CodeMirror-activeline",
-// and gives its background <div> the class "CodeMirror-activeline-background".
-
 (function(mod) {
   if (typeof exports == "object" && typeof module == "object") // CommonJS
     mod(require("../../lib/codemirror"));
   else if (typeof define == "function" && define.amd) // AMD
     define(["../../lib/codemirror"], mod);
   else // Plain browser env
     mod(CodeMirror);
 })(function(CodeMirror) {
   "use strict";
   var WRAP_CLASS = "CodeMirror-activeline";
   var BACK_CLASS = "CodeMirror-activeline-background";
   var GUTT_CLASS = "CodeMirror-activeline-gutter";
 
   CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) {
-    var prev = old && old != CodeMirror.Init;
-    if (val && !prev) {
+    var prev = old == CodeMirror.Init ? false : old;
+    if (val == prev) return
+    if (prev) {
+      cm.off("beforeSelectionChange", selectionChange);
+      clearActiveLines(cm);
+      delete cm.state.activeLines;
+    }
+    if (val) {
       cm.state.activeLines = [];
       updateActiveLines(cm, cm.listSelections());
       cm.on("beforeSelectionChange", selectionChange);
-    } else if (!val && prev) {
-      cm.off("beforeSelectionChange", selectionChange);
-      clearActiveLines(cm);
-      delete cm.state.activeLines;
     }
   });
 
   function clearActiveLines(cm) {
     for (var i = 0; i < cm.state.activeLines.length; i++) {
       cm.removeLineClass(cm.state.activeLines[i], "wrap", WRAP_CLASS);
       cm.removeLineClass(cm.state.activeLines[i], "background", BACK_CLASS);
       cm.removeLineClass(cm.state.activeLines[i], "gutter", GUTT_CLASS);
@@ -47,17 +43,19 @@
       if (a[i] != b[i]) return false;
     return true;
   }
 
   function updateActiveLines(cm, ranges) {
     var active = [];
     for (var i = 0; i < ranges.length; i++) {
       var range = ranges[i];
-      if (!range.empty()) continue;
+      var option = cm.getOption("styleActiveLine");
+      if (typeof option == "object" && option.nonEmpty ? range.anchor.line != range.head.line : !range.empty())
+        continue
       var line = cm.getLineHandleVisualStart(range.head.line);
       if (active[active.length - 1] != line) active.push(line);
     }
     if (sameArray(cm.state.activeLines, active)) return;
     cm.operation(function() {
       clearActiveLines(cm);
       for (var i = 0; i < active.length; i++) {
         cm.addLineClass(active[i], "wrap", WRAP_CLASS);
--- a/devtools/client/sourceeditor/codemirror/addon/selection/mark-selection.js
+++ b/devtools/client/sourceeditor/codemirror/addon/selection/mark-selection.js
@@ -29,21 +29,22 @@
       cm.off("cursorActivity", onCursorActivity);
       cm.off("change", onChange);
       clear(cm);
       cm.state.markedSelection = cm.state.markedSelectionStyle = null;
     }
   });
 
   function onCursorActivity(cm) {
-    cm.operation(function() { update(cm); });
+    if (cm.state.markedSelection)
+      cm.operation(function() { update(cm); });
   }
 
   function onChange(cm) {
-    if (cm.state.markedSelection.length)
+    if (cm.state.markedSelection && cm.state.markedSelection.length)
       cm.operation(function() { clear(cm); });
   }
 
   var CHUNK_SIZE = 8;
   var Pos = CodeMirror.Pos;
   var cmp = CodeMirror.cmpPos;
 
   function coverRange(cm, from, to, addAt) {
--- a/devtools/client/sourceeditor/codemirror/codemirror.bundle.js
+++ b/devtools/client/sourceeditor/codemirror/codemirror.bundle.js
@@ -38,17 +38,17 @@ var CodeMirror =
 /******/ 	__webpack_require__.p = "";
 
 /******/ 	// Load entry module and return exports
 /******/ 	return __webpack_require__(0);
 /******/ })
 /************************************************************************/
 /******/ ([
 /* 0 */
-/***/ function(module, exports, __webpack_require__) {
+/***/ (function(module, exports, __webpack_require__) {
 
 	__webpack_require__(1);
 	__webpack_require__(3);
 	__webpack_require__(4);
 	__webpack_require__(5);
 	__webpack_require__(6);
 	__webpack_require__(7);
 	__webpack_require__(8);
@@ -68,19 +68,19 @@ var CodeMirror =
 	__webpack_require__(22);
 	__webpack_require__(23);
 	__webpack_require__(24);
 	__webpack_require__(25);
 	__webpack_require__(26);
 	module.exports = __webpack_require__(2);
 
 
-/***/ },
+/***/ }),
 /* 1 */
-/***/ function(module, exports, __webpack_require__) {
+/***/ (function(module, exports, __webpack_require__) {
 
 	// CodeMirror, copyright (c) by Marijn Haverbeke and others
 	// Distributed under an MIT license: http://codemirror.net/LICENSE
 
 	// Open simple dialogs on top of an editor. Relies on dialog.css.
 
 	(function(mod) {
 	  if (true) // CommonJS
@@ -231,9142 +231,9807 @@ var CodeMirror =
 	    if (duration)
 	      doneTimer = setTimeout(close, duration);
 
 	    return close;
 	  });
 	});
 
 
-/***/ },
+/***/ }),
 /* 2 */
-/***/ function(module, exports, __webpack_require__) {
+/***/ (function(module, exports, __webpack_require__) {
 
 	// CodeMirror, copyright (c) by Marijn Haverbeke and others
 	// Distributed under an MIT license: http://codemirror.net/LICENSE
 
 	// This is CodeMirror (http://codemirror.net), a code editor
 	// implemented in JavaScript on top of the browser's DOM.
 	//
 	// You can find some technical background for some of the code below
 	// at http://marijnhaverbeke.nl/blog/#cm-internals .
 
-	(function(mod) {
-	  if (true) // CommonJS
-	    module.exports = mod();
-	  else if (typeof define == "function" && define.amd) // AMD
-	    return define([], mod);
-	  else // Plain browser env
-	    (this || window).CodeMirror = mod();
-	})(function() {
-	  "use strict";
-
-	  // BROWSER SNIFFING
-
-	  // Kludges for bugs and behavior differences that can't be feature
-	  // detected are enabled based on userAgent etc sniffing.
-	  var userAgent = navigator.userAgent;
-	  var platform = navigator.platform;
-
-	  var gecko = /gecko\/\d/i.test(userAgent);
-	  var ie_upto10 = /MSIE \d/.test(userAgent);
-	  var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
-	  var ie = ie_upto10 || ie_11up;
-	  var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
-	  var webkit = /WebKit\//.test(userAgent);
-	  var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
-	  var chrome = /Chrome\//.test(userAgent);
-	  var presto = /Opera\//.test(userAgent);
-	  var safari = /Apple Computer/.test(navigator.vendor);
-	  var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
-	  var phantom = /PhantomJS/.test(userAgent);
-
-	  var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
-	  // This is woefully incomplete. Suggestions for alternative methods welcome.
-	  var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
-	  var mac = ios || /Mac/.test(platform);
-	  var chromeOS = /\bCrOS\b/.test(userAgent);
-	  var windows = /win/i.test(platform);
-
-	  var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
-	  if (presto_version) presto_version = Number(presto_version[1]);
-	  if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
-	  // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
-	  var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
-	  var captureRightClick = gecko || (ie && ie_version >= 9);
-
-	  // Optimize some code when these features are not used.
-	  var sawReadOnlySpans = false, sawCollapsedSpans = false;
-
-	  // EDITOR CONSTRUCTOR
-
-	  // A CodeMirror instance represents an editor. This is the object
-	  // that user code is usually dealing with.
-
-	  function CodeMirror(place, options) {
-	    if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
-
-	    this.options = options = options ? copyObj(options) : {};
-	    // Determine effective options based on given values and defaults.
-	    copyObj(defaults, options, false);
-	    setGuttersForLineNumbers(options);
-
-	    var doc = options.value;
-	    if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
-	    this.doc = doc;
-
-	    var input = new CodeMirror.inputStyles[options.inputStyle](this);
-	    var display = this.display = new Display(place, doc, input);
-	    display.wrapper.CodeMirror = this;
-	    updateGutters(this);
-	    themeChanged(this);
-	    if (options.lineWrapping)
-	      this.display.wrapper.className += " CodeMirror-wrap";
-	    if (options.autofocus && !mobile) display.input.focus();
-	    initScrollbars(this);
-
-	    this.state = {
-	      keyMaps: [],  // stores maps added by addKeyMap
-	      overlays: [], // highlighting overlays, as added by addOverlay
-	      modeGen: 0,   // bumped when mode/overlay changes, used to invalidate highlighting info
-	      overwrite: false,
-	      delayingBlurEvent: false,
-	      focused: false,
-	      suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
-	      pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
-	      selectingText: false,
-	      draggingText: false,
-	      highlight: new Delayed(), // stores highlight worker timeout
-	      keySeq: null,  // Unfinished key sequence
-	      specialChars: null
-	    };
-
-	    var cm = this;
-
-	    // Override magic textarea content restore that IE sometimes does
-	    // on our hidden textarea on reload
-	    if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
-
-	    registerEventHandlers(this);
-	    ensureGlobalHandlers();
-
-	    startOperation(this);
-	    this.curOp.forceUpdate = true;
-	    attachDoc(this, doc);
-
-	    if ((options.autofocus && !mobile) || cm.hasFocus())
-	      setTimeout(bind(onFocus, this), 20);
-	    else
-	      onBlur(this);
-
-	    for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
-	      optionHandlers[opt](this, options[opt], Init);
-	    maybeUpdateLineNumberWidth(this);
-	    if (options.finishInit) options.finishInit(this);
-	    for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
-	    endOperation(this);
-	    // Suppress optimizelegibility in Webkit, since it breaks text
-	    // measuring on line wrapping boundaries.
-	    if (webkit && options.lineWrapping &&
-	        getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
-	      display.lineDiv.style.textRendering = "auto";
-	  }
-
-	  // DISPLAY CONSTRUCTOR
-
-	  // The display handles the DOM integration, both for input reading
-	  // and content drawing. It holds references to DOM nodes and
-	  // display-related state.
-
-	  function Display(place, doc, input) {
-	    var d = this;
-	    this.input = input;
-
-	    // Covers bottom-right square when both scrollbars are present.
-	    d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
-	    d.scrollbarFiller.setAttribute("cm-not-content", "true");
-	    // Covers bottom of gutter when coverGutterNextToScrollbar is on
-	    // and h scrollbar is present.
-	    d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
-	    d.gutterFiller.setAttribute("cm-not-content", "true");
-	    // Will contain the actual code, positioned to cover the viewport.
-	    d.lineDiv = elt("div", null, "CodeMirror-code");
-	    // Elements are added to these to represent selection and cursors.
-	    d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
-	    d.cursorDiv = elt("div", null, "CodeMirror-cursors");
-	    // A visibility: hidden element used to find the size of things.
-	    d.measure = elt("div", null, "CodeMirror-measure");
-	    // When lines outside of the viewport are measured, they are drawn in this.
-	    d.lineMeasure = elt("div", null, "CodeMirror-measure");
-	    // Wraps everything that needs to exist inside the vertically-padded coordinate system
-	    d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
-	                      null, "position: relative; outline: none");
-	    // Moved around its parent to cover visible view.
-	    d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
-	    // Set to the height of the document, allowing scrolling.
-	    d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
-	    d.sizerWidth = null;
-	    // Behavior of elts with overflow: auto and padding is
-	    // inconsistent across browsers. This is used to ensure the
-	    // scrollable area is big enough.
-	    d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
-	    // Will contain the gutters, if any.
-	    d.gutters = elt("div", null, "CodeMirror-gutters");
-	    d.lineGutter = null;
-	    // Actual scrollable element.
-	    d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
-	    d.scroller.setAttribute("tabIndex", "-1");
-	    // The element in which the editor lives.
-	    d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
-
-	    // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
-	    if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
-	    if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
-
-	    if (place) {
-	      if (place.appendChild) place.appendChild(d.wrapper);
-	      else place(d.wrapper);
-	    }
-
-	    // Current rendered range (may be bigger than the view window).
-	    d.viewFrom = d.viewTo = doc.first;
-	    d.reportedViewFrom = d.reportedViewTo = doc.first;
-	    // Information about the rendered lines.
-	    d.view = [];
-	    d.renderedView = null;
-	    // Holds info about a single rendered line when it was rendered
-	    // for measurement, while not in view.
-	    d.externalMeasured = null;
-	    // Empty space (in pixels) above the view
-	    d.viewOffset = 0;
-	    d.lastWrapHeight = d.lastWrapWidth = 0;
-	    d.updateLineNumbers = null;
-
-	    d.nativeBarWidth = d.barHeight = d.barWidth = 0;
-	    d.scrollbarsClipped = false;
-
-	    // Used to only resize the line number gutter when necessary (when
-	    // the amount of lines crosses a boundary that makes its width change)
-	    d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
-	    // Set to true when a non-horizontal-scrolling line widget is
-	    // added. As an optimization, line widget aligning is skipped when
-	    // this is false.
-	    d.alignWidgets = false;
-
-	    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
-
-	    // Tracks the maximum line length so that the horizontal scrollbar
-	    // can be kept static when scrolling.
-	    d.maxLine = null;
-	    d.maxLineLength = 0;
-	    d.maxLineChanged = false;
-
-	    // Used for measuring wheel scrolling granularity
-	    d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
-
-	    // True when shift is held down.
-	    d.shift = false;
-
-	    // Used to track whether anything happened since the context menu
-	    // was opened.
-	    d.selForContextMenu = null;
-
-	    d.activeTouch = null;
-
-	    input.init(d);
-	  }
-
-	  // STATE UPDATES
-
-	  // Used to get the editor into a consistent state again when options change.
-
-	  function loadMode(cm) {
-	    cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
-	    resetModeState(cm);
-	  }
-
-	  function resetModeState(cm) {
-	    cm.doc.iter(function(line) {
-	      if (line.stateAfter) line.stateAfter = null;
-	      if (line.styles) line.styles = null;
-	    });
-	    cm.doc.frontier = cm.doc.first;
-	    startWorker(cm, 100);
-	    cm.state.modeGen++;
-	    if (cm.curOp) regChange(cm);
-	  }
-
-	  function wrappingChanged(cm) {
-	    if (cm.options.lineWrapping) {
-	      addClass(cm.display.wrapper, "CodeMirror-wrap");
-	      cm.display.sizer.style.minWidth = "";
-	      cm.display.sizerWidth = null;
+	(function (global, factory) {
+	   true ? module.exports = factory() :
+	  typeof define === 'function' && define.amd ? define(factory) :
+	  (global.CodeMirror = factory());
+	}(this, (function () { 'use strict';
+
+	// Kludges for bugs and behavior differences that can't be feature
+	// detected are enabled based on userAgent etc sniffing.
+	var userAgent = navigator.userAgent
+	var platform = navigator.platform
+
+	var gecko = /gecko\/\d/i.test(userAgent)
+	var ie_upto10 = /MSIE \d/.test(userAgent)
+	var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent)
+	var edge = /Edge\/(\d+)/.exec(userAgent)
+	var ie = ie_upto10 || ie_11up || edge
+	var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1])
+	var webkit = !edge && /WebKit\//.test(userAgent)
+	var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent)
+	var chrome = !edge && /Chrome\//.test(userAgent)
+	var presto = /Opera\//.test(userAgent)
+	var safari = /Apple Computer/.test(navigator.vendor)
+	var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent)
+	var phantom = /PhantomJS/.test(userAgent)
+
+	var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent)
+	var android = /Android/.test(userAgent)
+	// This is woefully incomplete. Suggestions for alternative methods welcome.
+	var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent)
+	var mac = ios || /Mac/.test(platform)
+	var chromeOS = /\bCrOS\b/.test(userAgent)
+	var windows = /win/i.test(platform)
+
+	var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/)
+	if (presto_version) { presto_version = Number(presto_version[1]) }
+	if (presto_version && presto_version >= 15) { presto = false; webkit = true }
+	// Some browsers use the wrong event properties to signal cmd/ctrl on OS X
+	var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11))
+	var captureRightClick = gecko || (ie && ie_version >= 9)
+
+	function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
+
+	var rmClass = function(node, cls) {
+	  var current = node.className
+	  var match = classTest(cls).exec(current)
+	  if (match) {
+	    var after = current.slice(match.index + match[0].length)
+	    node.className = current.slice(0, match.index) + (after ? match[1] + after : "")
+	  }
+	}
+
+	function removeChildren(e) {
+	  for (var count = e.childNodes.length; count > 0; --count)
+	    { e.removeChild(e.firstChild) }
+	  return e
+	}
+
+	function removeChildrenAndAdd(parent, e) {
+	  return removeChildren(parent).appendChild(e)
+	}
+
+	function elt(tag, content, className, style) {
+	  var e = document.createElement(tag)
+	  if (className) { e.className = className }
+	  if (style) { e.style.cssText = style }
+	  if (typeof content == "string") { e.appendChild(document.createTextNode(content)) }
+	  else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]) } }
+	  return e
+	}
+	// wrapper for elt, which removes the elt from the accessibility tree
+	function eltP(tag, content, className, style) {
+	  var e = elt(tag, content, className, style)
+	  e.setAttribute("role", "presentation")
+	  return e
+	}
+
+	var range
+	if (document.createRange) { range = function(node, start, end, endNode) {
+	  var r = document.createRange()
+	  r.setEnd(endNode || node, end)
+	  r.setStart(node, start)
+	  return r
+	} }
+	else { range = function(node, start, end) {
+	  var r = document.body.createTextRange()
+	  try { r.moveToElementText(node.parentNode) }
+	  catch(e) { return r }
+	  r.collapse(true)
+	  r.moveEnd("character", end)
+	  r.moveStart("character", start)
+	  return r
+	} }
+
+	function contains(parent, child) {
+	  if (child.nodeType == 3) // Android browser always returns false when child is a textnode
+	    { child = child.parentNode }
+	  if (parent.contains)
+	    { return parent.contains(child) }
+	  do {
+	    if (child.nodeType == 11) { child = child.host }
+	    if (child == parent) { return true }
+	  } while (child = child.parentNode)
+	}
+
+	function activeElt() {
+	  // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
+	  // IE < 10 will throw when accessed while the page is loading or in an iframe.
+	  // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
+	  var activeElement
+	  try {
+	    activeElement = document.activeElement
+	  } catch(e) {
+	    activeElement = document.body || null
+	  }
+	  while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
+	    { activeElement = activeElement.shadowRoot.activeElement }
+	  return activeElement
+	}
+
+	function addClass(node, cls) {
+	  var current = node.className
+	  if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls }
+	}
+	function joinClasses(a, b) {
+	  var as = a.split(" ")
+	  for (var i = 0; i < as.length; i++)
+	    { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i] } }
+	  return b
+	}
+
+	var selectInput = function(node) { node.select() }
+	if (ios) // Mobile Safari apparently has a bug where select() is broken.
+	  { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length } }
+	else if (ie) // Suppress mysterious IE10 errors
+	  { selectInput = function(node) { try { node.select() } catch(_e) {} } }
+
+	function bind(f) {
+	  var args = Array.prototype.slice.call(arguments, 1)
+	  return function(){return f.apply(null, args)}
+	}
+
+	function copyObj(obj, target, overwrite) {
+	  if (!target) { target = {} }
+	  for (var prop in obj)
+	    { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
+	      { target[prop] = obj[prop] } }
+	  return target
+	}
+
+	// Counts the column offset in a string, taking tabs into account.
+	// Used mostly to find indentation.
+	function countColumn(string, end, tabSize, startIndex, startValue) {
+	  if (end == null) {
+	    end = string.search(/[^\s\u00a0]/)
+	    if (end == -1) { end = string.length }
+	  }
+	  for (var i = startIndex || 0, n = startValue || 0;;) {
+	    var nextTab = string.indexOf("\t", i)
+	    if (nextTab < 0 || nextTab >= end)
+	      { return n + (end - i) }
+	    n += nextTab - i
+	    n += tabSize - (n % tabSize)
+	    i = nextTab + 1
+	  }
+	}
+
+	var Delayed = function() {this.id = null};
+	Delayed.prototype.set = function (ms, f) {
+	  clearTimeout(this.id)
+	  this.id = setTimeout(f, ms)
+	};
+
+	function indexOf(array, elt) {
+	  for (var i = 0; i < array.length; ++i)
+	    { if (array[i] == elt) { return i } }
+	  return -1
+	}
+
+	// Number of pixels added to scroller and sizer to hide scrollbar
+	var scrollerGap = 30
+
+	// Returned or thrown by various protocols to signal 'I'm not
+	// handling this'.
+	var Pass = {toString: function(){return "CodeMirror.Pass"}}
+
+	// Reused option objects for setSelection & friends
+	var sel_dontScroll = {scroll: false};
+	var sel_mouse = {origin: "*mouse"};
+	var sel_move = {origin: "+move"};
+	// The inverse of countColumn -- find the offset that corresponds to
+	// a particular column.
+	function findColumn(string, goal, tabSize) {
+	  for (var pos = 0, col = 0;;) {
+	    var nextTab = string.indexOf("\t", pos)
+	    if (nextTab == -1) { nextTab = string.length }
+	    var skipped = nextTab - pos
+	    if (nextTab == string.length || col + skipped >= goal)
+	      { return pos + Math.min(skipped, goal - col) }
+	    col += nextTab - pos
+	    col += tabSize - (col % tabSize)
+	    pos = nextTab + 1
+	    if (col >= goal) { return pos }
+	  }
+	}
+
+	var spaceStrs = [""]
+	function spaceStr(n) {
+	  while (spaceStrs.length <= n)
+	    { spaceStrs.push(lst(spaceStrs) + " ") }
+	  return spaceStrs[n]
+	}
+
+	function lst(arr) { return arr[arr.length-1] }
+
+	function map(array, f) {
+	  var out = []
+	  for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i) }
+	  return out
+	}
+
+	function insertSorted(array, value, score) {
+	  var pos = 0, priority = score(value)
+	  while (pos < array.length && score(array[pos]) <= priority) { pos++ }
+	  array.splice(pos, 0, value)
+	}
+
+	function nothing() {}
+
+	function createObj(base, props) {
+	  var inst
+	  if (Object.create) {
+	    inst = Object.create(base)
+	  } else {
+	    nothing.prototype = base
+	    inst = new nothing()
+	  }
+	  if (props) { copyObj(props, inst) }
+	  return inst
+	}
+
+	var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/
+	function isWordCharBasic(ch) {
+	  return /\w/.test(ch) || ch > "\x80" &&
+	    (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
+	}
+	function isWordChar(ch, helper) {
+	  if (!helper) { return isWordCharBasic(ch) }
+	  if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
+	  return helper.test(ch)
+	}
+
+	function isEmpty(obj) {
+	  for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
+	  return true
+	}
+
+	// Extending unicode characters. A series of a non-extending char +
+	// any number of extending chars is treated as a single unit as far
+	// as editing and measuring is concerned. This is not fully correct,
+	// since some scripts/fonts/browsers also treat other configurations
+	// of code points as a group.
+	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]/
+	function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
+
+	// Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
+	function skipExtendingChars(str, pos, dir) {
+	  while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir }
+	  return pos
+	}
+
+	// Returns the value from the range [`from`; `to`] that satisfies
+	// `pred` and is closest to `from`. Assumes that at least `to` satisfies `pred`.
+	function findFirst(pred, from, to) {
+	  for (;;) {
+	    if (Math.abs(from - to) <= 1) { return pred(from) ? from : to }
+	    var mid = Math.floor((from + to) / 2)
+	    if (pred(mid)) { to = mid }
+	    else { from = mid }
+	  }
+	}
+
+	// The display handles the DOM integration, both for input reading
+	// and content drawing. It holds references to DOM nodes and
+	// display-related state.
+
+	function Display(place, doc, input) {
+	  var d = this
+	  this.input = input
+
+	  // Covers bottom-right square when both scrollbars are present.
+	  d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler")
+	  d.scrollbarFiller.setAttribute("cm-not-content", "true")
+	  // Covers bottom of gutter when coverGutterNextToScrollbar is on
+	  // and h scrollbar is present.
+	  d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler")
+	  d.gutterFiller.setAttribute("cm-not-content", "true")
+	  // Will contain the actual code, positioned to cover the viewport.
+	  d.lineDiv = eltP("div", null, "CodeMirror-code")
+	  // Elements are added to these to represent selection and cursors.
+	  d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1")
+	  d.cursorDiv = elt("div", null, "CodeMirror-cursors")
+	  // A visibility: hidden element used to find the size of things.
+	  d.measure = elt("div", null, "CodeMirror-measure")
+	  // When lines outside of the viewport are measured, they are drawn in this.
+	  d.lineMeasure = elt("div", null, "CodeMirror-measure")
+	  // Wraps everything that needs to exist inside the vertically-padded coordinate system
+	  d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
+	                    null, "position: relative; outline: none")
+	  var lines = eltP("div", [d.lineSpace], "CodeMirror-lines")
+	  // Moved around its parent to cover visible view.
+	  d.mover = elt("div", [lines], null, "position: relative")
+	  // Set to the height of the document, allowing scrolling.
+	  d.sizer = elt("div", [d.mover], "CodeMirror-sizer")
+	  d.sizerWidth = null
+	  // Behavior of elts with overflow: auto and padding is
+	  // inconsistent across browsers. This is used to ensure the
+	  // scrollable area is big enough.
+	  d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;")
+	  // Will contain the gutters, if any.
+	  d.gutters = elt("div", null, "CodeMirror-gutters")
+	  d.lineGutter = null
+	  // Actual scrollable element.
+	  d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll")
+	  d.scroller.setAttribute("tabIndex", "-1")
+	  // The element in which the editor lives.
+	  d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror")
+
+	  // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
+	  if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 }
+	  if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true }
+
+	  if (place) {
+	    if (place.appendChild) { place.appendChild(d.wrapper) }
+	    else { place(d.wrapper) }
+	  }
+
+	  // Current rendered range (may be bigger than the view window).
+	  d.viewFrom = d.viewTo = doc.first
+	  d.reportedViewFrom = d.reportedViewTo = doc.first
+	  // Information about the rendered lines.
+	  d.view = []
+	  d.renderedView = null
+	  // Holds info about a single rendered line when it was rendered
+	  // for measurement, while not in view.
+	  d.externalMeasured = null
+	  // Empty space (in pixels) above the view
+	  d.viewOffset = 0
+	  d.lastWrapHeight = d.lastWrapWidth = 0
+	  d.updateLineNumbers = null
+
+	  d.nativeBarWidth = d.barHeight = d.barWidth = 0
+	  d.scrollbarsClipped = false
+
+	  // Used to only resize the line number gutter when necessary (when
+	  // the amount of lines crosses a boundary that makes its width change)
+	  d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null
+	  // Set to true when a non-horizontal-scrolling line widget is
+	  // added. As an optimization, line widget aligning is skipped when
+	  // this is false.
+	  d.alignWidgets = false
+
+	  d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
+
+	  // Tracks the maximum line length so that the horizontal scrollbar
+	  // can be kept static when scrolling.
+	  d.maxLine = null
+	  d.maxLineLength = 0
+	  d.maxLineChanged = false
+
+	  // Used for measuring wheel scrolling granularity
+	  d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null
+
+	  // True when shift is held down.
+	  d.shift = false
+
+	  // Used to track whether anything happened since the context menu
+	  // was opened.
+	  d.selForContextMenu = null
+
+	  d.activeTouch = null
+
+	  input.init(d)
+	}
+
+	// Find the line object corresponding to the given line number.
+	function getLine(doc, n) {
+	  n -= doc.first
+	  if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
+	  var chunk = doc
+	  while (!chunk.lines) {
+	    for (var i = 0;; ++i) {
+	      var child = chunk.children[i], sz = child.chunkSize()
+	      if (n < sz) { chunk = child; break }
+	      n -= sz
+	    }
+	  }
+	  return chunk.lines[n]
+	}
+
+	// Get the part of a document between two positions, as an array of
+	// strings.
+	function getBetween(doc, start, end) {
+	  var out = [], n = start.line
+	  doc.iter(start.line, end.line + 1, function (line) {
+	    var text = line.text
+	    if (n == end.line) { text = text.slice(0, end.ch) }
+	    if (n == start.line) { text = text.slice(start.ch) }
+	    out.push(text)
+	    ++n
+	  })
+	  return out
+	}
+	// Get the lines between from and to, as array of strings.
+	function getLines(doc, from, to) {
+	  var out = []
+	  doc.iter(from, to, function (line) { out.push(line.text) }) // iter aborts when callback returns truthy value
+	  return out
+	}
+
+	// Update the height of a line, propagating the height change
+	// upwards to parent nodes.
+	function updateLineHeight(line, height) {
+	  var diff = height - line.height
+	  if (diff) { for (var n = line; n; n = n.parent) { n.height += diff } }
+	}
+
+	// Given a line object, find its line number by walking up through
+	// its parent links.
+	function lineNo(line) {
+	  if (line.parent == null) { return null }
+	  var cur = line.parent, no = indexOf(cur.lines, line)
+	  for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
+	    for (var i = 0;; ++i) {
+	      if (chunk.children[i] == cur) { break }
+	      no += chunk.children[i].chunkSize()
+	    }
+	  }
+	  return no + cur.first
+	}
+
+	// Find the line at the given vertical position, using the height
+	// information in the document tree.
+	function lineAtHeight(chunk, h) {
+	  var n = chunk.first
+	  outer: do {
+	    for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
+	      var child = chunk.children[i$1], ch = child.height
+	      if (h < ch) { chunk = child; continue outer }
+	      h -= ch
+	      n += child.chunkSize()
+	    }
+	    return n
+	  } while (!chunk.lines)
+	  var i = 0
+	  for (; i < chunk.lines.length; ++i) {
+	    var line = chunk.lines[i], lh = line.height
+	    if (h < lh) { break }
+	    h -= lh
+	  }
+	  return n + i
+	}
+
+	function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
+
+	function lineNumberFor(options, i) {
+	  return String(options.lineNumberFormatter(i + options.firstLineNumber))
+	}
+
+	// A Pos instance represents a position within the text.
+	function Pos(line, ch, sticky) {
+	  if ( sticky === void 0 ) sticky = null;
+
+	  if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
+	  this.line = line
+	  this.ch = ch
+	  this.sticky = sticky
+	}
+
+	// Compare two positions, return 0 if they are the same, a negative
+	// number when a is less, and a positive number otherwise.
+	function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
+
+	function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
+
+	function copyPos(x) {return Pos(x.line, x.ch)}
+	function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
+	function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
+
+	// Most of the external API clips given positions to make sure they
+	// actually exist within the document.
+	function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
+	function clipPos(doc, pos) {
+	  if (pos.line < doc.first) { return Pos(doc.first, 0) }
+	  var last = doc.first + doc.size - 1
+	  if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
+	  return clipToLen(pos, getLine(doc, pos.line).text.length)
+	}
+	function clipToLen(pos, linelen) {
+	  var ch = pos.ch
+	  if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
+	  else if (ch < 0) { return Pos(pos.line, 0) }
+	  else { return pos }
+	}
+	function clipPosArray(doc, array) {
+	  var out = []
+	  for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]) }
+	  return out
+	}
+
+	// Optimize some code when these features are not used.
+	var sawReadOnlySpans = false;
+	var sawCollapsedSpans = false;
+	function seeReadOnlySpans() {
+	  sawReadOnlySpans = true
+	}
+
+	function seeCollapsedSpans() {
+	  sawCollapsedSpans = true
+	}
+
+	// TEXTMARKER SPANS
+
+	function MarkedSpan(marker, from, to) {
+	  this.marker = marker
+	  this.from = from; this.to = to
+	}
+
+	// Search an array of spans for a span matching the given marker.
+	function getMarkedSpanFor(spans, marker) {
+	  if (spans) { for (var i = 0; i < spans.length; ++i) {
+	    var span = spans[i]
+	    if (span.marker == marker) { return span }
+	  } }
+	}
+	// Remove a span from an array, returning undefined if no spans are
+	// left (we don't store arrays for lines without spans).
+	function removeMarkedSpan(spans, span) {
+	  var r
+	  for (var i = 0; i < spans.length; ++i)
+	    { if (spans[i] != span) { (r || (r = [])).push(spans[i]) } }
+	  return r
+	}
+	// Add a span to a line.
+	function addMarkedSpan(line, span) {
+	  line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]
+	  span.marker.attachLine(line)
+	}
+
+	// Used for the algorithm that adjusts markers for a change in the
+	// document. These functions cut an array of spans at a given
+	// character position, returning an array of remaining chunks (or
+	// undefined if nothing remains).
+	function markedSpansBefore(old, startCh, isInsert) {
+	  var nw
+	  if (old) { for (var i = 0; i < old.length; ++i) {
+	    var span = old[i], marker = span.marker
+	    var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh)
+	    if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
+	      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
+	      ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to))
+	    }
+	  } }
+	  return nw
+	}
+	function markedSpansAfter(old, endCh, isInsert) {
+	  var nw
+	  if (old) { for (var i = 0; i < old.length; ++i) {
+	    var span = old[i], marker = span.marker
+	    var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh)
+	    if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
+	      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
+	      ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
+	                                            span.to == null ? null : span.to - endCh))
+	    }
+	  } }
+	  return nw
+	}
+
+	// Given a change object, compute the new set of marker spans that
+	// cover the line in which the change took place. Removes spans
+	// entirely within the change, reconnects spans belonging to the
+	// same marker that appear on both sides of the change, and cuts off
+	// spans partially within the change. Returns an array of span
+	// arrays with one element for each line in (after) the change.
+	function stretchSpansOverChange(doc, change) {
+	  if (change.full) { return null }
+	  var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans
+	  var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans
+	  if (!oldFirst && !oldLast) { return null }
+
+	  var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0
+	  // Get the spans that 'stick out' on both sides
+	  var first = markedSpansBefore(oldFirst, startCh, isInsert)
+	  var last = markedSpansAfter(oldLast, endCh, isInsert)
+
+	  // Next, merge those two ends
+	  var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0)
+	  if (first) {
+	    // Fix up .to properties of first
+	    for (var i = 0; i < first.length; ++i) {
+	      var span = first[i]
+	      if (span.to == null) {
+	        var found = getMarkedSpanFor(last, span.marker)
+	        if (!found) { span.to = startCh }
+	        else if (sameLine) { span.to = found.to == null ? null : found.to + offset }
+	      }
+	    }
+	  }
+	  if (last) {
+	    // Fix up .from in last (or move them into first in case of sameLine)
+	    for (var i$1 = 0; i$1 < last.length; ++i$1) {
+	      var span$1 = last[i$1]
+	      if (span$1.to != null) { span$1.to += offset }
+	      if (span$1.from == null) {
+	        var found$1 = getMarkedSpanFor(first, span$1.marker)
+	        if (!found$1) {
+	          span$1.from = offset
+	          if (sameLine) { (first || (first = [])).push(span$1) }
+	        }
+	      } else {
+	        span$1.from += offset
+	        if (sameLine) { (first || (first = [])).push(span$1) }
+	      }
+	    }
+	  }
+	  // Make sure we didn't create any zero-length spans
+	  if (first) { first = clearEmptySpans(first) }
+	  if (last && last != first) { last = clearEmptySpans(last) }
+
+	  var newMarkers = [first]
+	  if (!sameLine) {
+	    // Fill gap with whole-line-spans
+	    var gap = change.text.length - 2, gapMarkers
+	    if (gap > 0 && first)
+	      { for (var i$2 = 0; i$2 < first.length; ++i$2)
+	        { if (first[i$2].to == null)
+	          { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)) } } }
+	    for (var i$3 = 0; i$3 < gap; ++i$3)
+	      { newMarkers.push(gapMarkers) }
+	    newMarkers.push(last)
+	  }
+	  return newMarkers
+	}
+
+	// Remove spans that are empty and don't have a clearWhenEmpty
+	// option of false.
+	function clearEmptySpans(spans) {
+	  for (var i = 0; i < spans.length; ++i) {
+	    var span = spans[i]
+	    if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
+	      { spans.splice(i--, 1) }
+	  }
+	  if (!spans.length) { return null }
+	  return spans
+	}
+
+	// Used to 'clip' out readOnly ranges when making a change.
+	function removeReadOnlyRanges(doc, from, to) {
+	  var markers = null
+	  doc.iter(from.line, to.line + 1, function (line) {
+	    if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
+	      var mark = line.markedSpans[i].marker
+	      if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
+	        { (markers || (markers = [])).push(mark) }
+	    } }
+	  })
+	  if (!markers) { return null }
+	  var parts = [{from: from, to: to}]
+	  for (var i = 0; i < markers.length; ++i) {
+	    var mk = markers[i], m = mk.find(0)
+	    for (var j = 0; j < parts.length; ++j) {
+	      var p = parts[j]
+	      if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
+	      var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to)
+	      if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
+	        { newParts.push({from: p.from, to: m.from}) }
+	      if (dto > 0 || !mk.inclusiveRight && !dto)
+	        { newParts.push({from: m.to, to: p.to}) }
+	      parts.splice.apply(parts, newParts)
+	      j += newParts.length - 3
+	    }
+	  }
+	  return parts
+	}
+
+	// Connect or disconnect spans from a line.
+	function detachMarkedSpans(line) {
+	  var spans = line.markedSpans
+	  if (!spans) { return }
+	  for (var i = 0; i < spans.length; ++i)
+	    { spans[i].marker.detachLine(line) }
+	  line.markedSpans = null
+	}
+	function attachMarkedSpans(line, spans) {
+	  if (!spans) { return }
+	  for (var i = 0; i < spans.length; ++i)
+	    { spans[i].marker.attachLine(line) }
+	  line.markedSpans = spans
+	}
+
+	// Helpers used when computing which overlapping collapsed span
+	// counts as the larger one.
+	function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
+	function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
+
+	// Returns a number indicating which of two overlapping collapsed
+	// spans is larger (and thus includes the other). Falls back to
+	// comparing ids when the spans cover exactly the same range.
+	function compareCollapsedMarkers(a, b) {
+	  var lenDiff = a.lines.length - b.lines.length
+	  if (lenDiff != 0) { return lenDiff }
+	  var aPos = a.find(), bPos = b.find()
+	  var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b)
+	  if (fromCmp) { return -fromCmp }
+	  var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b)
+	  if (toCmp) { return toCmp }
+	  return b.id - a.id
+	}
+
+	// Find out whether a line ends or starts in a collapsed span. If
+	// so, return the marker for that span.
+	function collapsedSpanAtSide(line, start) {
+	  var sps = sawCollapsedSpans && line.markedSpans, found
+	  if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
+	    sp = sps[i]
+	    if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
+	        (!found || compareCollapsedMarkers(found, sp.marker) < 0))
+	      { found = sp.marker }
+	  } }
+	  return found
+	}
+	function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
+	function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
+
+	// Test whether there exists a collapsed span that partially
+	// overlaps (covers the start or end, but not both) of a new span.
+	// Such overlap is not allowed.
+	function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
+	  var line = getLine(doc, lineNo)
+	  var sps = sawCollapsedSpans && line.markedSpans
+	  if (sps) { for (var i = 0; i < sps.length; ++i) {
+	    var sp = sps[i]
+	    if (!sp.marker.collapsed) { continue }
+	    var found = sp.marker.find(0)
+	    var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker)
+	    var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker)
+	    if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
+	    if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
+	        fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
+	      { return true }
+	  } }
+	}
+
+	// A visual line is a line as drawn on the screen. Folding, for
+	// example, can cause multiple logical lines to appear on the same
+	// visual line. This finds the start of the visual line that the
+	// given line is part of (usually that is the line itself).
+	function visualLine(line) {
+	  var merged
+	  while (merged = collapsedSpanAtStart(line))
+	    { line = merged.find(-1, true).line }
+	  return line
+	}
+
+	function visualLineEnd(line) {
+	  var merged
+	  while (merged = collapsedSpanAtEnd(line))
+	    { line = merged.find(1, true).line }
+	  return line
+	}
+
+	// Returns an array of logical lines that continue the visual line
+	// started by the argument, or undefined if there are no such lines.
+	function visualLineContinued(line) {
+	  var merged, lines
+	  while (merged = collapsedSpanAtEnd(line)) {
+	    line = merged.find(1, true).line
+	    ;(lines || (lines = [])).push(line)
+	  }
+	  return lines
+	}
+
+	// Get the line number of the start of the visual line that the
+	// given line number is part of.
+	function visualLineNo(doc, lineN) {
+	  var line = getLine(doc, lineN), vis = visualLine(line)
+	  if (line == vis) { return lineN }
+	  return lineNo(vis)
+	}
+
+	// Get the line number of the start of the next visual line after
+	// the given line.
+	function visualLineEndNo(doc, lineN) {
+	  if (lineN > doc.lastLine()) { return lineN }
+	  var line = getLine(doc, lineN), merged
+	  if (!lineIsHidden(doc, line)) { return lineN }
+	  while (merged = collapsedSpanAtEnd(line))
+	    { line = merged.find(1, true).line }
+	  return lineNo(line) + 1
+	}
+
+	// Compute whether a line is hidden. Lines count as hidden when they
+	// are part of a visual line that starts with another line, or when
+	// they are entirely covered by collapsed, non-widget span.
+	function lineIsHidden(doc, line) {
+	  var sps = sawCollapsedSpans && line.markedSpans
+	  if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
+	    sp = sps[i]
+	    if (!sp.marker.collapsed) { continue }
+	    if (sp.from == null) { return true }
+	    if (sp.marker.widgetNode) { continue }
+	    if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
+	      { return true }
+	  } }
+	}
+	function lineIsHiddenInner(doc, line, span) {
+	  if (span.to == null) {
+	    var end = span.marker.find(1, true)
+	    return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
+	  }
+	  if (span.marker.inclusiveRight && span.to == line.text.length)
+	    { return true }
+	  for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
+	    sp = line.markedSpans[i]
+	    if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
+	        (sp.to == null || sp.to != span.from) &&
+	        (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
+	        lineIsHiddenInner(doc, line, sp)) { return true }
+	  }
+	}
+
+	// Find the height above the given line.
+	function heightAtLine(lineObj) {
+	  lineObj = visualLine(lineObj)
+
+	  var h = 0, chunk = lineObj.parent
+	  for (var i = 0; i < chunk.lines.length; ++i) {
+	    var line = chunk.lines[i]
+	    if (line == lineObj) { break }
+	    else { h += line.height }
+	  }
+	  for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
+	    for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
+	      var cur = p.children[i$1]
+	      if (cur == chunk) { break }
+	      else { h += cur.height }
+	    }
+	  }
+	  return h
+	}
+
+	// Compute the character length of a line, taking into account
+	// collapsed ranges (see markText) that might hide parts, and join
+	// other lines onto it.
+	function lineLength(line) {
+	  if (line.height == 0) { return 0 }
+	  var len = line.text.length, merged, cur = line
+	  while (merged = collapsedSpanAtStart(cur)) {
+	    var found = merged.find(0, true)
+	    cur = found.from.line
+	    len += found.from.ch - found.to.ch
+	  }
+	  cur = line
+	  while (merged = collapsedSpanAtEnd(cur)) {
+	    var found$1 = merged.find(0, true)
+	    len -= cur.text.length - found$1.from.ch
+	    cur = found$1.to.line
+	    len += cur.text.length - found$1.to.ch
+	  }
+	  return len
+	}
+
+	// Find the longest line in the document.
+	function findMaxLine(cm) {
+	  var d = cm.display, doc = cm.doc
+	  d.maxLine = getLine(doc, doc.first)
+	  d.maxLineLength = lineLength(d.maxLine)
+	  d.maxLineChanged = true
+	  doc.iter(function (line) {
+	    var len = lineLength(line)
+	    if (len > d.maxLineLength) {
+	      d.maxLineLength = len
+	      d.maxLine = line
+	    }
+	  })
+	}
+
+	// BIDI HELPERS
+
+	function iterateBidiSections(order, from, to, f) {
+	  if (!order) { return f(from, to, "ltr") }
+	  var found = false
+	  for (var i = 0; i < order.length; ++i) {
+	    var part = order[i]
+	    if (part.from < to && part.to > from || from == to && part.to == from) {
+	      f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr")
+	      found = true
+	    }
+	  }
+	  if (!found) { f(from, to, "ltr") }
+	}
+
+	var bidiOther = null
+	function getBidiPartAt(order, ch, sticky) {
+	  var found
+	  bidiOther = null
+	  for (var i = 0; i < order.length; ++i) {
+	    var cur = order[i]
+	    if (cur.from < ch && cur.to > ch) { return i }
+	    if (cur.to == ch) {
+	      if (cur.from != cur.to && sticky == "before") { found = i }
+	      else { bidiOther = i }
+	    }
+	    if (cur.from == ch) {
+	      if (cur.from != cur.to && sticky != "before") { found = i }
+	      else { bidiOther = i }
+	    }
+	  }
+	  return found != null ? found : bidiOther
+	}
+
+	// Bidirectional ordering algorithm
+	// See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
+	// that this (partially) implements.
+
+	// One-char codes used for character types:
+	// L (L):   Left-to-Right
+	// R (R):   Right-to-Left
+	// r (AL):  Right-to-Left Arabic
+	// 1 (EN):  European Number
+	// + (ES):  European Number Separator
+	// % (ET):  European Number Terminator
+	// n (AN):  Arabic Number
+	// , (CS):  Common Number Separator
+	// m (NSM): Non-Spacing Mark
+	// b (BN):  Boundary Neutral
+	// s (B):   Paragraph Separator
+	// t (S):   Segment Separator
+	// w (WS):  Whitespace
+	// N (ON):  Other Neutrals
+
+	// Returns null if characters are ordered as they appear
+	// (left-to-right), or an array of sections ({from, to, level}
+	// objects) in the order in which they occur visually.
+	var bidiOrdering = (function() {
+	  // Character types for codepoints 0 to 0xff
+	  var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"
+	  // Character types for codepoints 0x600 to 0x6f9
+	  var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"
+	  function charType(code) {
+	    if (code <= 0xf7) { return lowTypes.charAt(code) }
+	    else if (0x590 <= code && code <= 0x5f4) { return "R" }
+	    else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
+	    else if (0x6ee <= code && code <= 0x8ac) { return "r" }
+	    else if (0x2000 <= code && code <= 0x200b) { return "w" }
+	    else if (code == 0x200c) { return "b" }
+	    else { return "L" }
+	  }
+
+	  var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/
+	  var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/
+
+	  function BidiSpan(level, from, to) {
+	    this.level = level
+	    this.from = from; this.to = to
+	  }
+
+	  return function(str, direction) {
+	    var outerType = direction == "ltr" ? "L" : "R"
+
+	    if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
+	    var len = str.length, types = []
+	    for (var i = 0; i < len; ++i)
+	      { types.push(charType(str.charCodeAt(i))) }
+
+	    // W1. Examine each non-spacing mark (NSM) in the level run, and
+	    // change the type of the NSM to the type of the previous
+	    // character. If the NSM is at the start of the level run, it will
+	    // get the type of sor.
+	    for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
+	      var type = types[i$1]
+	      if (type == "m") { types[i$1] = prev }
+	      else { prev = type }
+	    }
+
+	    // W2. Search backwards from each instance of a European number
+	    // until the first strong type (R, L, AL, or sor) is found. If an
+	    // AL is found, change the type of the European number to Arabic
+	    // number.
+	    // W3. Change all ALs to R.
+	    for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
+	      var type$1 = types[i$2]
+	      if (type$1 == "1" && cur == "r") { types[i$2] = "n" }
+	      else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R" } }
+	    }
+
+	    // W4. A single European separator between two European numbers
+	    // changes to a European number. A single common separator between
+	    // two numbers of the same type changes to that type.
+	    for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
+	      var type$2 = types[i$3]
+	      if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1" }
+	      else if (type$2 == "," && prev$1 == types[i$3+1] &&
+	               (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1 }
+	      prev$1 = type$2
+	    }
+
+	    // W5. A sequence of European terminators adjacent to European
+	    // numbers changes to all European numbers.
+	    // W6. Otherwise, separators and terminators change to Other
+	    // Neutral.
+	    for (var i$4 = 0; i$4 < len; ++i$4) {
+	      var type$3 = types[i$4]
+	      if (type$3 == ",") { types[i$4] = "N" }
+	      else if (type$3 == "%") {
+	        var end = (void 0)
+	        for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
+	        var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"
+	        for (var j = i$4; j < end; ++j) { types[j] = replace }
+	        i$4 = end - 1
+	      }
+	    }
+
+	    // W7. Search backwards from each instance of a European number
+	    // until the first strong type (R, L, or sor) is found. If an L is
+	    // found, then change the type of the European number to L.
+	    for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
+	      var type$4 = types[i$5]
+	      if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L" }
+	      else if (isStrong.test(type$4)) { cur$1 = type$4 }
+	    }
+
+	    // N1. A sequence of neutrals takes the direction of the
+	    // surrounding strong text if the text on both sides has the same
+	    // direction. European and Arabic numbers act as if they were R in
+	    // terms of their influence on neutrals. Start-of-level-run (sor)
+	    // and end-of-level-run (eor) are used at level run boundaries.
+	    // N2. Any remaining neutrals take the embedding direction.
+	    for (var i$6 = 0; i$6 < len; ++i$6) {
+	      if (isNeutral.test(types[i$6])) {
+	        var end$1 = (void 0)
+	        for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
+	        var before = (i$6 ? types[i$6-1] : outerType) == "L"
+	        var after = (end$1 < len ? types[end$1] : outerType) == "L"
+	        var replace$1 = before == after ? (before ? "L" : "R") : outerType
+	        for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1 }
+	        i$6 = end$1 - 1
+	      }
+	    }
+
+	    // Here we depart from the documented algorithm, in order to avoid
+	    // building up an actual levels array. Since there are only three
+	    // levels (0, 1, 2) in an implementation that doesn't take
+	    // explicit embedding into account, we can build up the order on
+	    // the fly, without following the level-based algorithm.
+	    var order = [], m
+	    for (var i$7 = 0; i$7 < len;) {
+	      if (countsAsLeft.test(types[i$7])) {
+	        var start = i$7
+	        for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
+	        order.push(new BidiSpan(0, start, i$7))
+	      } else {
+	        var pos = i$7, at = order.length
+	        for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
+	        for (var j$2 = pos; j$2 < i$7;) {
+	          if (countsAsNum.test(types[j$2])) {
+	            if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)) }
+	            var nstart = j$2
+	            for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
+	            order.splice(at, 0, new BidiSpan(2, nstart, j$2))
+	            pos = j$2
+	          } else { ++j$2 }
+	        }
+	        if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)) }
+	      }
+	    }
+	    if (order[0].level == 1 && (m = str.match(/^\s+/))) {
+	      order[0].from = m[0].length
+	      order.unshift(new BidiSpan(0, 0, m[0].length))
+	    }
+	    if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
+	      lst(order).to -= m[0].length
+	      order.push(new BidiSpan(0, len - m[0].length, len))
+	    }
+
+	    return direction == "rtl" ? order.reverse() : order
+	  }
+	})()
+
+	// Get the bidi ordering for the given line (and cache it). Returns
+	// false for lines that are fully left-to-right, and an array of
+	// BidiSpan objects otherwise.
+	function getOrder(line, direction) {
+	  var order = line.order
+	  if (order == null) { order = line.order = bidiOrdering(line.text, direction) }
+	  return order
+	}
+
+	function moveCharLogically(line, ch, dir) {
+	  var target = skipExtendingChars(line.text, ch + dir, dir)
+	  return target < 0 || target > line.text.length ? null : target
+	}
+
+	function moveLogically(line, start, dir) {
+	  var ch = moveCharLogically(line, start.ch, dir)
+	  return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
+	}
+
+	function endOfLine(visually, cm, lineObj, lineNo, dir) {
+	  if (visually) {
+	    var order = getOrder(lineObj, cm.doc.direction)
+	    if (order) {
+	      var part = dir < 0 ? lst(order) : order[0]
+	      var moveInStorageOrder = (dir < 0) == (part.level == 1)
+	      var sticky = moveInStorageOrder ? "after" : "before"
+	      var ch
+	      // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
+	      // it could be that the last bidi part is not on the last visual line,
+	      // since visual lines contain content order-consecutive chunks.
+	      // Thus, in rtl, we are looking for the first (content-order) character
+	      // in the rtl chunk that is on the last line (that is, the same line
+	      // as the last (content-order) character).
+	      if (part.level > 0) {
+	        var prep = prepareMeasureForLine(cm, lineObj)
+	        ch = dir < 0 ? lineObj.text.length - 1 : 0
+	        var targetTop = measureCharPrepared(cm, prep, ch).top
+	        ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch)
+	        if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1) }
+	      } else { ch = dir < 0 ? part.to : part.from }
+	      return new Pos(lineNo, ch, sticky)
+	    }
+	  }
+	  return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
+	}
+
+	function moveVisually(cm, line, start, dir) {
+	  var bidi = getOrder(line, cm.doc.direction)
+	  if (!bidi) { return moveLogically(line, start, dir) }
+	  if (start.ch >= line.text.length) {
+	    start.ch = line.text.length
+	    start.sticky = "before"
+	  } else if (start.ch <= 0) {
+	    start.ch = 0
+	    start.sticky = "after"
+	  }
+	  var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]
+	  if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
+	    // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
+	    // nothing interesting happens.
+	    return moveLogically(line, start, dir)
+	  }
+
+	  var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }
+	  var prep
+	  var getWrappedLineExtent = function (ch) {
+	    if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
+	    prep = prep || prepareMeasureForLine(cm, line)
+	    return wrappedLineExtentChar(cm, line, prep, ch)
+	  }
+	  var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch)
+
+	  if (cm.doc.direction == "rtl" || part.level == 1) {
+	    var moveInStorageOrder = (part.level == 1) == (dir < 0)
+	    var ch = mv(start, moveInStorageOrder ? 1 : -1)
+	    if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
+	      // Case 2: We move within an rtl part or in an rtl editor on the same visual line
+	      var sticky = moveInStorageOrder ? "before" : "after"
+	      return new Pos(start.line, ch, sticky)
+	    }
+	  }
+
+	  // Case 3: Could not move within this bidi part in this visual line, so leave
+	  // the current bidi part
+
+	  var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
+	    var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
+	      ? new Pos(start.line, mv(ch, 1), "before")
+	      : new Pos(start.line, ch, "after"); }
+
+	    for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
+	      var part = bidi[partPos]
+	      var moveInStorageOrder = (dir > 0) == (part.level != 1)
+	      var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1)
+	      if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
+	      ch = moveInStorageOrder ? part.from : mv(part.to, -1)
+	      if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
+	    }
+	  }
+
+	  // Case 3a: Look for other bidi parts on the same visual line
+	  var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent)
+	  if (res) { return res }
+
+	  // Case 3b: Look for other bidi parts on the next visual line
+	  var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1)
+	  if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
+	    res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh))
+	    if (res) { return res }
+	  }
+
+	  // Case 4: Nowhere to move
+	  return null
+	}
+
+	// EVENT HANDLING
+
+	// Lightweight event framework. on/off also work on DOM nodes,
+	// registering native DOM handlers.
+
+	var noHandlers = []
+
+	var on = function(emitter, type, f) {
+	  if (emitter.addEventListener) {
+	    emitter.addEventListener(type, f, false)
+	  } else if (emitter.attachEvent) {
+	    emitter.attachEvent("on" + type, f)
+	  } else {
+	    var map = emitter._handlers || (emitter._handlers = {})
+	    map[type] = (map[type] || noHandlers).concat(f)
+	  }
+	}
+
+	function getHandlers(emitter, type) {
+	  return emitter._handlers && emitter._handlers[type] || noHandlers
+	}
+
+	function off(emitter, type, f) {
+	  if (emitter.removeEventListener) {
+	    emitter.removeEventListener(type, f, false)
+	  } else if (emitter.detachEvent) {
+	    emitter.detachEvent("on" + type, f)
+	  } else {
+	    var map = emitter._handlers, arr = map && map[type]
+	    if (arr) {
+	      var index = indexOf(arr, f)
+	      if (index > -1)
+	        { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)) }
+	    }
+	  }
+	}
+
+	function signal(emitter, type /*, values...*/) {
+	  var handlers = getHandlers(emitter, type)
+	  if (!handlers.length) { return }
+	  var args = Array.prototype.slice.call(arguments, 2)
+	  for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args) }
+	}
+
+	// The DOM events that CodeMirror handles can be overridden by
+	// registering a (non-DOM) handler on the editor for the event name,
+	// and preventDefault-ing the event in that handler.
+	function signalDOMEvent(cm, e, override) {
+	  if (typeof e == "string")
+	    { e = {type: e, preventDefault: function() { this.defaultPrevented = true }} }
+	  signal(cm, override || e.type, cm, e)
+	  return e_defaultPrevented(e) || e.codemirrorIgnore
+	}
+
+	function signalCursorActivity(cm) {
+	  var arr = cm._handlers && cm._handlers.cursorActivity
+	  if (!arr) { return }
+	  var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = [])
+	  for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
+	    { set.push(arr[i]) } }
+	}
+
+	function hasHandler(emitter, type) {
+	  return getHandlers(emitter, type).length > 0
+	}
+
+	// Add on and off methods to a constructor's prototype, to make
+	// registering events on such objects more convenient.
+	function eventMixin(ctor) {
+	  ctor.prototype.on = function(type, f) {on(this, type, f)}
+	  ctor.prototype.off = function(type, f) {off(this, type, f)}
+	}
+
+	// Due to the fact that we still support jurassic IE versions, some
+	// compatibility wrappers are needed.
+
+	function e_preventDefault(e) {
+	  if (e.preventDefault) { e.preventDefault() }
+	  else { e.returnValue = false }
+	}
+	function e_stopPropagation(e) {
+	  if (e.stopPropagation) { e.stopPropagation() }
+	  else { e.cancelBubble = true }
+	}
+	function e_defaultPrevented(e) {
+	  return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
+	}
+	function e_stop(e) {e_preventDefault(e); e_stopPropagation(e)}
+
+	function e_target(e) {return e.target || e.srcElement}
+	function e_button(e) {
+	  var b = e.which
+	  if (b == null) {
+	    if (e.button & 1) { b = 1 }
+	    else if (e.button & 2) { b = 3 }
+	    else if (e.button & 4) { b = 2 }
+	  }
+	  if (mac && e.ctrlKey && b == 1) { b = 3 }
+	  return b
+	}
+
+	// Detect drag-and-drop
+	var dragAndDrop = function() {
+	  // There is *some* kind of drag-and-drop support in IE6-8, but I
+	  // couldn't get it to work yet.
+	  if (ie && ie_version < 9) { return false }
+	  var div = elt('div')
+	  return "draggable" in div || "dragDrop" in div
+	}()
+
+	var zwspSupported
+	function zeroWidthElement(measure) {
+	  if (zwspSupported == null) {
+	    var test = elt("span", "\u200b")
+	    removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]))
+	    if (measure.firstChild.offsetHeight != 0)
+	      { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8) }
+	  }
+	  var node = zwspSupported ? elt("span", "\u200b") :
+	    elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px")
+	  node.setAttribute("cm-text", "")
+	  return node
+	}
+
+	// Feature-detect IE's crummy client rect reporting for bidi text
+	var badBidiRects
+	function hasBadBidiRects(measure) {
+	  if (badBidiRects != null) { return badBidiRects }
+	  var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"))
+	  var r0 = range(txt, 0, 1).getBoundingClientRect()
+	  var r1 = range(txt, 1, 2).getBoundingClientRect()
+	  removeChildren(measure)
+	  if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
+	  return badBidiRects = (r1.right - r0.right < 3)
+	}
+
+	// See if "".split is the broken IE version, if so, provide an
+	// alternative way to split lines.
+	var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
+	  var pos = 0, result = [], l = string.length
+	  while (pos <= l) {
+	    var nl = string.indexOf("\n", pos)
+	    if (nl == -1) { nl = string.length }
+	    var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl)
+	    var rt = line.indexOf("\r")
+	    if (rt != -1) {
+	      result.push(line.slice(0, rt))
+	      pos += rt + 1
 	    } else {
-	      rmClass(cm.display.wrapper, "CodeMirror-wrap");
-	      findMaxLine(cm);
-	    }
-	    estimateLineHeights(cm);
-	    regChange(cm);
-	    clearCaches(cm);
-	    setTimeout(function(){updateScrollbars(cm);}, 100);
-	  }
-
-	  // Returns a function that estimates the height of a line, to use as
-	  // first approximation until the line becomes visible (and is thus
-	  // properly measurable).
-	  function estimateHeight(cm) {
-	    var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
-	    var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
-	    return function(line) {
-	      if (lineIsHidden(cm.doc, line)) return 0;
-
-	      var widgetsHeight = 0;
-	      if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
-	        if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
-	      }
-
-	      if (wrapping)
-	        return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
-	      else
-	        return widgetsHeight + th;
-	    };
-	  }
-
-	  function estimateLineHeights(cm) {
-	    var doc = cm.doc, est = estimateHeight(cm);
-	    doc.iter(function(line) {
-	      var estHeight = est(line);
-	      if (estHeight != line.height) updateLineHeight(line, estHeight);
-	    });
-	  }
-
-	  function themeChanged(cm) {
-	    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
-	      cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
-	    clearCaches(cm);
-	  }
-
-	  function guttersChanged(cm) {
-	    updateGutters(cm);
-	    regChange(cm);
-	    setTimeout(function(){alignHorizontally(cm);}, 20);
-	  }
-
-	  // Rebuild the gutter elements, ensure the margin to the left of the
-	  // code matches their width.
-	  function updateGutters(cm) {
-	    var gutters = cm.display.gutters, specs = cm.options.gutters;
-	    removeChildren(gutters);
-	    for (var i = 0; i < specs.length; ++i) {
-	      var gutterClass = specs[i];
-	      var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
-	      if (gutterClass == "CodeMirror-linenumbers") {
-	        cm.display.lineGutter = gElt;
-	        gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
-	      }
-	    }
-	    gutters.style.display = i ? "" : "none";
-	    updateGutterSpace(cm);
-	  }
-
-	  function updateGutterSpace(cm) {
-	    var width = cm.display.gutters.offsetWidth;
-	    cm.display.sizer.style.marginLeft = width + "px";
-	  }
-
-	  // Compute the character length of a line, taking into account
-	  // collapsed ranges (see markText) that might hide parts, and join
-	  // other lines onto it.
-	  function lineLength(line) {
-	    if (line.height == 0) return 0;
-	    var len = line.text.length, merged, cur = line;
-	    while (merged = collapsedSpanAtStart(cur)) {
-	      var found = merged.find(0, true);
-	      cur = found.from.line;
-	      len += found.from.ch - found.to.ch;
-	    }
-	    cur = line;
-	    while (merged = collapsedSpanAtEnd(cur)) {
-	      var found = merged.find(0, true);
-	      len -= cur.text.length - found.from.ch;
-	      cur = found.to.line;
-	      len += cur.text.length - found.to.ch;
-	    }
-	    return len;
-	  }
-
-	  // Find the longest line in the document.
-	  function findMaxLine(cm) {
-	    var d = cm.display, doc = cm.doc;
-	    d.maxLine = getLine(doc, doc.first);
-	    d.maxLineLength = lineLength(d.maxLine);
-	    d.maxLineChanged = true;
-	    doc.iter(function(line) {
-	      var len = lineLength(line);
-	      if (len > d.maxLineLength) {
-	        d.maxLineLength = len;
-	        d.maxLine = line;
-	      }
-	    });
-	  }
-
-	  // Make sure the gutters options contains the element
-	  // "CodeMirror-linenumbers" when the lineNumbers option is true.
-	  function setGuttersForLineNumbers(options) {
-	    var found = indexOf(options.gutters, "CodeMirror-linenumbers");
-	    if (found == -1 && options.lineNumbers) {
-	      options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
-	    } else if (found > -1 && !options.lineNumbers) {
-	      options.gutters = options.gutters.slice(0);
-	      options.gutters.splice(found, 1);
-	    }
-	  }
-
-	  // SCROLLBARS
-
-	  // Prepare DOM reads needed to update the scrollbars. Done in one
-	  // shot to minimize update/measure roundtrips.
-	  function measureForScrollbars(cm) {
-	    var d = cm.display, gutterW = d.gutters.offsetWidth;
-	    var docH = Math.round(cm.doc.height + paddingVert(cm.display));
-	    return {
-	      clientHeight: d.scroller.clientHeight,
-	      viewHeight: d.wrapper.clientHeight,
-	      scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
-	      viewWidth: d.wrapper.clientWidth,
-	      barLeft: cm.options.fixedGutter ? gutterW : 0,
-	      docHeight: docH,
-	      scrollHeight: docH + scrollGap(cm) + d.barHeight,
-	      nativeBarWidth: d.nativeBarWidth,
-	      gutterWidth: gutterW
-	    };
-	  }
-
-	  function NativeScrollbars(place, scroll, cm) {
-	    this.cm = cm;
-	    var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
-	    var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
-	    place(vert); place(horiz);
-
-	    on(vert, "scroll", function() {
-	      if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
-	    });
-	    on(horiz, "scroll", function() {
-	      if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
-	    });
-
-	    this.checkedZeroWidth = false;
-	    // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
-	    if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
-	  }
-
-	  NativeScrollbars.prototype = copyObj({
-	    update: function(measure) {
-	      var needsH = measure.scrollWidth > measure.clientWidth + 1;
-	      var needsV = measure.scrollHeight > measure.clientHeight + 1;
-	      var sWidth = measure.nativeBarWidth;
-
-	      if (needsV) {
-	        this.vert.style.display = "block";
-	        this.vert.style.bottom = needsH ? sWidth + "px" : "0";
-	        var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
-	        // A bug in IE8 can cause this value to be negative, so guard it.
-	        this.vert.firstChild.style.height =
-	          Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
-	      } else {
-	        this.vert.style.display = "";
-	        this.vert.firstChild.style.height = "0";
-	      }
-
-	      if (needsH) {
-	        this.horiz.style.display = "block";
-	        this.horiz.style.right = needsV ? sWidth + "px" : "0";
-	        this.horiz.style.left = measure.barLeft + "px";
-	        var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
-	        this.horiz.firstChild.style.width =
-	          (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
-	      } else {
-	        this.horiz.style.display = "";
-	        this.horiz.firstChild.style.width = "0";
-	      }
-
-	      if (!this.checkedZeroWidth && measure.clientHeight > 0) {
-	        if (sWidth == 0) this.zeroWidthHack();
-	        this.checkedZeroWidth = true;
-	      }
-
-	      return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
-	    },
-	    setScrollLeft: function(pos) {
-	      if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
-	      if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz);
-	    },
-	    setScrollTop: function(pos) {
-	      if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
-	      if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert);
-	    },
-	    zeroWidthHack: function() {
-	      var w = mac && !mac_geMountainLion ? "12px" : "18px";
-	      this.horiz.style.height = this.vert.style.width = w;
-	      this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
-	      this.disableHoriz = new Delayed;
-	      this.disableVert = new Delayed;
-	    },
-	    enableZeroWidthBar: function(bar, delay) {
-	      bar.style.pointerEvents = "auto";
-	      function maybeDisable() {
-	        // To find out whether the scrollbar is still visible, we
-	        // check whether the element under the pixel in the bottom
-	        // left corner of the scrollbar box is the scrollbar box
-	        // itself (when the bar is still visible) or its filler child
-	        // (when the bar is hidden). If it is still visible, we keep
-	        // it enabled, if it's hidden, we disable pointer events.
-	        var box = bar.getBoundingClientRect();
-	        var elt = document.elementFromPoint(box.left + 1, box.bottom - 1);
-	        if (elt != bar) bar.style.pointerEvents = "none";
-	        else delay.set(1000, maybeDisable);
-	      }
-	      delay.set(1000, maybeDisable);
-	    },
-	    clear: function() {
-	      var parent = this.horiz.parentNode;
-	      parent.removeChild(this.horiz);
-	      parent.removeChild(this.vert);
-	    }
-	  }, NativeScrollbars.prototype);
-
-	  function NullScrollbars() {}
-
-	  NullScrollbars.prototype = copyObj({
-	    update: function() { return {bottom: 0, right: 0}; },
-	    setScrollLeft: function() {},
-	    setScrollTop: function() {},
-	    clear: function() {}
-	  }, NullScrollbars.prototype);
-
-	  CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
-
-	  function initScrollbars(cm) {
-	    if (cm.display.scrollbars) {
-	      cm.display.scrollbars.clear();
-	      if (cm.display.scrollbars.addClass)
-	        rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
-	    }
-
-	    cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
-	      cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
-	      // Prevent clicks in the scrollbars from killing focus
-	      on(node, "mousedown", function() {
-	        if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
-	      });
-	      node.setAttribute("cm-not-content", "true");
-	    }, function(pos, axis) {
-	      if (axis == "horizontal") setScrollLeft(cm, pos);
-	      else setScrollTop(cm, pos);
-	    }, cm);
-	    if (cm.display.scrollbars.addClass)
-	      addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
-	  }
-
-	  function updateScrollbars(cm, measure) {
-	    if (!measure) measure = measureForScrollbars(cm);
-	    var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
-	    updateScrollbarsInner(cm, measure);
-	    for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
-	      if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
-	        updateHeightsInViewport(cm);
-	      updateScrollbarsInner(cm, measureForScrollbars(cm));
-	      startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
-	    }
-	  }
-
-	  // Re-synchronize the fake scrollbars with the actual size of the
-	  // content.
-	  function updateScrollbarsInner(cm, measure) {
-	    var d = cm.display;
-	    var sizes = d.scrollbars.update(measure);
-
-	    d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
-	    d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
-	    d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
-
-	    if (sizes.right && sizes.bottom) {
-	      d.scrollbarFiller.style.display = "block";
-	      d.scrollbarFiller.style.height = sizes.bottom + "px";
-	      d.scrollbarFiller.style.width = sizes.right + "px";
-	    } else d.scrollbarFiller.style.display = "";
-	    if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
-	      d.gutterFiller.style.display = "block";
-	      d.gutterFiller.style.height = sizes.bottom + "px";
-	      d.gutterFiller.style.width = measure.gutterWidth + "px";
-	    } else d.gutterFiller.style.display = "";
-	  }
-
-	  // Compute the lines that are visible in a given viewport (defaults
-	  // the the current scroll position). viewport may contain top,
-	  // height, and ensure (see op.scrollToPos) properties.
-	  function visibleLines(display, doc, viewport) {
-	    var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
-	    top = Math.floor(top - paddingTop(display));
-	    var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
-
-	    var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
-	    // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
-	    // forces those lines into the viewport (if possible).
-	    if (viewport && viewport.ensure) {
-	      var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
-	      if (ensureFrom < from) {
-	        from = ensureFrom;
-	        to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
-	      } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
-	        from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
-	        to = ensureTo;
-	      }
-	    }
-	    return {from: from, to: Math.max(to, from + 1)};
-	  }
-
-	  // LINE NUMBERS
-
-	  // Re-align line numbers and gutter marks to compensate for
-	  // horizontal scrolling.
-	  function alignHorizontally(cm) {
-	    var display = cm.display, view = display.view;
-	    if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
-	    var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
-	    var gutterW = display.gutters.offsetWidth, left = comp + "px";
-	    for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
-	      if (cm.options.fixedGutter && view[i].gutter)
-	        view[i].gutter.style.left = left;
-	      var align = view[i].alignable;
-	      if (align) for (var j = 0; j < align.length; j++)
-	        align[j].style.left = left;
-	    }
-	    if (cm.options.fixedGutter)
-	      display.gutters.style.left = (comp + gutterW) + "px";
-	  }
-
-	  // Used to ensure that the line number gutter is still the right
-	  // size for the current document size. Returns true when an update
-	  // is needed.
-	  function maybeUpdateLineNumberWidth(cm) {
-	    if (!cm.options.lineNumbers) return false;
-	    var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
-	    if (last.length != display.lineNumChars) {
-	      var test = display.measure.appendChild(elt("div", [elt("div", last)],
-	                                                 "CodeMirror-linenumber CodeMirror-gutter-elt"));
-	      var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
-	      display.lineGutter.style.width = "";
-	      display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
-	      display.lineNumWidth = display.lineNumInnerWidth + padding;
-	      display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
-	      display.lineGutter.style.width = display.lineNumWidth + "px";
-	      updateGutterSpace(cm);
-	      return true;
-	    }
-	    return false;
-	  }
-
-	  function lineNumberFor(options, i) {
-	    return String(options.lineNumberFormatter(i + options.firstLineNumber));
-	  }
-
-	  // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
-	  // but using getBoundingClientRect to get a sub-pixel-accurate
-	  // result.
-	  function compensateForHScroll(display) {
-	    return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
-	  }
-
-	  // DISPLAY DRAWING
-
-	  function DisplayUpdate(cm, viewport, force) {
-	    var display = cm.display;
-
-	    this.viewport = viewport;
-	    // Store some values that we'll need later (but don't want to force a relayout for)
-	    this.visible = visibleLines(display, cm.doc, viewport);
-	    this.editorIsHidden = !display.wrapper.offsetWidth;
-	    this.wrapperHeight = display.wrapper.clientHeight;
-	    this.wrapperWidth = display.wrapper.clientWidth;
-	    this.oldDisplayWidth = displayWidth(cm);
-	    this.force = force;
-	    this.dims = getDimensions(cm);
-	    this.events = [];
-	  }
-
-	  DisplayUpdate.prototype.signal = function(emitter, type) {
-	    if (hasHandler(emitter, type))
-	      this.events.push(arguments);
-	  };
-	  DisplayUpdate.prototype.finish = function() {
-	    for (var i = 0; i < this.events.length; i++)
-	      signal.apply(null, this.events[i]);
-	  };
-
-	  function maybeClipScrollbars(cm) {
-	    var display = cm.display;
-	    if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
-	      display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
-	      display.heightForcer.style.height = scrollGap(cm) + "px";
-	      display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
-	      display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
-	      display.scrollbarsClipped = true;
-	    }
-	  }
-
-	  // Does the actual updating of the line display. Bails out
-	  // (returning false) when there is nothing to be done and forced is
-	  // false.
-	  function updateDisplayIfNeeded(cm, update) {
-	    var display = cm.display, doc = cm.doc;
-
-	    if (update.editorIsHidden) {
-	      resetView(cm);
-	      return false;
-	    }
-
-	    // Bail out if the visible area is already rendered and nothing changed.
-	    if (!update.force &&
-	        update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
-	        (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
-	        display.renderedView == display.view && countDirtyView(cm) == 0)
-	      return false;
-
-	    if (maybeUpdateLineNumberWidth(cm)) {
-	      resetView(cm);
-	      update.dims = getDimensions(cm);
-	    }
-
-	    // Compute a suitable new viewport (from & to)
-	    var end = doc.first + doc.size;
-	    var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
-	    var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
-	    if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
-	    if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
-	    if (sawCollapsedSpans) {
-	      from = visualLineNo(cm.doc, from);
-	      to = visualLineEndNo(cm.doc, to);
-	    }
-
-	    var different = from != display.viewFrom || to != display.viewTo ||
-	      display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
-	    adjustView(cm, from, to);
-
-	    display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
-	    // Position the mover div to align with the current scroll position
-	    cm.display.mover.style.top = display.viewOffset + "px";
-
-	    var toUpdate = countDirtyView(cm);
-	    if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
-	        (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
-	      return false;
-
-	    // For big changes, we hide the enclosing element during the
-	    // update, since that speeds up the operations on most browsers.
-	    var focused = activeElt();
-	    if (toUpdate > 4) display.lineDiv.style.display = "none";
-	    patchDisplay(cm, display.updateLineNumbers, update.dims);
-	    if (toUpdate > 4) display.lineDiv.style.display = "";
-	    display.renderedView = display.view;
-	    // There might have been a widget with a focused element that got
-	    // hidden or updated, if so re-focus it.
-	    if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
-
-	    // Prevent selection and cursors from interfering with the scroll
-	    // width and height.
-	    removeChildren(display.cursorDiv);
-	    removeChildren(display.selectionDiv);
-	    display.gutters.style.height = display.sizer.style.minHeight = 0;
-
-	    if (different) {
-	      display.lastWrapHeight = update.wrapperHeight;
-	      display.lastWrapWidth = update.wrapperWidth;
-	      startWorker(cm, 400);
-	    }
-
-	    display.updateLineNumbers = null;
-
-	    return true;
-	  }
-
-	  function postUpdateDisplay(cm, update) {
-	    var viewport = update.viewport;
-
-	    for (var first = true;; first = false) {
-	      if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
-	        // Clip forced viewport to actual scrollable area.
-	        if (viewport && viewport.top != null)
-	          viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
-	        // Updated line heights might result in the drawn area not
-	        // actually covering the viewport. Keep looping until it does.
-	        update.visible = visibleLines(cm.display, cm.doc, viewport);
-	        if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
-	          break;
-	      }
-	      if (!updateDisplayIfNeeded(cm, update)) break;
-	      updateHeightsInViewport(cm);
-	      var barMeasure = measureForScrollbars(cm);
-	      updateSelection(cm);
-	      updateScrollbars(cm, barMeasure);
-	      setDocumentHeight(cm, barMeasure);
-	    }
-
-	    update.signal(cm, "update", cm);
-	    if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
-	      update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
-	      cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
-	    }
-	  }
-
-	  function updateDisplaySimple(cm, viewport) {
-	    var update = new DisplayUpdate(cm, viewport);
-	    if (updateDisplayIfNeeded(cm, update)) {
-	      updateHeightsInViewport(cm);
-	      postUpdateDisplay(cm, update);
-	      var barMeasure = measureForScrollbars(cm);
-	      updateSelection(cm);
-	      updateScrollbars(cm, barMeasure);
-	      setDocumentHeight(cm, barMeasure);
-	      update.finish();
-	    }
-	  }
-
-	  function setDocumentHeight(cm, measure) {
-	    cm.display.sizer.style.minHeight = measure.docHeight + "px";
-	    cm.display.heightForcer.style.top = measure.docHeight + "px";
-	    cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
-	  }
-
-	  // Read the actual heights of the rendered lines, and update their
-	  // stored heights to match.
-	  function updateHeightsInViewport(cm) {
-	    var display = cm.display;
-	    var prevBottom = display.lineDiv.offsetTop;
-	    for (var i = 0; i < display.view.length; i++) {
-	      var cur = display.view[i], height;
-	      if (cur.hidden) continue;
-	      if (ie && ie_version < 8) {
-	        var bot = cur.node.offsetTop + cur.node.offsetHeight;
-	        height = bot - prevBottom;
-	        prevBottom = bot;
-	      } else {
-	        var box = cur.node.getBoundingClientRect();
-	        height = box.bottom - box.top;
-	      }
-	      var diff = cur.line.height - height;
-	      if (height < 2) height = textHeight(display);
-	      if (diff > .001 || diff < -.001) {
-	        updateLineHeight(cur.line, height);
-	        updateWidgetHeight(cur.line);
-	        if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
-	          updateWidgetHeight(cur.rest[j]);
-	      }
-	    }
-	  }
-
-	  // Read and store the height of line widgets associated with the
-	  // given line.
-	  function updateWidgetHeight(line) {
-	    if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
-	      line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight;
-	  }
-
-	  // Do a bulk-read of the DOM positions and sizes needed to draw the
-	  // view, so that we don't interleave reading and writing to the DOM.
-	  function getDimensions(cm) {
-	    var d = cm.display, left = {}, width = {};
-	    var gutterLeft = d.gutters.clientLeft;
-	    for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
-	      left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
-	      width[cm.options.gutters[i]] = n.clientWidth;
-	    }
-	    return {fixedPos: compensateForHScroll(d),
-	            gutterTotalWidth: d.gutters.offsetWidth,
-	            gutterLeft: left,
-	            gutterWidth: width,
-	            wrapperWidth: d.wrapper.clientWidth};
-	  }
-
-	  // Sync the actual display DOM structure with display.view, removing
-	  // nodes for lines that are no longer in view, and creating the ones
-	  // that are not there yet, and updating the ones that are out of
-	  // date.
-	  function patchDisplay(cm, updateNumbersFrom, dims) {
-	    var display = cm.display, lineNumbers = cm.options.lineNumbers;
-	    var container = display.lineDiv, cur = container.firstChild;
-
-	    function rm(node) {
-	      var next = node.nextSibling;
-	      // Works around a throw-scroll bug in OS X Webkit
-	      if (webkit && mac && cm.display.currentWheelTarget == node)
-	        node.style.display = "none";
-	      else
-	        node.parentNode.removeChild(node);
-	      return next;
-	    }
-
-	    var view = display.view, lineN = display.viewFrom;
-	    // Loop over the elements in the view, syncing cur (the DOM nodes
-	    // in display.lineDiv) with the view as we go.
-	    for (var i = 0; i < view.length; i++) {
-	      var lineView = view[i];
-	      if (lineView.hidden) {
-	      } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
-	        var node = buildLineElement(cm, lineView, lineN, dims);
-	        container.insertBefore(node, cur);
-	      } else { // Already drawn
-	        while (cur != lineView.node) cur = rm(cur);
-	        var updateNumber = lineNumbers && updateNumbersFrom != null &&
-	          updateNumbersFrom <= lineN && lineView.lineNumber;
-	        if (lineView.changes) {
-	          if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
-	          updateLineForChanges(cm, lineView, lineN, dims);
-	        }
-	        if (updateNumber) {
-	          removeChildren(lineView.lineNumber);
-	          lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
-	        }
-	        cur = lineView.node.nextSibling;
-	      }
-	      lineN += lineView.size;
-	    }
-	    while (cur) cur = rm(cur);
-	  }
-
-	  // When an aspect of a line changes, a string is added to
-	  // lineView.changes. This updates the relevant part of the line's
-	  // DOM structure.
-	  function updateLineForChanges(cm, lineView, lineN, dims) {
-	    for (var j = 0; j < lineView.changes.length; j++) {
-	      var type = lineView.changes[j];
-	      if (type == "text") updateLineText(cm, lineView);
-	      else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
-	      else if (type == "class") updateLineClasses(lineView);
-	      else if (type == "widget") updateLineWidgets(cm, lineView, dims);
-	    }
-	    lineView.changes = null;
-	  }
-
-	  // Lines with gutter elements, widgets or a background class need to
-	  // be wrapped, and have the extra elements added to the wrapper div
-	  function ensureLineWrapped(lineView) {
-	    if (lineView.node == lineView.text) {
-	      lineView.node = elt("div", null, null, "position: relative");
-	      if (lineView.text.parentNode)
-	        lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
-	      lineView.node.appendChild(lineView.text);
-	      if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
-	    }
-	    return lineView.node;
-	  }
-
-	  function updateLineBackground(lineView) {
-	    var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
-	    if (cls) cls += " CodeMirror-linebackground";
-	    if (lineView.background) {
-	      if (cls) lineView.background.className = cls;
-	      else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
-	    } else if (cls) {
-	      var wrap = ensureLineWrapped(lineView);
-	      lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
-	    }
-	  }
-
-	  // Wrapper around buildLineContent which will reuse the structure
-	  // in display.externalMeasured when possible.
-	  function getLineContent(cm, lineView) {
-	    var ext = cm.display.externalMeasured;
-	    if (ext && ext.line == lineView.line) {
-	      cm.display.externalMeasured = null;
-	      lineView.measure = ext.measure;
-	      return ext.built;
-	    }
-	    return buildLineContent(cm, lineView);
-	  }
-
-	  // Redraw the line's text. Interacts with the background and text
-	  // classes because the mode may output tokens that influence these
-	  // classes.
-	  function updateLineText(cm, lineView) {
-	    var cls = lineView.text.className;
-	    var built = getLineContent(cm, lineView);
-	    if (lineView.text == lineView.node) lineView.node = built.pre;
-	    lineView.text.parentNode.replaceChild(built.pre, lineView.text);
-	    lineView.text = built.pre;
-	    if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
-	      lineView.bgClass = built.bgClass;
-	      lineView.textClass = built.textClass;
-	      updateLineClasses(lineView);
-	    } else if (cls) {
-	      lineView.text.className = cls;
-	    }
-	  }
-
-	  function updateLineClasses(lineView) {
-	    updateLineBackground(lineView);
-	    if (lineView.line.wrapClass)
-	      ensureLineWrapped(lineView).className = lineView.line.wrapClass;
-	    else if (lineView.node != lineView.text)
-	      lineView.node.className = "";
-	    var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
-	    lineView.text.className = textClass || "";
-	  }
-
-	  function updateLineGutter(cm, lineView, lineN, dims) {
-	    if (lineView.gutter) {
-	      lineView.node.removeChild(lineView.gutter);
-	      lineView.gutter = null;
-	    }
-	    if (lineView.gutterBackground) {
-	      lineView.node.removeChild(lineView.gutterBackground);
-	      lineView.gutterBackground = null;
-	    }
-	    if (lineView.line.gutterClass) {
-	      var wrap = ensureLineWrapped(lineView);
-	      lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
-	                                      "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
-	                                      "px; width: " + dims.gutterTotalWidth + "px");
-	      wrap.insertBefore(lineView.gutterBackground, lineView.text);
-	    }
-	    var markers = lineView.line.gutterMarkers;
-	    if (cm.options.lineNumbers || markers) {
-	      var wrap = ensureLineWrapped(lineView);
-	      var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
-	                                             (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
-	      cm.display.input.setUneditable(gutterWrap);
-	      wrap.insertBefore(gutterWrap, lineView.text);
-	      if (lineView.line.gutterClass)
-	        gutterWrap.className += " " + lineView.line.gutterClass;
-	      if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
-	        lineView.lineNumber = gutterWrap.appendChild(
-	          elt("div", lineNumberFor(cm.options, lineN),
-	              "CodeMirror-linenumber CodeMirror-gutter-elt",
-	              "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
-	              + cm.display.lineNumInnerWidth + "px"));
-	      if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
-	        var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
-	        if (found)
-	          gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
-	                                     dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
-	      }
-	    }
-	  }
-
-	  function updateLineWidgets(cm, lineView, dims) {
-	    if (lineView.alignable) lineView.alignable = null;
-	    for (var node = lineView.node.firstChild, next; node; node = next) {
-	      var next = node.nextSibling;
-	      if (node.className == "CodeMirror-linewidget")
-	        lineView.node.removeChild(node);
-	    }
-	    insertLineWidgets(cm, lineView, dims);
-	  }
-
-	  // Build a line's DOM representation from scratch
-	  function buildLineElement(cm, lineView, lineN, dims) {
-	    var built = getLineContent(cm, lineView);
-	    lineView.text = lineView.node = built.pre;
-	    if (built.bgClass) lineView.bgClass = built.bgClass;
-	    if (built.textClass) lineView.textClass = built.textClass;
-
-	    updateLineClasses(lineView);
-	    updateLineGutter(cm, lineView, lineN, dims);
-	    insertLineWidgets(cm, lineView, dims);
-	    return lineView.node;
-	  }
-
-	  // A lineView may contain multiple logical lines (when merged by
-	  // collapsed spans). The widgets for all of them need to be drawn.
-	  function insertLineWidgets(cm, lineView, dims) {
-	    insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
-	    if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
-	      insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
-	  }
-
-	  function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
-	    if (!line.widgets) return;
-	    var wrap = ensureLineWrapped(lineView);
-	    for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
-	      var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
-	      if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
-	      positionLineWidget(widget, node, lineView, dims);
-	      cm.display.input.setUneditable(node);
-	      if (allowAbove && widget.above)
-	        wrap.insertBefore(node, lineView.gutter || lineView.text);
+	      result.push(line)
+	      pos = nl + 1
+	    }
+	  }
+	  return result
+	} : function (string) { return string.split(/\r\n?|\n/); }
+
+	var hasSelection = window.getSelection ? function (te) {
+	  try { return te.selectionStart != te.selectionEnd }
+	  catch(e) { return false }
+	} : function (te) {
+	  var range
+	  try {range = te.ownerDocument.selection.createRange()}
+	  catch(e) {}
+	  if (!range || range.parentElement() != te) { return false }
+	  return range.compareEndPoints("StartToEnd", range) != 0
+	}
+
+	var hasCopyEvent = (function () {
+	  var e = elt("div")
+	  if ("oncopy" in e) { return true }
+	  e.setAttribute("oncopy", "return;")
+	  return typeof e.oncopy == "function"
+	})()
+
+	var badZoomedRects = null
+	function hasBadZoomedRects(measure) {
+	  if (badZoomedRects != null) { return badZoomedRects }
+	  var node = removeChildrenAndAdd(measure, elt("span", "x"))
+	  var normal = node.getBoundingClientRect()
+	  var fromRange = range(node, 0, 1).getBoundingClientRect()
+	  return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
+	}
+
+	var modes = {};
+	var mimeModes = {};
+	// Extra arguments are stored as the mode's dependencies, which is
+	// used by (legacy) mechanisms like loadmode.js to automatically
+	// load a mode. (Preferred mechanism is the require/define calls.)
+	function defineMode(name, mode) {
+	  if (arguments.length > 2)
+	    { mode.dependencies = Array.prototype.slice.call(arguments, 2) }
+	  modes[name] = mode
+	}
+
+	function defineMIME(mime, spec) {
+	  mimeModes[mime] = spec
+	}
+
+	// Given a MIME type, a {name, ...options} config object, or a name
+	// string, return a mode config object.
+	function resolveMode(spec) {
+	  if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
+	    spec = mimeModes[spec]
+	  } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
+	    var found = mimeModes[spec.name]
+	    if (typeof found == "string") { found = {name: found} }
+	    spec = createObj(found, spec)
+	    spec.name = found.name
+	  } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
+	    return resolveMode("application/xml")
+	  } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
+	    return resolveMode("application/json")
+	  }
+	  if (typeof spec == "string") { return {name: spec} }
+	  else { return spec || {name: "null"} }
+	}
+
+	// Given a mode spec (anything that resolveMode accepts), find and
+	// initialize an actual mode object.
+	function getMode(options, spec) {
+	  spec = resolveMode(spec)
+	  var mfactory = modes[spec.name]
+	  if (!mfactory) { return getMode(options, "text/plain") }
+	  var modeObj = mfactory(options, spec)
+	  if (modeExtensions.hasOwnProperty(spec.name)) {
+	    var exts = modeExtensions[spec.name]
+	    for (var prop in exts) {
+	      if (!exts.hasOwnProperty(prop)) { continue }
+	      if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop] }
+	      modeObj[prop] = exts[prop]
+	    }
+	  }
+	  modeObj.name = spec.name
+	  if (spec.helperType) { modeObj.helperType = spec.helperType }
+	  if (spec.modeProps) { for (var prop$1 in spec.modeProps)
+	    { modeObj[prop$1] = spec.modeProps[prop$1] } }
+
+	  return modeObj
+	}
+
+	// This can be used to attach properties to mode objects from
+	// outside the actual mode definition.
+	var modeExtensions = {}
+	function extendMode(mode, properties) {
+	  var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {})
+	  copyObj(properties, exts)
+	}
+
+	function copyState(mode, state) {
+	  if (state === true) { return state }
+	  if (mode.copyState) { return mode.copyState(state) }
+	  var nstate = {}
+	  for (var n in state) {
+	    var val = state[n]
+	    if (val instanceof Array) { val = val.concat([]) }
+	    nstate[n] = val
+	  }
+	  return nstate
+	}
+
+	// Given a mode and a state (for that mode), find the inner mode and
+	// state at the position that the state refers to.
+	function innerMode(mode, state) {
+	  var info
+	  while (mode.innerMode) {
+	    info = mode.innerMode(state)
+	    if (!info || info.mode == mode) { break }
+	    state = info.state
+	    mode = info.mode
+	  }
+	  return info || {mode: mode, state: state}
+	}
+
+	function startState(mode, a1, a2) {
+	  return mode.startState ? mode.startState(a1, a2) : true
+	}
+
+	// STRING STREAM
+
+	// Fed to the mode parsers, provides helper functions to make
+	// parsers more succinct.
+
+	var StringStream = function(string, tabSize, lineOracle) {
+	  this.pos = this.start = 0
+	  this.string = string
+	  this.tabSize = tabSize || 8
+	  this.lastColumnPos = this.lastColumnValue = 0
+	  this.lineStart = 0
+	  this.lineOracle = lineOracle
+	};
+
+	StringStream.prototype.eol = function () {return this.pos >= this.string.length};
+	StringStream.prototype.sol = function () {return this.pos == this.lineStart};
+	StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
+	StringStream.prototype.next = function () {
+	  if (this.pos < this.string.length)
+	    { return this.string.charAt(this.pos++) }
+	};
+	StringStream.prototype.eat = function (match) {
+	  var ch = this.string.charAt(this.pos)
+	  var ok
+	  if (typeof match == "string") { ok = ch == match }
+	  else { ok = ch && (match.test ? match.test(ch) : match(ch)) }
+	  if (ok) {++this.pos; return ch}
+	};
+	StringStream.prototype.eatWhile = function (match) {
+	  var start = this.pos
+	  while (this.eat(match)){}
+	  return this.pos > start
+	};
+	StringStream.prototype.eatSpace = function () {
+	    var this$1 = this;
+
+	  var start = this.pos
+	  while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos }
+	  return this.pos > start
+	};
+	StringStream.prototype.skipToEnd = function () {this.pos = this.string.length};
+	StringStream.prototype.skipTo = function (ch) {
+	  var found = this.string.indexOf(ch, this.pos)
+	  if (found > -1) {this.pos = found; return true}
+	};
+	StringStream.prototype.backUp = function (n) {this.pos -= n};
+	StringStream.prototype.column = function () {
+	  if (this.lastColumnPos < this.start) {
+	    this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue)
+	    this.lastColumnPos = this.start
+	  }
+	  return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
+	};
+	StringStream.prototype.indentation = function () {
+	  return countColumn(this.string, null, this.tabSize) -
+	    (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
+	};
+	StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
+	  if (typeof pattern == "string") {
+	    var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }
+	    var substr = this.string.substr(this.pos, pattern.length)
+	    if (cased(substr) == cased(pattern)) {
+	      if (consume !== false) { this.pos += pattern.length }
+	      return true
+	    }
+	  } else {
+	    var match = this.string.slice(this.pos).match(pattern)
+	    if (match && match.index > 0) { return null }
+	    if (match && consume !== false) { this.pos += match[0].length }
+	    return match
+	  }
+	};
+	StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
+	StringStream.prototype.hideFirstChars = function (n, inner) {
+	  this.lineStart += n
+	  try { return inner() }
+	  finally { this.lineStart -= n }
+	};
+	StringStream.prototype.lookAhead = function (n) {
+	  var oracle = this.lineOracle
+	  return oracle && oracle.lookAhead(n)
+	};
+
+	var SavedContext = function(state, lookAhead) {
+	  this.state = state
+	  this.lookAhead = lookAhead
+	};
+
+	var Context = function(doc, state, line, lookAhead) {
+	  this.state = state
+	  this.doc = doc
+	  this.line = line
+	  this.maxLookAhead = lookAhead || 0
+	};
+
+	Context.prototype.lookAhead = function (n) {
+	  var line = this.doc.getLine(this.line + n)
+	  if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n }
+	  return line
+	};
+
+	Context.prototype.nextLine = function () {
+	  this.line++
+	  if (this.maxLookAhead > 0) { this.maxLookAhead-- }
+	};
+
+	Context.fromSaved = function (doc, saved, line) {
+	  if (saved instanceof SavedContext)
+	    { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
+	  else
+	    { return new Context(doc, copyState(doc.mode, saved), line) }
+	};
+
+	Context.prototype.save = function (copy) {
+	  var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state
+	  return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
+	};
+
+
+	// Compute a style array (an array starting with a mode generation
+	// -- for invalidation -- followed by pairs of end positions and
+	// style strings), which is used to highlight the tokens on the
+	// line.
+	function highlightLine(cm, line, context, forceToEnd) {
+	  // A styles array always starts with a number identifying the
+	  // mode/overlays that it is based on (for easy invalidation).
+	  var st = [cm.state.modeGen], lineClasses = {}
+	  // Compute the base array of styles
+	  runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
+	          lineClasses, forceToEnd)
+	  var state = context.state
+
+	  // Run overlays, adjust style array.
+	  var loop = function ( o ) {
+	    var overlay = cm.state.overlays[o], i = 1, at = 0
+	    context.state = true
+	    runMode(cm, line.text, overlay.mode, context, function (end, style) {
+	      var start = i
+	      // Ensure there's a token end at the current position, and that i points at it
+	      while (at < end) {
+	        var i_end = st[i]
+	        if (i_end > end)
+	          { st.splice(i, 1, end, st[i+1], i_end) }
+	        i += 2
+	        at = Math.min(end, i_end)
+	      }
+	      if (!style) { return }
+	      if (overlay.opaque) {
+	        st.splice(start, i - start, end, "overlay " + style)
+	        i = start + 2
+	      } else {
+	        for (; start < i; start += 2) {
+	          var cur = st[start+1]
+	          st[start+1] = (cur ? cur + " " : "") + "overlay " + style
+	        }
+	      }
+	    }, lineClasses)
+	  };
+
+	  for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
+	  context.state = state
+
+	  return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
+	}
+
+	function getLineStyles(cm, line, updateFrontier) {
+	  if (!line.styles || line.styles[0] != cm.state.modeGen) {
+	    var context = getContextBefore(cm, lineNo(line))
+	    var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state)
+	    var result = highlightLine(cm, line, context)
+	    if (resetState) { context.state = resetState }
+	    line.stateAfter = context.save(!resetState)
+	    line.styles = result.styles
+	    if (result.classes) { line.styleClasses = result.classes }
+	    else if (line.styleClasses) { line.styleClasses = null }
+	    if (updateFrontier === cm.doc.highlightFrontier)
+	      { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier) }
+	  }
+	  return line.styles
+	}
+
+	function getContextBefore(cm, n, precise) {
+	  var doc = cm.doc, display = cm.display
+	  if (!doc.mode.startState) { return new Context(doc, true, n) }
+	  var start = findStartLine(cm, n, precise)
+	  var saved = start > doc.first && getLine(doc, start - 1).stateAfter
+	  var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start)
+
+	  doc.iter(start, n, function (line) {
+	    processLine(cm, line.text, context)
+	    var pos = context.line
+	    line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null
+	    context.nextLine()
+	  })
+	  if (precise) { doc.modeFrontier = context.line }
+	  return context
+	}
+
+	// Lightweight form of highlight -- proceed over this line and
+	// update state, but don't save a style array. Used for lines that
+	// aren't currently visible.
+	function processLine(cm, text, context, startAt) {
+	  var mode = cm.doc.mode
+	  var stream = new StringStream(text, cm.options.tabSize, context)
+	  stream.start = stream.pos = startAt || 0
+	  if (text == "") { callBlankLine(mode, context.state) }
+	  while (!stream.eol()) {
+	    readToken(mode, stream, context.state)
+	    stream.start = stream.pos
+	  }
+	}
+
+	function callBlankLine(mode, state) {
+	  if (mode.blankLine) { return mode.blankLine(state) }
+	  if (!mode.innerMode) { return }
+	  var inner = innerMode(mode, state)
+	  if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
+	}
+
+	function readToken(mode, stream, state, inner) {
+	  for (var i = 0; i < 10; i++) {
+	    if (inner) { inner[0] = innerMode(mode, state).mode }
+	    var style = mode.token(stream, state)
+	    if (stream.pos > stream.start) { return style }
+	  }
+	  throw new Error("Mode " + mode.name + " failed to advance stream.")
+	}
+
+	var Token = function(stream, type, state) {
+	  this.start = stream.start; this.end = stream.pos
+	  this.string = stream.current()
+	  this.type = type || null
+	  this.state = state
+	};
+
+	// Utility for getTokenAt and getLineTokens
+	function takeToken(cm, pos, precise, asArray) {
+	  var doc = cm.doc, mode = doc.mode, style
+	  pos = clipPos(doc, pos)
+	  var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise)
+	  var stream = new StringStream(line.text, cm.options.tabSize, context), tokens
+	  if (asArray) { tokens = [] }
+	  while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
+	    stream.start = stream.pos
+	    style = readToken(mode, stream, context.state)
+	    if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))) }
+	  }
+	  return asArray ? tokens : new Token(stream, style, context.state)
+	}
+
+	function extractLineClasses(type, output) {
+	  if (type) { for (;;) {
+	    var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/)
+	    if (!lineClass) { break }
+	    type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length)
+	    var prop = lineClass[1] ? "bgClass" : "textClass"
+	    if (output[prop] == null)
+	      { output[prop] = lineClass[2] }
+	    else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
+	      { output[prop] += " " + lineClass[2] }
+	  } }
+	  return type
+	}
+
+	// Run the given mode's parser over a line, calling f for each token.
+	function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
+	  var flattenSpans = mode.flattenSpans
+	  if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans }
+	  var curStart = 0, curStyle = null
+	  var stream = new StringStream(text, cm.options.tabSize, context), style
+	  var inner = cm.options.addModeClass && [null]
+	  if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses) }
+	  while (!stream.eol()) {
+	    if (stream.pos > cm.options.maxHighlightLength) {
+	      flattenSpans = false
+	      if (forceToEnd) { processLine(cm, text, context, stream.pos) }
+	      stream.pos = text.length
+	      style = null
+	    } else {
+	      style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses)
+	    }
+	    if (inner) {
+	      var mName = inner[0].name
+	      if (mName) { style = "m-" + (style ? mName + " " + style : mName) }
+	    }
+	    if (!flattenSpans || curStyle != style) {
+	      while (curStart < stream.start) {
+	        curStart = Math.min(stream.start, curStart + 5000)
+	        f(curStart, curStyle)
+	      }
+	      curStyle = style
+	    }
+	    stream.start = stream.pos
+	  }
+	  while (curStart < stream.pos) {
+	    // Webkit seems to refuse to render text nodes longer than 57444
+	    // characters, and returns inaccurate measurements in nodes
+	    // starting around 5000 chars.
+	    var pos = Math.min(stream.pos, curStart + 5000)
+	    f(pos, curStyle)
+	    curStart = pos
+	  }
+	}
+
+	// Finds the line to start with when starting a parse. Tries to
+	// find a line with a stateAfter, so that it can start with a
+	// valid state. If that fails, it returns the line with the
+	// smallest indentation, which tends to need the least context to
+	// parse correctly.
+	function findStartLine(cm, n, precise) {
+	  var minindent, minline, doc = cm.doc
+	  var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100)
+	  for (var search = n; search > lim; --search) {
+	    if (search <= doc.first) { return doc.first }
+	    var line = getLine(doc, search - 1), after = line.stateAfter
+	    if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
+	      { return search }
+	    var indented = countColumn(line.text, null, cm.options.tabSize)
+	    if (minline == null || minindent > indented) {
+	      minline = search - 1
+	      minindent = indented
+	    }
+	  }
+	  return minline
+	}
+
+	function retreatFrontier(doc, n) {
+	  doc.modeFrontier = Math.min(doc.modeFrontier, n)
+	  if (doc.highlightFrontier < n - 10) { return }
+	  var start = doc.first
+	  for (var line = n - 1; line > start; line--) {
+	    var saved = getLine(doc, line).stateAfter
+	    // change is on 3
+	    // state on line 1 looked ahead 2 -- so saw 3
+	    // test 1 + 2 < 3 should cover this
+	    if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
+	      start = line + 1
+	      break
+	    }
+	  }
+	  doc.highlightFrontier = Math.min(doc.highlightFrontier, start)
+	}
+
+	// LINE DATA STRUCTURE
+
+	// Line objects. These hold state related to a line, including
+	// highlighting info (the styles array).
+	var Line = function(text, markedSpans, estimateHeight) {
+	  this.text = text
+	  attachMarkedSpans(this, markedSpans)
+	  this.height = estimateHeight ? estimateHeight(this) : 1
+	};
+
+	Line.prototype.lineNo = function () { return lineNo(this) };
+	eventMixin(Line)
+
+	// Change the content (text, markers) of a line. Automatically
+	// invalidates cached information and tries to re-estimate the
+	// line's height.
+	function updateLine(line, text, markedSpans, estimateHeight) {
+	  line.text = text
+	  if (line.stateAfter) { line.stateAfter = null }
+	  if (line.styles) { line.styles = null }
+	  if (line.order != null) { line.order = null }
+	  detachMarkedSpans(line)
+	  attachMarkedSpans(line, markedSpans)
+	  var estHeight = estimateHeight ? estimateHeight(line) : 1
+	  if (estHeight != line.height) { updateLineHeight(line, estHeight) }
+	}
+
+	// Detach a line from the document tree and its markers.
+	function cleanUpLine(line) {
+	  line.parent = null
+	  detachMarkedSpans(line)
+	}
+
+	// Convert a style as returned by a mode (either null, or a string
+	// containing one or more styles) to a CSS style. This is cached,
+	// and also looks for line-wide styles.
+	var styleToClassCache = {};
+	var styleToClassCacheWithMode = {};
+	function interpretTokenStyle(style, options) {
+	  if (!style || /^\s*$/.test(style)) { return null }
+	  var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache
+	  return cache[style] ||
+	    (cache[style] = style.replace(/\S+/g, "cm-$&"))
+	}
+
+	// Render the DOM representation of the text of a line. Also builds
+	// up a 'line map', which points at the DOM nodes that represent
+	// specific stretches of text, and is used by the measuring code.
+	// The returned object contains the DOM node, this map, and
+	// information about line-wide styles that were set by the mode.
+	function buildLineContent(cm, lineView) {
+	  // The padding-right forces the element to have a 'border', which
+	  // is needed on Webkit to be able to get line-level bounding
+	  // rectangles for it (in measureChar).
+	  var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null)
+	  var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
+	                 col: 0, pos: 0, cm: cm,
+	                 trailingSpace: false,
+	                 splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}
+	  lineView.measure = {}
+
+	  // Iterate over the logical lines that make up this visual line.
+	  for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
+	    var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0)
+	    builder.pos = 0
+	    builder.addToken = buildToken
+	    // Optionally wire in some hacks into the token-rendering
+	    // algorithm, to deal with browser quirks.
+	    if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
+	      { builder.addToken = buildTokenBadBidi(builder.addToken, order) }
+	    builder.map = []
+	    var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line)
+	    insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate))
+	    if (line.styleClasses) {
+	      if (line.styleClasses.bgClass)
+	        { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "") }
+	      if (line.styleClasses.textClass)
+	        { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "") }
+	    }
+
+	    // Ensure at least a single node is present, for measuring.
+	    if (builder.map.length == 0)
+	      { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))) }
+
+	    // Store the map and a cache object for the current logical line
+	    if (i == 0) {
+	      lineView.measure.map = builder.map
+	      lineView.measure.cache = {}
+	    } else {
+	      ;(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
+	      ;(lineView.measure.caches || (lineView.measure.caches = [])).push({})
+	    }
+	  }
+
+	  // See issue #2901
+	  if (webkit) {
+	    var last = builder.content.lastChild
+	    if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
+	      { builder.content.className = "cm-tab-wrap-hack" }
+	  }
+
+	  signal(cm, "renderLine", cm, lineView.line, builder.pre)
+	  if (builder.pre.className)
+	    { builder.textClass = joinClasses(builder.pre.className, builder.textClass || "") }
+
+	  return builder
+	}
+
+	function defaultSpecialCharPlaceholder(ch) {
+	  var token = elt("span", "\u2022", "cm-invalidchar")
+	  token.title = "\\u" + ch.charCodeAt(0).toString(16)
+	  token.setAttribute("aria-label", token.title)
+	  return token
+	}
+
+	// Build up the DOM representation for a single token, and add it to
+	// the line map. Takes care to render special characters separately.
+	function buildToken(builder, text, style, startStyle, endStyle, title, css) {
+	  if (!text) { return }
+	  var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text
+	  var special = builder.cm.state.specialChars, mustWrap = false
+	  var content
+	  if (!special.test(text)) {
+	    builder.col += text.length
+	    content = document.createTextNode(displayText)
+	    builder.map.push(builder.pos, builder.pos + text.length, content)
+	    if (ie && ie_version < 9) { mustWrap = true }
+	    builder.pos += text.length
+	  } else {
+	    content = document.createDocumentFragment()
+	    var pos = 0
+	    while (true) {
+	      special.lastIndex = pos
+	      var m = special.exec(text)
+	      var skipped = m ? m.index - pos : text.length - pos
+	      if (skipped) {
+	        var txt = document.createTextNode(displayText.slice(pos, pos + skipped))
+	        if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])) }
+	        else { content.appendChild(txt) }
+	        builder.map.push(builder.pos, builder.pos + skipped, txt)
+	        builder.col += skipped
+	        builder.pos += skipped
+	      }
+	      if (!m) { break }
+	      pos += skipped + 1
+	      var txt$1 = (void 0)
+	      if (m[0] == "\t") {
+	        var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize
+	        txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"))
+	        txt$1.setAttribute("role", "presentation")
+	        txt$1.setAttribute("cm-text", "\t")
+	        builder.col += tabWidth
+	      } else if (m[0] == "\r" || m[0] == "\n") {
+	        txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"))
+	        txt$1.setAttribute("cm-text", m[0])
+	        builder.col += 1
+	      } else {
+	        txt$1 = builder.cm.options.specialCharPlaceholder(m[0])
+	        txt$1.setAttribute("cm-text", m[0])
+	        if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])) }
+	        else { content.appendChild(txt$1) }
+	        builder.col += 1
+	      }
+	      builder.map.push(builder.pos, builder.pos + 1, txt$1)
+	      builder.pos++
+	    }
+	  }
+	  builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32
+	  if (style || startStyle || endStyle || mustWrap || css) {
+	    var fullStyle = style || ""
+	    if (startStyle) { fullStyle += startStyle }
+	    if (endStyle) { fullStyle += endStyle }
+	    var token = elt("span", [content], fullStyle, css)
+	    if (title) { token.title = title }
+	    return builder.content.appendChild(token)
+	  }
+	  builder.content.appendChild(content)
+	}
+
+	function splitSpaces(text, trailingBefore) {
+	  if (text.length > 1 && !/  /.test(text)) { return text }
+	  var spaceBefore = trailingBefore, result = ""
+	  for (var i = 0; i < text.length; i++) {
+	    var ch = text.charAt(i)
+	    if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
+	      { ch = "\u00a0" }
+	    result += ch
+	    spaceBefore = ch == " "
+	  }
+	  return result
+	}
+
+	// Work around nonsense dimensions being reported for stretches of
+	// right-to-left text.
+	function buildTokenBadBidi(inner, order) {
+	  return function (builder, text, style, startStyle, endStyle, title, css) {
+	    style = style ? style + " cm-force-border" : "cm-force-border"
+	    var start = builder.pos, end = start + text.length
+	    for (;;) {
+	      // Find the part that overlaps with the start of this text
+	      var part = (void 0)
+	      for (var i = 0; i < order.length; i++) {
+	        part = order[i]
+	        if (part.to > start && part.from <= start) { break }
+	      }
+	      if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
+	      inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css)
+	      startStyle = null
+	      text = text.slice(part.to - start)
+	      start = part.to
+	    }
+	  }
+	}
+
+	function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
+	  var widget = !ignoreWidget && marker.widgetNode
+	  if (widget) { builder.map.push(builder.pos, builder.pos + size, widget) }
+	  if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
+	    if (!widget)
+	      { widget = builder.content.appendChild(document.createElement("span")) }
+	    widget.setAttribute("cm-marker", marker.id)
+	  }
+	  if (widget) {
+	    builder.cm.display.input.setUneditable(widget)
+	    builder.content.appendChild(widget)
+	  }
+	  builder.pos += size
+	  builder.trailingSpace = false
+	}
+
+	// Outputs a number of spans to make up a line, taking highlighting
+	// and marked text into account.
+	function insertLineContent(line, builder, styles) {
+	  var spans = line.markedSpans, allText = line.text, at = 0
+	  if (!spans) {
+	    for (var i$1 = 1; i$1 < styles.length; i$1+=2)
+	      { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)) }
+	    return
+	  }
+
+	  var len = allText.length, pos = 0, i = 1, text = "", style, css
+	  var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed
+	  for (;;) {
+	    if (nextChange == pos) { // Update current marker set
+	      spanStyle = spanEndStyle = spanStartStyle = title = css = ""
+	      collapsed = null; nextChange = Infinity
+	      var foundBookmarks = [], endStyles = (void 0)
+	      for (var j = 0; j < spans.length; ++j) {
+	        var sp = spans[j], m = sp.marker
+	        if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
+	          foundBookmarks.push(m)
+	        } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
+	          if (sp.to != null && sp.to != pos && nextChange > sp.to) {
+	            nextChange = sp.to
+	            spanEndStyle = ""
+	          }
+	          if (m.className) { spanStyle += " " + m.className }
+	          if (m.css) { css = (css ? css + ";" : "") + m.css }
+	          if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle }
+	          if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to) }
+	          if (m.title && !title) { title = m.title }
+	          if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
+	            { collapsed = sp }
+	        } else if (sp.from > pos && nextChange > sp.from) {
+	          nextChange = sp.from
+	        }
+	      }
+	      if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
+	        { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1] } } }
+
+	      if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
+	        { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]) } }
+	      if (collapsed && (collapsed.from || 0) == pos) {
+	        buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
+	                           collapsed.marker, collapsed.from == null)
+	        if (collapsed.to == null) { return }
+	        if (collapsed.to == pos) { collapsed = false }
+	      }
+	    }
+	    if (pos >= len) { break }
+
+	    var upto = Math.min(len, nextChange)
+	    while (true) {
+	      if (text) {
+	        var end = pos + text.length
+	        if (!collapsed) {
+	          var tokenText = end > upto ? text.slice(0, upto - pos) : text
+	          builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
+	                           spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css)
+	        }
+	        if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
+	        pos = end
+	        spanStartStyle = ""
+	      }
+	      text = allText.slice(at, at = styles[i++])
+	      style = interpretTokenStyle(styles[i++], builder.cm.options)
+	    }
+	  }
+	}
+
+
+	// These objects are used to represent the visible (currently drawn)
+	// part of the document. A LineView may correspond to multiple
+	// logical lines, if those are connected by collapsed ranges.
+	function LineView(doc, line, lineN) {
+	  // The starting line
+	  this.line = line
+	  // Continuing lines, if any
+	  this.rest = visualLineContinued(line)
+	  // Number of logical lines in this visual line
+	  this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1
+	  this.node = this.text = null
+	  this.hidden = lineIsHidden(doc, line)
+	}
+
+	// Create a range of LineView objects for the given lines.
+	function buildViewArray(cm, from, to) {
+	  var array = [], nextPos
+	  for (var pos = from; pos < to; pos = nextPos) {
+	    var view = new LineView(cm.doc, getLine(cm.doc, pos), pos)
+	    nextPos = pos + view.size
+	    array.push(view)
+	  }
+	  return array
+	}
+
+	var operationGroup = null
+
+	function pushOperation(op) {
+	  if (operationGroup) {
+	    operationGroup.ops.push(op)
+	  } else {
+	    op.ownsGroup = operationGroup = {
+	      ops: [op],
+	      delayedCallbacks: []
+	    }
+	  }
+	}
+
+	function fireCallbacksForOps(group) {
+	  // Calls delayed callbacks and cursorActivity handlers until no
+	  // new ones appear
+	  var callbacks = group.delayedCallbacks, i = 0
+	  do {
+	    for (; i < callbacks.length; i++)
+	      { callbacks[i].call(null) }
+	    for (var j = 0; j < group.ops.length; j++) {
+	      var op = group.ops[j]
+	      if (op.cursorActivityHandlers)
+	        { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
+	          { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm) } }
+	    }
+	  } while (i < callbacks.length)
+	}
+
+	function finishOperation(op, endCb) {
+	  var group = op.ownsGroup
+	  if (!group) { return }
+
+	  try { fireCallbacksForOps(group) }
+	  finally {
+	    operationGroup = null
+	    endCb(group)
+	  }
+	}
+
+	var orphanDelayedCallbacks = null
+
+	// Often, we want to signal events at a point where we are in the
+	// middle of some work, but don't want the handler to start calling
+	// other methods on the editor, which might be in an inconsistent
+	// state or simply not expect any other events to happen.
+	// signalLater looks whether there are any handlers, and schedules
+	// them to be executed when the last operation ends, or, if no
+	// operation is active, when a timeout fires.
+	function signalLater(emitter, type /*, values...*/) {
+	  var arr = getHandlers(emitter, type)
+	  if (!arr.length) { return }
+	  var args = Array.prototype.slice.call(arguments, 2), list
+	  if (operationGroup) {
+	    list = operationGroup.delayedCallbacks
+	  } else if (orphanDelayedCallbacks) {
+	    list = orphanDelayedCallbacks
+	  } else {
+	    list = orphanDelayedCallbacks = []
+	    setTimeout(fireOrphanDelayed, 0)
+	  }
+	  var loop = function ( i ) {
+	    list.push(function () { return arr[i].apply(null, args); })
+	  };
+
+	  for (var i = 0; i < arr.length; ++i)
+	    loop( i );
+	}
+
+	function fireOrphanDelayed() {
+	  var delayed = orphanDelayedCallbacks
+	  orphanDelayedCallbacks = null
+	  for (var i = 0; i < delayed.length; ++i) { delayed[i]() }
+	}
+
+	// When an aspect of a line changes, a string is added to
+	// lineView.changes. This updates the relevant part of the line's
+	// DOM structure.
+	function updateLineForChanges(cm, lineView, lineN, dims) {
+	  for (var j = 0; j < lineView.changes.length; j++) {
+	    var type = lineView.changes[j]
+	    if (type == "text") { updateLineText(cm, lineView) }
+	    else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims) }
+	    else if (type == "class") { updateLineClasses(cm, lineView) }
+	    else if (type == "widget") { updateLineWidgets(cm, lineView, dims) }
+	  }
+	  lineView.changes = null
+	}
+
+	// Lines with gutter elements, widgets or a background class need to
+	// be wrapped, and have the extra elements added to the wrapper div
+	function ensureLineWrapped(lineView) {
+	  if (lineView.node == lineView.text) {
+	    lineView.node = elt("div", null, null, "position: relative")
+	    if (lineView.text.parentNode)
+	      { lineView.text.parentNode.replaceChild(lineView.node, lineView.text) }
+	    lineView.node.appendChild(lineView.text)
+	    if (ie && ie_version < 8) { lineView.node.style.zIndex = 2 }
+	  }
+	  return lineView.node
+	}
+
+	function updateLineBackground(cm, lineView) {
+	  var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass
+	  if (cls) { cls += " CodeMirror-linebackground" }
+	  if (lineView.background) {
+	    if (cls) { lineView.background.className = cls }
+	    else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null }
+	  } else if (cls) {
+	    var wrap = ensureLineWrapped(lineView)
+	    lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild)
+	    cm.display.input.setUneditable(lineView.background)
+	  }
+	}
+
+	// Wrapper around buildLineContent which will reuse the structure
+	// in display.externalMeasured when possible.
+	function getLineContent(cm, lineView) {
+	  var ext = cm.display.externalMeasured
+	  if (ext && ext.line == lineView.line) {
+	    cm.display.externalMeasured = null
+	    lineView.measure = ext.measure
+	    return ext.built
+	  }
+	  return buildLineContent(cm, lineView)
+	}
+
+	// Redraw the line's text. Interacts with the background and text
+	// classes because the mode may output tokens that influence these
+	// classes.
+	function updateLineText(cm, lineView) {
+	  var cls = lineView.text.className
+	  var built = getLineContent(cm, lineView)
+	  if (lineView.text == lineView.node) { lineView.node = built.pre }
+	  lineView.text.parentNode.replaceChild(built.pre, lineView.text)
+	  lineView.text = built.pre
+	  if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
+	    lineView.bgClass = built.bgClass
+	    lineView.textClass = built.textClass
+	    updateLineClasses(cm, lineView)
+	  } else if (cls) {
+	    lineView.text.className = cls
+	  }
+	}
+
+	function updateLineClasses(cm, lineView) {
+	  updateLineBackground(cm, lineView)
+	  if (lineView.line.wrapClass)
+	    { ensureLineWrapped(lineView).className = lineView.line.wrapClass }
+	  else if (lineView.node != lineView.text)
+	    { lineView.node.className = "" }
+	  var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass
+	  lineView.text.className = textClass || ""
+	}
+
+	function updateLineGutter(cm, lineView, lineN, dims) {
+	  if (lineView.gutter) {
+	    lineView.node.removeChild(lineView.gutter)
+	    lineView.gutter = null
+	  }
+	  if (lineView.gutterBackground) {
+	    lineView.node.removeChild(lineView.gutterBackground)
+	    lineView.gutterBackground = null
+	  }
+	  if (lineView.line.gutterClass) {
+	    var wrap = ensureLineWrapped(lineView)
+	    lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
+	                                    ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"))
+	    cm.display.input.setUneditable(lineView.gutterBackground)
+	    wrap.insertBefore(lineView.gutterBackground, lineView.text)
+	  }
+	  var markers = lineView.line.gutterMarkers
+	  if (cm.options.lineNumbers || markers) {
+	    var wrap$1 = ensureLineWrapped(lineView)
+	    var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"))
+	    cm.display.input.setUneditable(gutterWrap)
+	    wrap$1.insertBefore(gutterWrap, lineView.text)
+	    if (lineView.line.gutterClass)
+	      { gutterWrap.className += " " + lineView.line.gutterClass }
+	    if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
+	      { lineView.lineNumber = gutterWrap.appendChild(
+	        elt("div", lineNumberFor(cm.options, lineN),
+	            "CodeMirror-linenumber CodeMirror-gutter-elt",
+	            ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))) }
+	    if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
+	      var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]
+	      if (found)
+	        { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
+	                                   ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))) }
+	    } }
+	  }
+	}
+
+	function updateLineWidgets(cm, lineView, dims) {
+	  if (lineView.alignable) { lineView.alignable = null }
+	  for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
+	    next = node.nextSibling
+	    if (node.className == "CodeMirror-linewidget")
+	      { lineView.node.removeChild(node) }
+	  }
+	  insertLineWidgets(cm, lineView, dims)
+	}
+
+	// Build a line's DOM representation from scratch
+	function buildLineElement(cm, lineView, lineN, dims) {
+	  var built = getLineContent(cm, lineView)
+	  lineView.text = lineView.node = built.pre
+	  if (built.bgClass) { lineView.bgClass = built.bgClass }
+	  if (built.textClass) { lineView.textClass = built.textClass }
+
+	  updateLineClasses(cm, lineView)
+	  updateLineGutter(cm, lineView, lineN, dims)
+	  insertLineWidgets(cm, lineView, dims)
+	  return lineView.node
+	}
+
+	// A lineView may contain multiple logical lines (when merged by
+	// collapsed spans). The widgets for all of them need to be drawn.
+	function insertLineWidgets(cm, lineView, dims) {
+	  insertLineWidgetsFor(cm, lineView.line, lineView, dims, true)
+	  if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
+	    { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false) } }
+	}
+
+	function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
+	  if (!line.widgets) { return }
+	  var wrap = ensureLineWrapped(lineView)
+	  for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
+	    var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget")
+	    if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true") }
+	    positionLineWidget(widget, node, lineView, dims)
+	    cm.display.input.setUneditable(node)
+	    if (allowAbove && widget.above)
+	      { wrap.insertBefore(node, lineView.gutter || lineView.text) }
+	    else
+	      { wrap.appendChild(node) }
+	    signalLater(widget, "redraw")
+	  }
+	}
+
+	function positionLineWidget(widget, node, lineView, dims) {
+	  if (widget.noHScroll) {
+	    ;(lineView.alignable || (lineView.alignable = [])).push(node)
+	    var width = dims.wrapperWidth
+	    node.style.left = dims.fixedPos + "px"
+	    if (!widget.coverGutter) {
+	      width -= dims.gutterTotalWidth
+	      node.style.paddingLeft = dims.gutterTotalWidth + "px"
+	    }
+	    node.style.width = width + "px"
+	  }
+	  if (widget.coverGutter) {
+	    node.style.zIndex = 5
+	    node.style.position = "relative"
+	    if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px" }
+	  }
+	}
+
+	function widgetHeight(widget) {
+	  if (widget.height != null) { return widget.height }
+	  var cm = widget.doc.cm
+	  if (!cm) { return 0 }
+	  if (!contains(document.body, widget.node)) {
+	    var parentStyle = "position: relative;"
+	    if (widget.coverGutter)
+	      { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;" }
+	    if (widget.noHScroll)
+	      { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;" }
+	    removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle))
+	  }
+	  return widget.height = widget.node.parentNode.offsetHeight
+	}
+
+	// Return true when the given mouse event happened in a widget
+	function eventInWidget(display, e) {
+	  for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
+	    if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
+	        (n.parentNode == display.sizer && n != display.mover))
+	      { return true }
+	  }
+	}
+
+	// POSITION MEASUREMENT
+
+	function paddingTop(display) {return display.lineSpace.offsetTop}
+	function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
+	function paddingH(display) {
+	  if (display.cachedPaddingH) { return display.cachedPaddingH }
+	  var e = removeChildrenAndAdd(display.measure, elt("pre", "x"))
+	  var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle
+	  var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}
+	  if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data }
+	  return data
+	}
+
+	function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
+	function displayWidth(cm) {
+	  return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
+	}
+	function displayHeight(cm) {
+	  return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
+	}
+
+	// Ensure the lineView.wrapping.heights array is populated. This is
+	// an array of bottom offsets for the lines that make up a drawn
+	// line. When lineWrapping is on, there might be more than one
+	// height.
+	function ensureLineHeights(cm, lineView, rect) {
+	  var wrapping = cm.options.lineWrapping
+	  var curWidth = wrapping && displayWidth(cm)
+	  if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
+	    var heights = lineView.measure.heights = []
+	    if (wrapping) {
+	      lineView.measure.width = curWidth
+	      var rects = lineView.text.firstChild.getClientRects()
+	      for (var i = 0; i < rects.length - 1; i++) {
+	        var cur = rects[i], next = rects[i + 1]
+	        if (Math.abs(cur.bottom - next.bottom) > 2)
+	          { heights.push((cur.bottom + next.top) / 2 - rect.top) }
+	      }
+	    }
+	    heights.push(rect.bottom - rect.top)
+	  }
+	}
+
+	// Find a line map (mapping character offsets to text nodes) and a
+	// measurement cache for the given line number. (A line view might
+	// contain multiple lines when collapsed ranges are present.)
+	function mapFromLineView(lineView, line, lineN) {
+	  if (lineView.line == line)
+	    { return {map: lineView.measure.map, cache: lineView.measure.cache} }
+	  for (var i = 0; i < lineView.rest.length; i++)
+	    { if (lineView.rest[i] == line)
+	      { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
+	  for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
+	    { if (lineNo(lineView.rest[i$1]) > lineN)
+	      { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
+	}
+
+	// Render a line into the hidden node display.externalMeasured. Used
+	// when measurement is needed for a line that's not in the viewport.
+	function updateExternalMeasurement(cm, line) {
+	  line = visualLine(line)
+	  var lineN = lineNo(line)
+	  var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN)
+	  view.lineN = lineN
+	  var built = view.built = buildLineContent(cm, view)
+	  view.text = built.pre
+	  removeChildrenAndAdd(cm.display.lineMeasure, built.pre)
+	  return view
+	}
+
+	// Get a {top, bottom, left, right} box (in line-local coordinates)
+	// for a given character.
+	function measureChar(cm, line, ch, bias) {
+	  return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
+	}
+
+	// Find a line view that corresponds to the given line number.
+	function findViewForLine(cm, lineN) {
+	  if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
+	    { return cm.display.view[findViewIndex(cm, lineN)] }
+	  var ext = cm.display.externalMeasured
+	  if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
+	    { return ext }
+	}
+
+	// Measurement can be split in two steps, the set-up work that
+	// applies to the whole line, and the measurement of the actual
+	// character. Functions like coordsChar, that need to do a lot of
+	// measurements in a row, can thus ensure that the set-up work is
+	// only done once.
+	function prepareMeasureForLine(cm, line) {
+	  var lineN = lineNo(line)
+	  var view = findViewForLine(cm, lineN)
+	  if (view && !view.text) {
+	    view = null
+	  } else if (view && view.changes) {
+	    updateLineForChanges(cm, view, lineN, getDimensions(cm))
+	    cm.curOp.forceUpdate = true
+	  }
+	  if (!view)
+	    { view = updateExternalMeasurement(cm, line) }
+
+	  var info = mapFromLineView(view, line, lineN)
+	  return {
+	    line: line, view: view, rect: null,
+	    map: info.map, cache: info.cache, before: info.before,
+	    hasHeights: false
+	  }
+	}
+
+	// Given a prepared measurement object, measures the position of an
+	// actual character (or fetches it from the cache).
+	function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
+	  if (prepared.before) { ch = -1 }
+	  var key = ch + (bias || ""), found
+	  if (prepared.cache.hasOwnProperty(key)) {
+	    found = prepared.cache[key]
+	  } else {
+	    if (!prepared.rect)
+	      { prepared.rect = prepared.view.text.getBoundingClientRect() }
+	    if (!prepared.hasHeights) {
+	      ensureLineHeights(cm, prepared.view, prepared.rect)
+	      prepared.hasHeights = true
+	    }
+	    found = measureCharInner(cm, prepared, ch, bias)
+	    if (!found.bogus) { prepared.cache[key] = found }
+	  }
+	  return {left: found.left, right: found.right,
+	          top: varHeight ? found.rtop : found.top,
+	          bottom: varHeight ? found.rbottom : found.bottom}
+	}
+
+	var nullRect = {left: 0, right: 0, top: 0, bottom: 0}
+
+	function nodeAndOffsetInLineMap(map, ch, bias) {
+	  var node, start, end, collapse, mStart, mEnd
+	  // First, search the line map for the text node corresponding to,
+	  // or closest to, the target character.
+	  for (var i = 0; i < map.length; i += 3) {
+	    mStart = map[i]
+	    mEnd = map[i + 1]
+	    if (ch < mStart) {
+	      start = 0; end = 1
+	      collapse = "left"
+	    } else if (ch < mEnd) {
+	      start = ch - mStart
+	      end = start + 1
+	    } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
+	      end = mEnd - mStart
+	      start = end - 1
+	      if (ch >= mEnd) { collapse = "right" }
+	    }
+	    if (start != null) {
+	      node = map[i + 2]
+	      if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
+	        { collapse = bias }
+	      if (bias == "left" && start == 0)
+	        { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
+	          node = map[(i -= 3) + 2]
+	          collapse = "left"
+	        } }
+	      if (bias == "right" && start == mEnd - mStart)
+	        { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
+	          node = map[(i += 3) + 2]
+	          collapse = "right"
+	        } }
+	      break
+	    }
+	  }
+	  return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
+	}
+
+	function getUsefulRect(rects, bias) {
+	  var rect = nullRect
+	  if (bias == "left") { for (var i = 0; i < rects.length; i++) {
+	    if ((rect = rects[i]).left != rect.right) { break }
+	  } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
+	    if ((rect = rects[i$1]).left != rect.right) { break }
+	  } }
+	  return rect
+	}
+
+	function measureCharInner(cm, prepared, ch, bias) {
+	  var place = nodeAndOffsetInLineMap(prepared.map, ch, bias)
+	  var node = place.node, start = place.start, end = place.end, collapse = place.collapse
+
+	  var rect
+	  if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
+	    for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
+	      while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start }
+	      while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end }
+	      if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
+	        { rect = node.parentNode.getBoundingClientRect() }
 	      else
-	        wrap.appendChild(node);
-	      signalLater(widget, "redraw");
-	    }
-	  }
-
-	  function positionLineWidget(widget, node, lineView, dims) {
-	    if (widget.noHScroll) {
-	      (lineView.alignable || (lineView.alignable = [])).push(node);
-	      var width = dims.wrapperWidth;
-	      node.style.left = dims.fixedPos + "px";
-	      if (!widget.coverGutter) {
-	        width -= dims.gutterTotalWidth;
-	        node.style.paddingLeft = dims.gutterTotalWidth + "px";
-	      }
-	      node.style.width = width + "px";
-	    }
-	    if (widget.coverGutter) {
-	      node.style.zIndex = 5;
-	      node.style.position = "relative";
-	      if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
-	    }
-	  }
-
-	  // POSITION OBJECT
-
-	  // A Pos instance represents a position within the text.
-	  var Pos = CodeMirror.Pos = function(line, ch) {
-	    if (!(this instanceof Pos)) return new Pos(line, ch);
-	    this.line = line; this.ch = ch;
-	  };
-
-	  // Compare two positions, return 0 if they are the same, a negative
-	  // number when a is less, and a positive number otherwise.
-	  var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
-
-	  function copyPos(x) {return Pos(x.line, x.ch);}
-	  function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
-	  function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
-
-	  // INPUT HANDLING
-
-	  function ensureFocus(cm) {
-	    if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
-	  }
-
-	  // This will be set to a {lineWise: bool, text: [string]} object, so
-	  // that, when pasting, we know what kind of selections the copied
-	  // text was made out of.
-	  var lastCopied = null;
-
-	  function applyTextInput(cm, inserted, deleted, sel, origin) {
-	    var doc = cm.doc;
-	    cm.display.shift = false;
-	    if (!sel) sel = doc.sel;
-
-	    var paste = cm.state.pasteIncoming || origin == "paste";
-	    var textLines = doc.splitLines(inserted), multiPaste = null
-	    // When pasing N lines into N selections, insert one line per selection
-	    if (paste && sel.ranges.length > 1) {
-	      if (lastCopied && lastCopied.text.join("\n") == inserted) {
-	        if (sel.ranges.length % lastCopied.text.length == 0) {
-	          multiPaste = [];
-	          for (var i = 0; i < lastCopied.text.length; i++)
-	            multiPaste.push(doc.splitLines(lastCopied.text[i]));
-	        }
-	      } else if (textLines.length == sel.ranges.length) {
-	        multiPaste = map(textLines, function(l) { return [l]; });
-	      }
-	    }
-
-	    // Normal behavior is to insert the new text into every selection
-	    for (var i = sel.ranges.length - 1; i >= 0; i--) {
-	      var range = sel.ranges[i];
-	      var from = range.from(), to = range.to();
-	      if (range.empty()) {
-	        if (deleted && deleted > 0) // Handle deletion
-	          from = Pos(from.line, from.ch - deleted);
-	        else if (cm.state.overwrite && !paste) // Handle overwrite
-	          to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
-	        else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
-	          from = to = Pos(from.line, 0)
-	      }
-	      var updateInput = cm.curOp.updateInput;
-	      var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
-	                         origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
-	      makeChange(cm.doc, changeEvent);
-	      signalLater(cm, "inputRead", cm, changeEvent);
-	    }
-	    if (inserted && !paste)
-	      triggerElectric(cm, inserted);
-
-	    ensureCursorVisible(cm);
-	    cm.curOp.updateInput = updateInput;
-	    cm.curOp.typing = true;
-	    cm.state.pasteIncoming = cm.state.cutIncoming = false;
-	  }
-
-	  function handlePaste(e, cm) {
-	    var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
-	    if (pasted) {
-	      e.preventDefault();
-	      if (!cm.isReadOnly() && !cm.options.disableInput)
-	        runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
-	      return true;
-	    }
-	  }
-
-	  function triggerElectric(cm, inserted) {
-	    // When an 'electric' character is inserted, immediately trigger a reindent
-	    if (!cm.options.electricChars || !cm.options.smartIndent) return;
-	    var sel = cm.doc.sel;
-
-	    for (var i = sel.ranges.length - 1; i >= 0; i--) {
-	      var range = sel.ranges[i];
-	      if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
-	      var mode = cm.getModeAt(range.head);
-	      var indented = false;
-	      if (mode.electricChars) {
-	        for (var j = 0; j < mode.electricChars.length; j++)
-	          if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
-	            indented = indentLine(cm, range.head.line, "smart");
-	            break;
-	          }
-	      } else if (mode.electricInput) {
-	        if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
-	          indented = indentLine(cm, range.head.line, "smart");
-	      }
-	      if (indented) signalLater(cm, "electricInput", cm, range.head.line);
-	    }
-	  }
-
-	  function copyableRanges(cm) {
-	    var text = [], ranges = [];
-	    for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
-	      var line = cm.doc.sel.ranges[i].head.line;
-	      var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
-	      ranges.push(lineRange);
-	      text.push(cm.getRange(lineRange.anchor, lineRange.head));
-	    }
-	    return {text: text, ranges: ranges};
-	  }
-
-	  function disableBrowserMagic(field) {
-	    field.setAttribute("autocorrect", "off");
-	    field.setAttribute("autocapitalize", "off");
-	    field.setAttribute("spellcheck", "false");
-	  }
-
-	  // TEXTAREA INPUT STYLE
-
-	  function TextareaInput(cm) {
-	    this.cm = cm;
-	    // See input.poll and input.reset
-	    this.prevInput = "";
-
-	    // Flag that indicates whether we expect input to appear real soon
-	    // now (after some event like 'keypress' or 'input') and are
-	    // polling intensively.
-	    this.pollingFast = false;
-	    // Self-resetting timeout for the poller
-	    this.polling = new Delayed();
-	    // Tracks when input.reset has punted to just putting a short
-	    // string into the textarea instead of the full selection.
-	    this.inaccurateSelection = false;
-	    // Used to work around IE issue with selection being forgotten when focus moves away from textarea
-	    this.hasSelection = false;
-	    this.composing = null;
-	  };
-
-	  function hiddenTextarea() {
-	    var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
-	    var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
-	    // The textarea is kept positioned near the cursor to prevent the
-	    // fact that it'll be scrolled into view on input from scrolling
-	    // our fake cursor out of view. On webkit, when wrap=off, paste is
-	    // very slow. So make the area wide instead.
-	    if (webkit) te.style.width = "1000px";
-	    else te.setAttribute("wrap", "off");
-	    // If border: 0; -- iOS fails to open keyboard (issue #1287)
-	    if (ios) te.style.border = "1px solid black";
-	    disableBrowserMagic(te);
-	    return div;
-	  }
-
-	  TextareaInput.prototype = copyObj({
-	    init: function(display) {
-	      var input = this, cm = this.cm;
-
-	      // Wraps and hides input textarea
-	      var div = this.wrapper = hiddenTextarea();
-	      // The semihidden textarea that is focused when the editor is
-	      // focused, and receives input.
-	      var te = this.textarea = div.firstChild;
-	      display.wrapper.insertBefore(div, display.wrapper.firstChild);
-
-	      // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
-	      if (ios) te.style.width = "0px";
-
-	      on(te, "input", function() {
-	        if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
-	        input.poll();
-	      });
-
-	      on(te, "paste", function(e) {
-	        if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return
-
-	        cm.state.pasteIncoming = true;
-	        input.fastPoll();
-	      });
-
-	      function prepareCopyCut(e) {
-	        if (signalDOMEvent(cm, e)) return
-	        if (cm.somethingSelected()) {
-	          lastCopied = {lineWise: false, text: cm.getSelections()};
-	          if (input.inaccurateSelection) {
-	            input.prevInput = "";
-	            input.inaccurateSelection = false;
-	            te.value = lastCopied.text.join("\n");
-	            selectInput(te);
-	          }
-	        } else if (!cm.options.lineWiseCopyCut) {
-	          return;
-	        } else {
-	          var ranges = copyableRanges(cm);
-	          lastCopied = {lineWise: true, text: ranges.text};
-	          if (e.type == "cut") {
-	            cm.setSelections(ranges.ranges, null, sel_dontScroll);
-	          } else {
-	            input.prevInput = "";
-	            te.value = ranges.text.join("\n");
-	            selectInput(te);
-	          }
-	        }
-	        if (e.type == "cut") cm.state.cutIncoming = true;
-	      }
-	      on(te, "cut", prepareCopyCut);
-	      on(te, "copy", prepareCopyCut);
-
-	      on(display.scroller, "paste", function(e) {
-	        if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return;
-	        cm.state.pasteIncoming = true;
-	        input.focus();
-	      });
-
-	      // Prevent normal selection in the editor (we handle our own)
-	      on(display.lineSpace, "selectstart", function(e) {
-	        if (!eventInWidget(display, e)) e_preventDefault(e);
-	      });
-
-	      on(te, "compositionstart", function() {
-	        var start = cm.getCursor("from");
-	        if (input.composing) input.composing.range.clear()
-	        input.composing = {
-	          start: start,
-	          range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
-	        };
-	      });
-	      on(te, "compositionend", function() {
-	        if (input.composing) {
-	          input.poll();
-	          input.composing.range.clear();
-	          input.composing = null;
-	        }
-	      });
-	    },
-
-	    prepareSelection: function() {
-	      // Redraw the selection and/or cursor
-	      var cm = this.cm, display = cm.display, doc = cm.doc;
-	      var result = prepareSelection(cm);
-
-	      // Move the hidden textarea near the cursor to prevent scrolling artifacts
-	      if (cm.options.moveInputWithCursor) {
-	        var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
-	        var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
-	        result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
-	                                            headPos.top + lineOff.top - wrapOff.top));
-	        result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
-	                                             headPos.left + lineOff.left - wrapOff.left));
-	      }
-
-	      return result;
-	    },
-
-	    showSelection: function(drawn) {
-	      var cm = this.cm, display = cm.display;
-	      removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
-	      removeChildrenAndAdd(display.selectionDiv, drawn.selection);
-	      if (drawn.teTop != null) {
-	        this.wrapper.style.top = drawn.teTop + "px";
-	        this.wrapper.style.left = drawn.teLeft + "px";
-	      }
-	    },
-
-	    // Reset the input to correspond to the selection (or to be empty,
-	    // when not typing and nothing is selected)
-	    reset: function(typing) {
-	      if (this.contextMenuPending) return;
-	      var minimal, selected, cm = this.cm, doc = cm.doc;
-	      if (cm.somethingSelected()) {
-	        this.prevInput = "";
-	        var range = doc.sel.primary();
-	        minimal = hasCopyEvent &&
-	          (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
-	        var content = minimal ? "-" : selected || cm.getSelection();
-	        this.textarea.value = content;
-	        if (cm.state.focused) selectInput(this.textarea);
-	        if (ie && ie_version >= 9) this.hasSelection = content;
-	      } else if (!typing) {
-	        this.prevInput = this.textarea.value = "";
-	        if (ie && ie_version >= 9) this.hasSelection = null;
-	      }
-	      this.inaccurateSelection = minimal;
-	    },
-
-	    getField: function() { return this.textarea; },
-
-	    supportsTouch: function() { return false; },
-
-	    focus: function() {
-	      if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
-	        try { this.textarea.focus(); }
-	        catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
-	      }
-	    },
-
-	    blur: function() { this.textarea.blur(); },
-
-	    resetPosition: function() {
-	      this.wrapper.style.top = this.wrapper.style.left = 0;
-	    },
-
-	    receivedFocus: function() { this.slowPoll(); },
-
-	    // Poll for input changes, using the normal rate of polling. This
-	    // runs as long as the editor is focused.
-	    slowPoll: function() {
-	      var input = this;
-	      if (input.pollingFast) return;
-	      input.polling.set(this.cm.options.pollInterval, function() {
-	        input.poll();
-	        if (input.cm.state.focused) input.slowPoll();
-	      });
-	    },
-
-	    // When an event has just come in that is likely to add or change
-	    // something in the input textarea, we poll faster, to ensure that
-	    // the change appears on the screen quickly.
-	    fastPoll: function() {
-	      var missed = false, input = this;
-	      input.pollingFast = true;
-	      function p() {
-	        var changed = input.poll();
-	        if (!changed && !missed) {missed = true; input.polling.set(60, p);}
-	        else {input.pollingFast = false; input.slowPoll();}
-	      }
-	      input.polling.set(20, p);
-	    },
-
-	    // Read input from the textarea, and update the document to match.
-	    // When something is selected, it is present in the textarea, and
-	    // selected (unless it is huge, in which case a placeholder is
-	    // used). When nothing is selected, the cursor sits after previously
-	    // seen text (can be empty), which is stored in prevInput (we must
-	    // not reset the textarea when typing, because that breaks IME).
-	    poll: function() {
-	      var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
-	      // Since this is called a *lot*, try to bail out as cheaply as
-	      // possible when it is clear that nothing happened. hasSelection
-	      // will be the case when there is a lot of text in the textarea,
-	      // in which case reading its value would be expensive.
-	      if (this.contextMenuPending || !cm.state.focused ||
-	          (hasSelection(input) && !prevInput && !this.composing) ||
-	          cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
-	        return false;
-
-	      var text = input.value;
-	      // If nothing changed, bail.
-	      if (text == prevInput && !cm.somethingSelected()) return false;
-	      // Work around nonsensical selection resetting in IE9/10, and
-	      // inexplicable appearance of private area unicode characters on
-	      // some key combos in Mac (#2689).
-	      if (ie && ie_version >= 9 && this.hasSelection === text ||
-	          mac && /[\uf700-\uf7ff]/.test(text)) {
-	        cm.display.input.reset();
-	        return false;
-	      }
-
-	      if (cm.doc.sel == cm.display.selForContextMenu) {
-	        var first = text.charCodeAt(0);
-	        if (first == 0x200b && !prevInput) prevInput = "\u200b";
-	        if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
-	      }
-	      // Find the part of the input that is actually new
-	      var same = 0, l = Math.min(prevInput.length, text.length);
-	      while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
-
-	      var self = this;
-	      runInOp(cm, function() {
-	        applyTextInput(cm, text.slice(same), prevInput.length - same,
-	                       null, self.composing ? "*compose" : null);
-
-	        // Don't leave long text in the textarea, since it makes further polling slow
-	        if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
-	        else self.prevInput = text;
-
-	        if (self.composing) {
-	          self.composing.range.clear();
-	          self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
-	                                             {className: "CodeMirror-composing"});
-	        }
-	      });
-	      return true;
-	    },
-
-	    ensurePolled: function() {
-	      if (this.pollingFast && this.poll()) this.pollingFast = false;
-	    },
-
-	    onKeyPress: function() {
-	      if (ie && ie_version >= 9) this.hasSelection = null;
-	      this.fastPoll();
-	    },
-
-	    onContextMenu: function(e) {
-	      var input = this, cm = input.cm, display = cm.display, te = input.textarea;
-	      var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
-	      if (!pos || presto) return; // Opera is difficult.
-
-	      // Reset the current text selection only if the click is done outside of the selection
-	      // and 'resetSelectionOnContextMenu' option is true.
-	      var reset = cm.options.resetSelectionOnContextMenu;
-	      if (reset && cm.doc.sel.contains(pos) == -1)
-	        operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
-
-	      var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
-	      input.wrapper.style.cssText = "position: absolute"
-	      var wrapperBox = input.wrapper.getBoundingClientRect()
-	      te.style.cssText = "position: absolute; width: 30px; height: 30px; top: " + (e.clientY - wrapperBox.top - 5) +
-	        "px; left: " + (e.clientX - wrapperBox.left - 5) + "px; z-index: 1000; background: " +
-	        (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
-	        "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
-	      if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
-	      display.input.focus();
-	      if (webkit) window.scrollTo(null, oldScrollY);
-	      display.input.reset();
-	      // Adds "Select all" to context menu in FF
-	      if (!cm.somethingSelected()) te.value = input.prevInput = " ";
-	      input.contextMenuPending = true;
-	      display.selForContextMenu = cm.doc.sel;
-	      clearTimeout(display.detectingSelectAll);
-
-	      // Select-all will be greyed out if there's nothing to select, so
-	      // this adds a zero-width space so that we can later check whether
-	      // it got selected.
-	      function prepareSelectAllHack() {
-	        if (te.selectionStart != null) {
-	          var selected = cm.somethingSelected();
-	          var extval = "\u200b" + (selected ? te.value : "");
-	          te.value = "\u21da"; // Used to catch context-menu undo
-	          te.value = extval;
-	          input.prevInput = selected ? "" : "\u200b";
-	          te.selectionStart = 1; te.selectionEnd = extval.length;
-	          // Re-set this, in case some other handler touched the
-	          // selection in the meantime.
-	          display.selForContextMenu = cm.doc.sel;
-	        }
-	      }
-	      function rehide() {
-	        input.contextMenuPending = false;
-	        input.wrapper.style.cssText = oldWrapperCSS
-	        te.style.cssText = oldCSS;
-	        if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
-
-	        // Try to detect the user choosing select-all
-	        if (te.selectionStart != null) {
-	          if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
-	          var i = 0, poll = function() {
-	            if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
-	                te.selectionEnd > 0 && input.prevInput == "\u200b")
-	              operation(cm, commands.selectAll)(cm);
-	            else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
-	            else display.input.reset();
-	          };
-	          display.detectingSelectAll = setTimeout(poll, 200);
-	        }
-	      }
-
-	      if (ie && ie_version >= 9) prepareSelectAllHack();
-	      if (captureRightClick) {
-	        e_stop(e);
-	        var mouseup = function() {
-	          off(window, "mouseup", mouseup);
-	          setTimeout(rehide, 20);
-	        };
-	        on(window, "mouseup", mouseup);
-	      } else {
-	        setTimeout(rehide, 50);
-	      }
-	    },
-
-	    readOnlyChanged: function(val) {
-	      if (!val) this.reset();
-	    },
-
-	    setUneditable: nothing,
-
-	    needsContentAttribute: false
-	  }, TextareaInput.prototype);
-
-	  // CONTENTEDITABLE INPUT STYLE
-
-	  function ContentEditableInput(cm) {
-	    this.cm = cm;
-	    this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
-	    this.polling = new Delayed();
-	    this.gracePeriod = false;
-	  }
-
-	  ContentEditableInput.prototype = copyObj({
-	    init: function(display) {
-	      var input = this, cm = input.cm;
-	      var div = input.div = display.lineDiv;
-	      disableBrowserMagic(div);
-
-	      on(div, "paste", function(e) {
-	        if (!signalDOMEvent(cm, e)) handlePaste(e, cm);
-	      })
-
-	      on(div, "compositionstart", function(e) {
-	        var data = e.data;
-	        input.composing = {sel: cm.doc.sel, data: data, startData: data};
-	        if (!data) return;
-	        var prim = cm.doc.sel.primary();
-	        var line = cm.getLine(prim.head.line);
-	        var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
-	        if (found > -1 && found <= prim.head.ch)
-	          input.composing.sel = simpleSelection(Pos(prim.head.line, found),
-	                                                Pos(prim.head.line, found + data.length));
-	      });
-	      on(div, "compositionupdate", function(e) {
-	        input.composing.data = e.data;
-	      });
-	      on(div, "compositionend", function(e) {
-	        var ours = input.composing;
-	        if (!ours) return;
-	        if (e.data != ours.startData && !/\u200b/.test(e.data))
-	          ours.data = e.data;
-	        // Need a small delay to prevent other code (input event,
-	        // selection polling) from doing damage when fired right after
-	        // compositionend.
-	        setTimeout(function() {
-	          if (!ours.handled)
-	            input.applyComposition(ours);
-	          if (input.composing == ours)
-	            input.composing = null;
-	        }, 50);
-	      });
-
-	      on(div, "touchstart", function() {
-	        input.forceCompositionEnd();
-	      });
-
-	      on(div, "input", function() {
-	        if (input.composing) return;
-	        if (cm.isReadOnly() || !input.pollContent())
-	          runInOp(input.cm, function() {regChange(cm);});
-	      });
-
-	      function onCopyCut(e) {
-	        if (signalDOMEvent(cm, e)) return
-	        if (cm.somethingSelected()) {
-	          lastCopied = {lineWise: false, text: cm.getSelections()};
-	          if (e.type == "cut") cm.replaceSelection("", null, "cut");
-	        } else if (!cm.options.lineWiseCopyCut) {
-	          return;
-	        } else {
-	          var ranges = copyableRanges(cm);
-	          lastCopied = {lineWise: true, text: ranges.text};
-	          if (e.type == "cut") {
-	            cm.operation(function() {
-	              cm.setSelections(ranges.ranges, 0, sel_dontScroll);
-	              cm.replaceSelection("", null, "cut");
-	            });
-	          }
-	        }
-	        // iOS exposes the clipboard API, but seems to discard content inserted into it
-	        if (e.clipboardData && !ios) {
-	          e.preventDefault();
-	          e.clipboardData.clearData();
-	          e.clipboardData.setData("text/plain", lastCopied.text.join("\n"));
-	        } else {
-	          // Old-fashioned briefly-focus-a-textarea hack
-	          var kludge = hiddenTextarea(), te = kludge.firstChild;
-	          cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
-	          te.value = lastCopied.text.join("\n");
-	          var hadFocus = document.activeElement;
-	          selectInput(te);
-	          setTimeout(function() {
-	            cm.display.lineSpace.removeChild(kludge);
-	            hadFocus.focus();
-	          }, 50);
-	        }
-	      }
-	      on(div, "copy", onCopyCut);
-	      on(div, "cut", onCopyCut);
-	    },
-
-	    prepareSelection: function() {
-	      var result = prepareSelection(this.cm, false);
-	      result.focus = this.cm.state.focused;
-	      return result;
-	    },
-
-	    showSelection: function(info, takeFocus) {
-	      if (!info || !this.cm.display.view.length) return;
-	      if (info.focus || takeFocus) this.showPrimarySelection();
-	      this.showMultipleSelections(info);
-	    },
-
-	    showPrimarySelection: function() {
-	      var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
-	      var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
-	      var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
-	      if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
-	          cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
-	          cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
-	        return;
-
-	      var start = posToDOM(this.cm, prim.from());
-	      var end = posToDOM(this.cm, prim.to());
-	      if (!start && !end) return;
-
-	      var view = this.cm.display.view;
-	      var old = sel.rangeCount && sel.getRangeAt(0);
-	      if (!start) {
-	        start = {node: view[0].measure.map[2], offset: 0};
-	      } else if (!end) { // FIXME dangerously hacky
-	        var measure = view[view.length - 1].measure;
-	        var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
-	        end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
-	      }
-
-	      try { var rng = range(start.node, start.offset, end.offset, end.node); }
-	      catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
-	      if (rng) {
-	        if (!gecko && this.cm.state.focused) {
-	          sel.collapse(start.node, start.offset);
-	          if (!rng.collapsed) sel.addRange(rng);
-	        } else {
-	          sel.removeAllRanges();
-	          sel.addRange(rng);
-	        }
-	        if (old && sel.anchorNode == null) sel.addRange(old);
-	        else if (gecko) this.startGracePeriod();
-	      }
-	      this.rememberSelection();
-	    },
-
-	    startGracePeriod: function() {
-	      var input = this;
-	      clearTimeout(this.gracePeriod);
-	      this.gracePeriod = setTimeout(function() {
-	        input.gracePeriod = false;
-	        if (input.selectionChanged())
-	          input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
-	      }, 20);
-	    },
-
-	    showMultipleSelections: function(info) {
-	      removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
-	      removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
-	    },
-
-	    rememberSelection: function() {
-	      var sel = window.getSelection();
-	      this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
-	      this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
-	    },
-
-	    selectionInEditor: function() {
-	      var sel = window.getSelection();
-	      if (!sel.rangeCount) return false;
-	      var node = sel.getRangeAt(0).commonAncestorContainer;
-	      return contains(this.div, node);
-	    },
-
-	    focus: function() {
-	      if (this.cm.options.readOnly != "nocursor") this.div.focus();
-	    },
-	    blur: function() { this.div.blur(); },
-	    getField: function() { return this.div; },
-
-	    supportsTouch: function() { return true; },
-
-	    receivedFocus: function() {
-	      var input = this;
-	      if (this.selectionInEditor())
-	        this.pollSelection();
-	      else
-	        runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
-
-	      function poll() {
-	        if (input.cm.state.focused) {
-	          input.pollSelection();
-	          input.polling.set(input.cm.options.pollInterval, poll);
-	        }
-	      }
-	      this.polling.set(this.cm.options.pollInterval, poll);
-	    },
-
-	    selectionChanged: function() {
-	      var sel = window.getSelection();
-	      return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
-	        sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
-	    },
-
-	    pollSelection: function() {
-	      if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
-	        var sel = window.getSelection(), cm = this.cm;
-	        this.rememberSelection();
-	        var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
-	        var head = domToPos(cm, sel.focusNode, sel.focusOffset);
-	        if (anchor && head) runInOp(cm, function() {
-	          setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
-	          if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
-	        });
-	      }
-	    },
-
-	    pollContent: function() {
-	      var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
-	      var from = sel.from(), to = sel.to();
-	      if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
-
-	      var fromIndex;
-	      if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
-	        var fromLine = lineNo(display.view[0].line);
-	        var fromNode = display.view[0].node;
-	      } else {
-	        var fromLine = lineNo(display.view[fromIndex].line);
-	        var fromNode = display.view[fromIndex - 1].node.nextSibling;
-	      }
-	      var toIndex = findViewIndex(cm, to.line);
-	      if (toIndex == display.view.length - 1) {
-	        var toLine = display.viewTo - 1;
-	        var toNode = display.lineDiv.lastChild;
-	      } else {
-	        var toLine = lineNo(display.view[toIndex + 1].line) - 1;
-	        var toNode = display.view[toIndex + 1].node.previousSibling;
-	      }
-
-	      var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
-	      var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
-	      while (newText.length > 1 && oldText.length > 1) {
-	        if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
-	        else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
-	        else break;
-	      }
-
-	      var cutFront = 0, cutEnd = 0;
-	      var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
-	      while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
-	        ++cutFront;
-	      var newBot = lst(newText), oldBot = lst(oldText);
-	      var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
-	                               oldBot.length - (oldText.length == 1 ? cutFront : 0));
-	      while (cutEnd < maxCutEnd &&
-	             newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
-	        ++cutEnd;
-
-	      newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
-	      newText[0] = newText[0].slice(cutFront);
-
-	      var chFrom = Pos(fromLine, cutFront);
-	      var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
-	      if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
-	        replaceRange(cm.doc, newText, chFrom, chTo, "+input");
-	        return true;
-	      }
-	    },
-
-	    ensurePolled: function() {
-	      this.forceCompositionEnd();
-	    },
-	    reset: function() {
-	      this.forceCompositionEnd();
-	    },
-	    forceCompositionEnd: function() {
-	      if (!this.composing || this.composing.handled) return;
-	      this.applyComposition(this.composing);
-	      this.composing.handled = true;
-	      this.div.blur();
-	      this.div.focus();
-	    },
-	    applyComposition: function(composing) {
-	      if (this.cm.isReadOnly())
-	        operation(this.cm, regChange)(this.cm)
-	      else if (composing.data && composing.data != composing.startData)
-	        operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
-	    },
-
-	    setUneditable: function(node) {
-	      node.contentEditable = "false"
-	    },
-
-	    onKeyPress: function(e) {
-	      e.preventDefault();
-	      if (!this.cm.isReadOnly())
-	        operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
-	    },
-
-	    readOnlyChanged: function(val) {
-	      this.div.contentEditable = String(val != "nocursor")
-	    },
-
-	    onContextMenu: nothing,
-	    resetPosition: nothing,
-
-	    needsContentAttribute: true
-	  }, ContentEditableInput.prototype);
-
-	  function posToDOM(cm, pos) {
-	    var view = findViewForLine(cm, pos.line);
-	    if (!view || view.hidden) return null;
-	    var line = getLine(cm.doc, pos.line);
-	    var info = mapFromLineView(view, line, pos.line);
-
-	    var order = getOrder(line), side = "left";
-	    if (order) {
-	      var partPos = getBidiPartAt(order, pos.ch);
-	      side = partPos % 2 ? "right" : "left";
-	    }
-	    var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
-	    result.offset = result.collapse == "right" ? result.end : result.start;
-	    return result;
-	  }
-
-	  function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
-
-	  function domToPos(cm, node, offset) {
-	    var lineNode;
-	    if (node == cm.display.lineDiv) {
-	      lineNode = cm.display.lineDiv.childNodes[offset];
-	      if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
-	      node = null; offset = 0;
+	        { rect = getUsefulRect(range(node, start, end).getClientRects(), bias) }
+	      if (rect.left || rect.right || start == 0) { break }
+	      end = start
+	      start = start - 1
+	      collapse = "right"
+	    }
+	    if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect) }
+	  } else { // If it is a widget, simply get the box for the whole widget.
+	    if (start > 0) { collapse = bias = "right" }
+	    var rects
+	    if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
+	      { rect = rects[bias == "right" ? rects.length - 1 : 0] }
+	    else
+	      { rect = node.getBoundingClientRect() }
+	  }
+	  if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
+	    var rSpan = node.parentNode.getClientRects()[0]
+	    if (rSpan)
+	      { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom} }
+	    else
+	      { rect = nullRect }
+	  }
+
+	  var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top
+	  var mid = (rtop + rbot) / 2
+	  var heights = prepared.view.measure.heights
+	  var i = 0
+	  for (; i < heights.length - 1; i++)
+	    { if (mid < heights[i]) { break } }
+	  var top = i ? heights[i - 1] : 0, bot = heights[i]
+	  var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
+	                right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
+	                top: top, bottom: bot}
+	  if (!rect.left && !rect.right) { result.bogus = true }
+	  if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot }
+
+	  return result
+	}
+
+	// Work around problem with bounding client rects on ranges being
+	// returned incorrectly when zoomed on IE10 and below.
+	function maybeUpdateRectForZooming(measure, rect) {
+	  if (!window.screen || screen.logicalXDPI == null ||
+	      screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
+	    { return rect }
+	  var scaleX = screen.logicalXDPI / screen.deviceXDPI
+	  var scaleY = screen.logicalYDPI / screen.deviceYDPI
+	  return {left: rect.left * scaleX, right: rect.right * scaleX,
+	          top: rect.top * scaleY, bottom: rect.bottom * scaleY}
+	}
+
+	function clearLineMeasurementCacheFor(lineView) {
+	  if (lineView.measure) {
+	    lineView.measure.cache = {}
+	    lineView.measure.heights = null
+	    if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
+	      { lineView.measure.caches[i] = {} } }
+	  }
+	}
+
+	function clearLineMeasurementCache(cm) {
+	  cm.display.externalMeasure = null
+	  removeChildren(cm.display.lineMeasure)
+	  for (var i = 0; i < cm.display.view.length; i++)
+	    { clearLineMeasurementCacheFor(cm.display.view[i]) }
+	}
+
+	function clearCaches(cm) {
+	  clearLineMeasurementCache(cm)
+	  cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null
+	  if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true }
+	  cm.display.lineNumChars = null
+	}
+
+	function pageScrollX() {
+	  // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
+	  // which causes page_Offset and bounding client rects to use
+	  // different reference viewports and invalidate our calculations.
+	  if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
+	  return window.pageXOffset || (document.documentElement || document.body).scrollLeft
+	}
+	function pageScrollY() {
+	  if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
+	  return window.pageYOffset || (document.documentElement || document.body).scrollTop
+	}
+
+	// Converts a {top, bottom, left, right} box from line-local
+	// coordinates into another coordinate system. Context may be one of
+	// "line", "div" (display.lineDiv), "local"./null (editor), "window",
+	// or "page".
+	function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
+	  if (!includeWidgets && lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) {
+	    var size = widgetHeight(lineObj.widgets[i])
+	    rect.top += size; rect.bottom += size
+	  } } }
+	  if (context == "line") { return rect }
+	  if (!context) { context = "local" }
+	  var yOff = heightAtLine(lineObj)
+	  if (context == "local") { yOff += paddingTop(cm.display) }
+	  else { yOff -= cm.display.viewOffset }
+	  if (context == "page" || context == "window") {
+	    var lOff = cm.display.lineSpace.getBoundingClientRect()
+	    yOff += lOff.top + (context == "window" ? 0 : pageScrollY())
+	    var xOff = lOff.left + (context == "window" ? 0 : pageScrollX())
+	    rect.left += xOff; rect.right += xOff
+	  }
+	  rect.top += yOff; rect.bottom += yOff
+	  return rect
+	}
+
+	// Coverts a box from "div" coords to another coordinate system.
+	// Context may be "window", "page", "div", or "local"./null.
+	function fromCoordSystem(cm, coords, context) {
+	  if (context == "div") { return coords }
+	  var left = coords.left, top = coords.top
+	  // First move into "page" coordinate system
+	  if (context == "page") {
+	    left -= pageScrollX()
+	    top -= pageScrollY()
+	  } else if (context == "local" || !context) {
+	    var localBox = cm.display.sizer.getBoundingClientRect()
+	    left += localBox.left
+	    top += localBox.top
+	  }
+
+	  var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect()
+	  return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
+	}
+
+	function charCoords(cm, pos, context, lineObj, bias) {
+	  if (!lineObj) { lineObj = getLine(cm.doc, pos.line) }
+	  return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
+	}
+
+	// Returns a box for a given cursor position, which may have an
+	// 'other' property containing the position of the secondary cursor
+	// on a bidi boundary.
+	// A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
+	// and after `char - 1` in writing order of `char - 1`
+	// A cursor Pos(line, char, "after") is on the same visual line as `char`
+	// and before `char` in writing order of `char`
+	// Examples (upper-case letters are RTL, lower-case are LTR):
+	//     Pos(0, 1, ...)
+	//     before   after
+	// ab     a|b     a|b
+	// aB     a|B     aB|
+	// Ab     |Ab     A|b
+	// AB     B|A     B|A
+	// Every position after the last character on a line is considered to stick
+	// to the last character on the line.
+	function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
+	  lineObj = lineObj || getLine(cm.doc, pos.line)
+	  if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj) }
+	  function get(ch, right) {
+	    var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight)
+	    if (right) { m.left = m.right; } else { m.right = m.left }
+	    return intoCoordSystem(cm, lineObj, m, context)
+	  }
+	  var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky
+	  if (ch >= lineObj.text.length) {
+	    ch = lineObj.text.length
+	    sticky = "before"
+	  } else if (ch <= 0) {
+	    ch = 0
+	    sticky = "after"
+	  }
+	  if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
+
+	  function getBidi(ch, partPos, invert) {
+	    var part = order[partPos], right = (part.level % 2) != 0
+	    return get(invert ? ch - 1 : ch, right != invert)
+	  }
+	  var partPos = getBidiPartAt(order, ch, sticky)
+	  var other = bidiOther
+	  var val = getBidi(ch, partPos, sticky == "before")
+	  if (other != null) { val.other = getBidi(ch, other, sticky != "before") }
+	  return val
+	}
+
+	// Used to cheaply estimate the coordinates for a position. Used for
+	// intermediate scroll updates.
+	function estimateCoords(cm, pos) {
+	  var left = 0
+	  pos = clipPos(cm.doc, pos)
+	  if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch }
+	  var lineObj = getLine(cm.doc, pos.line)
+	  var top = heightAtLine(lineObj) + paddingTop(cm.display)
+	  return {left: left, right: left, top: top, bottom: top + lineObj.height}
+	}
+
+	// Positions returned by coordsChar contain some extra information.
+	// xRel is the relative x position of the input coordinates compared
+	// to the found position (so xRel > 0 means the coordinates are to
+	// the right of the character position, for example). When outside
+	// is true, that means the coordinates lie outside the line's
+	// vertical range.
+	function PosWithInfo(line, ch, sticky, outside, xRel) {
+	  var pos = Pos(line, ch, sticky)
+	  pos.xRel = xRel
+	  if (outside) { pos.outside = true }
+	  return pos
+	}
+
+	// Compute the character position closest to the given coordinates.
+	// Input must be lineSpace-local ("div" coordinate system).
+	function coordsChar(cm, x, y) {
+	  var doc = cm.doc
+	  y += cm.display.viewOffset
+	  if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
+	  var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1
+	  if (lineN > last)
+	    { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
+	  if (x < 0) { x = 0 }
+
+	  var lineObj = getLine(doc, lineN)
+	  for (;;) {
+	    var found = coordsCharInner(cm, lineObj, lineN, x, y)
+	    var merged = collapsedSpanAtEnd(lineObj)
+	    var mergedPos = merged && merged.find(0, true)
+	    if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
+	      { lineN = lineNo(lineObj = mergedPos.to.line) }
+	    else
+	      { return found }
+	  }
+	}
+
+	function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
+	  var measure = function (ch) { return intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line"); }
+	  var end = lineObj.text.length
+	  var begin = findFirst(function (ch) { return measure(ch - 1).bottom <= y; }, end, 0)
+	  end = findFirst(function (ch) { return measure(ch).top > y; }, begin, end)
+	  return {begin: begin, end: end}
+	}
+
+	function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
+	  var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top
+	  return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
+	}
+
+	function coordsCharInner(cm, lineObj, lineNo, x, y) {
+	  y -= heightAtLine(lineObj)
+	  var begin = 0, end = lineObj.text.length
+	  var preparedMeasure = prepareMeasureForLine(cm, lineObj)
+	  var pos
+	  var order = getOrder(lineObj, cm.doc.direction)
+	  if (order) {
+	    if (cm.options.lineWrapping) {
+	      ;var assign;
+	      ((assign = wrappedLineExtent(cm, lineObj, preparedMeasure, y), begin = assign.begin, end = assign.end, assign))
+	    }
+	    pos = new Pos(lineNo, Math.floor(begin + (end - begin) / 2))
+	    var beginLeft = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left
+	    var dir = beginLeft < x ? 1 : -1
+	    var prevDiff, diff = beginLeft - x, prevPos
+	    var steps = Math.ceil((end - begin) / 4)
+	    outer: do {
+	      prevDiff = diff
+	      prevPos = pos
+	      var i = 0
+	      for (; i < steps; ++i) {
+	        var prevPos$1 = pos
+	        pos = moveVisually(cm, lineObj, pos, dir)
+	        if (pos == null || pos.ch < begin || end <= (pos.sticky == "before" ? pos.ch - 1 : pos.ch)) {
+	          pos = prevPos$1
+	          break outer
+	        }
+	      }
+	      diff = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left - x
+	      if (steps > 1) {
+	        var diff_change_per_step = Math.abs(diff - prevDiff) / steps
+	        steps = Math.min(steps, Math.ceil(Math.abs(diff) / diff_change_per_step))
+	        dir = diff < 0 ? 1 : -1
+	      }
+	    } while (diff != 0 && (steps > 1 || ((dir < 0) != (diff < 0) && (Math.abs(diff) <= Math.abs(prevDiff)))))
+	    if (Math.abs(diff) > Math.abs(prevDiff)) {
+	      if ((diff < 0) == (prevDiff < 0)) { throw new Error("Broke out of infinite loop in coordsCharInner") }
+	      pos = prevPos
+	    }
+	  } else {
+	    var ch = findFirst(function (ch) {
+	      var box = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line")
+	      if (box.top > y) {
+	        // For the cursor stickiness
+	        end = Math.min(ch, end)
+	        return true
+	      }
+	      else if (box.bottom <= y) { return false }
+	      else if (box.left > x) { return true }
+	      else if (box.right < x) { return false }
+	      else { return (x - box.left < box.right - x) }
+	    }, begin, end)
+	    ch = skipExtendingChars(lineObj.text, ch, 1)
+	    pos = new Pos(lineNo, ch, ch == end ? "before" : "after")
+	  }
+	  var coords = cursorCoords(cm, pos, "line", lineObj, preparedMeasure)
+	  if (y < coords.top || coords.bottom < y) { pos.outside = true }
+	  pos.xRel = x < coords.left ? -1 : (x > coords.right ? 1 : 0)
+	  return pos
+	}
+
+	var measureText
+	// Compute the default text height.
+	function textHeight(display) {
+	  if (display.cachedTextHeight != null) { return display.cachedTextHeight }
+	  if (measureText == null) {
+	    measureText = elt("pre")
+	    // Measure a bunch of lines, for browsers that compute
+	    // fractional heights.
+	    for (var i = 0; i < 49; ++i) {
+	      measureText.appendChild(document.createTextNode("x"))
+	      measureText.appendChild(elt("br"))
+	    }
+	    measureText.appendChild(document.createTextNode("x"))
+	  }
+	  removeChildrenAndAdd(display.measure, measureText)
+	  var height = measureText.offsetHeight / 50
+	  if (height > 3) { display.cachedTextHeight = height }
+	  removeChildren(display.measure)
+	  return height || 1
+	}
+
+	// Compute the default character width.
+	function charWidth(display) {
+	  if (display.cachedCharWidth != null) { return display.cachedCharWidth }
+	  var anchor = elt("span", "xxxxxxxxxx")
+	  var pre = elt("pre", [anchor])
+	  removeChildrenAndAdd(display.measure, pre)
+	  var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10
+	  if (width > 2) { display.cachedCharWidth = width }
+	  return width || 10
+	}
+
+	// Do a bulk-read of the DOM positions and sizes needed to draw the
+	// view, so that we don't interleave reading and writing to the DOM.
+	function getDimensions(cm) {
+	  var d = cm.display, left = {}, width = {}
+	  var gutterLeft = d.gutters.clientLeft
+	  for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
+	    left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft
+	    width[cm.options.gutters[i]] = n.clientWidth
+	  }
+	  return {fixedPos: compensateForHScroll(d),
+	          gutterTotalWidth: d.gutters.offsetWidth,
+	          gutterLeft: left,
+	          gutterWidth: width,
+	          wrapperWidth: d.wrapper.clientWidth}
+	}
+
+	// Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
+	// but using getBoundingClientRect to get a sub-pixel-accurate
+	// result.
+	function compensateForHScroll(display) {
+	  return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
+	}
+
+	// Returns a function that estimates the height of a line, to use as
+	// first approximation until the line becomes visible (and is thus
+	// properly measurable).
+	function estimateHeight(cm) {
+	  var th = textHeight(cm.display), wrapping = cm.options.lineWrapping
+	  var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3)
+	  return function (line) {
+	    if (lineIsHidden(cm.doc, line)) { return 0 }
+
+	    var widgetsHeight = 0
+	    if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
+	      if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height }
+	    } }
+
+	    if (wrapping)
+	      { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
+	    else
+	      { return widgetsHeight + th }
+	  }
+	}
+
+	function estimateLineHeights(cm) {
+	  var doc = cm.doc, est = estimateHeight(cm)
+	  doc.iter(function (line) {
+	    var estHeight = est(line)
+	    if (estHeight != line.height) { updateLineHeight(line, estHeight) }
+	  })
+	}
+
+	// Given a mouse event, find the corresponding position. If liberal
+	// is false, it checks whether a gutter or scrollbar was clicked,
+	// and returns null if it was. forRect is used by rectangular
+	// selections, and tries to estimate a character position even for
+	// coordinates beyond the right of the text.
+	function posFromMouse(cm, e, liberal, forRect) {
+	  var display = cm.display
+	  if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
+
+	  var x, y, space = display.lineSpace.getBoundingClientRect()
+	  // Fails unpredictably on IE[67] when mouse is dragged around quickly.
+	  try { x = e.clientX - space.left; y = e.clientY - space.top }
+	  catch (e) { return null }
+	  var coords = coordsChar(cm, x, y), line
+	  if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
+	    var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length
+	    coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff))
+	  }
+	  return coords
+	}
+
+	// Find the view element corresponding to a given line. Return null
+	// when the line isn't visible.
+	function findViewIndex(cm, n) {
+	  if (n >= cm.display.viewTo) { return null }
+	  n -= cm.display.viewFrom
+	  if (n < 0) { return null }
+	  var view = cm.display.view
+	  for (var i = 0; i < view.length; i++) {
+	    n -= view[i].size
+	    if (n < 0) { return i }
+	  }
+	}
+
+	function updateSelection(cm) {
+	  cm.display.input.showSelection(cm.display.input.prepareSelection())
+	}
+
+	function prepareSelection(cm, primary) {
+	  var doc = cm.doc, result = {}
+	  var curFragment = result.cursors = document.createDocumentFragment()
+	  var selFragment = result.selection = document.createDocumentFragment()
+
+	  for (var i = 0; i < doc.sel.ranges.length; i++) {
+	    if (primary === false && i == doc.sel.primIndex) { continue }
+	    var range = doc.sel.ranges[i]
+	    if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
+	    var collapsed = range.empty()
+	    if (collapsed || cm.options.showCursorWhenSelecting)
+	      { drawSelectionCursor(cm, range.head, curFragment) }
+	    if (!collapsed)
+	      { drawSelectionRange(cm, range, selFragment) }
+	  }
+	  return result
+	}
+
+	// Draws a cursor for the given range
+	function drawSelectionCursor(cm, head, output) {
+	  var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine)
+
+	  var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"))
+	  cursor.style.left = pos.left + "px"
+	  cursor.style.top = pos.top + "px"
+	  cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"
+
+	  if (pos.other) {
+	    // Secondary cursor, shown when on a 'jump' in bi-directional text
+	    var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"))
+	    otherCursor.style.display = ""
+	    otherCursor.style.left = pos.other.left + "px"
+	    otherCursor.style.top = pos.other.top + "px"
+	    otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"
+	  }
+	}
+
+	// Draws the given range as a highlighted selection
+	function drawSelectionRange(cm, range, output) {
+	  var display = cm.display, doc = cm.doc
+	  var fragment = document.createDocumentFragment()
+	  var padding = paddingH(cm.display), leftSide = padding.left
+	  var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right
+
+	  function add(left, top, width, bottom) {
+	    if (top < 0) { top = 0 }
+	    top = Math.round(top)
+	    bottom = Math.round(bottom)
+	    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")))
+	  }
+
+	  function drawForLine(line, fromArg, toArg) {
+	    var lineObj = getLine(doc, line)
+	    var lineLen = lineObj.text.length
+	    var start, end
+	    function coords(ch, bias) {
+	      return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
+	    }
+
+	    iterateBidiSections(getOrder(lineObj, doc.direction), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) {
+	      var leftPos = coords(from, "left"), rightPos, left, right
+	      if (from == to) {
+	        rightPos = leftPos
+	        left = right = leftPos.left
+	      } else {
+	        rightPos = coords(to - 1, "right")
+	        if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp }
+	        left = leftPos.left
+	        right = rightPos.right
+	      }
+	      if (fromArg == null && from == 0) { left = leftSide }
+	      if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
+	        add(left, leftPos.top, null, leftPos.bottom)
+	        left = leftSide
+	        if (leftPos.bottom < rightPos.top) { add(left, leftPos.bottom, null, rightPos.top) }
+	      }
+	      if (toArg == null && to == lineLen) { right = rightSide }
+	      if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
+	        { start = leftPos }
+	      if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
+	        { end = rightPos }
+	      if (left < leftSide + 1) { left = leftSide }
+	      add(left, rightPos.top, right - left, rightPos.bottom)
+	    })
+	    return {start: start, end: end}
+	  }
+
+	  var sFrom = range.from(), sTo = range.to()
+	  if (sFrom.line == sTo.line) {
+	    drawForLine(sFrom.line, sFrom.ch, sTo.ch)
+	  } else {
+	    var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line)
+	    var singleVLine = visualLine(fromLine) == visualLine(toLine)
+	    var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end
+	    var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start
+	    if (singleVLine) {
+	      if (leftEnd.top < rightStart.top - 2) {
+	        add(leftEnd.right, leftEnd.top, null, leftEnd.bottom)
+	        add(leftSide, rightStart.top, rightStart.left, rightStart.bottom)
+	      } else {
+	        add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom)
+	      }
+	    }
+	    if (leftEnd.bottom < rightStart.top)
+	      { add(leftSide, leftEnd.bottom, null, rightStart.top) }
+	  }
+
+	  output.appendChild(fragment)
+	}
+
+	// Cursor-blinking
+	function restartBlink(cm) {
+	  if (!cm.state.focused) { return }
+	  var display = cm.display
+	  clearInterval(display.blinker)
+	  var on = true
+	  display.cursorDiv.style.visibility = ""
+	  if (cm.options.cursorBlinkRate > 0)
+	    { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
+	      cm.options.cursorBlinkRate) }
+	  else if (cm.options.cursorBlinkRate < 0)
+	    { display.cursorDiv.style.visibility = "hidden" }
+	}
+
+	function ensureFocus(cm) {
+	  if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm) }
+	}
+
+	function delayBlurEvent(cm) {
+	  cm.state.delayingBlurEvent = true
+	  setTimeout(function () { if (cm.state.delayingBlurEvent) {
+	    cm.state.delayingBlurEvent = false
+	    onBlur(cm)
+	  } }, 100)
+	}
+
+	function onFocus(cm, e) {
+	  if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false }
+
+	  if (cm.options.readOnly == "nocursor") { return }
+	  if (!cm.state.focused) {
+	    signal(cm, "focus", cm, e)
+	    cm.state.focused = true
+	    addClass(cm.display.wrapper, "CodeMirror-focused")
+	    // This test prevents this from firing when a context
+	    // menu is closed (since the input reset would kill the
+	    // select-all detection hack)
+	    if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
+	      cm.display.input.reset()
+	      if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20) } // Issue #1730
+	    }
+	    cm.display.input.receivedFocus()
+	  }
+	  restartBlink(cm)
+	}
+	function onBlur(cm, e) {
+	  if (cm.state.delayingBlurEvent) { return }
+
+	  if (cm.state.focused) {
+	    signal(cm, "blur", cm, e)
+	    cm.state.focused = false
+	    rmClass(cm.display.wrapper, "CodeMirror-focused")
+	  }
+	  clearInterval(cm.display.blinker)
+	  setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false } }, 150)
+	}
+
+	// Read the actual heights of the rendered lines, and update their
+	// stored heights to match.
+	function updateHeightsInViewport(cm) {
+	  var display = cm.display
+	  var prevBottom = display.lineDiv.offsetTop
+	  for (var i = 0; i < display.view.length; i++) {
+	    var cur = display.view[i], height = (void 0)
+	    if (cur.hidden) { continue }
+	    if (ie && ie_version < 8) {
+	      var bot = cur.node.offsetTop + cur.node.offsetHeight
+	      height = bot - prevBottom
+	      prevBottom = bot
 	    } else {
-	      for (lineNode = node;; lineNode = lineNode.parentNode) {
-	        if (!lineNode || lineNode == cm.display.lineDiv) return null;
-	        if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
-	      }
-	    }
-	    for (var i = 0; i < cm.display.view.length; i++) {
-	      var lineView = cm.display.view[i];
-	      if (lineView.node == lineNode)
-	        return locateNodeInLineView(lineView, node, offset);
-	    }
-	  }
-
-	  function locateNodeInLineView(lineView, node, offset) {
-	    var wrapper = lineView.text.firstChild, bad = false;
-	    if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
-	    if (node == wrapper) {
-	      bad = true;
-	      node = wrapper.childNodes[offset];
-	      offset = 0;
-	      if (!node) {
-	        var line = lineView.rest ? lst(lineView.rest) : lineView.line;
-	        return badPos(Pos(lineNo(line), line.text.length), bad);
-	      }
-	    }
-
-	    var textNode = node.nodeType == 3 ? node : null, topNode = node;
-	    if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
-	      textNode = node.firstChild;
-	      if (offset) offset = textNode.nodeValue.length;
-	    }
-	    while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
-	    var measure = lineView.measure, maps = measure.maps;
-
-	    function find(textNode, topNode, offset) {
-	      for (var i = -1; i < (maps ? maps.length : 0); i++) {
-	        var map = i < 0 ? measure.map : maps[i];
-	        for (var j = 0; j < map.length; j += 3) {
-	          var curNode = map[j + 2];
-	          if (curNode == textNode || curNode == topNode) {
-	            var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
-	            var ch = map[j] + offset;
-	            if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
-	            return Pos(line, ch);
-	          }
-	        }
-	      }
-	    }
-	    var found = find(textNode, topNode, offset);
-	    if (found) return badPos(found, bad);
-
-	    // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
-	    for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
-	      found = find(after, after.firstChild, 0);
-	      if (found)
-	        return badPos(Pos(found.line, found.ch - dist), bad);
-	      else
-	        dist += after.textContent.length;
-	    }
-	    for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
-	      found = find(before, before.firstChild, -1);
-	      if (found)
-	        return badPos(Pos(found.line, found.ch + dist), bad);
-	      else
-	        dist += after.textContent.length;
-	    }
-	  }
-
-	  function domTextBetween(cm, from, to, fromLine, toLine) {
-	    var text = "", closing = false, lineSep = cm.doc.lineSeparator();
-	    function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
-	    function walk(node) {
-	      if (node.nodeType == 1) {
-	        var cmText = node.getAttribute("cm-text");
-	        if (cmText != null) {
-	          if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
-	          text += cmText;
-	          return;
-	        }
-	        var markerID = node.getAttribute("cm-marker"), range;
-	        if (markerID) {
-	          var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
-	          if (found.length && (range = found[0].find()))
-	            text += getBetween(cm.doc, range.from, range.to).join(lineSep);
-	          return;
-	        }
-	        if (node.getAttribute("contenteditable") == "false") return;
-	        for (var i = 0; i < node.childNodes.length; i++)
-	          walk(node.childNodes[i]);
-	        if (/^(pre|div|p)$/i.test(node.nodeName))
-	          closing = true;
-	      } else if (node.nodeType == 3) {
-	        var val = node.nodeValue;
-	        if (!val) return;
-	        if (closing) {
-	          text += lineSep;
-	          closing = false;
-	        }
-	        text += val;
-	      }
-	    }
-	    for (;;) {
-	      walk(from);
-	      if (from == to) break;
-	      from = from.nextSibling;
-	    }
-	    return text;
-	  }
-
-	  CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
-
-	  // SELECTION / CURSOR
-
-	  // Selection objects are immutable. A new one is created every time
-	  // the selection changes. A selection is one or more non-overlapping
-	  // (and non-touching) ranges, sorted, and an integer that indicates
-	  // which one is the primary selection (the one that's scrolled into
-	  // view, that getCursor returns, etc).
-	  function Selection(ranges, primIndex) {
-	    this.ranges = ranges;
-	    this.primIndex = primIndex;
-	  }
-
-	  Selection.prototype = {
-	    primary: function() { return this.ranges[this.primIndex]; },
-	    equals: function(other) {
-	      if (other == this) return true;
-	      if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
-	      for (var i = 0; i < this.ranges.length; i++) {
-	        var here = this.ranges[i], there = other.ranges[i];
-	        if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
-	      }
-	      return true;
-	    },
-	    deepCopy: function() {
-	      for (var out = [], i = 0; i < this.ranges.length; i++)
-	        out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
-	      return new Selection(out, this.primIndex);
-	    },
-	    somethingSelected: function() {
-	      for (var i = 0; i < this.ranges.length; i++)
-	        if (!this.ranges[i].empty()) return true;
-	      return false;
-	    },
-	    contains: function(pos, end) {
-	      if (!end) end = pos;
-	      for (var i = 0; i < this.ranges.length; i++) {
-	        var range = this.ranges[i];
-	        if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
-	          return i;
-	      }
-	      return -1;
-	    }
-	  };
-
-	  function Range(anchor, head) {
-	    this.anchor = anchor; this.head = head;
-	  }
-
-	  Range.prototype = {
-	    from: function() { return minPos(this.anchor, this.head); },
-	    to: function() { return maxPos(this.anchor, this.head); },
-	    empty: function() {
-	      return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
-	    }
-	  };
-
-	  // Take an unsorted, potentially overlapping set of ranges, and
-	  // build a selection out of it. 'Consumes' ranges array (modifying
-	  // it).
-	  function normalizeSelection(ranges, primIndex) {
-	    var prim = ranges[primIndex];
-	    ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
-	    primIndex = indexOf(ranges, prim);
-	    for (var i = 1; i < ranges.length; i++) {
-	      var cur = ranges[i], prev = ranges[i - 1];
-	      if (cmp(prev.to(), cur.from()) >= 0) {
-	        var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
-	        var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
-	        if (i <= primIndex) --primIndex;
-	        ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
-	      }
-	    }
-	    return new Selection(ranges, primIndex);
-	  }
-
-	  function simpleSelection(anchor, head) {
-	    return new Selection([new Range(anchor, head || anchor)], 0);
-	  }
-
-	  // Most of the external API clips given positions to make sure they
-	  // actually exist within the document.
-	  function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
-	  function clipPos(doc, pos) {
-	    if (pos.line < doc.first) return Pos(doc.first, 0);
-	    var last = doc.first + doc.size - 1;
-	    if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
-	    return clipToLen(pos, getLine(doc, pos.line).text.length);
-	  }
-	  function clipToLen(pos, linelen) {
-	    var ch = pos.ch;
-	    if (ch == null || ch > linelen) return Pos(pos.line, linelen);
-	    else if (ch < 0) return Pos(pos.line, 0);
-	    else return pos;
-	  }
-	  function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
-	  function clipPosArray(doc, array) {
-	    for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
-	    return out;
-	  }
-
-	  // SELECTION UPDATES
-
-	  // The 'scroll' parameter given to many of these indicated whether
-	  // the new cursor position should be scrolled into view after
-	  // modifying the selection.
-
-	  // If shift is held or the extend flag is set, extends a range to
-	  // include a given position (and optionally a second position).
-	  // Otherwise, simply returns the range between the given positions.
-	  // Used for cursor motion and such.
-	  function extendRange(doc, range, head, other) {
-	    if (doc.cm && doc.cm.display.shift || doc.extend) {
-	      var anchor = range.anchor;
-	      if (other) {
-	        var posBefore = cmp(head, anchor) < 0;
-	        if (posBefore != (cmp(other, anchor) < 0)) {
-	          anchor = head;
-	          head = other;
-	        } else if (posBefore != (cmp(head, other) < 0)) {
-	          head = other;
-	        }
-	      }
-	      return new Range(anchor, head);
+	      var box = cur.node.getBoundingClientRect()
+	      height = box.bottom - box.top
+	    }
+	    var diff = cur.line.height - height
+	    if (height < 2) { height = textHeight(display) }
+	    if (diff > .005 || diff < -.005) {
+	      updateLineHeight(cur.line, height)
+	      updateWidgetHeight(cur.line)
+	      if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
+	        { updateWidgetHeight(cur.rest[j]) } }
+	    }
+	  }
+	}
+
+	// Read and store the height of line widgets associated with the
+	// given line.
+	function updateWidgetHeight(line) {
+	  if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i)
+	    { line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight } }
+	}
+
+	// Compute the lines that are visible in a given viewport (defaults
+	// the the current scroll position). viewport may contain top,
+	// height, and ensure (see op.scrollToPos) properties.
+	function visibleLines(display, doc, viewport) {
+	  var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop
+	  top = Math.floor(top - paddingTop(display))
+	  var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight
+
+	  var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom)
+	  // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
+	  // forces those lines into the viewport (if possible).
+	  if (viewport && viewport.ensure) {
+	    var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line
+	    if (ensureFrom < from) {
+	      from = ensureFrom
+	      to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)
+	    } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
+	      from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight)
+	      to = ensureTo
+	    }
+	  }
+	  return {from: from, to: Math.max(to, from + 1)}
+	}
+
+	// Re-align line numbers and gutter marks to compensate for
+	// horizontal scrolling.
+	function alignHorizontally(cm) {
+	  var display = cm.display, view = display.view
+	  if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
+	  var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft
+	  var gutterW = display.gutters.offsetWidth, left = comp + "px"
+	  for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
+	    if (cm.options.fixedGutter) {
+	      if (view[i].gutter)
+	        { view[i].gutter.style.left = left }
+	      if (view[i].gutterBackground)
+	        { view[i].gutterBackground.style.left = left }
+	    }
+	    var align = view[i].alignable
+	    if (align) { for (var j = 0; j < align.length; j++)
+	      { align[j].style.left = left } }
+	  } }
+	  if (cm.options.fixedGutter)
+	    { display.gutters.style.left = (comp + gutterW) + "px" }
+	}
+
+	// Used to ensure that the line number gutter is still the right
+	// size for the current document size. Returns true when an update
+	// is needed.
+	function maybeUpdateLineNumberWidth(cm) {
+	  if (!cm.options.lineNumbers) { return false }
+	  var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display
+	  if (last.length != display.lineNumChars) {
+	    var test = display.measure.appendChild(elt("div", [elt("div", last)],
+	                                               "CodeMirror-linenumber CodeMirror-gutter-elt"))
+	    var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW
+	    display.lineGutter.style.width = ""
+	    display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1
+	    display.lineNumWidth = display.lineNumInnerWidth + padding
+	    display.lineNumChars = display.lineNumInnerWidth ? last.length : -1
+	    display.lineGutter.style.width = display.lineNumWidth + "px"
+	    updateGutterSpace(cm)
+	    return true
+	  }
+	  return false
+	}
+
+	// SCROLLING THINGS INTO VIEW
+
+	// If an editor sits on the top or bottom of the window, partially
+	// scrolled out of view, this ensures that the cursor is visible.
+	function maybeScrollWindow(cm, rect) {
+	  if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
+
+	  var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null
+	  if (rect.top + box.top < 0) { doScroll = true }
+	  else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false }
+	  if (doScroll != null && !phantom) {
+	    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;"))
+	    cm.display.lineSpace.appendChild(scrollNode)
+	    scrollNode.scrollIntoView(doScroll)
+	    cm.display.lineSpace.removeChild(scrollNode)
+	  }
+	}
+
+	// Scroll a given position into view (immediately), verifying that
+	// it actually became visible (as line heights are accurately
+	// measured, the position of something may 'drift' during drawing).
+	function scrollPosIntoView(cm, pos, end, margin) {
+	  if (margin == null) { margin = 0 }
+	  var rect
+	  if (!cm.options.lineWrapping && pos == end) {
+	    // Set pos and end to the cursor positions around the character pos sticks to
+	    // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
+	    // If pos == Pos(_, 0, "before"), pos and end are unchanged
+	    pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos
+	    end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos
+	  }
+	  for (var limit = 0; limit < 5; limit++) {
+	    var changed = false
+	    var coords = cursorCoords(cm, pos)
+	    var endCoords = !end || end == pos ? coords : cursorCoords(cm, end)
+	    rect = {left: Math.min(coords.left, endCoords.left),
+	            top: Math.min(coords.top, endCoords.top) - margin,
+	            right: Math.max(coords.left, endCoords.left),
+	            bottom: Math.max(coords.bottom, endCoords.bottom) + margin}
+	    var scrollPos = calculateScrollPos(cm, rect)
+	    var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft
+	    if (scrollPos.scrollTop != null) {
+	      updateScrollTop(cm, scrollPos.scrollTop)
+	      if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true }
+	    }
+	    if (scrollPos.scrollLeft != null) {
+	      setScrollLeft(cm, scrollPos.scrollLeft)
+	      if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true }
+	    }
+	    if (!changed) { break }
+	  }
+	  return rect
+	}
+
+	// Scroll a given set of coordinates into view (immediately).
+	function scrollIntoView(cm, rect) {
+	  var scrollPos = calculateScrollPos(cm, rect)
+	  if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop) }
+	  if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft) }
+	}
+
+	// Calculate a new scroll position needed to scroll the given
+	// rectangle into view. Returns an object with scrollTop and
+	// scrollLeft properties. When these are undefined, the
+	// vertical/horizontal position does not need to be adjusted.
+	function calculateScrollPos(cm, rect) {
+	  var display = cm.display, snapMargin = textHeight(cm.display)
+	  if (rect.top < 0) { rect.top = 0 }
+	  var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop
+	  var screen = displayHeight(cm), result = {}
+	  if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen }
+	  var docBottom = cm.doc.height + paddingVert(display)
+	  var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin
+	  if (rect.top < screentop) {
+	    result.scrollTop = atTop ? 0 : rect.top
+	  } else if (rect.bottom > screentop + screen) {
+	    var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen)
+	    if (newTop != screentop) { result.scrollTop = newTop }
+	  }
+
+	  var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft
+	  var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0)
+	  var tooWide = rect.right - rect.left > screenw
+	  if (tooWide) { rect.right = rect.left + screenw }
+	  if (rect.left < 10)
+	    { result.scrollLeft = 0 }
+	  else if (rect.left < screenleft)
+	    { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)) }
+	  else if (rect.right > screenw + screenleft - 3)
+	    { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw }
+	  return result
+	}
+
+	// Store a relative adjustment to the scroll position in the current
+	// operation (to be applied when the operation finishes).
+	function addToScrollTop(cm, top) {
+	  if (top == null) { return }
+	  resolveScrollToPos(cm)
+	  cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top
+	}
+
+	// Make sure that at the end of the operation the current cursor is
+	// shown.
+	function ensureCursorVisible(cm) {
+	  resolveScrollToPos(cm)
+	  var cur = cm.getCursor()
+	  cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin}
+	}
+
+	function scrollToCoords(cm, x, y) {
+	  if (x != null || y != null) { resolveScrollToPos(cm) }
+	  if (x != null) { cm.curOp.scrollLeft = x }
+	  if (y != null) { cm.curOp.scrollTop = y }
+	}
+
+	function scrollToRange(cm, range) {
+	  resolveScrollToPos(cm)
+	  cm.curOp.scrollToPos = range
+	}
+
+	// When an operation has its scrollToPos property set, and another
+	// scroll action is applied before the end of the operation, this
+	// 'simulates' scrolling that position into view in a cheap way, so
+	// that the effect of intermediate scroll commands is not ignored.
+	function resolveScrollToPos(cm) {
+	  var range = cm.curOp.scrollToPos
+	  if (range) {
+	    cm.curOp.scrollToPos = null
+	    var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to)
+	    scrollToCoordsRange(cm, from, to, range.margin)
+	  }
+	}
+
+	function scrollToCoordsRange(cm, from, to, margin) {
+	  var sPos = calculateScrollPos(cm, {
+	    left: Math.min(from.left, to.left),
+	    top: Math.min(from.top, to.top) - margin,
+	    right: Math.max(from.right, to.right),
+	    bottom: Math.max(from.bottom, to.bottom) + margin
+	  })
+	  scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop)
+	}
+
+	// Sync the scrollable area and scrollbars, ensure the viewport
+	// covers the visible area.
+	function updateScrollTop(cm, val) {
+	  if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
+	  if (!gecko) { updateDisplaySimple(cm, {top: val}) }
+	  setScrollTop(cm, val, true)
+	  if (gecko) { updateDisplaySimple(cm) }
+	  startWorker(cm, 100)
+	}
+
+	function setScrollTop(cm, val, forceScroll) {
+	  val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)
+	  if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
+	  cm.doc.scrollTop = val
+	  cm.display.scrollbars.setScrollTop(val)
+	  if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val }
+	}
+
+	// Sync scroller and scrollbar, ensure the gutter elements are
+	// aligned.
+	function setScrollLeft(cm, val, isScroller, forceScroll) {
+	  val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)
+	  if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
+	  cm.doc.scrollLeft = val
+	  alignHorizontally(cm)
+	  if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val }
+	  cm.display.scrollbars.setScrollLeft(val)
+	}
+
+	// SCROLLBARS
+
+	// Prepare DOM reads needed to update the scrollbars. Done in one
+	// shot to minimize update/measure roundtrips.
+	function measureForScrollbars(cm) {
+	  var d = cm.display, gutterW = d.gutters.offsetWidth
+	  var docH = Math.round(cm.doc.height + paddingVert(cm.display))
+	  return {
+	    clientHeight: d.scroller.clientHeight,
+	    viewHeight: d.wrapper.clientHeight,
+	    scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
+	    viewWidth: d.wrapper.clientWidth,
+	    barLeft: cm.options.fixedGutter ? gutterW : 0,
+	    docHeight: docH,
+	    scrollHeight: docH + scrollGap(cm) + d.barHeight,
+	    nativeBarWidth: d.nativeBarWidth,
+	    gutterWidth: gutterW
+	  }
+	}
+
+	var NativeScrollbars = function(place, scroll, cm) {
+	  this.cm = cm
+	  var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar")
+	  var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar")
+	  place(vert); place(horiz)
+
+	  on(vert, "scroll", function () {
+	    if (vert.clientHeight) { scroll(vert.scrollTop, "vertical") }
+	  })
+	  on(horiz, "scroll", function () {
+	    if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal") }
+	  })
+
+	  this.checkedZeroWidth = false
+	  // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
+	  if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px" }
+	};
+
+	NativeScrollbars.prototype.update = function (measure) {
+	  var needsH = measure.scrollWidth > measure.clientWidth + 1
+	  var needsV = measure.scrollHeight > measure.clientHeight + 1
+	  var sWidth = measure.nativeBarWidth
+
+	  if (needsV) {
+	    this.vert.style.display = "block"
+	    this.vert.style.bottom = needsH ? sWidth + "px" : "0"
+	    var totalHeight = measure.viewHeight - (needsH ? sWidth : 0)
+	    // A bug in IE8 can cause this value to be negative, so guard it.
+	    this.vert.firstChild.style.height =
+	      Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"
+	  } else {
+	    this.vert.style.display = ""
+	    this.vert.firstChild.style.height = "0"
+	  }
+
+	  if (needsH) {
+	    this.horiz.style.display = "block"
+	    this.horiz.style.right = needsV ? sWidth + "px" : "0"
+	    this.horiz.style.left = measure.barLeft + "px"
+	    var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0)
+	    this.horiz.firstChild.style.width =
+	      Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"
+	  } else {
+	    this.horiz.style.display = ""
+	    this.horiz.firstChild.style.width = "0"
+	  }
+
+	  if (!this.checkedZeroWidth && measure.clientHeight > 0) {
+	    if (sWidth == 0) { this.zeroWidthHack() }
+	    this.checkedZeroWidth = true
+	  }
+
+	  return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
+	};
+
+	NativeScrollbars.prototype.setScrollLeft = function (pos) {
+	  if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos }
+	  if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz") }
+	};
+
+	NativeScrollbars.prototype.setScrollTop = function (pos) {
+	  if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos }
+	  if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert") }
+	};
+
+	NativeScrollbars.prototype.zeroWidthHack = function () {
+	  var w = mac && !mac_geMountainLion ? "12px" : "18px"
+	  this.horiz.style.height = this.vert.style.width = w
+	  this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"
+	  this.disableHoriz = new Delayed
+	  this.disableVert = new Delayed
+	};
+
+	NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
+	  bar.style.pointerEvents = "auto"
+	  function maybeDisable() {
+	    // To find out whether the scrollbar is still visible, we
+	    // check whether the element under the pixel in the bottom
+	    // right corner of the scrollbar box is the scrollbar box
+	    // itself (when the bar is still visible) or its filler child
+	    // (when the bar is hidden). If it is still visible, we keep
+	    // it enabled, if it's hidden, we disable pointer events.
+	    var box = bar.getBoundingClientRect()
+	    var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
+	        : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1)
+	    if (elt != bar) { bar.style.pointerEvents = "none" }
+	    else { delay.set(1000, maybeDisable) }
+	  }
+	  delay.set(1000, maybeDisable)
+	};
+
+	NativeScrollbars.prototype.clear = function () {
+	  var parent = this.horiz.parentNode
+	  parent.removeChild(this.horiz)
+	  parent.removeChild(this.vert)
+	};
+
+	var NullScrollbars = function () {};
+
+	NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
+	NullScrollbars.prototype.setScrollLeft = function () {};
+	NullScrollbars.prototype.setScrollTop = function () {};
+	NullScrollbars.prototype.clear = function () {};
+
+	function updateScrollbars(cm, measure) {
+	  if (!measure) { measure = measureForScrollbars(cm) }
+	  var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight
+	  updateScrollbarsInner(cm, measure)
+	  for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
+	    if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
+	      { updateHeightsInViewport(cm) }
+	    updateScrollbarsInner(cm, measureForScrollbars(cm))
+	    startWidth = cm.display.barWidth; startHeight = cm.display.barHeight
+	  }
+	}
+
+	// Re-synchronize the fake scrollbars with the actual size of the
+	// content.
+	function updateScrollbarsInner(cm, measure) {
+	  var d = cm.display
+	  var sizes = d.scrollbars.update(measure)
+
+	  d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"
+	  d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"
+	  d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
+
+	  if (sizes.right && sizes.bottom) {
+	    d.scrollbarFiller.style.display = "block"
+	    d.scrollbarFiller.style.height = sizes.bottom + "px"
+	    d.scrollbarFiller.style.width = sizes.right + "px"
+	  } else { d.scrollbarFiller.style.display = "" }
+	  if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
+	    d.gutterFiller.style.display = "block"
+	    d.gutterFiller.style.height = sizes.bottom + "px"
+	    d.gutterFiller.style.width = measure.gutterWidth + "px"
+	  } else { d.gutterFiller.style.display = "" }
+	}
+
+	var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}
+
+	function initScrollbars(cm) {
+	  if (cm.display.scrollbars) {
+	    cm.display.scrollbars.clear()
+	    if (cm.display.scrollbars.addClass)
+	      { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
+	  }
+
+	  cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
+	    cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller)
+	    // Prevent clicks in the scrollbars from killing focus
+	    on(node, "mousedown", function () {
+	      if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0) }
+	    })
+	    node.setAttribute("cm-not-content", "true")
+	  }, function (pos, axis) {
+	    if (axis == "horizontal") { setScrollLeft(cm, pos) }
+	    else { updateScrollTop(cm, pos) }
+	  }, cm)
+	  if (cm.display.scrollbars.addClass)
+	    { addClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
+	}
+
+	// Operations are used to wrap a series of changes to the editor
+	// state in such a way that each change won't have to update the
+	// cursor and display (which would be awkward, slow, and
+	// error-prone). Instead, display updates are batched and then all
+	// combined and executed at once.
+
+	var nextOpId = 0
+	// Start a new operation.
+	function startOperation(cm) {
+	  cm.curOp = {
+	    cm: cm,
+	    viewChanged: false,      // Flag that indicates that lines might need to be redrawn
+	    startHeight: cm.doc.height, // Used to detect need to update scrollbar
+	    forceUpdate: false,      // Used to force a redraw
+	    updateInput: null,       // Whether to reset the input textarea
+	    typing: false,           // Whether this reset should be careful to leave existing text (for compositing)
+	    changeObjs: null,        // Accumulated changes, for firing change events
+	    cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
+	    cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
+	    selectionChanged: false, // Whether the selection needs to be redrawn
+	    updateMaxLine: false,    // Set when the widest line needs to be determined anew
+	    scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
+	    scrollToPos: null,       // Used to scroll to a specific position
+	    focus: false,
+	    id: ++nextOpId           // Unique ID
+	  }
+	  pushOperation(cm.curOp)
+	}
+
+	// Finish an operation, updating the display and signalling delayed events
+	function endOperation(cm) {
+	  var op = cm.curOp
+	  finishOperation(op, function (group) {
+	    for (var i = 0; i < group.ops.length; i++)
+	      { group.ops[i].cm.curOp = null }
+	    endOperations(group)
+	  })
+	}
+
+	// The DOM updates done when an operation finishes are batched so
+	// that the minimum number of relayouts are required.
+	function endOperations(group) {
+	  var ops = group.ops
+	  for (var i = 0; i < ops.length; i++) // Read DOM
+	    { endOperation_R1(ops[i]) }
+	  for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
+	    { endOperation_W1(ops[i$1]) }
+	  for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
+	    { endOperation_R2(ops[i$2]) }
+	  for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
+	    { endOperation_W2(ops[i$3]) }
+	  for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
+	    { endOperation_finish(ops[i$4]) }
+	}
+
+	function endOperation_R1(op) {
+	  var cm = op.cm, display = cm.display
+	  maybeClipScrollbars(cm)
+	  if (op.updateMaxLine) { findMaxLine(cm) }
+
+	  op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
+	    op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
+	                       op.scrollToPos.to.line >= display.viewTo) ||
+	    display.maxLineChanged && cm.options.lineWrapping
+	  op.update = op.mustUpdate &&
+	    new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate)
+	}
+
+	function endOperation_W1(op) {
+	  op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update)
+	}
+
+	function endOperation_R2(op) {
+	  var cm = op.cm, display = cm.display
+	  if (op.updatedDisplay) { updateHeightsInViewport(cm) }
+
+	  op.barMeasure = measureForScrollbars(cm)
+
+	  // If the max line changed since it was last measured, measure it,
+	  // and ensure the document's width matches it.
+	  // updateDisplay_W2 will use these properties to do the actual resizing
+	  if (display.maxLineChanged && !cm.options.lineWrapping) {
+	    op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3
+	    cm.display.sizerWidth = op.adjustWidthTo
+	    op.barMeasure.scrollWidth =
+	      Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth)
+	    op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm))
+	  }
+
+	  if (op.updatedDisplay || op.selectionChanged)
+	    { op.preparedSelection = display.input.prepareSelection(op.focus) }
+	}
+
+	function endOperation_W2(op) {
+	  var cm = op.cm
+
+	  if (op.adjustWidthTo != null) {
+	    cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"
+	    if (op.maxScrollLeft < cm.doc.scrollLeft)
+	      { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) }
+	    cm.display.maxLineChanged = false
+	  }
+
+	  var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus())
+	  if (op.preparedSelection)
+	    { cm.display.input.showSelection(op.preparedSelection, takeFocus) }
+	  if (op.updatedDisplay || op.startHeight != cm.doc.height)
+	    { updateScrollbars(cm, op.barMeasure) }
+	  if (op.updatedDisplay)
+	    { setDocumentHeight(cm, op.barMeasure) }
+
+	  if (op.selectionChanged) { restartBlink(cm) }
+
+	  if (cm.state.focused && op.updateInput)
+	    { cm.display.input.reset(op.typing) }
+	  if (takeFocus) { ensureFocus(op.cm) }
+	}
+
+	function endOperation_finish(op) {
+	  var cm = op.cm, display = cm.display, doc = cm.doc
+
+	  if (op.updatedDisplay) { postUpdateDisplay(cm, op.update) }
+
+	  // Abort mouse wheel delta measurement, when scrolling explicitly
+	  if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
+	    { display.wheelStartX = display.wheelStartY = null }
+
+	  // Propagate the scroll position to the actual DOM scroller
+	  if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll) }
+
+	  if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true) }
+	  // If we need to scroll a specific position into view, do so.
+	  if (op.scrollToPos) {
+	    var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
+	                                 clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin)
+	    maybeScrollWindow(cm, rect)
+	  }
+
+	  // Fire events for markers that are hidden/unidden by editing or
+	  // undoing
+	  var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers
+	  if (hidden) { for (var i = 0; i < hidden.length; ++i)
+	    { if (!hidden[i].lines.length) { signal(hidden[i], "hide") } } }
+	  if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
+	    { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide") } } }
+
+	  if (display.wrapper.offsetHeight)
+	    { doc.scrollTop = cm.display.scroller.scrollTop }
+
+	  // Fire change events, and delayed event handlers
+	  if (op.changeObjs)
+	    { signal(cm, "changes", cm, op.changeObjs) }
+	  if (op.update)
+	    { op.update.finish() }
+	}
+
+	// Run the given function in an operation
+	function runInOp(cm, f) {
+	  if (cm.curOp) { return f() }
+	  startOperation(cm)
+	  try { return f() }
+	  finally { endOperation(cm) }
+	}
+	// Wraps a function in an operation. Returns the wrapped function.
+	function operation(cm, f) {
+	  return function() {
+	    if (cm.curOp) { return f.apply(cm, arguments) }
+	    startOperation(cm)
+	    try { return f.apply(cm, arguments) }
+	    finally { endOperation(cm) }
+	  }
+	}
+	// Used to add methods to editor and doc instances, wrapping them in
+	// operations.
+	function methodOp(f) {
+	  return function() {
+	    if (this.curOp) { return f.apply(this, arguments) }
+	    startOperation(this)
+	    try { return f.apply(this, arguments) }
+	    finally { endOperation(this) }
+	  }
+	}
+	function docMethodOp(f) {
+	  return function() {
+	    var cm = this.cm
+	    if (!cm || cm.curOp) { return f.apply(this, arguments) }
+	    startOperation(cm)
+	    try { return f.apply(this, arguments) }
+	    finally { endOperation(cm) }
+	  }
+	}
+
+	// Updates the display.view data structure for a given change to the
+	// document. From and to are in pre-change coordinates. Lendiff is
+	// the amount of lines added or subtracted by the change. This is
+	// used for changes that span multiple lines, or change the way
+	// lines are divided into visual lines. regLineChange (below)
+	// registers single-line changes.
+	function regChange(cm, from, to, lendiff) {
+	  if (from == null) { from = cm.doc.first }
+	  if (to == null) { to = cm.doc.first + cm.doc.size }
+	  if (!lendiff) { lendiff = 0 }
+
+	  var display = cm.display
+	  if (lendiff && to < display.viewTo &&
+	      (display.updateLineNumbers == null || display.updateLineNumbers > from))
+	    { display.updateLineNumbers = from }
+
+	  cm.curOp.viewChanged = true
+
+	  if (from >= display.viewTo) { // Change after
+	    if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
+	      { resetView(cm) }
+	  } else if (to <= display.viewFrom) { // Change before
+	    if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
+	      resetView(cm)
 	    } else {
-	      return new Range(other || head, head);
-	    }
-	  }
-
-	  // Extend the primary selection range, discard the rest.
-	  function extendSelection(doc, head, other, options) {
-	    setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
-	  }
-
-	  // Extend all selections (pos is an array of selections with length
-	  // equal the number of selections)
-	  function extendSelections(doc, heads, options) {
-	    for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
-	      out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
-	    var newSel = normalizeSelection(out, doc.sel.primIndex);
-	    setSelection(doc, newSel, options);
-	  }
-
-	  // Updates a single range in the selection.
-	  function replaceOneSelection(doc, i, range, options) {
-	    var ranges = doc.sel.ranges.slice(0);
-	    ranges[i] = range;
-	    setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
-	  }
-
-	  // Reset the selection to a single range.
-	  function setSimpleSelection(doc, anchor, head, options) {
-	    setSelection(doc, simpleSelection(anchor, head), options);
-	  }
-
-	  // Give beforeSelectionChange handlers a change to influence a
-	  // selection update.
-	  function filterSelectionChange(doc, sel, options) {
-	    var obj = {
-	      ranges: sel.ranges,
-	      update: function(ranges) {
-	        this.ranges = [];
-	        for (var i = 0; i < ranges.length; i++)
-	          this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
-	                                     clipPos(doc, ranges[i].head));
-	      },
-	      origin: options && options.origin
-	    };
-	    signal(doc, "beforeSelectionChange", doc, obj);
-	    if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
-	    if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
-	    else return sel;
-	  }
-
-	  function setSelectionReplaceHistory(doc, sel, options) {
-	    var done = doc.history.done, last = lst(done);
-	    if (last && last.ranges) {
-	      done[done.length - 1] = sel;
-	      setSelectionNoUndo(doc, sel, options);
+	      display.viewFrom += lendiff
+	      display.viewTo += lendiff
+	    }
+	  } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
+	    resetView(cm)
+	  } else if (from <= display.viewFrom) { // Top overlap
+	    var cut = viewCuttingPoint(cm, to, to + lendiff, 1)
+	    if (cut) {
+	      display.view = display.view.slice(cut.index)
+	      display.viewFrom = cut.lineN
+	      display.viewTo += lendiff
+	    } else {
+	      resetView(cm)
+	    }
+	  } else if (to >= display.viewTo) { // Bottom overlap
+	    var cut$1 = viewCuttingPoint(cm, from, from, -1)
+	    if (cut$1) {
+	      display.view = display.view.slice(0, cut$1.index)
+	      display.viewTo = cut$1.lineN
+	    } else {
+	      resetView(cm)
+	    }
+	  } else { // Gap in the middle
+	    var cutTop = viewCuttingPoint(cm, from, from, -1)
+	    var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1)
+	    if (cutTop && cutBot) {
+	      display.view = display.view.slice(0, cutTop.index)
+	        .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
+	        .concat(display.view.slice(cutBot.index))
+	      display.viewTo += lendiff
 	    } else {
-	      setSelection(doc, sel, options);
-	    }
-	  }
-
-	  // Set a new selection.
-	  function setSelection(doc, sel, options) {
-	    setSelectionNoUndo(doc, sel, options);
-	    addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
-	  }
-
-	  function setSelectionNoUndo(doc, sel, options) {
-	    if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
-	      sel = filterSelectionChange(doc, sel, options);
-
-	    var bias = options && options.bias ||
-	      (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
-	    setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
-
-	    if (!(options && options.scroll === false) && doc.cm)
-	      ensureCursorVisible(doc.cm);
-	  }
-
-	  function setSelectionInner(doc, sel) {
-	    if (sel.equals(doc.sel)) return;
-
-	    doc.sel = sel;
-
-	    if (doc.cm) {
-	      doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
-	      signalCursorActivity(doc.cm);
-	    }
-	    signalLater(doc, "cursorActivity", doc);
-	  }
-
-	  // Verify that the selection does not partially select any atomic
-	  // marked ranges.
-	  function reCheckSelection(doc) {
-	    setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
-	  }
-
-	  // Return a selection that does not partially select any atomic
-	  // ranges.
-	  function skipAtomicInSelection(doc, sel, bias, mayClear) {
-	    var out;
-	    for (var i = 0; i < sel.ranges.length; i++) {
-	      var range = sel.ranges[i];
-	      var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
-	      var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
-	      var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
-	      if (out || newAnchor != range.anchor || newHead != range.head) {
-	        if (!out) out = sel.ranges.slice(0, i);
-	        out[i] = new Range(newAnchor, newHead);
-	      }
-	    }
-	    return out ? normalizeSelection(out, sel.primIndex) : sel;
-	  }
-
-	  function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
-	    var line = getLine(doc, pos.line);
-	    if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
-	      var sp = line.markedSpans[i], m = sp.marker;
-	      if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
-	          (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
-	        if (mayClear) {
-	          signal(m, "beforeCursorEnter");
-	          if (m.explicitlyCleared) {
-	            if (!line.markedSpans) break;
-	            else {--i; continue;}
-	          }
-	        }
-	        if (!m.atomic) continue;
-
-	        if (oldPos) {
-	          var near = m.find(dir < 0 ? 1 : -1), diff;
-	          if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
-	            near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null);
-	          if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
-	            return skipAtomicInner(doc, near, pos, dir, mayClear);
-	        }
-
-	        var far = m.find(dir < 0 ? -1 : 1);
-	        if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
-	          far = movePos(doc, far, dir, far.line == pos.line ? line : null);
-	        return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null;
-	      }
-	    }
-	    return pos;
-	  }
-
-	  // Ensure a given position is not inside an atomic range.
-	  function skipAtomic(doc, pos, oldPos, bias, mayClear) {
-	    var dir = bias || 1;
-	    var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
-	        (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
-	        skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
-	        (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
-	    if (!found) {
-	      doc.cantEdit = true;
-	      return Pos(doc.first, 0);
-	    }
-	    return found;
-	  }
-
-	  function movePos(doc, pos, dir, line) {
-	    if (dir < 0 && pos.ch == 0) {
-	      if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1));
-	      else return null;
-	    } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
-	      if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0);
-	      else return null;
-	    } else {
-	      return new Pos(pos.line, pos.ch + dir);
-	    }
-	  }
-
-	  // SELECTION DRAWING
-
-	  function updateSelection(cm) {
-	    cm.display.input.showSelection(cm.display.input.prepareSelection());
-	  }
-
-	  function prepareSelection(cm, primary) {
-	    var doc = cm.doc, result = {};
-	    var curFragment = result.cursors = document.createDocumentFragment();
-	    var selFragment = result.selection = document.createDocumentFragment();
-
-	    for (var i = 0; i < doc.sel.ranges.length; i++) {
-	      if (primary === false && i == doc.sel.primIndex) continue;
-	      var range = doc.sel.ranges[i];
-	      if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) continue;
-	      var collapsed = range.empty();
-	      if (collapsed || cm.options.showCursorWhenSelecting)
-	        drawSelectionCursor(cm, range.head, curFragment);
-	      if (!collapsed)
-	        drawSelectionRange(cm, range, selFragment);
-	    }
-	    return result;
-	  }
-
-	  // Draws a cursor for the given range
-	  function drawSelectionCursor(cm, head, output) {
-	    var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
-
-	    var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
-	    cursor.style.left = pos.left + "px";
-	    cursor.style.top = pos.top + "px";
-	    cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
-
-	    if (pos.other) {
-	      // Secondary cursor, shown when on a 'jump' in bi-directional text
-	      var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
-	      otherCursor.style.display = "";
-	      otherCursor.style.left = pos.other.left + "px";
-	      otherCursor.style.top = pos.other.top + "px";
-	      otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
-	    }
-	  }
-
-	  // Draws the given range as a highlighted selection
-	  function drawSelectionRange(cm, range, output) {
-	    var display = cm.display, doc = cm.doc;
-	    var fragment = document.createDocumentFragment();
-	    var padding = paddingH(cm.display), leftSide = padding.left;
-	    var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
-
-	    function add(left, top, width, bottom) {
-	      if (top < 0) top = 0;
-	      top = Math.round(top);
-	      bottom = Math.round(bottom);
-	      fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
-	                               "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
-	                               "px; height: " + (bottom - top) + "px"));
-	    }
-
-	    function drawForLine(line, fromArg, toArg) {
-	      var lineObj = getLine(doc, line);
-	      var lineLen = lineObj.text.length;
-	      var start, end;
-	      function coords(ch, bias) {
-	        return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
-	      }
-
-	      iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
-	        var leftPos = coords(from, "left"), rightPos, left, right;
-	        if (from == to) {
-	          rightPos = leftPos;
-	          left = right = leftPos.left;
-	        } else {
-	          rightPos = coords(to - 1, "right");
-	          if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
-	          left = leftPos.left;
-	          right = rightPos.right;
-	        }
-	        if (fromArg == null && from == 0) left = leftSide;
-	        if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
-	          add(left, leftPos.top, null, leftPos.bottom);
-	          left = leftSide;
-	          if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
-	        }
-	        if (toArg == null && to == lineLen) right = rightSide;
-	        if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
-	          start = leftPos;
-	        if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
-	          end = rightPos;
-	        if (left < leftSide + 1) left = leftSide;
-	        add(left, rightPos.top, right - left, rightPos.bottom);
-	      });
-	      return {start: start, end: end};
-	    }
-
-	    var sFrom = range.from(), sTo = range.to();
-	    if (sFrom.line == sTo.line) {
-	      drawForLine(sFrom.line, sFrom.ch, sTo.ch);
+	      resetView(cm)
+	    }
+	  }
+
+	  var ext = display.externalMeasured
+	  if (ext) {
+	    if (to < ext.lineN)
+	      { ext.lineN += lendiff }
+	    else if (from < ext.lineN + ext.size)
+	      { display.externalMeasured = null }
+	  }
+	}
+
+	// Register a change to a single line. Type must be one of "text",
+	// "gutter", "class", "widget"
+	function regLineChange(cm, line, type) {
+	  cm.curOp.viewChanged = true
+	  var display = cm.display, ext = cm.display.externalMeasured
+	  if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
+	    { display.externalMeasured = null }
+
+	  if (line < display.viewFrom || line >= display.viewTo) { return }
+	  var lineView = display.view[findViewIndex(cm, line)]
+	  if (lineView.node == null) { return }
+	  var arr = lineView.changes || (lineView.changes = [])
+	  if (indexOf(arr, type) == -1) { arr.push(type) }
+	}
+
+	// Clear the view.
+	function resetView(cm) {
+	  cm.display.viewFrom = cm.display.viewTo = cm.doc.first
+	  cm.display.view = []
+	  cm.display.viewOffset = 0
+	}
+
+	function viewCuttingPoint(cm, oldN, newN, dir) {
+	  var index = findViewIndex(cm, oldN), diff, view = cm.display.view
+	  if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
+	    { return {index: index, lineN: newN} }
+	  var n = cm.display.viewFrom
+	  for (var i = 0; i < index; i++)
+	    { n += view[i].size }
+	  if (n != oldN) {
+	    if (dir > 0) {
+	      if (index == view.length - 1) { return null }
+	      diff = (n + view[index].size) - oldN
+	      index++
 	    } else {
-	      var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
-	      var singleVLine = visualLine(fromLine) == visualLine(toLine);
-	      var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
-	      var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
-	      if (singleVLine) {
-	        if (leftEnd.top < rightStart.top - 2) {
-	          add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
-	          add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
-	        } else {
-	          add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
-	        }
-	      }
-	      if (leftEnd.bottom < rightStart.top)
-	        add(leftSide, leftEnd.bottom, null, rightStart.top);
-	    }
-
-	    output.appendChild(fragment);
-	  }
-
-	  // Cursor-blinking
-	  function restartBlink(cm) {
-	    if (!cm.state.focused) return;
-	    var display = cm.display;
-	    clearInterval(display.blinker);
-	    var on = true;
-	    display.cursorDiv.style.visibility = "";
-	    if (cm.options.cursorBlinkRate > 0)
-	      display.blinker = setInterval(function() {
-	        display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
-	      }, cm.options.cursorBlinkRate);
-	    else if (cm.options.cursorBlinkRate < 0)
-	      display.cursorDiv.style.visibility = "hidden";
-	  }
-
-	  // HIGHLIGHT WORKER
-
-	  function startWorker(cm, time) {
-	    if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
-	      cm.state.highlight.set(time, bind(highlightWorker, cm));
-	  }
-
-	  function highlightWorker(cm) {
-	    var doc = cm.doc;
-	    if (doc.frontier < doc.first) doc.frontier = doc.first;
-	    if (doc.frontier >= cm.display.viewTo) return;
-	    var end = +new Date + cm.options.workTime;
-	    var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
-	    var changedLines = [];
-
-	    doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
-	      if (doc.frontier >= cm.display.viewFrom) { // Visible
-	        var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
-	        var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
-	        line.styles = highlighted.styles;
-	        var oldCls = line.styleClasses, newCls = highlighted.classes;
-	        if (newCls) line.styleClasses = newCls;
-	        else if (oldCls) line.styleClasses = null;
-	        var ischange = !oldStyles || oldStyles.length != line.styles.length ||
-	          oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
-	        for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
-	        if (ischange) changedLines.push(doc.frontier);
-	        line.stateAfter = tooLong ? state : copyState(doc.mode, state);
-	      } else {
-	        if (line.text.length <= cm.options.maxHighlightLength)
-	          processLine(cm, line.text, state);
-	        line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
-	      }
-	      ++doc.frontier;
-	      if (+new Date > end) {
-	        startWorker(cm, cm.options.workDelay);
-	        return true;
-	      }
-	    });
-	    if (changedLines.length) runInOp(cm, function() {
-	      for (var i = 0; i < changedLines.length; i++)
-	        regLineChange(cm, changedLines[i], "text");
-	    });
-	  }
-
-	  // Finds the line to start with when starting a parse. Tries to
-	  // find a line with a stateAfter, so that it can start with a
-	  // valid state. If that fails, it returns the line with the
-	  // smallest indentation, which tends to need the least context to
-	  // parse correctly.
-	  function findStartLine(cm, n, precise) {
-	    var minindent, minline, doc = cm.doc;
-	    var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
-	    for (var search = n; search > lim; --search) {
-	      if (search <= doc.first) return doc.first;
-	      var line = getLine(doc, search - 1);
-	      if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
-	      var indented = countColumn(line.text, null, cm.options.tabSize);
-	      if (minline == null || minindent > indented) {
-	        minline = search - 1;
-	        minindent = indented;
-	      }
-	    }
-	    return minline;
-	  }
-
-	  function getStateBefore(cm, n, precise) {
-	    var doc = cm.doc, display = cm.display;
-	    if (!doc.mode.startState) return true;
-	    var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
-	    if (!state) state = startState(doc.mode);
-	    else state = copyState(doc.mode, state);
-	    doc.iter(pos, n, function(line) {
-	      processLine(cm, line.text, state);
-	      var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
-	      line.stateAfter = save ? copyState(doc.mode, state) : null;
-	      ++pos;
-	    });
-	    if (precise) doc.frontier = pos;
-	    return state;
-	  }
-
-	  // POSITION MEASUREMENT
-
-	  function paddingTop(display) {return display.lineSpace.offsetTop;}
-	  function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
-	  function paddingH(display) {
-	    if (display.cachedPaddingH) return display.cachedPaddingH;
-	    var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
-	    var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
-	    var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
-	    if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
-	    return data;
-	  }
-
-	  function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
-	  function displayWidth(cm) {
-	    return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
-	  }
-	  function displayHeight(cm) {
-	    return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
-	  }
-
-	  // Ensure the lineView.wrapping.heights array is populated. This is
-	  // an array of bottom offsets for the lines that make up a drawn
-	  // line. When lineWrapping is on, there might be more than one
-	  // height.
-	  function ensureLineHeights(cm, lineView, rect) {
-	    var wrapping = cm.options.lineWrapping;
-	    var curWidth = wrapping && displayWidth(cm);
-	    if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
-	      var heights = lineView.measure.heights = [];
-	      if (wrapping) {
-	        lineView.measure.width = curWidth;
-	        var rects = lineView.text.firstChild.getClientRects();
-	        for (var i = 0; i < rects.length - 1; i++) {
-	          var cur = rects[i], next = rects[i + 1];
-	          if (Math.abs(cur.bottom - next.bottom) > 2)
-	            heights.push((cur.bottom + next.top) / 2 - rect.top);
-	        }
-	      }
-	      heights.push(rect.bottom - rect.top);
-	    }
-	  }
-
-	  // Find a line map (mapping character offsets to text nodes) and a
-	  // measurement cache for the given line number. (A line view might
-	  // contain multiple lines when collapsed ranges are present.)
-	  function mapFromLineView(lineView, line, lineN) {
-	    if (lineView.line == line)
-	      return {map: lineView.measure.map, cache: lineView.measure.cache};
-	    for (var i = 0; i < lineView.rest.length; i++)
-	      if (lineView.rest[i] == line)
-	        return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
-	    for (var i = 0; i < lineView.rest.length; i++)
-	      if (lineNo(lineView.rest[i]) > lineN)
-	        return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
-	  }
-
-	  // Render a line into the hidden node display.externalMeasured. Used
-	  // when measurement is needed for a line that's not in the viewport.
-	  function updateExternalMeasurement(cm, line) {
-	    line = visualLine(line);
-	    var lineN = lineNo(line);
-	    var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
-	    view.lineN = lineN;
-	    var built = view.built = buildLineContent(cm, view);
-	    view.text = built.pre;
-	    removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
-	    return view;
-	  }
-
-	  // Get a {top, bottom, left, right} box (in line-local coordinates)
-	  // for a given character.
-	  function measureChar(cm, line, ch, bias) {
-	    return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
-	  }
-
-	  // Find a line view that corresponds to the given line number.
-	  function findViewForLine(cm, lineN) {
-	    if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
-	      return cm.display.view[findViewIndex(cm, lineN)];
-	    var ext = cm.display.externalMeasured;
-	    if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
-	      return ext;
-	  }
-
-	  // Measurement can be split in two steps, the set-up work that
-	  // applies to the whole line, and the measurement of the actual
-	  // character. Functions like coordsChar, that need to do a lot of
-	  // measurements in a row, can thus ensure that the set-up work is
-	  // only done once.
-	  function prepareMeasureForLine(cm, line) {
-	    var lineN = lineNo(line);
-	    var view = findViewForLine(cm, lineN);
-	    if (view && !view.text) {
-	      view = null;
-	    } else if (view && view.changes) {
-	      updateLineForChanges(cm, view, lineN, getDimensions(cm));
-	      cm.curOp.forceUpdate = true;
-	    }
-	    if (!view)
-	      view = updateExternalMeasurement(cm, line);
-
-	    var info = mapFromLineView(view, line, lineN);
-	    return {
-	      line: line, view: view, rect: null,
-	      map: info.map, cache: info.cache, before: info.before,
-	      hasHeights: false
-	    };
-	  }
-
-	  // Given a prepared measurement object, measures the position of an
-	  // actual character (or fetches it from the cache).
-	  function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
-	    if (prepared.before) ch = -1;
-	    var key = ch + (bias || ""), found;
-	    if (prepared.cache.hasOwnProperty(key)) {
-	      found = prepared.cache[key];
+	      diff = n - oldN
+	    }
+	    oldN += diff; newN += diff
+	  }
+	  while (visualLineNo(cm.doc, newN) != newN) {
+	    if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
+	    newN += dir * view[index - (dir < 0 ? 1 : 0)].size
+	    index += dir
+	  }
+	  return {index: index, lineN: newN}
+	}
+
+	// Force the view to cover a given range, adding empty view element
+	// or clipping off existing ones as needed.
+	function adjustView(cm, from, to) {
+	  var display = cm.display, view = display.view
+	  if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
+	    display.view = buildViewArray(cm, from, to)
+	    display.viewFrom = from
+	  } else {
+	    if (display.viewFrom > from)
+	      { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view) }
+	    else if (display.viewFrom < from)
+	      { display.view = display.view.slice(findViewIndex(cm, from)) }
+	    display.viewFrom = from
+	    if (display.viewTo < to)
+	      { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)) }
+	    else if (display.viewTo > to)
+	      { display.view = display.view.slice(0, findViewIndex(cm, to)) }
+	  }
+	  display.viewTo = to
+	}
+
+	// Count the number of lines in the view whose DOM representation is
+	// out of date (or nonexistent).
+	function countDirtyView(cm) {
+	  var view = cm.display.view, dirty = 0
+	  for (var i = 0; i < view.length; i++) {
+	    var lineView = view[i]
+	    if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty }
+	  }
+	  return dirty
+	}
+
+	// HIGHLIGHT WORKER
+
+	function startWorker(cm, time) {
+	  if (cm.doc.highlightFrontier < cm.display.viewTo)
+	    { cm.state.highlight.set(time, bind(highlightWorker, cm)) }
+	}
+
+	function highlightWorker(cm) {
+	  var doc = cm.doc
+	  if (doc.highlightFrontier >= cm.display.viewTo) { return }
+	  var end = +new Date + cm.options.workTime
+	  var context = getContextBefore(cm, doc.highlightFrontier)
+	  var changedLines = []
+
+	  doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
+	    if (context.line >= cm.display.viewFrom) { // Visible
+	      var oldStyles = line.styles
+	      var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null
+	      var highlighted = highlightLine(cm, line, context, true)
+	      if (resetState) { context.state = resetState }
+	      line.styles = highlighted.styles
+	      var oldCls = line.styleClasses, newCls = highlighted.classes
+	      if (newCls) { line.styleClasses = newCls }
+	      else if (oldCls) { line.styleClasses = null }
+	      var ischange = !oldStyles || oldStyles.length != line.styles.length ||
+	        oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass)
+	      for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i] }
+	      if (ischange) { changedLines.push(context.line) }
+	      line.stateAfter = context.save()
+	      context.nextLine()
 	    } else {
-	      if (!prepared.rect)
-	        prepared.rect = prepared.view.text.getBoundingClientRect();
-	      if (!prepared.hasHeights) {
-	        ensureLineHeights(cm, prepared.view, prepared.rect);
-	        prepared.hasHeights = true;
-	      }
-	      found = measureCharInner(cm, prepared, ch, bias);
-	      if (!found.bogus) prepared.cache[key] = found;
-	    }
-	    return {left: found.left, right: found.right,
-	            top: varHeight ? found.rtop : found.top,
-	            bottom: varHeight ? found.rbottom : found.bottom};
-	  }
-
-	  var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
-
-	  function nodeAndOffsetInLineMap(map, ch, bias) {
-	    var node, start, end, collapse;
-	    // First, search the line map for the text node corresponding to,
-	    // or closest to, the target character.
-	    for (var i = 0; i < map.length; i += 3) {
-	      var mStart = map[i], mEnd = map[i + 1];
-	      if (ch < mStart) {
-	        start = 0; end = 1;
-	        collapse = "left";
-	      } else if (ch < mEnd) {
-	        start = ch - mStart;
-	        end = start + 1;
-	      } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
-	        end = mEnd - mStart;
-	        start = end - 1;
-	        if (ch >= mEnd) collapse = "right";
-	      }
-	      if (start != null) {
-	        node = map[i + 2];
-	        if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
-	          collapse = bias;
-	        if (bias == "left" && start == 0)
-	          while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
-	            node = map[(i -= 3) + 2];
-	            collapse = "left";
-	          }
-	        if (bias == "right" && start == mEnd - mStart)
-	          while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
-	            node = map[(i += 3) + 2];
-	            collapse = "right";
-	          }
-	        break;
-	      }
-	    }
-	    return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
-	  }
-
-	  function measureCharInner(cm, prepared, ch, bias) {
-	    var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
-	    var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
-
-	    var rect;
-	    if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
-	      for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
-	        while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
-	        while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
-	        if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
-	          rect = node.parentNode.getBoundingClientRect();
-	        } else if (ie && cm.options.lineWrapping) {
-	          var rects = range(node, start, end).getClientRects();
-	          if (rects.length)
-	            rect = rects[bias == "right" ? rects.length - 1 : 0];
-	          else
-	            rect = nullRect;
-	        } else {
-	          rect = range(node, start, end).getBoundingClientRect() || nullRect;
-	        }
-	        if (rect.left || rect.right || start == 0) break;
-	        end = start;
-	        start = start - 1;
-	        collapse = "right";
-	      }
-	      if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
-	    } else { // If it is a widget, simply get the box for the whole widget.
-	      if (start > 0) collapse = bias = "right";
-	      var rects;
-	      if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
-	        rect = rects[bias == "right" ? rects.length - 1 : 0];
-	      else
-	        rect = node.getBoundingClientRect();
-	    }
-	    if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
-	      var rSpan = node.parentNode.getClientRects()[0];
-	      if (rSpan)
-	        rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
-	      else
-	        rect = nullRect;
-	    }
-
-	    var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
-	    var mid = (rtop + rbot) / 2;
-	    var heights = prepared.view.measure.heights;
-	    for (var i = 0; i < heights.length - 1; i++)
-	      if (mid < heights[i]) break;
-	    var top = i ? heights[i - 1] : 0, bot = heights[i];
-	    var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
-	                  right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
-	                  top: top, bottom: bot};
-	    if (!rect.left && !rect.right) result.bogus = true;
-	    if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
-
-	    return result;
-	  }
-
-	  // Work around problem with bounding client rects on ranges being
-	  // returned incorrectly when zoomed on IE10 and below.
-	  function maybeUpdateRectForZooming(measure, rect) {
-	    if (!window.screen || screen.logicalXDPI == null ||
-	        screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
-	      return rect;
-	    var scaleX = screen.logicalXDPI / screen.deviceXDPI;
-	    var scaleY = screen.logicalYDPI / screen.deviceYDPI;
-	    return {left: rect.left * scaleX, right: rect.right * scaleX,
-	            top: rect.top * scaleY, bottom: rect.bottom * scaleY};
-	  }
-
-	  function clearLineMeasurementCacheFor(lineView) {
-	    if (lineView.measure) {
-	      lineView.measure.cache = {};
-	      lineView.measure.heights = null;
-	      if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
-	        lineView.measure.caches[i] = {};
-	    }
-	  }
-
-	  function clearLineMeasurementCache(cm) {
-	    cm.display.externalMeasure = null;
-	    removeChildren(cm.display.lineMeasure);
-	    for (var i = 0; i < cm.display.view.length; i++)
-	      clearLineMeasurementCacheFor(cm.display.view[i]);
-	  }
-
-	  function clearCaches(cm) {
-	    clearLineMeasurementCache(cm);
-	    cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
-	    if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
-	    cm.display.lineNumChars = null;
-	  }
-
-	  function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
-	  function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
-
-	  // Converts a {top, bottom, left, right} box from line-local
-	  // coordinates into another coordinate system. Context may be one of
-	  // "line", "div" (display.lineDiv), "local"/null (editor), "window",
-	  // or "page".
-	  function intoCoordSystem(cm, lineObj, rect, context) {
-	    if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
-	      var size = widgetHeight(lineObj.widgets[i]);
-	      rect.top += size; rect.bottom += size;
-	    }
-	    if (context == "line") return rect;
-	    if (!context) context = "local";
-	    var yOff = heightAtLine(lineObj);
-	    if (context == "local") yOff += paddingTop(cm.display);
-	    else yOff -= cm.display.viewOffset;
-	    if (context == "page" || context == "window") {
-	      var lOff = cm.display.lineSpace.getBoundingClientRect();
-	      yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
-	      var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
-	      rect.left += xOff; rect.right += xOff;
-	    }
-	    rect.top += yOff; rect.bottom += yOff;
-	    return rect;
-	  }
-
-	  // Coverts a box from "div" coords to another coordinate system.
-	  // Context may be "window", "page", "div", or "local"/null.
-	  function fromCoordSystem(cm, coords, context) {
-	    if (context == "div") return coords;
-	    var left = coords.left, top = coords.top;
-	    // First move into "page" coordinate system
-	    if (context == "page") {
-	      left -= pageScrollX();
-	      top -= pageScrollY();
-	    } else if (context == "local" || !context) {
-	      var localBox = cm.display.sizer.getBoundingClientRect();
-	      left += localBox.left;
-	      top += localBox.top;
-	    }
-
-	    var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
-	    return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
-	  }
-
-	  function charCoords(cm, pos, context, lineObj, bias) {
-	    if (!lineObj) lineObj = getLine(cm.doc, pos.line);
-	    return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
-	  }
-
-	  // Returns a box for a given cursor position, which may have an
-	  // 'other' property containing the position of the secondary cursor
-	  // on a bidi boundary.
-	  function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
-	    lineObj = lineObj || getLine(cm.doc, pos.line);
-	    if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
-	    function get(ch, right) {
-	      var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
-	      if (right) m.left = m.right; else m.right = m.left;
-	      return intoCoordSystem(cm, lineObj, m, context);
-	    }
-	    function getBidi(ch, partPos) {
-	      var part = order[partPos], right = part.level % 2;
-	      if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
-	        part = order[--partPos];
-	        ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
-	        right = true;
-	      } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
-	        part = order[++partPos];
-	        ch = bidiLeft(part) - part.level % 2;
-	        right = false;
-	      }
-	      if (right && ch == part.to && ch > part.from) return get(ch - 1);
-	      return get(ch, right);
-	    }
-	    var order = getOrder(lineObj), ch = pos.ch;
-	    if (!order) return get(ch);
-	    var partPos = getBidiPartAt(order, ch);
-	    var val = getBidi(ch, partPos);
-	    if (bidiOther != null) val.other = getBidi(ch, bidiOther);
-	    return val;
-	  }
-
-	  // Used to cheaply estimate the coordinates for a position. Used for
-	  // intermediate scroll updates.
-	  function estimateCoords(cm, pos) {
-	    var left = 0, pos = clipPos(cm.doc, pos);
-	    if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
-	    var lineObj = getLine(cm.doc, pos.line);
-	    var top = heightAtLine(lineObj) + paddingTop(cm.display);
-	    return {left: left, right: left, top: top, bottom: top + lineObj.height};
-	  }
-
-	  // Positions returned by coordsChar contain some extra information.
-	  // xRel is the relative x position of the input coordinates compared
-	  // to the found position (so xRel > 0 means the coordinates are to
-	  // the right of the character position, for example). When outside
-	  // is true, that means the coordinates lie outside the line's
-	  // vertical range.
-	  function PosWithInfo(line, ch, outside, xRel) {
-	    var pos = Pos(line, ch);
-	    pos.xRel = xRel;
-	    if (outside) pos.outside = true;
-	    return pos;
-	  }
-
-	  // Compute the character position closest to the given coordinates.
-	  // Input must be lineSpace-local ("div" coordinate system).
-	  function coordsChar(cm, x, y) {
-	    var doc = cm.doc;
-	    y += cm.display.viewOffset;
-	    if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
-	    var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
-	    if (lineN > last)
-	      return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
-	    if (x < 0) x = 0;
-
-	    var lineObj = getLine(doc, lineN);
-	    for (;;) {
-	      var found = coordsCharInner(cm, lineObj, lineN, x, y);
-	      var merged = collapsedSpanAtEnd(lineObj);
-	      var mergedPos = merged && merged.find(0, true);
-	      if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
-	        lineN = lineNo(lineObj = mergedPos.to.line);
-	      else
-	        return found;
-	    }
-	  }
-
-	  function coordsCharInner(cm, lineObj, lineNo, x, y) {
-	    var innerOff = y - heightAtLine(lineObj);
-	    var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
-	    var preparedMeasure = prepareMeasureForLine(cm, lineObj);
-
-	    function getX(ch) {
-	      var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
-	      wrongLine = true;
-	      if (innerOff > sp.bottom) return sp.left - adjust;
-	      else if (innerOff < sp.top) return sp.left + adjust;
-	      else wrongLine = false;
-	      return sp.left;
-	    }
-
-	    var bidi = getOrder(lineObj), dist = lineObj.text.length;
-	    var from = lineLeft(lineObj), to = lineRight(lineObj);
-	    var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
-
-	    if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
-	    // Do a binary search between these bounds.
-	    for (;;) {
-	      if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
-	        var ch = x < fromX || x - fromX <= toX - x ? from : to;
-	        var outside = ch == from ? fromOutside : toOutside
-	        var xDiff = x - (ch == from ? fromX : toX);
-	        // This is a kludge to handle the case where the coordinates
-	        // are after a line-wrapped line. We should replace it with a
-	        // more general handling of cursor positions around line
-	        // breaks. (Issue #4078)
-	        if (toOutside && !bidi && !/\s/.test(lineObj.text.charAt(ch)) && xDiff > 0 &&
-	            ch < lineObj.text.length && preparedMeasure.view.measure.heights.length > 1) {
-	          var charSize = measureCharPrepared(cm, preparedMeasure, ch, "right");
-	          if (innerOff <= charSize.bottom && innerOff >= charSize.top && Math.abs(x - charSize.right) < xDiff) {
-	            outside = false
-	            ch++
-	            xDiff = x - charSize.right
-	          }
-	        }
-	        while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
-	        var pos = PosWithInfo(lineNo, ch, outside, xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
-	        return pos;
-	      }
-	      var step = Math.ceil(dist / 2), middle = from + step;
-	      if (bidi) {
-	        middle = from;
-	        for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
-	      }
-	      var middleX = getX(middle);
-	      if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
-	      else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
-	    }
-	  }
-
-	  var measureText;
-	  // Compute the default text height.
-	  function textHeight(display) {
-	    if (display.cachedTextHeight != null) return display.cachedTextHeight;
-	    if (measureText == null) {
-	      measureText = elt("pre");
-	      // Measure a bunch of lines, for browsers that compute
-	      // fractional heights.
-	      for (var i = 0; i < 49; ++i) {
-	        measureText.appendChild(document.createTextNode("x"));
-	        measureText.appendChild(elt("br"));
-	      }
-	      measureText.appendChild(document.createTextNode("x"));
-	    }
-	    removeChildrenAndAdd(display.measure, measureText);
-	    var height = measureText.offsetHeight / 50;
-	    if (height > 3) display.cachedTextHeight = height;
-	    removeChildren(display.measure);
-	    return height || 1;
-	  }
-
-	  // Compute the default character width.
-	  function charWidth(display) {
-	    if (display.cachedCharWidth != null) return display.cachedCharWidth;
-	    var anchor = elt("span", "xxxxxxxxxx");
-	    var pre = elt("pre", [anchor]);
-	    removeChildrenAndAdd(display.measure, pre);
-	    var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
-	    if (width > 2) display.cachedCharWidth = width;
-	    return width || 10;
-	  }
-
-	  // OPERATIONS
-
-	  // Operations are used to wrap a series of changes to the editor
-	  // state in such a way that each change won't have to update the
-	  // cursor and display (which would be awkward, slow, and
-	  // error-prone). Instead, display updates are batched and then all
-	  // combined and executed at once.
-
-	  var operationGroup = null;
-
-	  var nextOpId = 0;
-	  // Start a new operation.
-	  function startOperation(cm) {
-	    cm.curOp = {
-	      cm: cm,
-	      viewChanged: false,      // Flag that indicates that lines might need to be redrawn
-	      startHeight: cm.doc.height, // Used to detect need to update scrollbar
-	      forceUpdate: false,      // Used to force a redraw
-	      updateInput: null,       // Whether to reset the input textarea
-	      typing: false,           // Whether this reset should be careful to leave existing text (for compositing)
-	      changeObjs: null,        // Accumulated changes, for firing change events
-	      cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
-	      cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
-	      selectionChanged: false, // Whether the selection needs to be redrawn
-	      updateMaxLine: false,    // Set when the widest line needs to be determined anew
-	      scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
-	      scrollToPos: null,       // Used to scroll to a specific position
-	      focus: false,
-	      id: ++nextOpId           // Unique ID
-	    };
-	    if (operationGroup) {
-	      operationGroup.ops.push(cm.curOp);
-	    } else {
-	      cm.curOp.ownsGroup = operationGroup = {
-	        ops: [cm.curOp],
-	        delayedCallbacks: []
-	      };
-	    }
-	  }
-
-	  function fireCallbacksForOps(group) {
-	    // Calls delayed callbacks and cursorActivity handlers until no
-	    // new ones appear
-	    var callbacks = group.delayedCallbacks, i = 0;
-	    do {
-	      for (; i < callbacks.length; i++)
-	        callbacks[i].call(null);
-	      for (var j = 0; j < group.ops.length; j++) {
-	        var op = group.ops[j];
-	        if (op.cursorActivityHandlers)
-	          while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
-	            op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
-	      }
-	    } while (i < callbacks.length);
-	  }
-
-	  // Finish an operation, updating the display and signalling delayed events
-	  function endOperation(cm) {
-	    var op = cm.curOp, group = op.ownsGroup;
-	    if (!group) return;
-
-	    try { fireCallbacksForOps(group); }
-	    finally {
-	      operationGroup = null;
-	      for (var i = 0; i < group.ops.length; i++)
-	        group.ops[i].cm.curOp = null;
-	      endOperations(group);
-	    }
-	  }
-
-	  // The DOM updates done when an operation finishes are batched so
-	  // that the minimum number of relayouts are required.
-	  function endOperations(group) {
-	    var ops = group.ops;
-	    for (var i = 0; i < ops.length; i++) // Read DOM
-	      endOperation_R1(ops[i]);
-	    for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
-	      endOperation_W1(ops[i]);
-	    for (var i = 0; i < ops.length; i++) // Read DOM
-	      endOperation_R2(ops[i]);
-	    for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
-	      endOperation_W2(ops[i]);
-	    for (var i = 0; i < ops.length; i++) // Read DOM
-	      endOperation_finish(ops[i]);
-	  }
-
-	  function endOperation_R1(op) {
-	    var cm = op.cm, display = cm.display;
-	    maybeClipScrollbars(cm);
-	    if (op.updateMaxLine) findMaxLine(cm);
-
-	    op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
-	      op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
-	                         op.scrollToPos.to.line >= display.viewTo) ||
-	      display.maxLineChanged && cm.options.lineWrapping;
-	    op.update = op.mustUpdate &&
-	      new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
-	  }
-
-	  function endOperation_W1(op) {
-	    op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
-	  }
-
-	  function endOperation_R2(op) {
-	    var cm = op.cm, display = cm.display;
-	    if (op.updatedDisplay) updateHeightsInViewport(cm);
-
-	    op.barMeasure = measureForScrollbars(cm);
-
-	    // If the max line changed since it was last measured, measure it,
-	    // and ensure the document's width matches it.
-	    // updateDisplay_W2 will use these properties to do the actual resizing
-	    if (display.maxLineChanged && !cm.options.lineWrapping) {
-	      op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
-	      cm.display.sizerWidth = op.adjustWidthTo;
-	      op.barMeasure.scrollWidth =
-	        Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
-	      op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
-	    }
-
-	    if (op.updatedDisplay || op.selectionChanged)
-	      op.preparedSelection = display.input.prepareSelection(op.focus);
-	  }
-
-	  function endOperation_W2(op) {
-	    var cm = op.cm;
-
-	    if (op.adjustWidthTo != null) {
-	      cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
-	      if (op.maxScrollLeft < cm.doc.scrollLeft)
-	        setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
-	      cm.display.maxLineChanged = false;
-	    }
-
-	    var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus())
-	    if (op.preparedSelection)
-	      cm.display.input.showSelection(op.preparedSelection, takeFocus);
-	    if (op.updatedDisplay || op.startHeight != cm.doc.height)
-	      updateScrollbars(cm, op.barMeasure);
-	    if (op.updatedDisplay)
-	      setDocumentHeight(cm, op.barMeasure);
-
-	    if (op.selectionChanged) restartBlink(cm);
-
-	    if (cm.state.focused && op.updateInput)
-	      cm.display.input.reset(op.typing);
-	    if (takeFocus) ensureFocus(op.cm);
-	  }
-
-	  function endOperation_finish(op) {
-	    var cm = op.cm, display = cm.display, doc = cm.doc;
-
-	    if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
-
-	    // Abort mouse wheel delta measurement, when scrolling explicitly
-	    if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
-	      display.wheelStartX = display.wheelStartY = null;
-
-	    // Propagate the scroll position to the actual DOM scroller
-	    if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
-	      doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
-	      display.scrollbars.setScrollTop(doc.scrollTop);
-	      display.scroller.scrollTop = doc.scrollTop;
-	    }
-	    if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
-	      doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
-	      display.scrollbars.setScrollLeft(doc.scrollLeft);
-	      display.scroller.scrollLeft = doc.scrollLeft;
-	      alignHorizontally(cm);
-	    }
-	    // If we need to scroll a specific position into view, do so.
-	    if (op.scrollToPos) {
-	      var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
-	                                     clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
-	      if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
-	    }
-
-	    // Fire events for markers that are hidden/unidden by editing or
-	    // undoing
-	    var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
-	    if (hidden) for (var i = 0; i < hidden.length; ++i)
-	      if (!hidden[i].lines.length) signal(hidden[i], "hide");
-	    if (unhidden) for (var i = 0; i < unhidden.length; ++i)
-	      if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
-
-	    if (display.wrapper.offsetHeight)
-	      doc.scrollTop = cm.display.scroller.scrollTop;
-
-	    // Fire change events, and delayed event handlers
-	    if (op.changeObjs)
-	      signal(cm, "changes", cm, op.changeObjs);
-	    if (op.update)
-	      op.update.finish();
-	  }
-
-	  // Run the given function in an operation
-	  function runInOp(cm, f) {
-	    if (cm.curOp) return f();
-	    startOperation(cm);
-	    try { return f(); }
-	    finally { endOperation(cm); }
-	  }
-	  // Wraps a function in an operation. Returns the wrapped function.
-	  function operation(cm, f) {
-	    return function() {
-	      if (cm.curOp) return f.apply(cm, arguments);
-	      startOperation(cm);
-	      try { return f.apply(cm, arguments); }
-	      finally { endOperation(cm); }
-	    };
-	  }
-	  // Used to add methods to editor and doc instances, wrapping them in
-	  // operations.
-	  function methodOp(f) {
-	    return function() {
-	      if (this.curOp) return f.apply(this, arguments);
-	      startOperation(this);
-	      try { return f.apply(this, arguments); }
-	      finally { endOperation(this); }
-	    };
-	  }
-	  function docMethodOp(f) {
-	    return function() {
-	      var cm = this.cm;
-	      if (!cm || cm.curOp) return f.apply(this, arguments);
-	      startOperation(cm);
-	      try { return f.apply(this, arguments); }
-	      finally { endOperation(cm); }
-	    };
-	  }
-
-	  // VIEW TRACKING
-
-	  // These objects are used to represent the visible (currently drawn)
-	  // part of the document. A LineView may correspond to multiple
-	  // logical lines, if those are connected by collapsed ranges.
-	  function LineView(doc, line, lineN) {
-	    // The starting line
-	    this.line = line;
-	    // Continuing lines, if any
-	    this.rest = visualLineContinued(line);
-	    // Number of logical lines in this visual line
-	    this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
-	    this.node = this.text = null;
-	    this.hidden = lineIsHidden(doc, line);
-	  }
-
-	  // Create a range of LineView objects for the given lines.
-	  function buildViewArray(cm, from, to) {
-	    var array = [], nextPos;
-	    for (var pos = from; pos < to; pos = nextPos) {
-	      var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
-	      nextPos = pos + view.size;
-	      array.push(view);
-	    }
-	    return array;
-	  }
-
-	  // Updates the display.view data structure for a given change to the
-	  // document. From and to are in pre-change coordinates. Lendiff is
-	  // the amount of lines added or subtracted by the change. This is
-	  // used for changes that span multiple lines, or change the way
-	  // lines are divided into visual lines. regLineChange (below)
-	  // registers single-line changes.
-	  function regChange(cm, from, to, lendiff) {
-	    if (from == null) from = cm.doc.first;
-	    if (to == null) to = cm.doc.first + cm.doc.size;
-	    if (!lendiff) lendiff = 0;
-
-	    var display = cm.display;
-	    if (lendiff && to < display.viewTo &&
-	        (display.updateLineNumbers == null || display.updateLineNumbers > from))
-	      display.updateLineNumbers = from;
-
-	    cm.curOp.viewChanged = true;
-
-	    if (from >= display.viewTo) { // Change after
-	      if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
-	        resetView(cm);
-	    } else if (to <= display.viewFrom) { // Change before
-	      if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
-	        resetView(cm);
-	      } else {
-	        display.viewFrom += lendiff;
-	        display.viewTo += lendiff;
-	      }
-	    } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
-	      resetView(cm);
-	    } else if (from <= display.viewFrom) { // Top overlap
-	      var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
-	      if (cut) {
-	        display.view = display.view.slice(cut.index);
-	        display.viewFrom = cut.lineN;
-	        display.viewTo += lendiff;
-	      } else {
-	        resetView(cm);
-	      }
-	    } else if (to >= display.viewTo) { // Bottom overlap
-	      var cut = viewCuttingPoint(cm, from, from, -1);
-	      if (cut) {
-	        display.view = display.view.slice(0, cut.index);
-	        display.viewTo = cut.lineN;
-	      } else {
-	        resetView(cm);
-	      }
-	    } else { // Gap in the middle
-	      var cutTop = viewCuttingPoint(cm, from, from, -1);
-	      var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
-	      if (cutTop && cutBot) {
-	        display.view = display.view.slice(0, cutTop.index)
-	          .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
-	          .concat(display.view.slice(cutBot.index));
-	        display.viewTo += lendiff;
-	      } else {
-	        resetView(cm);
-	      }
-	    }
-
-	    var ext = display.externalMeasured;
-	    if (ext) {
-	      if (to < ext.lineN)
-	        ext.lineN += lendiff;
-	      else if (from < ext.lineN + ext.size)
-	        display.externalMeasured = null;
-	    }
-	  }
-
-	  // Register a change to a single line. Type must be one of "text",
-	  // "gutter", "class", "widget"
-	  function regLineChange(cm, line, type) {
-	    cm.curOp.viewChanged = true;
-	    var display = cm.display, ext = cm.display.externalMeasured;
-	    if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
-	      display.externalMeasured = null;
-
-	    if (line < display.viewFrom || line >= display.viewTo) return;
-	    var lineView = display.view[findViewIndex(cm, line)];
-	    if (lineView.node == null) return;
-	    var arr = lineView.changes || (lineView.changes = []);
-	    if (indexOf(arr, type) == -1) arr.push(type);
-	  }
-
-	  // Clear the view.
-	  function resetView(cm) {
-	    cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
-	    cm.display.view = [];
-	    cm.display.viewOffset = 0;
-	  }
-
-	  // Find the view element corresponding to a given line. Return null
-	  // when the line isn't visible.
-	  function findViewIndex(cm, n) {
-	    if (n >= cm.display.viewTo) return null;
-	    n -= cm.display.viewFrom;
-	    if (n < 0) return null;
-	    var view = cm.display.view;
-	    for (var i = 0; i < view.length; i++) {
-	      n -= view[i].size;
-	      if (n < 0) return i;
-	    }
-	  }
-
-	  function viewCuttingPoint(cm, oldN, newN, dir) {
-	    var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
-	    if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
-	      return {index: index, lineN: newN};
-	    for (var i = 0, n = cm.display.viewFrom; i < index; i++)
-	      n += view[i].size;
-	    if (n != oldN) {
-	      if (dir > 0) {
-	        if (index == view.length - 1) return null;
-	        diff = (n + view[index].size) - oldN;
-	        index++;
-	      } else {
-	        diff = n - oldN;
-	      }
-	      oldN += diff; newN += diff;
-	    }
-	    while (visualLineNo(cm.doc, newN) != newN) {
-	      if (index == (dir < 0 ? 0 : view.length - 1)) return null;
-	      newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
-	      index += dir;
-	    }
-	    return {index: index, lineN: newN};
-	  }
-
-	  // Force the view to cover a given range, adding empty view element
-	  // or clipping off existing ones as needed.
-	  function adjustView(cm, from, to) {
-	    var display = cm.display, view = display.view;
-	    if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
-	      display.view = buildViewArray(cm, from, to);
-	      display.viewFrom = from;
-	    } else {
-	      if (display.viewFrom > from)
-	        display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
-	      else if (display.viewFrom < from)
-	        display.view = display.view.slice(findViewIndex(cm, from));
-	      display.viewFrom = from;
-	      if (display.viewTo < to)
-	        display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
-	      else if (display.viewTo > to)
-	        display.view = display.view.slice(0, findViewIndex(cm, to));
-	    }
-	    display.viewTo = to;
-	  }
-
-	  // Count the number of lines in the view whose DOM representation is
-	  // out of date (or nonexistent).
-	  function countDirtyView(cm) {
-	    var view = cm.display.view, dirty = 0;
-	    for (var i = 0; i < view.length; i++) {
-	      var lineView = view[i];
-	      if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
-	    }
-	    return dirty;
-	  }
-
-	  // EVENT HANDLERS
-
-	  // Attach the necessary event handlers when initializing the editor
-	  function registerEventHandlers(cm) {
-	    var d = cm.display;
-	    on(d.scroller, "mousedown", operation(cm, onMouseDown));
-	    // Older IE's will not fire a second mousedown for a double click
-	    if (ie && ie_version < 11)
-	      on(d.scroller, "dblclick", operation(cm, function(e) {
-	        if (signalDOMEvent(cm, e)) return;
-	        var pos = posFromMouse(cm, e);
-	        if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
-	        e_preventDefault(e);
-	        var word = cm.findWordAt(pos);
-	        extendSelection(cm.doc, word.anchor, word.head);
-	      }));
-	    else
-	      on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
-	    // Some browsers fire contextme