<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[210337] branches/safari-603-branch/Source/WebInspectorUI</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.webkit.org/projects/webkit/changeset/210337">210337</a></dd>
<dt>Author</dt> <dd>matthew_hanson@apple.com</dd>
<dt>Date</dt> <dd>2017-01-05 09:08:47 -0800 (Thu, 05 Jan 2017)</dd>
</dl>

<h3>Log Message</h3>
<pre>Merge <a href="http://trac.webkit.org/projects/webkit/changeset/210032">r210032</a>. rdar://problem/29744608</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#branchessafari603branchSourceWebInspectorUIChangeLog">branches/safari-603-branch/Source/WebInspectorUI/ChangeLog</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIScriptsupdatecodemirrorresourcesrb">branches/safari-603-branch/Source/WebInspectorUI/Scripts/update-codemirror-resources.rb</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorLICENSE">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/LICENSE</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorclojurejs">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/clojure.js</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorclosebracketsjs">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/closebrackets.js</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorcodemirrorcss">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/codemirror.css</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorcodemirrorjs">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/codemirror.js</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorcoffeescriptjs">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/coffeescript.js</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorcommentjs">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/comment.js</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorcssjs">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/css.js</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorhtmlmixedjs">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/htmlmixed.js</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorjavascriptjs">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/javascript.js</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorlivescriptjs">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/livescript.js</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrormatchbracketsjs">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/matchbrackets.js</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirroroverlayjs">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/overlay.js</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorplaceholderjs">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/placeholder.js</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorrunmodejs">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/runmode.js</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorsqljs">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/sql.js</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorsublimejs">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/sublime.js</a></li>
<li><a href="#branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorxmljs">branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/xml.js</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="branchessafari603branchSourceWebInspectorUIChangeLog"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/ChangeLog (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/ChangeLog        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/ChangeLog        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -1,3 +1,45 @@
</span><ins>+2017-01-05  Matthew Hanson  &lt;matthew_hanson@apple.com&gt;
+
+        Merge r210032. rdar://problem/29744608
+
+    2016-12-20  Joseph Pecoraro  &lt;pecoraro@apple.com&gt;
+
+            Web Inspector: Update CodeMirror to support async/await keyword and other ES2017 features
+            https://bugs.webkit.org/show_bug.cgi?id=165677
+
+            Rubber-stamped by Brian Burg.
+
+            Update CodeMirror from version 5.5.1 to 5.21.1. Highlights include:
+
+              - Syntax highlighting for ES2017 features (async/await)
+              - Syntax highlighting improvements for some ES6 features (new.target)
+              - Syntax highlighting for CSS4 #rrggbbaa and #rgba colors
+
+            As well as a number of smaller bug fixes.
+
+            Had to add a few semicolons to codemirror.js so that our minifier
+            didn't choke in a few places due to ASI behavior.
+
+            * Scripts/update-codemirror-resources.rb:
+            * UserInterface/External/CodeMirror/LICENSE:
+            * UserInterface/External/CodeMirror/clojure.js:
+            * UserInterface/External/CodeMirror/closebrackets.js:
+            * UserInterface/External/CodeMirror/codemirror.css:
+            * UserInterface/External/CodeMirror/codemirror.js:
+            * UserInterface/External/CodeMirror/coffeescript.js:
+            * UserInterface/External/CodeMirror/comment.js:
+            * UserInterface/External/CodeMirror/css.js:
+            * UserInterface/External/CodeMirror/htmlmixed.js:
+            * UserInterface/External/CodeMirror/javascript.js:
+            * UserInterface/External/CodeMirror/livescript.js:
+            * UserInterface/External/CodeMirror/matchbrackets.js:
+            * UserInterface/External/CodeMirror/overlay.js:
+            * UserInterface/External/CodeMirror/placeholder.js:
+            * UserInterface/External/CodeMirror/runmode.js:
+            * UserInterface/External/CodeMirror/sql.js:
+            * UserInterface/External/CodeMirror/sublime.js:
+            * UserInterface/External/CodeMirror/xml.js:
+
</ins><span class="cx"> 2016-12-16  Joseph Pecoraro  &lt;pecoraro@apple.com&gt;
</span><span class="cx"> 
</span><span class="cx">         JSContext Inspector: Avoid some possible exceptions inspecting a JSContext
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIScriptsupdatecodemirrorresourcesrb"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/Scripts/update-codemirror-resources.rb (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/Scripts/update-codemirror-resources.rb        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/Scripts/update-codemirror-resources.rb        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -14,7 +14,7 @@
</span><span class="cx">   end
</span><span class="cx"> 
</span><span class="cx">   Dir.chdir(path) do
</span><del>-    results = `git config --list | grep 'marijnh/CodeMirror\.git'`
</del><ins>+    results = `git config --list | grep 'codemirror/CodeMirror\.git'`
</ins><span class="cx">     if $?.exitstatus != 0 || results.split(&quot;\n&quot;).empty?
</span><span class="cx">       puts &quot;ERROR: Provided CodeMirror path does not appear to be a CodeMirror checkout.&quot;
</span><span class="cx">       exit 1
</span><span class="lines">@@ -29,6 +29,7 @@
</span><span class="cx"> web_inspector_code_mirror_resources_path = File.join web_inspector_user_interface_path, &quot;/External/CodeMirror&quot;
</span><span class="cx"> 
</span><span class="cx"> CODE_MIRROR_FILES_TO_COPY = %w(
</span><ins>+  LICENSE
</ins><span class="cx">   addon/comment/comment.js
</span><span class="cx">   addon/display/placeholder.js
</span><span class="cx">   addon/edit/closebrackets.js
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorLICENSE"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/LICENSE (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/LICENSE        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/LICENSE        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -1,4 +1,4 @@
</span><del>-Copyright (C) 2015 by Marijn Haverbeke &lt;marijnh@gmail.com&gt; and others
</del><ins>+Copyright (C) 2016 by Marijn Haverbeke &lt;marijnh@gmail.com&gt; and others
</ins><span class="cx"> 
</span><span class="cx"> Permission is hereby granted, free of charge, to any person obtaining a copy
</span><span class="cx"> of this software and associated documentation files (the &quot;Software&quot;), to deal
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorclojurejs"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/clojure.js (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/clojure.js        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/clojure.js        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -31,14 +31,70 @@
</span><span class="cx">     var atoms = makeKeywords(&quot;true false nil&quot;);
</span><span class="cx"> 
</span><span class="cx">     var keywords = makeKeywords(
</span><del>-      &quot;defn defn- def def- defonce defmulti defmethod defmacro defstruct deftype defprotocol defrecord defproject deftest slice defalias defhinted defmacro- defn-memo defnk defnk defonce- defunbound defunbound- defvar defvar- let letfn do case cond condp for loop recur when when-not when-let when-first if if-let if-not . .. -&gt; -&gt;&gt; doto and or dosync doseq dotimes dorun doall load import unimport ns in-ns refer try catch finally throw with-open with-local-vars binding gen-class gen-and-load-class gen-and-save-class handler-case handle&quot;);
</del><ins>+      &quot;defn defn- def def- defonce defmulti defmethod defmacro defstruct deftype defprotocol defrecord defproject deftest &quot; +
+      &quot;slice defalias defhinted defmacro- defn-memo defnk defnk defonce- defunbound defunbound- defvar defvar- let letfn &quot; +
+      &quot;do case cond condp for loop recur when when-not when-let when-first if if-let if-not . .. -&gt; -&gt;&gt; doto and or dosync &quot; +
+      &quot;doseq dotimes dorun doall load import unimport ns in-ns refer try catch finally throw with-open with-local-vars &quot; +
+      &quot;binding gen-class gen-and-load-class gen-and-save-class handler-case handle&quot;);
</ins><span class="cx"> 
</span><span class="cx">     var builtins = makeKeywords(
</span><del>-        &quot;* *' *1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* *command-line-args* *compile-files* *compile-path* *compiler-options* *data-readers* *e *err* *file* *flush-on-newline* *fn-loader* *in* *math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *unchecked-math* *use-context-classloader* *verbose-defrecords* *warn-on-reflection* + +' - -' -&gt; -&gt;&gt; -&gt;ArrayChunk -&gt;Vec -&gt;VecNode -&gt;VecSeq -cache-protocol-fn -reset-methods .. / &lt; &lt;= = == &gt; &gt;= EMPTY-NODE accessor aclone add-classpath add-watch agent agent-error agent-errors aget alength alias all-ns alter alter-meta! alter-var-root amap ancestors and apply areduce array-map aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for await1 bases bean bigdec bigint biginteger binding bit-and bit-an
 d-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* bound? butlast byte byte-array bytes case cast char char-array char-escape-string char-name-string char? chars chunk chunk-append chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class class? clear-agent-errors clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement concat cond condp conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec dec' decimal? declare default-data-readers definline definterface defmacro defmethod defmulti defn defn- defonce defprotocol defrecord defstruct deftype delay delay? deliver denominator deref derive descendants destructure disj disj! dissoc dissoc! distinct distinct? doall dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-
 seq error-handler error-mode eval even? every-pred every? ex-data ex-info extend extend-protocol extend-type extenders extends? false? ffirst file-seq filter filterv find find-keyword find-ns find-protocol-impl find-protocol-method find-var first flatten float float-array float? floats flush fn fn? fnext fnil for force format frequencies future future-call future-cancel future-cancelled? future-done? future? gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator group-by hash hash-combine hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc inc' init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt keep keep-indexed key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array make-hierarchy
  map map-indexed map? mapcat mapv max max-key memfn memoize merge merge-with meta method-sig methods min min-key mod munge name namespace namespace-munge neg? newline next nfirst nil? nnext not not-any? not-empty not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias ns-unmap nth nthnext nthrest num number? numerator object-array odd? or parents partial partition partition-all partition-by pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers primitives-classnames print print-ctor print-dup print-method print-simple print-str printf println println-str prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot rand rand-int rand-nth range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string realized? reduce reduce-kv reductions ref ref-history-count ref-max-his
 tory ref-min-history ref-set refer refer-clojure reify release-pending-sends rem remove remove-all-methods remove-method remove-ns remove-watch repeat repeatedly replace replicate require reset! reset-meta! resolve rest restart-agent resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? seque sequence sequential? set set-error-handler! set-error-mode! set-validator! set? short short-array shorts shuffle shutdown-agents slurp some some-fn sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-symbol? spit split-at split-with str string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync take take-last take-nth take-while test the-ns thread-bound? time to-array to-array-2d trampoline transient tree-seq true? type unchecked-add unchecked-add-int unchecked-byte unchecked-char unchecked-dec unchecked-dec-int unchecked-divide-int unchecked-double unchecked-float unchecked-inc unchecked-inc-int
  unchecked-int unchecked-long unchecked-multiply unchecked-multiply-int unchecked-negate unchecked-negate-int unchecked-remainder-int unchecked-short unchecked-subtract unchecked-subtract-int underive unquote unquote-splicing update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector-of vector? when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context with-local-vars with-meta with-open with-out-str with-precision with-redefs with-redefs-fn xml-seq zero? zipmap *default-data-reader-fn* as-&gt; cond-&gt; cond-&gt;&gt; reduced reduced? send-via set-agent-send-executor! set-agent-send-off-executor! some-&gt; some-&gt;&gt;&quot;);
</del><ins>+        &quot;* *' *1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* *command-line-args* *compile-files* &quot; +
+        &quot;*compile-path* *compiler-options* *data-readers* *e *err* *file* *flush-on-newline* *fn-loader* *in* &quot; +
+        &quot;*math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* &quot; +
+        &quot;*source-path* *unchecked-math* *use-context-classloader* *verbose-defrecords* *warn-on-reflection* + +' - -' -&gt; &quot; +
+        &quot;-&gt;&gt; -&gt;ArrayChunk -&gt;Vec -&gt;VecNode -&gt;VecSeq -cache-protocol-fn -reset-methods .. / &lt; &lt;= = == &gt; &gt;= EMPTY-NODE accessor &quot; +
+        &quot;aclone add-classpath add-watch agent agent-error agent-errors aget alength alias all-ns alter alter-meta! &quot; +
+        &quot;alter-var-root amap ancestors and apply areduce array-map aset aset-boolean aset-byte aset-char aset-double &quot; +
+        &quot;aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for await1 &quot; +
+        &quot;bases bean bigdec bigint biginteger binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set &quot; +
+        &quot;bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* bound? butlast &quot; +
+        &quot;byte byte-array bytes case cat cast char char-array char-escape-string char-name-string char? chars chunk chunk-append &quot; +
+        &quot;chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class class? clear-agent-errors &quot; +
+        &quot;clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement completing concat cond condp &quot; +
+        &quot;conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec dec' decimal? &quot; +
+        &quot;declare dedupe default-data-readers definline definterface defmacro defmethod defmulti defn defn- defonce defprotocol &quot; +
+        &quot;defrecord defstruct deftype delay delay? deliver denominator deref derive descendants destructure disj disj! dissoc &quot; +
+        &quot;dissoc! distinct distinct? doall dorun doseq dosync dotimes doto double double-array doubles drop drop-last &quot; +
+        &quot;drop-while eduction empty empty? ensure enumeration-seq error-handler error-mode eval even? every-pred every? ex-data ex-info &quot; +
+        &quot;extend extend-protocol extend-type extenders extends? false? ffirst file-seq filter filterv find find-keyword &quot; +
+        &quot;find-ns find-protocol-impl find-protocol-method find-var first flatten float float-array float? floats flush fn fn? &quot; +
+        &quot;fnext fnil for force format frequencies future future-call future-cancel future-cancelled? future-done? future? &quot; +
+        &quot;gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator group-by hash &quot; +
+        &quot;hash-combine hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc inc' init-proxy instance? &quot; +
+        &quot;int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt keep &quot; +
+        &quot;keep-indexed key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file &quot; +
+        &quot;load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array &quot; +
+        &quot;make-hierarchy map map-indexed map? mapcat mapv max max-key memfn memoize merge merge-with meta method-sig methods &quot; +
+        &quot;min min-key mod munge name namespace namespace-munge neg? newline next nfirst nil? nnext not not-any? not-empty &quot; +
+        &quot;not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias &quot; +
+        &quot;ns-unmap nth nthnext nthrest num number? numerator object-array odd? or parents partial partition partition-all &quot; +
+        &quot;partition-by pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers &quot; +
+        &quot;primitives-classnames print print-ctor print-dup print-method print-simple print-str printf println println-str &quot; +
+        &quot;prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues &quot; +
+        &quot;quot rand rand-int rand-nth random-sample range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern &quot; +
+        &quot;re-seq read read-line read-string realized? reduce reduce-kv reductions ref ref-history-count ref-max-history &quot; +
+        &quot;ref-min-history ref-set refer refer-clojure reify release-pending-sends rem remove remove-all-methods &quot; +
+        &quot;remove-method remove-ns remove-watch repeat repeatedly replace replicate require reset! reset-meta! resolve rest &quot; +
+        &quot;restart-agent resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? &quot; +
+        &quot;seque sequence sequential? set set-error-handler! set-error-mode! set-validator! set? short short-array shorts &quot; +
+        &quot;shuffle shutdown-agents slurp some some-fn sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? &quot; +
+        &quot;special-symbol? spit split-at split-with str string? struct struct-map subs subseq subvec supers swap! symbol &quot; +
+        &quot;symbol? sync take take-last take-nth take-while test the-ns thread-bound? time to-array to-array-2d trampoline transduce &quot; +
+        &quot;transient tree-seq true? type unchecked-add unchecked-add-int unchecked-byte unchecked-char unchecked-dec &quot; +
+        &quot;unchecked-dec-int unchecked-divide-int unchecked-double unchecked-float unchecked-inc unchecked-inc-int &quot; +
+        &quot;unchecked-int unchecked-long unchecked-multiply unchecked-multiply-int unchecked-negate unchecked-negate-int &quot;+
+        &quot;unchecked-remainder-int unchecked-short unchecked-subtract unchecked-subtract-int underive unquote &quot; +
+        &quot;unquote-splicing update update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector-of &quot; +
+        &quot;vector? volatile! volatile? vreset! vswap! when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context &quot; +
+        &quot;with-local-vars with-meta with-open with-out-str with-precision with-redefs with-redefs-fn xml-seq zero? zipmap &quot; +
+        &quot;*default-data-reader-fn* as-&gt; cond-&gt; cond-&gt;&gt; reduced reduced? send-via set-agent-send-executor! &quot; +
+        &quot;set-agent-send-off-executor! some-&gt; some-&gt;&gt;&quot;);
</ins><span class="cx"> 
</span><span class="cx">     var indentKeys = makeKeywords(
</span><span class="cx">         // Built-ins
</span><del>-        &quot;ns fn def defn defmethod bound-fn if if-not case condp when while when-not when-first do future comment doto locking proxy with-open with-precision reify deftype defrecord defprotocol extend extend-protocol extend-type try catch &quot; +
</del><ins>+        &quot;ns fn def defn defmethod bound-fn if if-not case condp when while when-not when-first do future comment doto &quot; +
+        &quot;locking proxy with-open with-precision reify deftype defrecord defprotocol extend extend-protocol extend-type &quot; +
+        &quot;try catch &quot; +
</ins><span class="cx"> 
</span><span class="cx">         // Binding forms
</span><span class="cx">         &quot;let letfn binding loop for doseq dotimes when-let if-let &quot; +
</span><span class="lines">@@ -59,7 +115,8 @@
</span><span class="cx">         sign: /[+-]/,
</span><span class="cx">         exponent: /e/i,
</span><span class="cx">         keyword_char: /[^\s\(\[\;\)\]]/,
</span><del>-        symbol: /[\w*+!\-\._?:&lt;&gt;\/\xa1-\uffff]/
</del><ins>+        symbol: /[\w*+!\-\._?:&lt;&gt;\/\xa1-\uffff]/,
+        block_indent: /^(?:def|with)[^\/]+$|\/(?:def|with)/
</ins><span class="cx">     };
</span><span class="cx"> 
</span><span class="cx">     function stateStack(indent, type, prev) { // represents a state stack object
</span><span class="lines">@@ -96,6 +153,9 @@
</span><span class="cx">             if ( '.' == stream.peek() ) {
</span><span class="cx">                 stream.eat('.');
</span><span class="cx">                 stream.eatWhile(tests.digit);
</span><ins>+            } else if ('/' == stream.peek() ) {
+                stream.eat('/');
+                stream.eatWhile(tests.digit);
</ins><span class="cx">             }
</span><span class="cx"> 
</span><span class="cx">             if ( stream.eat(tests.exponent) ) {
</span><span class="lines">@@ -139,7 +199,7 @@
</span><span class="cx">             }
</span><span class="cx"> 
</span><span class="cx">             // skip spaces
</span><del>-            if (stream.eatSpace()) {
</del><ins>+            if (state.mode != &quot;string&quot; &amp;&amp; stream.eatSpace()) {
</ins><span class="cx">                 return null;
</span><span class="cx">             }
</span><span class="cx">             var returnType = null;
</span><span class="lines">@@ -187,7 +247,7 @@
</span><span class="cx">                         }
</span><span class="cx"> 
</span><span class="cx">                         if (keyWord.length &gt; 0 &amp;&amp; (indentKeys.propertyIsEnumerable(keyWord) ||
</span><del>-                                                   /^(?:def|with)/.test(keyWord))) { // indent-word
</del><ins>+                                                   tests.block_indent.test(keyWord))) { // indent-word
</ins><span class="cx">                             pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
</span><span class="cx">                         } else { // non-indent word
</span><span class="cx">                             // we continue eating the spaces
</span><span class="lines">@@ -240,5 +300,7 @@
</span><span class="cx"> });
</span><span class="cx"> 
</span><span class="cx"> CodeMirror.defineMIME(&quot;text/x-clojure&quot;, &quot;clojure&quot;);
</span><ins>+CodeMirror.defineMIME(&quot;text/x-clojurescript&quot;, &quot;clojure&quot;);
+CodeMirror.defineMIME(&quot;application/edn&quot;, &quot;clojure&quot;);
</ins><span class="cx"> 
</span><span class="cx"> });
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorclosebracketsjs"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/closebrackets.js (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/closebrackets.js        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/closebrackets.js        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -63,7 +63,7 @@
</span><span class="cx">     }
</span><span class="cx">     for (var i = ranges.length - 1; i &gt;= 0; i--) {
</span><span class="cx">       var cur = ranges[i].head;
</span><del>-      cm.replaceRange(&quot;&quot;, Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1));
</del><ins>+      cm.replaceRange(&quot;&quot;, Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), &quot;+delete&quot;);
</ins><span class="cx">     }
</span><span class="cx">   }
</span><span class="cx"> 
</span><span class="lines">@@ -90,6 +90,12 @@
</span><span class="cx">     });
</span><span class="cx">   }
</span><span class="cx"> 
</span><ins>+  function contractSelection(sel) {
+    var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) &gt; 0;
+    return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)),
+            head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))};
+  }
+
</ins><span class="cx">   function handleChar(cm, ch) {
</span><span class="cx">     var conf = getConfig(cm);
</span><span class="cx">     if (!conf || cm.getOption(&quot;disableInput&quot;)) return CodeMirror.Pass;
</span><span class="lines">@@ -103,7 +109,7 @@
</span><span class="cx">     var ranges = cm.listSelections();
</span><span class="cx">     var opening = pos % 2 == 0;
</span><span class="cx"> 
</span><del>-    var type, next;
</del><ins>+    var type;
</ins><span class="cx">     for (var i = 0; i &lt; ranges.length; i++) {
</span><span class="cx">       var range = ranges[i], cur = range.head, curType;
</span><span class="cx">       var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
</span><span class="lines">@@ -110,7 +116,9 @@
</span><span class="cx">       if (opening &amp;&amp; !range.empty()) {
</span><span class="cx">         curType = &quot;surround&quot;;
</span><span class="cx">       } else if ((identical || !opening) &amp;&amp; next == ch) {
</span><del>-        if (triples.indexOf(ch) &gt;= 0 &amp;&amp; cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
</del><ins>+        if (identical &amp;&amp; stringStartsAfter(cm, cur))
+          curType = &quot;both&quot;;
+        else if (triples.indexOf(ch) &gt;= 0 &amp;&amp; cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
</ins><span class="cx">           curType = &quot;skipThree&quot;;
</span><span class="cx">         else
</span><span class="cx">           curType = &quot;skip&quot;;
</span><span class="lines">@@ -145,6 +153,10 @@
</span><span class="cx">         for (var i = 0; i &lt; sels.length; i++)
</span><span class="cx">           sels[i] = left + sels[i] + right;
</span><span class="cx">         cm.replaceSelections(sels, &quot;around&quot;);
</span><ins>+        sels = cm.listSelections().slice();
+        for (var i = 0; i &lt; sels.length; i++)
+          sels[i] = contractSelection(sels[i]);
+        cm.setSelections(sels);
</ins><span class="cx">       } else if (type == &quot;both&quot;) {
</span><span class="cx">         cm.replaceSelection(left + right, null);
</span><span class="cx">         cm.triggerElectric(left + right);
</span><span class="lines">@@ -182,4 +194,9 @@
</span><span class="cx">       stream.start = stream.pos;
</span><span class="cx">     }
</span><span class="cx">   }
</span><ins>+
+  function stringStartsAfter(cm, pos) {
+    var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1))
+    return /\bstring/.test(token.type) &amp;&amp; token.start == pos.ch
+  }
</ins><span class="cx"> });
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorcodemirrorcss"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/codemirror.css (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/codemirror.css        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/codemirror.css        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -52,7 +52,7 @@
</span><span class="cx"> }
</span><span class="cx"> .cm-fat-cursor .CodeMirror-cursor {
</span><span class="cx">   width: auto;
</span><del>-  border: 0;
</del><ins>+  border: 0 !important;
</ins><span class="cx">   background: #7e7;
</span><span class="cx"> }
</span><span class="cx"> .cm-fat-cursor div.CodeMirror-cursors {
</span><span class="lines">@@ -88,8 +88,14 @@
</span><span class="cx"> 
</span><span class="cx"> .cm-tab { display: inline-block; text-decoration: inherit; }
</span><span class="cx"> 
</span><ins>+.CodeMirror-rulers {
+  position: absolute;
+  left: 0; right: 0; top: -50px; bottom: -20px;
+  overflow: hidden;
+}
</ins><span class="cx"> .CodeMirror-ruler {
</span><span class="cx">   border-left: 1px solid #ccc;
</span><ins>+  top: 0; bottom: 0;
</ins><span class="cx">   position: absolute;
</span><span class="cx"> }
</span><span class="cx"> 
</span><span class="lines">@@ -165,7 +171,7 @@
</span><span class="cx"> }
</span><span class="cx"> 
</span><span class="cx"> /* The fake, visible scrollbars. Used to force redraw during scrolling
</span><del>-   before actuall scrolling happens, thus preventing shaking and
</del><ins>+   before actual scrolling happens, thus preventing shaking and
</ins><span class="cx">    flickering artifacts. */
</span><span class="cx"> .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
</span><span class="cx">   position: absolute;
</span><span class="lines">@@ -191,6 +197,7 @@
</span><span class="cx"> 
</span><span class="cx"> .CodeMirror-gutters {
</span><span class="cx">   position: absolute; left: 0; top: 0;
</span><ins>+  min-height: 100%;
</ins><span class="cx">   z-index: 3;
</span><span class="cx"> }
</span><span class="cx"> .CodeMirror-gutter {
</span><span class="lines">@@ -197,10 +204,8 @@
</span><span class="cx">   white-space: normal;
</span><span class="cx">   height: 100%;
</span><span class="cx">   display: inline-block;
</span><ins>+  vertical-align: top;
</ins><span class="cx">   margin-bottom: -30px;
</span><del>-  /* Hack to make IE7 behave */
-  *zoom:1;
-  *display:inline;
</del><span class="cx"> }
</span><span class="cx"> .CodeMirror-gutter-wrapper {
</span><span class="cx">   position: absolute;
</span><span class="lines">@@ -244,6 +249,8 @@
</span><span class="cx">   position: relative;
</span><span class="cx">   overflow: visible;
</span><span class="cx">   -webkit-tap-highlight-color: transparent;
</span><ins>+  -webkit-font-variant-ligatures: contextual;
+  font-variant-ligatures: contextual;
</ins><span class="cx"> }
</span><span class="cx"> .CodeMirror-wrap pre {
</span><span class="cx">   word-wrap: break-word;
</span><span class="lines">@@ -287,7 +294,10 @@
</span><span class="cx">   visibility: hidden;
</span><span class="cx"> }
</span><span class="cx"> 
</span><del>-.CodeMirror-cursor { position: absolute; }
</del><ins>+.CodeMirror-cursor {
+  position: absolute;
+  pointer-events: none;
+}
</ins><span class="cx"> .CodeMirror-measure pre { position: static; }
</span><span class="cx"> 
</span><span class="cx"> div.CodeMirror-cursors {
</span><span class="lines">@@ -314,9 +324,6 @@
</span><span class="cx">   background: rgba(255, 255, 0, .4);
</span><span class="cx"> }
</span><span class="cx"> 
</span><del>-/* IE7 hack to prevent it from returning funny offsetTops on the spans */
-.CodeMirror span { *vertical-align: text-bottom; }
-
</del><span class="cx"> /* Used to force a border model for a node */
</span><span class="cx"> .cm-force-border { padding-right: .1px; }
</span><span class="cx"> 
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorcodemirrorjs"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/codemirror.js (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/codemirror.js        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/codemirror.js        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -7,4878 +7,7677 @@
</span><span class="cx"> // You can find some technical background for some of the code below
</span><span class="cx"> // at http://marijnhaverbeke.nl/blog/#cm-internals .
</span><span class="cx"> 
</span><del>-(function(mod) {
-  if (typeof exports == &quot;object&quot; &amp;&amp; typeof module == &quot;object&quot;) // CommonJS
-    module.exports = mod();
-  else if (typeof define == &quot;function&quot; &amp;&amp; define.amd) // AMD
-    return define([], mod);
-  else // Plain browser env
-    this.CodeMirror = mod();
-})(function() {
-  &quot;use strict&quot;;
</del><ins>+(function (global, factory) {
+  typeof exports === 'object' &amp;&amp; typeof module !== 'undefined' ? module.exports = factory() :
+  typeof define === 'function' &amp;&amp; define.amd ? define(factory) :
+  (global.CodeMirror = factory());
+}(this, (function () { 'use strict';
</ins><span class="cx"> 
</span><del>-  // BROWSER SNIFFING
</del><ins>+// 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
</ins><span class="cx"> 
</span><del>-  // Kludges for bugs and behavior differences that can't be feature
-  // detected are enabled based on userAgent etc sniffing.
</del><ins>+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 &amp;&amp; (ie_upto10 ? document.documentMode || 6 : ie_11up[1])
+var webkit = /WebKit\//.test(userAgent)
+var qtwebkit = webkit &amp;&amp; /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)
</ins><span class="cx"> 
</span><del>-  var gecko = /gecko\/\d/i.test(navigator.userAgent);
-  var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
-  var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
-  var ie = ie_upto10 || ie_11up;
-  var ie_version = ie &amp;&amp; (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
-  var webkit = /WebKit\//.test(navigator.userAgent);
-  var qtwebkit = webkit &amp;&amp; /Qt\/\d+\.\d+/.test(navigator.userAgent);
-  var chrome = /Chrome\//.test(navigator.userAgent);
-  var presto = /Opera\//.test(navigator.userAgent);
-  var safari = /Apple Computer/.test(navigator.vendor);
-  var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
-  var phantom = /PhantomJS/.test(navigator.userAgent);
</del><ins>+var ios = /AppleWebKit/.test(userAgent) &amp;&amp; /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)
</ins><span class="cx"> 
</span><del>-  var ios = /AppleWebKit/.test(navigator.userAgent) &amp;&amp; /Mobile\/\w+/.test(navigator.userAgent);
-  // This is woefully incomplete. Suggestions for alternative methods welcome.
-  var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
-  var mac = ios || /Mac/.test(navigator.platform);
-  var windows = /win/i.test(navigator.platform);
</del><ins>+var presto_version = presto &amp;&amp; userAgent.match(/Version\/(\d*\.\d*)/)
+if (presto_version) { presto_version = Number(presto_version[1]) }
+if (presto_version &amp;&amp; presto_version &gt;= 15) { presto = false; webkit = true }
+// Some browsers use the wrong event properties to signal cmd/ctrl on OS X
+var flipCtrlCmd = mac &amp;&amp; (qtwebkit || presto &amp;&amp; (presto_version == null || presto_version &lt; 12.11))
+var captureRightClick = gecko || (ie &amp;&amp; ie_version &gt;= 9)
</ins><span class="cx"> 
</span><del>-  var presto_version = presto &amp;&amp; navigator.userAgent.match(/Version\/(\d*\.\d*)/);
-  if (presto_version) presto_version = Number(presto_version[1]);
-  if (presto_version &amp;&amp; presto_version &gt;= 15) { presto = false; webkit = true; }
-  // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
-  var flipCtrlCmd = mac &amp;&amp; (qtwebkit || presto &amp;&amp; (presto_version == null || presto_version &lt; 12.11));
-  var captureRightClick = gecko || (ie &amp;&amp; ie_version &gt;= 9);
</del><ins>+function classTest(cls) { return new RegExp(&quot;(^|\\s)&quot; + cls + &quot;(?:$|\\s)\\s*&quot;) }
</ins><span class="cx"> 
</span><del>-  // Optimize some code when these features are not used.
-  var sawReadOnlySpans = false, sawCollapsedSpans = false;
</del><ins>+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 : &quot;&quot;)
+  }
+}
</ins><span class="cx"> 
</span><del>-  // EDITOR CONSTRUCTOR
</del><ins>+function removeChildren(e) {
+  for (var count = e.childNodes.length; count &gt; 0; --count)
+    { e.removeChild(e.firstChild) }
+  return e
+}
</ins><span class="cx"> 
</span><del>-  // A CodeMirror instance represents an editor. This is the object
-  // that user code is usually dealing with.
</del><ins>+function removeChildrenAndAdd(parent, e) {
+  return removeChildren(parent).appendChild(e)
+}
</ins><span class="cx"> 
</span><del>-  function CodeMirror(place, options) {
-    if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
</del><ins>+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 == &quot;string&quot;) { e.appendChild(document.createTextNode(content)) }
+  else if (content) { for (var i = 0; i &lt; content.length; ++i) { e.appendChild(content[i]) } }
+  return e
+}
</ins><span class="cx"> 
</span><del>-    this.options = options = options ? copyObj(options) : {};
-    // Determine effective options based on given values and defaults.
-    copyObj(defaults, options, false);
-    setGuttersForLineNumbers(options);
</del><ins>+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(&quot;character&quot;, end)
+  r.moveStart(&quot;character&quot;, start)
+  return r
+} }
</ins><span class="cx"> 
</span><del>-    var doc = options.value;
-    if (typeof doc == &quot;string&quot;) doc = new Doc(doc, options.mode, null, options.lineSeparator);
-    this.doc = doc;
</del><ins>+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)
+}
</ins><span class="cx"> 
</span><del>-    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 += &quot; CodeMirror-wrap&quot;;
-    if (options.autofocus &amp;&amp; !mobile) display.input.focus();
-    initScrollbars(this);
</del><ins>+function activeElt() {
+  // IE and Edge may throw an &quot;Unspecified Error&quot; when accessing document.activeElement.
+  // IE &lt; 10 will throw when accessed while the page is loading or in an iframe.
+  // IE &gt; 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 &amp;&amp; activeElement.root &amp;&amp; activeElement.root.activeElement)
+    { activeElement = activeElement.root.activeElement }
+  return activeElement
+}
</ins><span class="cx"> 
</span><del>-    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
-    };
</del><ins>+function addClass(node, cls) {
+  var current = node.className
+  if (!classTest(cls).test(current)) { node.className += (current ? &quot; &quot; : &quot;&quot;) + cls }
+}
+function joinClasses(a, b) {
+  var as = a.split(&quot; &quot;)
+  for (var i = 0; i &lt; as.length; i++)
+    { if (as[i] &amp;&amp; !classTest(as[i]).test(b)) { b += &quot; &quot; + as[i] } }
+  return b
+}
</ins><span class="cx"> 
</span><del>-    var cm = this;
</del><ins>+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) {} } }
</ins><span class="cx"> 
</span><del>-    // Override magic textarea content restore that IE sometimes does
-    // on our hidden textarea on reload
-    if (ie &amp;&amp; ie_version &lt; 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
</del><ins>+function bind(f) {
+  var args = Array.prototype.slice.call(arguments, 1)
+  return function(){return f.apply(null, args)}
+}
</ins><span class="cx"> 
</span><del>-    registerEventHandlers(this);
-    ensureGlobalHandlers();
</del><ins>+function copyObj(obj, target, overwrite) {
+  if (!target) { target = {} }
+  for (var prop in obj)
+    { if (obj.hasOwnProperty(prop) &amp;&amp; (overwrite !== false || !target.hasOwnProperty(prop)))
+      { target[prop] = obj[prop] } }
+  return target
+}
</ins><span class="cx"> 
</span><del>-    startOperation(this);
-    this.curOp.forceUpdate = true;
-    attachDoc(this, doc);
</del><ins>+// 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(&quot;\t&quot;, i)
+    if (nextTab &lt; 0 || nextTab &gt;= end)
+      { return n + (end - i) }
+    n += nextTab - i
+    n += tabSize - (n % tabSize)
+    i = nextTab + 1
+  }
+}
</ins><span class="cx"> 
</span><del>-    if ((options.autofocus &amp;&amp; !mobile) || cm.hasFocus())
-      setTimeout(bind(onFocus, this), 20);
-    else
-      onBlur(this);
</del><ins>+function Delayed() {this.id = null}
+Delayed.prototype.set = function(ms, f) {
+  clearTimeout(this.id)
+  this.id = setTimeout(f, ms)
+}
</ins><span class="cx"> 
</span><del>-    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 &lt; initHooks.length; ++i) initHooks[i](this);
-    endOperation(this);
-    // Suppress optimizelegibility in Webkit, since it breaks text
-    // measuring on line wrapping boundaries.
-    if (webkit &amp;&amp; options.lineWrapping &amp;&amp;
-        getComputedStyle(display.lineDiv).textRendering == &quot;optimizelegibility&quot;)
-      display.lineDiv.style.textRendering = &quot;auto&quot;;
-  }
</del><ins>+function indexOf(array, elt) {
+  for (var i = 0; i &lt; array.length; ++i)
+    { if (array[i] == elt) { return i } }
+  return -1
+}
</ins><span class="cx"> 
</span><del>-  // DISPLAY CONSTRUCTOR
</del><ins>+// Number of pixels added to scroller and sizer to hide scrollbar
+var scrollerGap = 30
</ins><span class="cx"> 
</span><del>-  // The display handles the DOM integration, both for input reading
-  // and content drawing. It holds references to DOM nodes and
-  // display-related state.
</del><ins>+// Returned or thrown by various protocols to signal 'I'm not
+// handling this'.
+var Pass = {toString: function(){return &quot;CodeMirror.Pass&quot;}}
</ins><span class="cx"> 
</span><del>-  function Display(place, doc, input) {
-    var d = this;
-    this.input = input;
</del><ins>+// Reused option objects for setSelection &amp; friends
+var sel_dontScroll = {scroll: false};
+var sel_mouse = {origin: &quot;*mouse&quot;};
+var sel_move = {origin: &quot;+move&quot;};
+// 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(&quot;\t&quot;, pos)
+    if (nextTab == -1) { nextTab = string.length }
+    var skipped = nextTab - pos
+    if (nextTab == string.length || col + skipped &gt;= goal)
+      { return pos + Math.min(skipped, goal - col) }
+    col += nextTab - pos
+    col += tabSize - (col % tabSize)
+    pos = nextTab + 1
+    if (col &gt;= goal) { return pos }
+  }
+}
</ins><span class="cx"> 
</span><del>-    // Covers bottom-right square when both scrollbars are present.
-    d.scrollbarFiller = elt(&quot;div&quot;, null, &quot;CodeMirror-scrollbar-filler&quot;);
-    d.scrollbarFiller.setAttribute(&quot;cm-not-content&quot;, &quot;true&quot;);
-    // Covers bottom of gutter when coverGutterNextToScrollbar is on
-    // and h scrollbar is present.
-    d.gutterFiller = elt(&quot;div&quot;, null, &quot;CodeMirror-gutter-filler&quot;);
-    d.gutterFiller.setAttribute(&quot;cm-not-content&quot;, &quot;true&quot;);
-    // Will contain the actual code, positioned to cover the viewport.
-    d.lineDiv = elt(&quot;div&quot;, null, &quot;CodeMirror-code&quot;);
-    // Elements are added to these to represent selection and cursors.
-    d.selectionDiv = elt(&quot;div&quot;, null, null, &quot;position: relative; z-index: 1&quot;);
-    d.cursorDiv = elt(&quot;div&quot;, null, &quot;CodeMirror-cursors&quot;);
-    // A visibility: hidden element used to find the size of things.
-    d.measure = elt(&quot;div&quot;, null, &quot;CodeMirror-measure&quot;);
-    // When lines outside of the viewport are measured, they are drawn in this.
-    d.lineMeasure = elt(&quot;div&quot;, null, &quot;CodeMirror-measure&quot;);
-    // Wraps everything that needs to exist inside the vertically-padded coordinate system
-    d.lineSpace = elt(&quot;div&quot;, [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
-                      null, &quot;position: relative; outline: none&quot;);
-    // Moved around its parent to cover visible view.
-    d.mover = elt(&quot;div&quot;, [elt(&quot;div&quot;, [d.lineSpace], &quot;CodeMirror-lines&quot;)], null, &quot;position: relative&quot;);
-    // Set to the height of the document, allowing scrolling.
-    d.sizer = elt(&quot;div&quot;, [d.mover], &quot;CodeMirror-sizer&quot;);
-    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(&quot;div&quot;, null, null, &quot;position: absolute; height: &quot; + scrollerGap + &quot;px; width: 1px;&quot;);
-    // Will contain the gutters, if any.
-    d.gutters = elt(&quot;div&quot;, null, &quot;CodeMirror-gutters&quot;);
-    d.lineGutter = null;
-    // Actual scrollable element.
-    d.scroller = elt(&quot;div&quot;, [d.sizer, d.heightForcer, d.gutters], &quot;CodeMirror-scroll&quot;);
-    d.scroller.setAttribute(&quot;tabIndex&quot;, &quot;-1&quot;);
-    // The element in which the editor lives.
-    d.wrapper = elt(&quot;div&quot;, [d.scrollbarFiller, d.gutterFiller, d.scroller], &quot;CodeMirror&quot;);
</del><ins>+var spaceStrs = [&quot;&quot;]
+function spaceStr(n) {
+  while (spaceStrs.length &lt;= n)
+    { spaceStrs.push(lst(spaceStrs) + &quot; &quot;) }
+  return spaceStrs[n]
+}
</ins><span class="cx"> 
</span><del>-    // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
-    if (ie &amp;&amp; ie_version &lt; 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
-    if (!webkit &amp;&amp; !(gecko &amp;&amp; mobile)) d.scroller.draggable = true;
</del><ins>+function lst(arr) { return arr[arr.length-1] }
</ins><span class="cx"> 
</span><del>-    if (place) {
-      if (place.appendChild) place.appendChild(d.wrapper);
-      else place(d.wrapper);
-    }
</del><ins>+function map(array, f) {
+  var out = []
+  for (var i = 0; i &lt; array.length; i++) { out[i] = f(array[i], i) }
+  return out
+}
</ins><span class="cx"> 
</span><del>-    // 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;
</del><ins>+function insertSorted(array, value, score) {
+  var pos = 0, priority = score(value)
+  while (pos &lt; array.length &amp;&amp; score(array[pos]) &lt;= priority) { pos++ }
+  array.splice(pos, 0, value)
+}
</ins><span class="cx"> 
</span><del>-    d.nativeBarWidth = d.barHeight = d.barWidth = 0;
-    d.scrollbarsClipped = false;
</del><ins>+function nothing() {}
</ins><span class="cx"> 
</span><del>-    // 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;
</del><ins>+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
+}
</ins><span class="cx"> 
</span><del>-    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
</del><ins>+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 &gt; &quot;\x80&quot; &amp;&amp;
+    (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
+}
+function isWordChar(ch, helper) {
+  if (!helper) { return isWordCharBasic(ch) }
+  if (helper.source.indexOf(&quot;\\w&quot;) &gt; -1 &amp;&amp; isWordCharBasic(ch)) { return true }
+  return helper.test(ch)
+}
</ins><span class="cx"> 
</span><del>-    // 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;
</del><ins>+function isEmpty(obj) {
+  for (var n in obj) { if (obj.hasOwnProperty(n) &amp;&amp; obj[n]) { return false } }
+  return true
+}
</ins><span class="cx"> 
</span><del>-    // Used for measuring wheel scrolling granularity
-    d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
</del><ins>+// 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-\u
 0f97\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) &gt;= 768 &amp;&amp; extendingChars.test(ch) }
</ins><span class="cx"> 
</span><del>-    // True when shift is held down.
-    d.shift = false;
</del><ins>+// The display handles the DOM integration, both for input reading
+// and content drawing. It holds references to DOM nodes and
+// display-related state.
</ins><span class="cx"> 
</span><del>-    // Used to track whether anything happened since the context menu
-    // was opened.
-    d.selForContextMenu = null;
</del><ins>+function Display(place, doc, input) {
+  var d = this
+  this.input = input
</ins><span class="cx"> 
</span><del>-    d.activeTouch = null;
</del><ins>+  // Covers bottom-right square when both scrollbars are present.
+  d.scrollbarFiller = elt(&quot;div&quot;, null, &quot;CodeMirror-scrollbar-filler&quot;)
+  d.scrollbarFiller.setAttribute(&quot;cm-not-content&quot;, &quot;true&quot;)
+  // Covers bottom of gutter when coverGutterNextToScrollbar is on
+  // and h scrollbar is present.
+  d.gutterFiller = elt(&quot;div&quot;, null, &quot;CodeMirror-gutter-filler&quot;)
+  d.gutterFiller.setAttribute(&quot;cm-not-content&quot;, &quot;true&quot;)
+  // Will contain the actual code, positioned to cover the viewport.
+  d.lineDiv = elt(&quot;div&quot;, null, &quot;CodeMirror-code&quot;)
+  // Elements are added to these to represent selection and cursors.
+  d.selectionDiv = elt(&quot;div&quot;, null, null, &quot;position: relative; z-index: 1&quot;)
+  d.cursorDiv = elt(&quot;div&quot;, null, &quot;CodeMirror-cursors&quot;)
+  // A visibility: hidden element used to find the size of things.
+  d.measure = elt(&quot;div&quot;, null, &quot;CodeMirror-measure&quot;)
+  // When lines outside of the viewport are measured, they are drawn in this.
+  d.lineMeasure = elt(&quot;div&quot;, null, &quot;CodeMirror-measure&quot;)
+  // Wraps everything that needs to exist inside the vertically-padded coordinate system
+  d.lineSpace = elt(&quot;div&quot;, [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
+                    null, &quot;position: relative; outline: none&quot;)
+  // Moved around its parent to cover visible view.
+  d.mover = elt(&quot;div&quot;, [elt(&quot;div&quot;, [d.lineSpace], &quot;CodeMirror-lines&quot;)], null, &quot;position: relative&quot;)
+  // Set to the height of the document, allowing scrolling.
+  d.sizer = elt(&quot;div&quot;, [d.mover], &quot;CodeMirror-sizer&quot;)
+  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(&quot;div&quot;, null, null, &quot;position: absolute; height: &quot; + scrollerGap + &quot;px; width: 1px;&quot;)
+  // Will contain the gutters, if any.
+  d.gutters = elt(&quot;div&quot;, null, &quot;CodeMirror-gutters&quot;)
+  d.lineGutter = null
+  // Actual scrollable element.
+  d.scroller = elt(&quot;div&quot;, [d.sizer, d.heightForcer, d.gutters], &quot;CodeMirror-scroll&quot;)
+  d.scroller.setAttribute(&quot;tabIndex&quot;, &quot;-1&quot;)
+  // The element in which the editor lives.
+  d.wrapper = elt(&quot;div&quot;, [d.scrollbarFiller, d.gutterFiller, d.scroller], &quot;CodeMirror&quot;)
</ins><span class="cx"> 
</span><del>-    input.init(d);
</del><ins>+  // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
+  if (ie &amp;&amp; ie_version &lt; 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 }
+  if (!webkit &amp;&amp; !(gecko &amp;&amp; mobile)) { d.scroller.draggable = true }
+
+  if (place) {
+    if (place.appendChild) { place.appendChild(d.wrapper) }
+    else { place(d.wrapper) }
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // STATE UPDATES
</del><ins>+  // 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
</ins><span class="cx"> 
</span><del>-  // Used to get the editor into a consistent state again when options change.
</del><ins>+  d.nativeBarWidth = d.barHeight = d.barWidth = 0
+  d.scrollbarsClipped = false
</ins><span class="cx"> 
</span><del>-  function loadMode(cm) {
-    cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
-    resetModeState(cm);
</del><ins>+  // 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 &lt; 0 || n &gt;= doc.size) { throw new Error(&quot;There is no line &quot; + (n + doc.first) + &quot; in the document.&quot;) }
+  var chunk = doc
+  while (!chunk.lines) {
+    for (var i = 0;; ++i) {
+      var child = chunk.children[i], sz = child.chunkSize()
+      if (n &lt; sz) { chunk = child; break }
+      n -= sz
+    }
</ins><span class="cx">   }
</span><ins>+  return chunk.lines[n]
+}
</ins><span class="cx"> 
</span><del>-  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);
</del><ins>+// 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()
+    }
</ins><span class="cx">   }
</span><ins>+  return no + cur.first
+}
</ins><span class="cx"> 
</span><del>-  function wrappingChanged(cm) {
-    if (cm.options.lineWrapping) {
-      addClass(cm.display.wrapper, &quot;CodeMirror-wrap&quot;);
-      cm.display.sizer.style.minWidth = &quot;&quot;;
-      cm.display.sizerWidth = null;
-    } else {
-      rmClass(cm.display.wrapper, &quot;CodeMirror-wrap&quot;);
-      findMaxLine(cm);
</del><ins>+// 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 &lt; chunk.children.length; ++i$1) {
+      var child = chunk.children[i$1], ch = child.height
+      if (h &lt; ch) { chunk = child; continue outer }
+      h -= ch
+      n += child.chunkSize()
</ins><span class="cx">     }
</span><del>-    estimateLineHeights(cm);
-    regChange(cm);
-    clearCaches(cm);
-    setTimeout(function(){updateScrollbars(cm);}, 100);
</del><ins>+    return n
+  } while (!chunk.lines)
+  var i = 0
+  for (; i &lt; chunk.lines.length; ++i) {
+    var line = chunk.lines[i], lh = line.height
+    if (h &lt; lh) { break }
+    h -= lh
</ins><span class="cx">   }
</span><ins>+  return n + i
+}
</ins><span class="cx"> 
</span><del>-  // 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 &amp;&amp; Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
-    return function(line) {
-      if (lineIsHidden(cm.doc, line)) return 0;
</del><ins>+function isLine(doc, l) {return l &gt;= doc.first &amp;&amp; l &lt; doc.first + doc.size}
</ins><span class="cx"> 
</span><del>-      var widgetsHeight = 0;
-      if (line.widgets) for (var i = 0; i &lt; line.widgets.length; i++) {
-        if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
</del><ins>+function lineNumberFor(options, i) {
+  return String(options.lineNumberFormatter(i + options.firstLineNumber))
+}
+
+// A Pos instance represents a position within the text.
+function Pos (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.
+function cmp(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) &lt; 0 ? b : a }
+function minPos(a, b) { return cmp(a, b) &lt; 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 &lt; doc.first) { return Pos(doc.first, 0) }
+  var last = doc.first + doc.size - 1
+  if (pos.line &gt; 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 &gt; linelen) { return Pos(pos.line, linelen) }
+  else if (ch &lt; 0) { return Pos(pos.line, 0) }
+  else { return pos }
+}
+function clipPosArray(doc, array) {
+  var out = []
+  for (var i = 0; i &lt; 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 &lt; 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 &lt; 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 &lt; old.length; ++i) {
+    var span = old[i], marker = span.marker
+    var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from &lt;= startCh : span.from &lt; startCh)
+    if (startsBefore || span.from == startCh &amp;&amp; marker.type == &quot;bookmark&quot; &amp;&amp; (!isInsert || !span.marker.insertLeft)) {
+      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to &gt;= startCh : span.to &gt; 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 &lt; old.length; ++i) {
+    var span = old[i], marker = span.marker
+    var endsAfter = span.to == null || (marker.inclusiveRight ? span.to &gt;= endCh : span.to &gt; endCh)
+    if (endsAfter || span.from == endCh &amp;&amp; marker.type == &quot;bookmark&quot; &amp;&amp; (!isInsert || span.marker.insertLeft)) {
+      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from &lt;= endCh : span.from &lt; 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) &amp;&amp; getLine(doc, change.from.line).markedSpans
+  var oldLast = isLine(doc, change.to.line) &amp;&amp; getLine(doc, change.to.line).markedSpans
+  if (!oldFirst &amp;&amp; !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 &lt; 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 }
</ins><span class="cx">       }
</span><ins>+    }
+  }
+  if (last) {
+    // Fix up .from in last (or move them into first in case of sameLine)
+    for (var i$1 = 0; i$1 &lt; 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 &amp;&amp; last != first) { last = clearEmptySpans(last) }
</ins><span class="cx"> 
</span><del>-      if (wrapping)
-        return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
-      else
-        return widgetsHeight + th;
-    };
</del><ins>+  var newMarkers = [first]
+  if (!sameLine) {
+    // Fill gap with whole-line-spans
+    var gap = change.text.length - 2, gapMarkers
+    if (gap &gt; 0 &amp;&amp; first)
+      { for (var i$2 = 0; i$2 &lt; 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 &lt; gap; ++i$3)
+      { newMarkers.push(gapMarkers) }
+    newMarkers.push(last)
</ins><span class="cx">   }
</span><ins>+  return newMarkers
+}
</ins><span class="cx"> 
</span><del>-  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);
-    });
</del><ins>+// Remove spans that are empty and don't have a clearWhenEmpty
+// option of false.
+function clearEmptySpans(spans) {
+  for (var i = 0; i &lt; spans.length; ++i) {
+    var span = spans[i]
+    if (span.from != null &amp;&amp; span.from == span.to &amp;&amp; span.marker.clearWhenEmpty !== false)
+      { spans.splice(i--, 1) }
</ins><span class="cx">   }
</span><ins>+  if (!spans.length) { return null }
+  return spans
+}
</ins><span class="cx"> 
</span><del>-  function themeChanged(cm) {
-    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, &quot;&quot;) +
-      cm.options.theme.replace(/(^|\s)\s*/g, &quot; cm-s-&quot;);
-    clearCaches(cm);
</del><ins>+// 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 &lt; line.markedSpans.length; ++i) {
+      var mark = line.markedSpans[i].marker
+      if (mark.readOnly &amp;&amp; (!markers || indexOf(markers, mark) == -1))
+        { (markers || (markers = [])).push(mark) }
+    } }
+  })
+  if (!markers) { return null }
+  var parts = [{from: from, to: to}]
+  for (var i = 0; i &lt; markers.length; ++i) {
+    var mk = markers[i], m = mk.find(0)
+    for (var j = 0; j &lt; parts.length; ++j) {
+      var p = parts[j]
+      if (cmp(p.to, m.from) &lt; 0 || cmp(p.from, m.to) &gt; 0) { continue }
+      var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to)
+      if (dfrom &lt; 0 || !mk.inclusiveLeft &amp;&amp; !dfrom)
+        { newParts.push({from: p.from, to: m.from}) }
+      if (dto &gt; 0 || !mk.inclusiveRight &amp;&amp; !dto)
+        { newParts.push({from: m.to, to: p.to}) }
+      parts.splice.apply(parts, newParts)
+      j += newParts.length - 1
+    }
</ins><span class="cx">   }
</span><ins>+  return parts
+}
</ins><span class="cx"> 
</span><del>-  function guttersChanged(cm) {
-    updateGutters(cm);
-    regChange(cm);
-    setTimeout(function(){alignHorizontally(cm);}, 20);
</del><ins>+// Connect or disconnect spans from a line.
+function detachMarkedSpans(line) {
+  var spans = line.markedSpans
+  if (!spans) { return }
+  for (var i = 0; i &lt; spans.length; ++i)
+    { spans[i].marker.detachLine(line) }
+  line.markedSpans = null
+}
+function attachMarkedSpans(line, spans) {
+  if (!spans) { return }
+  for (var i = 0; i &lt; 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 &amp;&amp; line.markedSpans, found
+  if (sps) { for (var sp = (void 0), i = 0; i &lt; sps.length; ++i) {
+    sp = sps[i]
+    if (sp.marker.collapsed &amp;&amp; (start ? sp.from : sp.to) == null &amp;&amp;
+        (!found || compareCollapsedMarkers(found, sp.marker) &lt; 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 &amp;&amp; line.markedSpans
+  if (sps) { for (var i = 0; i &lt; 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 &gt;= 0 &amp;&amp; toCmp &lt;= 0 || fromCmp &lt;= 0 &amp;&amp; toCmp &gt;= 0) { continue }
+    if (fromCmp &lt;= 0 &amp;&amp; (sp.marker.inclusiveRight &amp;&amp; marker.inclusiveLeft ? cmp(found.to, from) &gt;= 0 : cmp(found.to, from) &gt; 0) ||
+        fromCmp &gt;= 0 &amp;&amp; (sp.marker.inclusiveRight &amp;&amp; marker.inclusiveLeft ? cmp(found.from, to) &lt;= 0 : cmp(found.from, to) &lt; 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
+}
+
+// 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)
</ins><span class="cx">   }
</span><ins>+  return lines
+}
</ins><span class="cx"> 
</span><del>-  // 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 &lt; specs.length; ++i) {
-      var gutterClass = specs[i];
-      var gElt = gutters.appendChild(elt(&quot;div&quot;, null, &quot;CodeMirror-gutter &quot; + gutterClass));
-      if (gutterClass == &quot;CodeMirror-linenumbers&quot;) {
-        cm.display.lineGutter = gElt;
-        gElt.style.width = (cm.display.lineNumWidth || 1) + &quot;px&quot;;
-      }
</del><ins>+// 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 &gt; 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 &amp;&amp; line.markedSpans
+  if (sps) { for (var sp = (void 0), i = 0; i &lt; 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 &amp;&amp; sp.marker.inclusiveLeft &amp;&amp; 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 &amp;&amp; span.to == line.text.length)
+    { return true }
+  for (var sp = (void 0), i = 0; i &lt; line.markedSpans.length; ++i) {
+    sp = line.markedSpans[i]
+    if (sp.marker.collapsed &amp;&amp; !sp.marker.widgetNode &amp;&amp; sp.from == span.to &amp;&amp;
+        (sp.to == null || sp.to != span.from) &amp;&amp;
+        (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &amp;&amp;
+        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 &lt; 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 &lt; p.children.length; ++i$1) {
+      var cur = p.children[i$1]
+      if (cur == chunk) { break }
+      else { h += cur.height }
</ins><span class="cx">     }
</span><del>-    gutters.style.display = i ? &quot;&quot; : &quot;none&quot;;
-    updateGutterSpace(cm);
</del><span class="cx">   }
</span><ins>+  return h
+}
</ins><span class="cx"> 
</span><del>-  function updateGutterSpace(cm) {
-    var width = cm.display.gutters.offsetWidth;
-    cm.display.sizer.style.marginLeft = width + &quot;px&quot;;
</del><ins>+// 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
</ins><span class="cx">   }
</span><ins>+  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
+}
</ins><span class="cx"> 
</span><del>-  // 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;
</del><ins>+// 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 &gt; d.maxLineLength) {
+      d.maxLineLength = len
+      d.maxLine = line
</ins><span class="cx">     }
</span><del>-    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;
</del><ins>+  })
+}
+
+// BIDI HELPERS
+
+function iterateBidiSections(order, from, to, f) {
+  if (!order) { return f(from, to, &quot;ltr&quot;) }
+  var found = false
+  for (var i = 0; i &lt; order.length; ++i) {
+    var part = order[i]
+    if (part.from &lt; to &amp;&amp; part.to &gt; from || from == to &amp;&amp; part.to == from) {
+      f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? &quot;rtl&quot; : &quot;ltr&quot;)
+      found = true
</ins><span class="cx">     }
</span><del>-    return len;
</del><span class="cx">   }
</span><ins>+  if (!found) { f(from, to, &quot;ltr&quot;) }
+}
</ins><span class="cx"> 
</span><del>-  // 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 &gt; d.maxLineLength) {
-        d.maxLineLength = len;
-        d.maxLine = line;
</del><ins>+function bidiLeft(part) { return part.level % 2 ? part.to : part.from }
+function bidiRight(part) { return part.level % 2 ? part.from : part.to }
+
+function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0 }
+function lineRight(line) {
+  var order = getOrder(line)
+  if (!order) { return line.text.length }
+  return bidiRight(lst(order))
+}
+
+function compareBidiLevel(order, a, b) {
+  var linedir = order[0].level
+  if (a == linedir) { return true }
+  if (b == linedir) { return false }
+  return a &lt; b
+}
+
+var bidiOther = null
+function getBidiPartAt(order, pos) {
+  var found
+  bidiOther = null
+  for (var i = 0; i &lt; order.length; ++i) {
+    var cur = order[i]
+    if (cur.from &lt; pos &amp;&amp; cur.to &gt; pos) { return i }
+    if ((cur.from == pos || cur.to == pos)) {
+      if (found == null) {
+        found = i
+      } else if (compareBidiLevel(order, cur.level, order[found].level)) {
+        if (cur.from != cur.to) { bidiOther = found }
+        return i
+      } else {
+        if (cur.from != cur.to) { bidiOther = i }
+        return found
</ins><span class="cx">       }
</span><del>-    });
</del><ins>+    }
</ins><span class="cx">   }
</span><ins>+  return found
+}
</ins><span class="cx"> 
</span><del>-  // Make sure the gutters options contains the element
-  // &quot;CodeMirror-linenumbers&quot; when the lineNumbers option is true.
-  function setGuttersForLineNumbers(options) {
-    var found = indexOf(options.gutters, &quot;CodeMirror-linenumbers&quot;);
-    if (found == -1 &amp;&amp; options.lineNumbers) {
-      options.gutters = options.gutters.concat([&quot;CodeMirror-linenumbers&quot;]);
-    } else if (found &gt; -1 &amp;&amp; !options.lineNumbers) {
-      options.gutters = options.gutters.slice(0);
-      options.gutters.splice(found, 1);
</del><ins>+function moveInLine(line, pos, dir, byUnit) {
+  if (!byUnit) { return pos + dir }
+  do { pos += dir }
+  while (pos &gt; 0 &amp;&amp; isExtendingChar(line.text.charAt(pos)))
+  return pos
+}
+
+// This is needed in order to move 'visually' through bi-directional
+// text -- i.e., pressing left should make the cursor go left, even
+// when in RTL text. The tricky part is the 'jumps', where RTL and
+// LTR text touch each other. This often requires the cursor offset
+// to move more than one unit, in order to visually move one unit.
+function moveVisually(line, start, dir, byUnit) {
+  var bidi = getOrder(line)
+  if (!bidi) { return moveLogically(line, start, dir, byUnit) }
+  var pos = getBidiPartAt(bidi, start), part = bidi[pos]
+  var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit)
+
+  for (;;) {
+    if (target &gt; part.from &amp;&amp; target &lt; part.to) { return target }
+    if (target == part.from || target == part.to) {
+      if (getBidiPartAt(bidi, target) == pos) { return target }
+      part = bidi[pos += dir]
+      return (dir &gt; 0) == part.level % 2 ? part.to : part.from
+    } else {
+      part = bidi[pos += dir]
+      if (!part) { return null }
+      if ((dir &gt; 0) == part.level % 2)
+        { target = moveInLine(line, part.to, -1, byUnit) }
+      else
+        { target = moveInLine(line, part.from, 1, byUnit) }
</ins><span class="cx">     }
</span><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // SCROLLBARS
</del><ins>+function moveLogically(line, start, dir, byUnit) {
+  var target = start + dir
+  if (byUnit) { while (target &gt; 0 &amp;&amp; isExtendingChar(line.text.charAt(target))) { target += dir } }
+  return target &lt; 0 || target &gt; line.text.length ? null : target
+}
</ins><span class="cx"> 
</span><del>-  // 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
-    };
</del><ins>+// 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 = &quot;bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN&quot;
+  // Character types for codepoints 0x600 to 0x6f9
+  var arabicTypes = &quot;nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111&quot;
+  function charType(code) {
+    if (code &lt;= 0xf7) { return lowTypes.charAt(code) }
+    else if (0x590 &lt;= code &amp;&amp; code &lt;= 0x5f4) { return &quot;R&quot; }
+    else if (0x600 &lt;= code &amp;&amp; code &lt;= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
+    else if (0x6ee &lt;= code &amp;&amp; code &lt;= 0x8ac) { return &quot;r&quot; }
+    else if (0x2000 &lt;= code &amp;&amp; code &lt;= 0x200b) { return &quot;w&quot; }
+    else if (code == 0x200c) { return &quot;b&quot; }
+    else { return &quot;L&quot; }
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  function NativeScrollbars(place, scroll, cm) {
-    this.cm = cm;
-    var vert = this.vert = elt(&quot;div&quot;, [elt(&quot;div&quot;, null, null, &quot;min-width: 1px&quot;)], &quot;CodeMirror-vscrollbar&quot;);
-    var horiz = this.horiz = elt(&quot;div&quot;, [elt(&quot;div&quot;, null, null, &quot;height: 100%; min-height: 1px&quot;)], &quot;CodeMirror-hscrollbar&quot;);
-    place(vert); place(horiz);
</del><ins>+  var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
+  var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
+  // Browsers seem to always treat the boundaries of block elements as being L.
+  var outerType = &quot;L&quot;
</ins><span class="cx"> 
</span><del>-    on(vert, &quot;scroll&quot;, function() {
-      if (vert.clientHeight) scroll(vert.scrollTop, &quot;vertical&quot;);
-    });
-    on(horiz, &quot;scroll&quot;, function() {
-      if (horiz.clientWidth) scroll(horiz.scrollLeft, &quot;horizontal&quot;);
-    });
-
-    this.checkedOverlay = false;
-    // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
-    if (ie &amp;&amp; ie_version &lt; 8) this.horiz.style.minHeight = this.vert.style.minWidth = &quot;18px&quot;;
</del><ins>+  function BidiSpan(level, from, to) {
+    this.level = level
+    this.from = from; this.to = to
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  NativeScrollbars.prototype = copyObj({
-    update: function(measure) {
-      var needsH = measure.scrollWidth &gt; measure.clientWidth + 1;
-      var needsV = measure.scrollHeight &gt; measure.clientHeight + 1;
-      var sWidth = measure.nativeBarWidth;
</del><ins>+  return function(str) {
+    if (!bidiRE.test(str)) { return false }
+    var len = str.length, types = []
+    for (var i = 0; i &lt; len; ++i)
+      { types.push(charType(str.charCodeAt(i))) }
</ins><span class="cx"> 
</span><del>-      if (needsV) {
-        this.vert.style.display = &quot;block&quot;;
-        this.vert.style.bottom = needsH ? sWidth + &quot;px&quot; : &quot;0&quot;;
-        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) + &quot;px&quot;;
-      } else {
-        this.vert.style.display = &quot;&quot;;
-        this.vert.firstChild.style.height = &quot;0&quot;;
</del><ins>+    // 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 &lt; len; ++i$1) {
+      var type = types[i$1]
+      if (type == &quot;m&quot;) { 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 &lt; len; ++i$2) {
+      var type$1 = types[i$2]
+      if (type$1 == &quot;1&quot; &amp;&amp; cur == &quot;r&quot;) { types[i$2] = &quot;n&quot; }
+      else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == &quot;r&quot;) { types[i$2] = &quot;R&quot; } }
+    }
+
+    // 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 &lt; len - 1; ++i$3) {
+      var type$2 = types[i$3]
+      if (type$2 == &quot;+&quot; &amp;&amp; prev$1 == &quot;1&quot; &amp;&amp; types[i$3+1] == &quot;1&quot;) { types[i$3] = &quot;1&quot; }
+      else if (type$2 == &quot;,&quot; &amp;&amp; prev$1 == types[i$3+1] &amp;&amp;
+               (prev$1 == &quot;1&quot; || prev$1 == &quot;n&quot;)) { 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 &lt; len; ++i$4) {
+      var type$3 = types[i$4]
+      if (type$3 == &quot;,&quot;) { types[i$4] = &quot;N&quot; }
+      else if (type$3 == &quot;%&quot;) {
+        var end = (void 0)
+        for (end = i$4 + 1; end &lt; len &amp;&amp; types[end] == &quot;%&quot;; ++end) {}
+        var replace = (i$4 &amp;&amp; types[i$4-1] == &quot;!&quot;) || (end &lt; len &amp;&amp; types[end] == &quot;1&quot;) ? &quot;1&quot; : &quot;N&quot;
+        for (var j = i$4; j &lt; end; ++j) { types[j] = replace }
+        i$4 = end - 1
</ins><span class="cx">       }
</span><ins>+    }
</ins><span class="cx"> 
</span><del>-      if (needsH) {
-        this.horiz.style.display = &quot;block&quot;;
-        this.horiz.style.right = needsV ? sWidth + &quot;px&quot; : &quot;0&quot;;
-        this.horiz.style.left = measure.barLeft + &quot;px&quot;;
-        var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
-        this.horiz.firstChild.style.width =
-          (measure.scrollWidth - measure.clientWidth + totalWidth) + &quot;px&quot;;
-      } else {
-        this.horiz.style.display = &quot;&quot;;
-        this.horiz.firstChild.style.width = &quot;0&quot;;
</del><ins>+    // 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 &lt; len; ++i$5) {
+      var type$4 = types[i$5]
+      if (cur$1 == &quot;L&quot; &amp;&amp; type$4 == &quot;1&quot;) { types[i$5] = &quot;L&quot; }
+      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 &lt; len; ++i$6) {
+      if (isNeutral.test(types[i$6])) {
+        var end$1 = (void 0)
+        for (end$1 = i$6 + 1; end$1 &lt; len &amp;&amp; isNeutral.test(types[end$1]); ++end$1) {}
+        var before = (i$6 ? types[i$6-1] : outerType) == &quot;L&quot;
+        var after = (end$1 &lt; len ? types[end$1] : outerType) == &quot;L&quot;
+        var replace$1 = before || after ? &quot;L&quot; : &quot;R&quot;
+        for (var j$1 = i$6; j$1 &lt; end$1; ++j$1) { types[j$1] = replace$1 }
+        i$6 = end$1 - 1
</ins><span class="cx">       }
</span><ins>+    }
</ins><span class="cx"> 
</span><del>-      if (!this.checkedOverlay &amp;&amp; measure.clientHeight &gt; 0) {
-        if (sWidth == 0) this.overlayHack();
-        this.checkedOverlay = true;
</del><ins>+    // 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 &lt; len;) {
+      if (countsAsLeft.test(types[i$7])) {
+        var start = i$7
+        for (++i$7; i$7 &lt; len &amp;&amp; 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 &lt; len &amp;&amp; types[i$7] != &quot;L&quot;; ++i$7) {}
+        for (var j$2 = pos; j$2 &lt; i$7;) {
+          if (countsAsNum.test(types[j$2])) {
+            if (pos &lt; j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)) }
+            var nstart = j$2
+            for (++j$2; j$2 &lt; i$7 &amp;&amp; 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 &lt; i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)) }
</ins><span class="cx">       }
</span><del>-
-      return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
-    },
-    setScrollLeft: function(pos) {
-      if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
-    },
-    setScrollTop: function(pos) {
-      if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
-    },
-    overlayHack: function() {
-      var w = mac &amp;&amp; !mac_geMountainLion ? &quot;12px&quot; : &quot;18px&quot;;
-      this.horiz.style.minHeight = this.vert.style.minWidth = w;
-      var self = this;
-      var barMouseDown = function(e) {
-        if (e_target(e) != self.vert &amp;&amp; e_target(e) != self.horiz)
-          operation(self.cm, onMouseDown)(e);
-      };
-      on(this.vert, &quot;mousedown&quot;, barMouseDown);
-      on(this.horiz, &quot;mousedown&quot;, barMouseDown);
-    },
-    clear: function() {
-      var parent = this.horiz.parentNode;
-      parent.removeChild(this.horiz);
-      parent.removeChild(this.vert);
</del><span class="cx">     }
</span><del>-  }, NativeScrollbars.prototype);
</del><ins>+    if (order[0].level == 1 &amp;&amp; (m = str.match(/^\s+/))) {
+      order[0].from = m[0].length
+      order.unshift(new BidiSpan(0, 0, m[0].length))
+    }
+    if (lst(order).level == 1 &amp;&amp; (m = str.match(/\s+$/))) {
+      lst(order).to -= m[0].length
+      order.push(new BidiSpan(0, len - m[0].length, len))
+    }
+    if (order[0].level == 2)
+      { order.unshift(new BidiSpan(1, order[0].to, order[0].to)) }
+    if (order[0].level != lst(order).level)
+      { order.push(new BidiSpan(order[0].level, len, len)) }
</ins><span class="cx"> 
</span><del>-  function NullScrollbars() {}
</del><ins>+    return order
+  }
+})()
</ins><span class="cx"> 
</span><del>-  NullScrollbars.prototype = copyObj({
-    update: function() { return {bottom: 0, right: 0}; },
-    setScrollLeft: function() {},
-    setScrollTop: function() {},
-    clear: function() {}
-  }, NullScrollbars.prototype);
</del><ins>+// 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) {
+  var order = line.order
+  if (order == null) { order = line.order = bidiOrdering(line.text) }
+  return order
+}
</ins><span class="cx"> 
</span><del>-  CodeMirror.scrollbarModel = {&quot;native&quot;: NativeScrollbars, &quot;null&quot;: NullScrollbars};
</del><ins>+// EVENT HANDLING
</ins><span class="cx"> 
</span><del>-  function initScrollbars(cm) {
-    if (cm.display.scrollbars) {
-      cm.display.scrollbars.clear();
-      if (cm.display.scrollbars.addClass)
-        rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
-    }
</del><ins>+// Lightweight event framework. on/off also work on DOM nodes,
+// registering native DOM handlers.
</ins><span class="cx"> 
</span><del>-    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, &quot;mousedown&quot;, function() {
-        if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
-      });
-      node.setAttribute(&quot;cm-not-content&quot;, &quot;true&quot;);
-    }, function(pos, axis) {
-      if (axis == &quot;horizontal&quot;) setScrollLeft(cm, pos);
-      else setScrollTop(cm, pos);
-    }, cm);
-    if (cm.display.scrollbars.addClass)
-      addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
</del><ins>+var noHandlers = []
+
+var on = function(emitter, type, f) {
+  if (emitter.addEventListener) {
+    emitter.addEventListener(type, f, false)
+  } else if (emitter.attachEvent) {
+    emitter.attachEvent(&quot;on&quot; + type, f)
+  } else {
+    var map = emitter._handlers || (emitter._handlers = {})
+    map[type] = (map[type] || noHandlers).concat(f)
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  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 &lt; 4 &amp;&amp; startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
-      if (startWidth != cm.display.barWidth &amp;&amp; cm.options.lineWrapping)
-        updateHeightsInViewport(cm);
-      updateScrollbarsInner(cm, measureForScrollbars(cm));
-      startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
</del><ins>+function getHandlers(emitter, type) {
+  return emitter._handlers &amp;&amp; emitter._handlers[type] || noHandlers
+}
+
+function off(emitter, type, f) {
+  if (emitter.removeEventListener) {
+    emitter.removeEventListener(type, f, false)
+  } else if (emitter.detachEvent) {
+    emitter.detachEvent(&quot;on&quot; + type, f)
+  } else {
+    var map = emitter._handlers, arr = map &amp;&amp; map[type]
+    if (arr) {
+      var index = indexOf(arr, f)
+      if (index &gt; -1)
+        { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)) }
</ins><span class="cx">     }
</span><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // 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);
</del><ins>+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 &lt; handlers.length; ++i) { handlers[i].apply(null, args) }
+}
</ins><span class="cx"> 
</span><del>-    d.sizer.style.paddingRight = (d.barWidth = sizes.right) + &quot;px&quot;;
-    d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + &quot;px&quot;;
</del><ins>+// 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 == &quot;string&quot;)
+    { e = {type: e, preventDefault: function() { this.defaultPrevented = true }} }
+  signal(cm, override || e.type, cm, e)
+  return e_defaultPrevented(e) || e.codemirrorIgnore
+}
</ins><span class="cx"> 
</span><del>-    if (sizes.right &amp;&amp; sizes.bottom) {
-      d.scrollbarFiller.style.display = &quot;block&quot;;
-      d.scrollbarFiller.style.height = sizes.bottom + &quot;px&quot;;
-      d.scrollbarFiller.style.width = sizes.right + &quot;px&quot;;
-    } else d.scrollbarFiller.style.display = &quot;&quot;;
-    if (sizes.bottom &amp;&amp; cm.options.coverGutterNextToScrollbar &amp;&amp; cm.options.fixedGutter) {
-      d.gutterFiller.style.display = &quot;block&quot;;
-      d.gutterFiller.style.height = sizes.bottom + &quot;px&quot;;
-      d.gutterFiller.style.width = measure.gutterWidth + &quot;px&quot;;
-    } else d.gutterFiller.style.display = &quot;&quot;;
</del><ins>+function signalCursorActivity(cm) {
+  var arr = cm._handlers &amp;&amp; cm._handlers.cursorActivity
+  if (!arr) { return }
+  var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = [])
+  for (var i = 0; i &lt; arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
+    { set.push(arr[i]) } }
+}
+
+function hasHandler(emitter, type) {
+  return getHandlers(emitter, type).length &gt; 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 &amp; 1) { b = 1 }
+    else if (e.button &amp; 2) { b = 3 }
+    else if (e.button &amp; 4) { b = 2 }
</ins><span class="cx">   }
</span><ins>+  if (mac &amp;&amp; e.ctrlKey &amp;&amp; b == 1) { b = 3 }
+  return b
+}
</ins><span class="cx"> 
</span><del>-  // 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 &amp;&amp; viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
-    top = Math.floor(top - paddingTop(display));
-    var bottom = viewport &amp;&amp; viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
</del><ins>+// 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 &amp;&amp; ie_version &lt; 9) { return false }
+  var div = elt('div')
+  return &quot;draggable&quot; in div || &quot;dragDrop&quot; in div
+}()
</ins><span class="cx"> 
</span><del>-    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 &amp;&amp; viewport.ensure) {
-      var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
-      if (ensureFrom &lt; from) {
-        from = ensureFrom;
-        to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
-      } else if (Math.min(ensureTo, doc.lastLine()) &gt;= to) {
-        from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
-        to = ensureTo;
-      }
-    }
-    return {from: from, to: Math.max(to, from + 1)};
</del><ins>+var zwspSupported
+function zeroWidthElement(measure) {
+  if (zwspSupported == null) {
+    var test = elt(&quot;span&quot;, &quot;\u200b&quot;)
+    removeChildrenAndAdd(measure, elt(&quot;span&quot;, [test, document.createTextNode(&quot;x&quot;)]))
+    if (measure.firstChild.offsetHeight != 0)
+      { zwspSupported = test.offsetWidth &lt;= 1 &amp;&amp; test.offsetHeight &gt; 2 &amp;&amp; !(ie &amp;&amp; ie_version &lt; 8) }
</ins><span class="cx">   }
</span><ins>+  var node = zwspSupported ? elt(&quot;span&quot;, &quot;\u200b&quot;) :
+    elt(&quot;span&quot;, &quot;\u00a0&quot;, null, &quot;display: inline-block; width: 1px; margin-right: -1px&quot;)
+  node.setAttribute(&quot;cm-text&quot;, &quot;&quot;)
+  return node
+}
</ins><span class="cx"> 
</span><del>-  // LINE NUMBERS
</del><ins>+// 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(&quot;A\u062eA&quot;))
+  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 &lt; 3)
+}
</ins><span class="cx"> 
</span><del>-  // 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 &amp;&amp; (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
-    var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
-    var gutterW = display.gutters.offsetWidth, left = comp + &quot;px&quot;;
-    for (var i = 0; i &lt; view.length; i++) if (!view[i].hidden) {
-      if (cm.options.fixedGutter &amp;&amp; view[i].gutter)
-        view[i].gutter.style.left = left;
-      var align = view[i].alignable;
-      if (align) for (var j = 0; j &lt; align.length; j++)
-        align[j].style.left = left;
</del><ins>+// See if &quot;&quot;.split is the broken IE version, if so, provide an
+// alternative way to split lines.
+var splitLinesAuto = &quot;\n\nb&quot;.split(/\n/).length != 3 ? function (string) {
+  var pos = 0, result = [], l = string.length
+  while (pos &lt;= l) {
+    var nl = string.indexOf(&quot;\n&quot;, pos)
+    if (nl == -1) { nl = string.length }
+    var line = string.slice(pos, string.charAt(nl - 1) == &quot;\r&quot; ? nl - 1 : nl)
+    var rt = line.indexOf(&quot;\r&quot;)
+    if (rt != -1) {
+      result.push(line.slice(0, rt))
+      pos += rt + 1
+    } else {
+      result.push(line)
+      pos = nl + 1
</ins><span class="cx">     }
</span><del>-    if (cm.options.fixedGutter)
-      display.gutters.style.left = (comp + gutterW) + &quot;px&quot;;
</del><span class="cx">   }
</span><ins>+  return result
+} : function (string) { return string.split(/\r\n?|\n/); }
</ins><span class="cx"> 
</span><del>-  // 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(&quot;div&quot;, [elt(&quot;div&quot;, last)],
-                                                 &quot;CodeMirror-linenumber CodeMirror-gutter-elt&quot;));
-      var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
-      display.lineGutter.style.width = &quot;&quot;;
-      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 + &quot;px&quot;;
-      updateGutterSpace(cm);
-      return true;
</del><ins>+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(&quot;StartToEnd&quot;, range) != 0
+}
+
+var hasCopyEvent = (function () {
+  var e = elt(&quot;div&quot;)
+  if (&quot;oncopy&quot; in e) { return true }
+  e.setAttribute(&quot;oncopy&quot;, &quot;return;&quot;)
+  return typeof e.oncopy == &quot;function&quot;
+})()
+
+var badZoomedRects = null
+function hasBadZoomedRects(measure) {
+  if (badZoomedRects != null) { return badZoomedRects }
+  var node = removeChildrenAndAdd(measure, elt(&quot;span&quot;, &quot;x&quot;))
+  var normal = node.getBoundingClientRect()
+  var fromRange = range(node, 0, 1).getBoundingClientRect()
+  return badZoomedRects = Math.abs(normal.left - fromRange.left) &gt; 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 &gt; 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 == &quot;string&quot; &amp;&amp; mimeModes.hasOwnProperty(spec)) {
+    spec = mimeModes[spec]
+  } else if (spec &amp;&amp; typeof spec.name == &quot;string&quot; &amp;&amp; mimeModes.hasOwnProperty(spec.name)) {
+    var found = mimeModes[spec.name]
+    if (typeof found == &quot;string&quot;) { found = {name: found} }
+    spec = createObj(found, spec)
+    spec.name = found.name
+  } else if (typeof spec == &quot;string&quot; &amp;&amp; /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
+    return resolveMode(&quot;application/xml&quot;)
+  } else if (typeof spec == &quot;string&quot; &amp;&amp; /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
+    return resolveMode(&quot;application/json&quot;)
+  }
+  if (typeof spec == &quot;string&quot;) { return {name: spec} }
+  else { return spec || {name: &quot;null&quot;} }
+}
+
+// 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, &quot;text/plain&quot;) }
+  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[&quot;_&quot; + prop] = modeObj[prop] }
+      modeObj[prop] = exts[prop]
</ins><span class="cx">     }
</span><del>-    return false;
</del><span class="cx">   }
</span><ins>+  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] } }
</ins><span class="cx"> 
</span><del>-  function lineNumberFor(options, i) {
-    return String(options.lineNumberFormatter(i + options.firstLineNumber));
</del><ins>+  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
</ins><span class="cx">   }
</span><ins>+  return nstate
+}
</ins><span class="cx"> 
</span><del>-  // 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;
</del><ins>+// 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
</ins><span class="cx">   }
</span><ins>+  return info || {mode: mode, state: state}
+}
</ins><span class="cx"> 
</span><del>-  // DISPLAY DRAWING
</del><ins>+function startState(mode, a1, a2) {
+  return mode.startState ? mode.startState(a1, a2) : true
+}
</ins><span class="cx"> 
</span><del>-  function DisplayUpdate(cm, viewport, force) {
-    var display = cm.display;
</del><ins>+// STRING STREAM
</ins><span class="cx"> 
</span><del>-    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 = [];
-  }
</del><ins>+// Fed to the mode parsers, provides helper functions to make
+// parsers more succinct.
</ins><span class="cx"> 
</span><del>-  DisplayUpdate.prototype.signal = function(emitter, type) {
-    if (hasHandler(emitter, type))
-      this.events.push(arguments);
-  };
-  DisplayUpdate.prototype.finish = function() {
-    for (var i = 0; i &lt; this.events.length; i++)
-      signal.apply(null, this.events[i]);
-  };
</del><ins>+var StringStream = function(string, tabSize) {
+  this.pos = this.start = 0
+  this.string = string
+  this.tabSize = tabSize || 8
+  this.lastColumnPos = this.lastColumnValue = 0
+  this.lineStart = 0
+}
</ins><span class="cx"> 
</span><del>-  function maybeClipScrollbars(cm) {
-    var display = cm.display;
-    if (!display.scrollbarsClipped &amp;&amp; display.scroller.offsetWidth) {
-      display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
-      display.heightForcer.style.height = scrollGap(cm) + &quot;px&quot;;
-      display.sizer.style.marginBottom = -display.nativeBarWidth + &quot;px&quot;;
-      display.sizer.style.borderRightWidth = scrollGap(cm) + &quot;px&quot;;
-      display.scrollbarsClipped = true;
</del><ins>+StringStream.prototype = {
+  eol: function() {return this.pos &gt;= this.string.length},
+  sol: function() {return this.pos == this.lineStart},
+  peek: function() {return this.string.charAt(this.pos) || undefined},
+  next: function() {
+    if (this.pos &lt; this.string.length)
+      { return this.string.charAt(this.pos++) }
+  },
+  eat: function(match) {
+    var ch = this.string.charAt(this.pos)
+    var ok
+    if (typeof match == &quot;string&quot;) { ok = ch == match }
+    else { ok = ch &amp;&amp; (match.test ? match.test(ch) : match(ch)) }
+    if (ok) {++this.pos; return ch}
+  },
+  eatWhile: function(match) {
+    var start = this.pos
+    while (this.eat(match)){}
+    return this.pos &gt; start
+  },
+  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 &gt; start
+  },
+  skipToEnd: function() {this.pos = this.string.length},
+  skipTo: function(ch) {
+    var found = this.string.indexOf(ch, this.pos)
+    if (found &gt; -1) {this.pos = found; return true}
+  },
+  backUp: function(n) {this.pos -= n},
+  column: function() {
+    if (this.lastColumnPos &lt; this.start) {
+      this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue)
+      this.lastColumnPos = this.start
</ins><span class="cx">     }
</span><ins>+    return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
+  },
+  indentation: function() {
+    return countColumn(this.string, null, this.tabSize) -
+      (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
+  },
+  match: function(pattern, consume, caseInsensitive) {
+    if (typeof pattern == &quot;string&quot;) {
+      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 &amp;&amp; match.index &gt; 0) { return null }
+      if (match &amp;&amp; consume !== false) { this.pos += match[0].length }
+      return match
+    }
+  },
+  current: function(){return this.string.slice(this.start, this.pos)},
+  hideFirstChars: function(n, inner) {
+    this.lineStart += n
+    try { return inner() }
+    finally { this.lineStart -= n }
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // 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;
</del><ins>+// 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, state, 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, state, function (end, style) { return st.push(end, style); },
+    lineClasses, forceToEnd)
</ins><span class="cx"> 
</span><del>-    if (update.editorIsHidden) {
-      resetView(cm);
-      return false;
-    }
</del><ins>+  // Run overlays, adjust style array.
+  var loop = function ( o ) {
+    var overlay = cm.state.overlays[o], i = 1, at = 0
+    runMode(cm, line.text, overlay.mode, true, function (end, style) {
+      var start = i
+      // Ensure there's a token end at the current position, and that i points at it
+      while (at &lt; end) {
+        var i_end = st[i]
+        if (i_end &gt; 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, &quot;overlay &quot; + style)
+        i = start + 2
+      } else {
+        for (; start &lt; i; start += 2) {
+          var cur = st[start+1]
+          st[start+1] = (cur ? cur + &quot; &quot; : &quot;&quot;) + &quot;overlay &quot; + style
+        }
+      }
+    }, lineClasses)
+  };
</ins><span class="cx"> 
</span><del>-    // Bail out if the visible area is already rendered and nothing changed.
-    if (!update.force &amp;&amp;
-        update.visible.from &gt;= display.viewFrom &amp;&amp; update.visible.to &lt;= display.viewTo &amp;&amp;
-        (display.updateLineNumbers == null || display.updateLineNumbers &gt;= display.viewTo) &amp;&amp;
-        display.renderedView == display.view &amp;&amp; countDirtyView(cm) == 0)
-      return false;
</del><ins>+  for (var o = 0; o &lt; cm.state.overlays.length; ++o) loop( o );
</ins><span class="cx"> 
</span><del>-    if (maybeUpdateLineNumberWidth(cm)) {
-      resetView(cm);
-      update.dims = getDimensions(cm);
-    }
</del><ins>+  return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
+}
</ins><span class="cx"> 
</span><del>-    // Compute a suitable new viewport (from &amp; 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 &lt; from &amp;&amp; from - display.viewFrom &lt; 20) from = Math.max(doc.first, display.viewFrom);
-    if (display.viewTo &gt; to &amp;&amp; display.viewTo - to &lt; 20) to = Math.min(end, display.viewTo);
-    if (sawCollapsedSpans) {
-      from = visualLineNo(cm.doc, from);
-      to = visualLineEndNo(cm.doc, to);
-    }
</del><ins>+function getLineStyles(cm, line, updateFrontier) {
+  if (!line.styles || line.styles[0] != cm.state.modeGen) {
+    var state = getStateBefore(cm, lineNo(line))
+    var result = highlightLine(cm, line, line.text.length &gt; cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state)
+    line.stateAfter = state
+    line.styles = result.styles
+    if (result.classes) { line.styleClasses = result.classes }
+    else if (line.styleClasses) { line.styleClasses = null }
+    if (updateFrontier === cm.doc.frontier) { cm.doc.frontier++ }
+  }
+  return line.styles
+}
</ins><span class="cx"> 
</span><del>-    var different = from != display.viewFrom || to != display.viewTo ||
-      display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
-    adjustView(cm, from, to);
</del><ins>+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 &gt; doc.first &amp;&amp; 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 &gt;= display.viewFrom &amp;&amp; pos &lt; display.viewTo
+    line.stateAfter = save ? copyState(doc.mode, state) : null
+    ++pos
+  })
+  if (precise) { doc.frontier = pos }
+  return state
+}
</ins><span class="cx"> 
</span><del>-    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 + &quot;px&quot;;
</del><ins>+// 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, state, startAt) {
+  var mode = cm.doc.mode
+  var stream = new StringStream(text, cm.options.tabSize)
+  stream.start = stream.pos = startAt || 0
+  if (text == &quot;&quot;) { callBlankLine(mode, state) }
+  while (!stream.eol()) {
+    readToken(mode, stream, state)
+    stream.start = stream.pos
+  }
+}
</ins><span class="cx"> 
</span><del>-    var toUpdate = countDirtyView(cm);
-    if (!different &amp;&amp; toUpdate == 0 &amp;&amp; !update.force &amp;&amp; display.renderedView == display.view &amp;&amp;
-        (display.updateLineNumbers == null || display.updateLineNumbers &gt;= display.viewTo))
-      return false;
</del><ins>+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) }
+}
</ins><span class="cx"> 
</span><del>-    // 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 &gt; 4) display.lineDiv.style.display = &quot;none&quot;;
-    patchDisplay(cm, display.updateLineNumbers, update.dims);
-    if (toUpdate &gt; 4) display.lineDiv.style.display = &quot;&quot;;
-    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 &amp;&amp; activeElt() != focused &amp;&amp; focused.offsetHeight) focused.focus();
</del><ins>+function readToken(mode, stream, state, inner) {
+  for (var i = 0; i &lt; 10; i++) {
+    if (inner) { inner[0] = innerMode(mode, state).mode }
+    var style = mode.token(stream, state)
+    if (stream.pos &gt; stream.start) { return style }
+  }
+  throw new Error(&quot;Mode &quot; + mode.name + &quot; failed to advance stream.&quot;)
+}
</ins><span class="cx"> 
</span><del>-    // 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;
</del><ins>+// Utility for getTokenAt and getLineTokens
+function takeToken(cm, pos, precise, asArray) {
+  var getObj = function (copy) { return ({
+    start: stream.start, end: stream.pos,
+    string: stream.current(),
+    type: style || null,
+    state: copy ? copyState(doc.mode, state) : state
+  }); }
</ins><span class="cx"> 
</span><del>-    if (different) {
-      display.lastWrapHeight = update.wrapperHeight;
-      display.lastWrapWidth = update.wrapperWidth;
-      startWorker(cm, 400);
-    }
</del><ins>+  var doc = cm.doc, mode = doc.mode, style
+  pos = clipPos(doc, pos)
+  var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise)
+  var stream = new StringStream(line.text, cm.options.tabSize), tokens
+  if (asArray) { tokens = [] }
+  while ((asArray || stream.pos &lt; pos.ch) &amp;&amp; !stream.eol()) {
+    stream.start = stream.pos
+    style = readToken(mode, stream, state)
+    if (asArray) { tokens.push(getObj(true)) }
+  }
+  return asArray ? tokens : getObj()
+}
</ins><span class="cx"> 
</span><del>-    display.updateLineNumbers = null;
</del><ins>+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] ? &quot;bgClass&quot; : &quot;textClass&quot;
+    if (output[prop] == null)
+      { output[prop] = lineClass[2] }
+    else if (!(new RegExp(&quot;(?:^|\s)&quot; + lineClass[2] + &quot;(?:$|\s)&quot;)).test(output[prop]))
+      { output[prop] += &quot; &quot; + lineClass[2] }
+  } }
+  return type
+}
</ins><span class="cx"> 
</span><del>-    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 &amp;&amp; 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 &gt;= cm.display.viewFrom &amp;&amp; update.visible.to &lt;= cm.display.viewTo)
-          break;
</del><ins>+// Run the given mode's parser over a line, calling f for each token.
+function runMode(cm, text, mode, state, 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), style
+  var inner = cm.options.addModeClass &amp;&amp; [null]
+  if (text == &quot;&quot;) { extractLineClasses(callBlankLine(mode, state), lineClasses) }
+  while (!stream.eol()) {
+    if (stream.pos &gt; cm.options.maxHighlightLength) {
+      flattenSpans = false
+      if (forceToEnd) { processLine(cm, text, state, stream.pos) }
+      stream.pos = text.length
+      style = null
+    } else {
+      style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses)
+    }
+    if (inner) {
+      var mName = inner[0].name
+      if (mName) { style = &quot;m-&quot; + (style ? mName + &quot; &quot; + style : mName) }
+    }
+    if (!flattenSpans || curStyle != style) {
+      while (curStart &lt; stream.start) {
+        curStart = Math.min(stream.start, curStart + 5000)
+        f(curStart, curStyle)
</ins><span class="cx">       }
</span><del>-      if (!updateDisplayIfNeeded(cm, update)) break;
-      updateHeightsInViewport(cm);
-      var barMeasure = measureForScrollbars(cm);
-      updateSelection(cm);
-      setDocumentHeight(cm, barMeasure);
-      updateScrollbars(cm, barMeasure);
</del><ins>+      curStyle = style
</ins><span class="cx">     }
</span><ins>+    stream.start = stream.pos
+  }
+  while (curStart &lt; 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
+  }
+}
</ins><span class="cx"> 
</span><del>-    update.signal(cm, &quot;update&quot;, cm);
-    if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
-      update.signal(cm, &quot;viewportChange&quot;, cm, cm.display.viewFrom, cm.display.viewTo);
-      cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
</del><ins>+// 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 &gt; lim; --search) {
+    if (search &lt;= doc.first) { return doc.first }
+    var line = getLine(doc, search - 1)
+    if (line.stateAfter &amp;&amp; (!precise || search &lt;= doc.frontier)) { return search }
+    var indented = countColumn(line.text, null, cm.options.tabSize)
+    if (minline == null || minindent &gt; indented) {
+      minline = search - 1
+      minindent = indented
</ins><span class="cx">     }
</span><span class="cx">   }
</span><ins>+  return minline
+}
</ins><span class="cx"> 
</span><del>-  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);
-      setDocumentHeight(cm, barMeasure);
-      updateScrollbars(cm, barMeasure);
-      update.finish();
</del><ins>+// LINE DATA STRUCTURE
+
+// Line objects. These hold state related to a line, including
+// highlighting info (the styles array).
+function Line(text, markedSpans, estimateHeight) {
+  this.text = text
+  attachMarkedSpans(this, markedSpans)
+  this.height = estimateHeight ? estimateHeight(this) : 1
+}
+eventMixin(Line)
+Line.prototype.lineNo = function() { return lineNo(this) }
+
+// 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, &quot;cm-$&amp;&quot;))
+}
+
+// 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 = elt(&quot;span&quot;, null, null, webkit ? &quot;padding-right: .1px&quot; : null)
+  var builder = {pre: elt(&quot;pre&quot;, [content], &quot;CodeMirror-line&quot;), content: content,
+                 col: 0, pos: 0, cm: cm,
+                 trailingSpace: false,
+                 splitSpaces: (ie || webkit) &amp;&amp; cm.getOption(&quot;lineWrapping&quot;)}
+  lineView.measure = {}
+
+  // Iterate over the logical lines that make up this visual line.
+  for (var i = 0; i &lt;= (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) &amp;&amp; (order = getOrder(line)))
+      { builder.addToken = buildTokenBadBidi(builder.addToken, order) }
+    builder.map = []
+    var allowFrontierUpdate = lineView != cm.display.externalMeasured &amp;&amp; lineNo(line)
+    insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate))
+    if (line.styleClasses) {
+      if (line.styleClasses.bgClass)
+        { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || &quot;&quot;) }
+      if (line.styleClasses.textClass)
+        { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || &quot;&quot;) }
</ins><span class="cx">     }
</span><ins>+
+    // 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({})
+    }
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  function setDocumentHeight(cm, measure) {
-    cm.display.sizer.style.minHeight = measure.docHeight + &quot;px&quot;;
-    var total = measure.docHeight + cm.display.barHeight;
-    cm.display.heightForcer.style.top = total + &quot;px&quot;;
-    cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + &quot;px&quot;;
</del><ins>+  // See issue #2901
+  if (webkit) {
+    var last = builder.content.lastChild
+    if (/\bcm-tab\b/.test(last.className) || (last.querySelector &amp;&amp; last.querySelector(&quot;.cm-tab&quot;)))
+      { builder.content.className = &quot;cm-tab-wrap-hack&quot; }
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // 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 &lt; display.view.length; i++) {
-      var cur = display.view[i], height;
-      if (cur.hidden) continue;
-      if (ie &amp;&amp; ie_version &lt; 8) {
-        var bot = cur.node.offsetTop + cur.node.offsetHeight;
-        height = bot - prevBottom;
-        prevBottom = bot;
</del><ins>+  signal(cm, &quot;renderLine&quot;, cm, lineView.line, builder.pre)
+  if (builder.pre.className)
+    { builder.textClass = joinClasses(builder.pre.className, builder.textClass || &quot;&quot;) }
+
+  return builder
+}
+
+function defaultSpecialCharPlaceholder(ch) {
+  var token = elt(&quot;span&quot;, &quot;\u2022&quot;, &quot;cm-invalidchar&quot;)
+  token.title = &quot;\\u&quot; + ch.charCodeAt(0).toString(16)
+  token.setAttribute(&quot;aria-label&quot;, 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 &amp;&amp; ie_version &lt; 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 &amp;&amp; ie_version &lt; 9) { content.appendChild(elt(&quot;span&quot;, [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] == &quot;\t&quot;) {
+        var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize
+        txt$1 = content.appendChild(elt(&quot;span&quot;, spaceStr(tabWidth), &quot;cm-tab&quot;))
+        txt$1.setAttribute(&quot;role&quot;, &quot;presentation&quot;)
+        txt$1.setAttribute(&quot;cm-text&quot;, &quot;\t&quot;)
+        builder.col += tabWidth
+      } else if (m[0] == &quot;\r&quot; || m[0] == &quot;\n&quot;) {
+        txt$1 = content.appendChild(elt(&quot;span&quot;, m[0] == &quot;\r&quot; ? &quot;\u240d&quot; : &quot;\u2424&quot;, &quot;cm-invalidchar&quot;))
+        txt$1.setAttribute(&quot;cm-text&quot;, m[0])
+        builder.col += 1
</ins><span class="cx">       } else {
</span><del>-        var box = cur.node.getBoundingClientRect();
-        height = box.bottom - box.top;
</del><ins>+        txt$1 = builder.cm.options.specialCharPlaceholder(m[0])
+        txt$1.setAttribute(&quot;cm-text&quot;, m[0])
+        if (ie &amp;&amp; ie_version &lt; 9) { content.appendChild(elt(&quot;span&quot;, [txt$1])) }
+        else { content.appendChild(txt$1) }
+        builder.col += 1
</ins><span class="cx">       }
</span><del>-      var diff = cur.line.height - height;
-      if (height &lt; 2) height = textHeight(display);
-      if (diff &gt; .001 || diff &lt; -.001) {
-        updateLineHeight(cur.line, height);
-        updateWidgetHeight(cur.line);
-        if (cur.rest) for (var j = 0; j &lt; cur.rest.length; j++)
-          updateWidgetHeight(cur.rest[j]);
-      }
</del><ins>+      builder.map.push(builder.pos, builder.pos + 1, txt$1)
+      builder.pos++
</ins><span class="cx">     }
</span><span class="cx">   }
</span><ins>+  builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32
+  if (style || startStyle || endStyle || mustWrap || css) {
+    var fullStyle = style || &quot;&quot;
+    if (startStyle) { fullStyle += startStyle }
+    if (endStyle) { fullStyle += endStyle }
+    var token = elt(&quot;span&quot;, [content], fullStyle, css)
+    if (title) { token.title = title }
+    return builder.content.appendChild(token)
+  }
+  builder.content.appendChild(content)
+}
</ins><span class="cx"> 
</span><del>-  // Read and store the height of line widgets associated with the
-  // given line.
-  function updateWidgetHeight(line) {
-    if (line.widgets) for (var i = 0; i &lt; line.widgets.length; ++i)
-      line.widgets[i].height = line.widgets[i].node.offsetHeight;
</del><ins>+function splitSpaces(text, trailingBefore) {
+  if (text.length &gt; 1 &amp;&amp; !/  /.test(text)) { return text }
+  var spaceBefore = trailingBefore, result = &quot;&quot;
+  for (var i = 0; i &lt; text.length; i++) {
+    var ch = text.charAt(i)
+    if (ch == &quot; &quot; &amp;&amp; spaceBefore &amp;&amp; (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
+      { ch = &quot;\u00a0&quot; }
+    result += ch
+    spaceBefore = ch == &quot; &quot;
</ins><span class="cx">   }
</span><ins>+  return result
+}
</ins><span class="cx"> 
</span><del>-  // 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;
</del><ins>+// 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 + &quot; cm-force-border&quot; : &quot;cm-force-border&quot;
+    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 &lt; order.length; i++) {
+        part = order[i]
+        if (part.to &gt; start &amp;&amp; part.from &lt;= start) { break }
+      }
+      if (part.to &gt;= 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
</ins><span class="cx">     }
</span><del>-    return {fixedPos: compensateForHScroll(d),
-            gutterTotalWidth: d.gutters.offsetWidth,
-            gutterLeft: left,
-            gutterWidth: width,
-            wrapperWidth: d.wrapper.clientWidth};
</del><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // 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;
</del><ins>+function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
+  var widget = !ignoreWidget &amp;&amp; marker.widgetNode
+  if (widget) { builder.map.push(builder.pos, builder.pos + size, widget) }
+  if (!ignoreWidget &amp;&amp; builder.cm.display.input.needsContentAttribute) {
+    if (!widget)
+      { widget = builder.content.appendChild(document.createElement(&quot;span&quot;)) }
+    widget.setAttribute(&quot;cm-marker&quot;, marker.id)
+  }
+  if (widget) {
+    builder.cm.display.input.setUneditable(widget)
+    builder.content.appendChild(widget)
+  }
+  builder.pos += size
+  builder.trailingSpace = false
+}
</ins><span class="cx"> 
</span><del>-    function rm(node) {
-      var next = node.nextSibling;
-      // Works around a throw-scroll bug in OS X Webkit
-      if (webkit &amp;&amp; mac &amp;&amp; cm.display.currentWheelTarget == node)
-        node.style.display = &quot;none&quot;;
-      else
-        node.parentNode.removeChild(node);
-      return next;
</del><ins>+// 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 &lt; 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 = &quot;&quot;, style, css
+  var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed
+  for (;;) {
+    if (nextChange == pos) { // Update current marker set
+      spanStyle = spanEndStyle = spanStartStyle = title = css = &quot;&quot;
+      collapsed = null; nextChange = Infinity
+      var foundBookmarks = [], endStyles = (void 0)
+      for (var j = 0; j &lt; spans.length; ++j) {
+        var sp = spans[j], m = sp.marker
+        if (m.type == &quot;bookmark&quot; &amp;&amp; sp.from == pos &amp;&amp; m.widgetNode) {
+          foundBookmarks.push(m)
+        } else if (sp.from &lt;= pos &amp;&amp; (sp.to == null || sp.to &gt; pos || m.collapsed &amp;&amp; sp.to == pos &amp;&amp; sp.from == pos)) {
+          if (sp.to != null &amp;&amp; sp.to != pos &amp;&amp; nextChange &gt; sp.to) {
+            nextChange = sp.to
+            spanEndStyle = &quot;&quot;
+          }
+          if (m.className) { spanStyle += &quot; &quot; + m.className }
+          if (m.css) { css = (css ? css + &quot;;&quot; : &quot;&quot;) + m.css }
+          if (m.startStyle &amp;&amp; sp.from == pos) { spanStartStyle += &quot; &quot; + m.startStyle }
+          if (m.endStyle &amp;&amp; sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to) }
+          if (m.title &amp;&amp; !title) { title = m.title }
+          if (m.collapsed &amp;&amp; (!collapsed || compareCollapsedMarkers(collapsed.marker, m) &lt; 0))
+            { collapsed = sp }
+        } else if (sp.from &gt; pos &amp;&amp; nextChange &gt; sp.from) {
+          nextChange = sp.from
+        }
+      }
+      if (endStyles) { for (var j$1 = 0; j$1 &lt; endStyles.length; j$1 += 2)
+        { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += &quot; &quot; + endStyles[j$1] } } }
+
+      if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 &lt; foundBookmarks.length; ++j$2)
+        { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]) } }
+      if (collapsed &amp;&amp; (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 }
+      }
</ins><span class="cx">     }
</span><ins>+    if (pos &gt;= len) { break }
</ins><span class="cx"> 
</span><del>-    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 &lt; 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 &amp;&amp; updateNumbersFrom != null &amp;&amp;
-          updateNumbersFrom &lt;= lineN &amp;&amp; lineView.lineNumber;
-        if (lineView.changes) {
-          if (indexOf(lineView.changes, &quot;gutter&quot;) &gt; -1) updateNumber = false;
-          updateLineForChanges(cm, lineView, lineN, dims);
</del><ins>+    var upto = Math.min(len, nextChange)
+    while (true) {
+      if (text) {
+        var end = pos + text.length
+        if (!collapsed) {
+          var tokenText = end &gt; upto ? text.slice(0, upto - pos) : text
+          builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
+                           spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : &quot;&quot;, title, css)
</ins><span class="cx">         }
</span><del>-        if (updateNumber) {
-          removeChildren(lineView.lineNumber);
-          lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
-        }
-        cur = lineView.node.nextSibling;
</del><ins>+        if (end &gt;= upto) {text = text.slice(upto - pos); pos = upto; break}
+        pos = end
+        spanStartStyle = &quot;&quot;
</ins><span class="cx">       }
</span><del>-      lineN += lineView.size;
</del><ins>+      text = allText.slice(at, at = styles[i++])
+      style = interpretTokenStyle(styles[i++], builder.cm.options)
</ins><span class="cx">     }
</span><del>-    while (cur) cur = rm(cur);
</del><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // 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 &lt; lineView.changes.length; j++) {
-      var type = lineView.changes[j];
-      if (type == &quot;text&quot;) updateLineText(cm, lineView);
-      else if (type == &quot;gutter&quot;) updateLineGutter(cm, lineView, lineN, dims);
-      else if (type == &quot;class&quot;) updateLineClasses(lineView);
-      else if (type == &quot;widget&quot;) updateLineWidgets(cm, lineView, dims);
-    }
-    lineView.changes = null;
</del><ins>+
+// 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 &lt; to; pos = nextPos) {
+    var view = new LineView(cm.doc, getLine(cm.doc, pos), pos)
+    nextPos = pos + view.size
+    array.push(view)
</ins><span class="cx">   }
</span><ins>+  return array
+}
</ins><span class="cx"> 
</span><del>-  // 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(&quot;div&quot;, null, null, &quot;position: relative&quot;);
-      if (lineView.text.parentNode)
-        lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
-      lineView.node.appendChild(lineView.text);
-      if (ie &amp;&amp; ie_version &lt; 8) lineView.node.style.zIndex = 2;
</del><ins>+var operationGroup = null
+
+function pushOperation(op) {
+  if (operationGroup) {
+    operationGroup.ops.push(op)
+  } else {
+    op.ownsGroup = operationGroup = {
+      ops: [op],
+      delayedCallbacks: []
</ins><span class="cx">     }
</span><del>-    return lineView.node;
</del><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  function updateLineBackground(lineView) {
-    var cls = lineView.bgClass ? lineView.bgClass + &quot; &quot; + (lineView.line.bgClass || &quot;&quot;) : lineView.line.bgClass;
-    if (cls) cls += &quot; CodeMirror-linebackground&quot;;
-    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(&quot;div&quot;, null, cls), wrap.firstChild);
</del><ins>+function fireCallbacksForOps(group) {
+  // Calls delayed callbacks and cursorActivity handlers until no
+  // new ones appear
+  var callbacks = group.delayedCallbacks, i = 0
+  do {
+    for (; i &lt; callbacks.length; i++)
+      { callbacks[i].call(null) }
+    for (var j = 0; j &lt; group.ops.length; j++) {
+      var op = group.ops[j]
+      if (op.cursorActivityHandlers)
+        { while (op.cursorActivityCalled &lt; op.cursorActivityHandlers.length)
+          { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm) } }
</ins><span class="cx">     }
</span><del>-  }
</del><ins>+  } while (i &lt; callbacks.length)
+}
</ins><span class="cx"> 
</span><del>-  // Wrapper around buildLineContent which will reuse the structure
-  // in display.externalMeasured when possible.
-  function getLineContent(cm, lineView) {
-    var ext = cm.display.externalMeasured;
-    if (ext &amp;&amp; ext.line == lineView.line) {
-      cm.display.externalMeasured = null;
-      lineView.measure = ext.measure;
-      return ext.built;
-    }
-    return buildLineContent(cm, lineView);
</del><ins>+function finishOperation(op, endCb) {
+  var group = op.ownsGroup
+  if (!group) { return }
+
+  try { fireCallbacksForOps(group) }
+  finally {
+    operationGroup = null
+    endCb(group)
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // 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;
-    }
</del><ins>+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)
</ins><span class="cx">   }
</span><ins>+  var loop = function ( i ) {
+    list.push(function () { return arr[i].apply(null, args); })
+  };
</ins><span class="cx"> 
</span><del>-  function updateLineClasses(lineView) {
-    updateLineBackground(lineView);
-    if (lineView.line.wrapClass)
-      ensureLineWrapped(lineView).className = lineView.line.wrapClass;
-    else if (lineView.node != lineView.text)
-      lineView.node.className = &quot;&quot;;
-    var textClass = lineView.textClass ? lineView.textClass + &quot; &quot; + (lineView.line.textClass || &quot;&quot;) : lineView.line.textClass;
-    lineView.text.className = textClass || &quot;&quot;;
</del><ins>+  for (var i = 0; i &lt; arr.length; ++i)
+    loop( i );
+}
+
+function fireOrphanDelayed() {
+  var delayed = orphanDelayedCallbacks
+  orphanDelayedCallbacks = null
+  for (var i = 0; i &lt; 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 &lt; lineView.changes.length; j++) {
+    var type = lineView.changes[j]
+    if (type == &quot;text&quot;) { updateLineText(cm, lineView) }
+    else if (type == &quot;gutter&quot;) { updateLineGutter(cm, lineView, lineN, dims) }
+    else if (type == &quot;class&quot;) { updateLineClasses(lineView) }
+    else if (type == &quot;widget&quot;) { updateLineWidgets(cm, lineView, dims) }
</ins><span class="cx">   }
</span><ins>+  lineView.changes = null
+}
</ins><span class="cx"> 
</span><del>-  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(&quot;div&quot;, null, &quot;CodeMirror-gutter-background &quot; + lineView.line.gutterClass,
-                                      &quot;left: &quot; + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
-                                      &quot;px; width: &quot; + dims.gutterTotalWidth + &quot;px&quot;);
-      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(&quot;div&quot;, null, &quot;CodeMirror-gutter-wrapper&quot;, &quot;left: &quot; +
-                                             (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + &quot;px&quot;);
-      cm.display.input.setUneditable(gutterWrap);
-      wrap.insertBefore(gutterWrap, lineView.text);
-      if (lineView.line.gutterClass)
-        gutterWrap.className += &quot; &quot; + lineView.line.gutterClass;
-      if (cm.options.lineNumbers &amp;&amp; (!markers || !markers[&quot;CodeMirror-linenumbers&quot;]))
-        lineView.lineNumber = gutterWrap.appendChild(
-          elt(&quot;div&quot;, lineNumberFor(cm.options, lineN),
-              &quot;CodeMirror-linenumber CodeMirror-gutter-elt&quot;,
-              &quot;left: &quot; + dims.gutterLeft[&quot;CodeMirror-linenumbers&quot;] + &quot;px; width: &quot;
-              + cm.display.lineNumInnerWidth + &quot;px&quot;));
-      if (markers) for (var k = 0; k &lt; cm.options.gutters.length; ++k) {
-        var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) &amp;&amp; markers[id];
-        if (found)
-          gutterWrap.appendChild(elt(&quot;div&quot;, [found], &quot;CodeMirror-gutter-elt&quot;, &quot;left: &quot; +
-                                     dims.gutterLeft[id] + &quot;px; width: &quot; + dims.gutterWidth[id] + &quot;px&quot;));
-      }
-    }
</del><ins>+// 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(&quot;div&quot;, null, null, &quot;position: relative&quot;)
+    if (lineView.text.parentNode)
+      { lineView.text.parentNode.replaceChild(lineView.node, lineView.text) }
+    lineView.node.appendChild(lineView.text)
+    if (ie &amp;&amp; ie_version &lt; 8) { lineView.node.style.zIndex = 2 }
</ins><span class="cx">   }
</span><ins>+  return lineView.node
+}
</ins><span class="cx"> 
</span><del>-  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 == &quot;CodeMirror-linewidget&quot;)
-        lineView.node.removeChild(node);
-    }
-    insertLineWidgets(cm, lineView, dims);
</del><ins>+function updateLineBackground(lineView) {
+  var cls = lineView.bgClass ? lineView.bgClass + &quot; &quot; + (lineView.line.bgClass || &quot;&quot;) : lineView.line.bgClass
+  if (cls) { cls += &quot; CodeMirror-linebackground&quot; }
+  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(&quot;div&quot;, null, cls), wrap.firstChild)
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // 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;
</del><ins>+// Wrapper around buildLineContent which will reuse the structure
+// in display.externalMeasured when possible.
+function getLineContent(cm, lineView) {
+  var ext = cm.display.externalMeasured
+  if (ext &amp;&amp; ext.line == lineView.line) {
+    cm.display.externalMeasured = null
+    lineView.measure = ext.measure
+    return ext.built
</ins><span class="cx">   }
</span><ins>+  return buildLineContent(cm, lineView)
+}
</ins><span class="cx"> 
</span><del>-  // 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 &lt; lineView.rest.length; i++)
-      insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
</del><ins>+// 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
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
-    if (!line.widgets) return;
-    var wrap = ensureLineWrapped(lineView);
-    for (var i = 0, ws = line.widgets; i &lt; ws.length; ++i) {
-      var widget = ws[i], node = elt(&quot;div&quot;, [widget.node], &quot;CodeMirror-linewidget&quot;);
-      if (!widget.handleMouseEvents) node.setAttribute(&quot;cm-ignore-events&quot;, &quot;true&quot;);
-      positionLineWidget(widget, node, lineView, dims);
-      cm.display.input.setUneditable(node);
-      if (allowAbove &amp;&amp; widget.above)
-        wrap.insertBefore(node, lineView.gutter || lineView.text);
-      else
-        wrap.appendChild(node);
-      signalLater(widget, &quot;redraw&quot;);
-    }
</del><ins>+function updateLineClasses(lineView) {
+  updateLineBackground(lineView)
+  if (lineView.line.wrapClass)
+    { ensureLineWrapped(lineView).className = lineView.line.wrapClass }
+  else if (lineView.node != lineView.text)
+    { lineView.node.className = &quot;&quot; }
+  var textClass = lineView.textClass ? lineView.textClass + &quot; &quot; + (lineView.line.textClass || &quot;&quot;) : lineView.line.textClass
+  lineView.text.className = textClass || &quot;&quot;
+}
+
+function updateLineGutter(cm, lineView, lineN, dims) {
+  if (lineView.gutter) {
+    lineView.node.removeChild(lineView.gutter)
+    lineView.gutter = null
</ins><span class="cx">   }
</span><ins>+  if (lineView.gutterBackground) {
+    lineView.node.removeChild(lineView.gutterBackground)
+    lineView.gutterBackground = null
+  }
+  if (lineView.line.gutterClass) {
+    var wrap = ensureLineWrapped(lineView)
+    lineView.gutterBackground = elt(&quot;div&quot;, null, &quot;CodeMirror-gutter-background &quot; + lineView.line.gutterClass,
+                                    (&quot;left: &quot; + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + &quot;px; width: &quot; + (dims.gutterTotalWidth) + &quot;px&quot;))
+    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(&quot;div&quot;, null, &quot;CodeMirror-gutter-wrapper&quot;, (&quot;left: &quot; + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + &quot;px&quot;))
+    cm.display.input.setUneditable(gutterWrap)
+    wrap$1.insertBefore(gutterWrap, lineView.text)
+    if (lineView.line.gutterClass)
+      { gutterWrap.className += &quot; &quot; + lineView.line.gutterClass }
+    if (cm.options.lineNumbers &amp;&amp; (!markers || !markers[&quot;CodeMirror-linenumbers&quot;]))
+      { lineView.lineNumber = gutterWrap.appendChild(
+        elt(&quot;div&quot;, lineNumberFor(cm.options, lineN),
+            &quot;CodeMirror-linenumber CodeMirror-gutter-elt&quot;,
+            (&quot;left: &quot; + (dims.gutterLeft[&quot;CodeMirror-linenumbers&quot;]) + &quot;px; width: &quot; + (cm.display.lineNumInnerWidth) + &quot;px&quot;))) }
+    if (markers) { for (var k = 0; k &lt; cm.options.gutters.length; ++k) {
+      var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) &amp;&amp; markers[id]
+      if (found)
+        { gutterWrap.appendChild(elt(&quot;div&quot;, [found], &quot;CodeMirror-gutter-elt&quot;,
+                                   (&quot;left: &quot; + (dims.gutterLeft[id]) + &quot;px; width: &quot; + (dims.gutterWidth[id]) + &quot;px&quot;))) }
+    } }
+  }
+}
</ins><span class="cx"> 
</span><del>-  function positionLineWidget(widget, node, lineView, dims) {
-    if (widget.noHScroll) {
-      (lineView.alignable || (lineView.alignable = [])).push(node);
-      var width = dims.wrapperWidth;
-      node.style.left = dims.fixedPos + &quot;px&quot;;
-      if (!widget.coverGutter) {
-        width -= dims.gutterTotalWidth;
-        node.style.paddingLeft = dims.gutterTotalWidth + &quot;px&quot;;
-      }
-      node.style.width = width + &quot;px&quot;;
-    }
-    if (widget.coverGutter) {
-      node.style.zIndex = 5;
-      node.style.position = &quot;relative&quot;;
-      if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + &quot;px&quot;;
-    }
</del><ins>+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 == &quot;CodeMirror-linewidget&quot;)
+      { lineView.node.removeChild(node) }
</ins><span class="cx">   }
</span><ins>+  insertLineWidgets(cm, lineView, dims)
+}
</ins><span class="cx"> 
</span><del>-  // POSITION OBJECT
</del><ins>+// 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 }
</ins><span class="cx"> 
</span><del>-  // 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;
-  };
</del><ins>+  updateLineClasses(lineView)
+  updateLineGutter(cm, lineView, lineN, dims)
+  insertLineWidgets(cm, lineView, dims)
+  return lineView.node
+}
</ins><span class="cx"> 
</span><del>-  // 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; };
</del><ins>+// 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 &lt; lineView.rest.length; i++)
+    { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false) } }
+}
</ins><span class="cx"> 
</span><del>-  function copyPos(x) {return Pos(x.line, x.ch);}
-  function maxPos(a, b) { return cmp(a, b) &lt; 0 ? b : a; }
-  function minPos(a, b) { return cmp(a, b) &lt; 0 ? a : b; }
</del><ins>+function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
+  if (!line.widgets) { return }
+  var wrap = ensureLineWrapped(lineView)
+  for (var i = 0, ws = line.widgets; i &lt; ws.length; ++i) {
+    var widget = ws[i], node = elt(&quot;div&quot;, [widget.node], &quot;CodeMirror-linewidget&quot;)
+    if (!widget.handleMouseEvents) { node.setAttribute(&quot;cm-ignore-events&quot;, &quot;true&quot;) }
+    positionLineWidget(widget, node, lineView, dims)
+    cm.display.input.setUneditable(node)
+    if (allowAbove &amp;&amp; widget.above)
+      { wrap.insertBefore(node, lineView.gutter || lineView.text) }
+    else
+      { wrap.appendChild(node) }
+    signalLater(widget, &quot;redraw&quot;)
+  }
+}
</ins><span class="cx"> 
</span><del>-  // INPUT HANDLING
</del><ins>+function positionLineWidget(widget, node, lineView, dims) {
+  if (widget.noHScroll) {
+    ;(lineView.alignable || (lineView.alignable = [])).push(node)
+    var width = dims.wrapperWidth
+    node.style.left = dims.fixedPos + &quot;px&quot;
+    if (!widget.coverGutter) {
+      width -= dims.gutterTotalWidth
+      node.style.paddingLeft = dims.gutterTotalWidth + &quot;px&quot;
+    }
+    node.style.width = width + &quot;px&quot;
+  }
+  if (widget.coverGutter) {
+    node.style.zIndex = 5
+    node.style.position = &quot;relative&quot;
+    if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + &quot;px&quot; }
+  }
+}
</ins><span class="cx"> 
</span><del>-  function ensureFocus(cm) {
-    if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
</del><ins>+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 = &quot;position: relative;&quot;
+    if (widget.coverGutter)
+      { parentStyle += &quot;margin-left: -&quot; + cm.display.gutters.offsetWidth + &quot;px;&quot; }
+    if (widget.noHScroll)
+      { parentStyle += &quot;width: &quot; + cm.display.wrapper.clientWidth + &quot;px;&quot; }
+    removeChildrenAndAdd(cm.display.measure, elt(&quot;div&quot;, [widget.node], null, parentStyle))
</ins><span class="cx">   }
</span><ins>+  return widget.height = widget.node.parentNode.offsetHeight
+}
</ins><span class="cx"> 
</span><del>-  function isReadOnly(cm) {
-    return cm.options.readOnly || cm.doc.cantEdit;
</del><ins>+// 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 &amp;&amp; n.getAttribute(&quot;cm-ignore-events&quot;) == &quot;true&quot;) ||
+        (n.parentNode == display.sizer &amp;&amp; n != display.mover))
+      { return true }
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // This will be set to an array of strings when copying, so that,
-  // when pasting, we know what kind of selections the copied text
-  // was made out of.
-  var lastCopied = null;
</del><ins>+// POSITION MEASUREMENT
</ins><span class="cx"> 
</span><del>-  function applyTextInput(cm, inserted, deleted, sel, origin) {
-    var doc = cm.doc;
-    cm.display.shift = false;
-    if (!sel) sel = doc.sel;
</del><ins>+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(&quot;pre&quot;, &quot;x&quot;))
+  var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle
+  var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}
+  if (!isNaN(data.left) &amp;&amp; !isNaN(data.right)) { display.cachedPaddingH = data }
+  return data
+}
</ins><span class="cx"> 
</span><del>-    var paste = cm.state.pasteIncoming || origin == &quot;paste&quot;;
-    var textLines = doc.splitLines(inserted), multiPaste = null;
-    // When pasing N lines into N selections, insert one line per selection
-    if (paste &amp;&amp; sel.ranges.length &gt; 1) {
-      if (lastCopied &amp;&amp; lastCopied.join(&quot;\n&quot;) == inserted) {
-        if (sel.ranges.length % lastCopied.length == 0) {
-          multiPaste = [];
-          for (var i = 0; i &lt; lastCopied.length; i++)
-            multiPaste.push(doc.splitLines(lastCopied[i]));
-        }
-      } else if (textLines.length == sel.ranges.length) {
-        multiPaste = map(textLines, function(l) { return [l]; });
-      }
-    }
</del><ins>+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
+}
</ins><span class="cx"> 
</span><del>-    // Normal behavior is to insert the new text into every selection
-    for (var i = sel.ranges.length - 1; i &gt;= 0; i--) {
-      var range = sel.ranges[i];
-      var from = range.from(), to = range.to();
-      if (range.empty()) {
-        if (deleted &amp;&amp; deleted &gt; 0) // Handle deletion
-          from = Pos(from.line, from.ch - deleted);
-        else if (cm.state.overwrite &amp;&amp; !paste) // Handle overwrite
-          to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
</del><ins>+// 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 &amp;&amp; displayWidth(cm)
+  if (!lineView.measure.heights || wrapping &amp;&amp; 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 &lt; rects.length - 1; i++) {
+        var cur = rects[i], next = rects[i + 1]
+        if (Math.abs(cur.bottom - next.bottom) &gt; 2)
+          { heights.push((cur.bottom + next.top) / 2 - rect.top) }
</ins><span class="cx">       }
</span><del>-      var updateInput = cm.curOp.updateInput;
-      var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
-                         origin: origin || (paste ? &quot;paste&quot; : cm.state.cutIncoming ? &quot;cut&quot; : &quot;+input&quot;)};
-      makeChange(cm.doc, changeEvent);
-      signalLater(cm, &quot;inputRead&quot;, cm, changeEvent);
</del><span class="cx">     }
</span><del>-    if (inserted &amp;&amp; !paste)
-      triggerElectric(cm, inserted);
</del><ins>+    heights.push(rect.bottom - rect.top)
+  }
+}
</ins><span class="cx"> 
</span><del>-    ensureCursorVisible(cm);
-    cm.curOp.updateInput = updateInput;
-    cm.curOp.typing = true;
-    cm.state.pasteIncoming = cm.state.cutIncoming = false;
</del><ins>+// 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 &lt; 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 &lt; lineView.rest.length; i$1++)
+    { if (lineNo(lineView.rest[i$1]) &gt; 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 &gt;= cm.display.viewFrom &amp;&amp; lineN &lt; cm.display.viewTo)
+    { return cm.display.view[findViewIndex(cm, lineN)] }
+  var ext = cm.display.externalMeasured
+  if (ext &amp;&amp; lineN &gt;= ext.lineN &amp;&amp; lineN &lt; 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 &amp;&amp; !view.text) {
+    view = null
+  } else if (view &amp;&amp; view.changes) {
+    updateLineForChanges(cm, view, lineN, getDimensions(cm))
+    cm.curOp.forceUpdate = true
</ins><span class="cx">   }
</span><ins>+  if (!view)
+    { view = updateExternalMeasurement(cm, line) }
</ins><span class="cx"> 
</span><del>-  function handlePaste(e, cm) {
-    var pasted = e.clipboardData &amp;&amp; e.clipboardData.getData(&quot;text/plain&quot;);
-    if (pasted) {
-      e.preventDefault();
-      if (!isReadOnly(cm) &amp;&amp; !cm.options.disableInput)
-        runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, &quot;paste&quot;); });
-      return true;
</del><ins>+  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 || &quot;&quot;), 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
</ins><span class="cx">     }
</span><ins>+    found = measureCharInner(cm, prepared, ch, bias)
+    if (!found.bogus) { prepared.cache[key] = found }
</ins><span class="cx">   }
</span><ins>+  return {left: found.left, right: found.right,
+          top: varHeight ? found.rtop : found.top,
+          bottom: varHeight ? found.rbottom : found.bottom}
+}
</ins><span class="cx"> 
</span><del>-  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;
</del><ins>+var nullRect = {left: 0, right: 0, top: 0, bottom: 0}
</ins><span class="cx"> 
</span><del>-    for (var i = sel.ranges.length - 1; i &gt;= 0; i--) {
-      var range = sel.ranges[i];
-      if (range.head.ch &gt; 100 || (i &amp;&amp; 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 &lt; mode.electricChars.length; j++)
-          if (inserted.indexOf(mode.electricChars.charAt(j)) &gt; -1) {
-            indented = indentLine(cm, range.head.line, &quot;smart&quot;);
-            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, &quot;smart&quot;);
-      }
-      if (indented) signalLater(cm, &quot;electricInput&quot;, cm, range.head.line);
</del><ins>+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 &lt; map.length; i += 3) {
+    mStart = map[i]
+    mEnd = map[i + 1]
+    if (ch &lt; mStart) {
+      start = 0; end = 1
+      collapse = &quot;left&quot;
+    } else if (ch &lt; mEnd) {
+      start = ch - mStart
+      end = start + 1
+    } else if (i == map.length - 3 || ch == mEnd &amp;&amp; map[i + 3] &gt; ch) {
+      end = mEnd - mStart
+      start = end - 1
+      if (ch &gt;= mEnd) { collapse = &quot;right&quot; }
</ins><span class="cx">     }
</span><ins>+    if (start != null) {
+      node = map[i + 2]
+      if (mStart == mEnd &amp;&amp; bias == (node.insertLeft ? &quot;left&quot; : &quot;right&quot;))
+        { collapse = bias }
+      if (bias == &quot;left&quot; &amp;&amp; start == 0)
+        { while (i &amp;&amp; map[i - 2] == map[i - 3] &amp;&amp; map[i - 1].insertLeft) {
+          node = map[(i -= 3) + 2]
+          collapse = &quot;left&quot;
+        } }
+      if (bias == &quot;right&quot; &amp;&amp; start == mEnd - mStart)
+        { while (i &lt; map.length - 3 &amp;&amp; map[i + 3] == map[i + 4] &amp;&amp; !map[i + 5].insertLeft) {
+          node = map[(i += 3) + 2]
+          collapse = &quot;right&quot;
+        } }
+      break
+    }
</ins><span class="cx">   }
</span><ins>+  return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
+}
</ins><span class="cx"> 
</span><del>-  function copyableRanges(cm) {
-    var text = [], ranges = [];
-    for (var i = 0; i &lt; 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));
</del><ins>+function getUsefulRect(rects, bias) {
+  var rect = nullRect
+  if (bias == &quot;left&quot;) { for (var i = 0; i &lt; rects.length; i++) {
+    if ((rect = rects[i]).left != rect.right) { break }
+  } } else { for (var i$1 = rects.length - 1; i$1 &gt;= 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 &lt; 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
+      while (start &amp;&amp; isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start }
+      while (place.coverStart + end &lt; place.coverEnd &amp;&amp; isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end }
+      if (ie &amp;&amp; ie_version &lt; 9 &amp;&amp; start == 0 &amp;&amp; end == place.coverEnd - place.coverStart)
+        { rect = node.parentNode.getBoundingClientRect() }
+      else
+        { rect = getUsefulRect(range(node, start, end).getClientRects(), bias) }
+      if (rect.left || rect.right || start == 0) { break }
+      end = start
+      start = start - 1
+      collapse = &quot;right&quot;
</ins><span class="cx">     }
</span><del>-    return {text: text, ranges: ranges};
</del><ins>+    if (ie &amp;&amp; ie_version &lt; 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect) }
+  } else { // If it is a widget, simply get the box for the whole widget.
+    if (start &gt; 0) { collapse = bias = &quot;right&quot; }
+    var rects
+    if (cm.options.lineWrapping &amp;&amp; (rects = node.getClientRects()).length &gt; 1)
+      { rect = rects[bias == &quot;right&quot; ? rects.length - 1 : 0] }
+    else
+      { rect = node.getBoundingClientRect() }
</ins><span class="cx">   }
</span><del>-
-  function disableBrowserMagic(field) {
-    field.setAttribute(&quot;autocorrect&quot;, &quot;off&quot;);
-    field.setAttribute(&quot;autocapitalize&quot;, &quot;off&quot;);
-    field.setAttribute(&quot;spellcheck&quot;, &quot;false&quot;);
</del><ins>+  if (ie &amp;&amp; ie_version &lt; 9 &amp;&amp; !start &amp;&amp; (!rect || !rect.left &amp;&amp; !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 }
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // TEXTAREA INPUT STYLE
</del><ins>+  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 &lt; heights.length - 1; i++)
+    { if (mid &lt; heights[i]) { break } }
+  var top = i ? heights[i - 1] : 0, bot = heights[i]
+  var result = {left: (collapse == &quot;right&quot; ? rect.right : rect.left) - prepared.rect.left,
+                right: (collapse == &quot;left&quot; ? rect.left : rect.right) - prepared.rect.left,
+                top: top, bottom: bot}
+  if (!rect.left &amp;&amp; !rect.right) { result.bogus = true }
+  if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot }
</ins><span class="cx"> 
</span><del>-  function TextareaInput(cm) {
-    this.cm = cm;
-    // See input.poll and input.reset
-    this.prevInput = &quot;&quot;;
</del><ins>+  return result
+}
</ins><span class="cx"> 
</span><del>-    // 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;
-  };
</del><ins>+// 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}
+}
</ins><span class="cx"> 
</span><del>-  function hiddenTextarea() {
-    var te = elt(&quot;textarea&quot;, null, null, &quot;position: absolute; padding: 0; width: 1px; height: 1em; outline: none&quot;);
-    var div = elt(&quot;div&quot;, [te], null, &quot;overflow: hidden; position: relative; width: 3px; height: 0px;&quot;);
-    // 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 = &quot;1000px&quot;;
-    else te.setAttribute(&quot;wrap&quot;, &quot;off&quot;);
-    // If border: 0; -- iOS fails to open keyboard (issue #1287)
-    if (ios) te.style.border = &quot;1px solid black&quot;;
-    disableBrowserMagic(te);
-    return div;
</del><ins>+function clearLineMeasurementCacheFor(lineView) {
+  if (lineView.measure) {
+    lineView.measure.cache = {}
+    lineView.measure.heights = null
+    if (lineView.rest) { for (var i = 0; i &lt; lineView.rest.length; i++)
+      { lineView.measure.caches[i] = {} } }
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  TextareaInput.prototype = copyObj({
-    init: function(display) {
-      var input = this, cm = this.cm;
</del><ins>+function clearLineMeasurementCache(cm) {
+  cm.display.externalMeasure = null
+  removeChildren(cm.display.lineMeasure)
+  for (var i = 0; i &lt; cm.display.view.length; i++)
+    { clearLineMeasurementCacheFor(cm.display.view[i]) }
+}
</ins><span class="cx"> 
</span><del>-      // 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);
</del><ins>+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
+}
</ins><span class="cx"> 
</span><del>-      // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
-      if (ios) te.style.width = &quot;0px&quot;;
</del><ins>+function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft }
+function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop }
</ins><span class="cx"> 
</span><del>-      on(te, &quot;input&quot;, function() {
-        if (ie &amp;&amp; ie_version &gt;= 9 &amp;&amp; input.hasSelection) input.hasSelection = null;
-        input.poll();
-      });
</del><ins>+// Converts a {top, bottom, left, right} box from line-local
+// coordinates into another coordinate system. Context may be one of
+// &quot;line&quot;, &quot;div&quot; (display.lineDiv), &quot;local&quot;./null (editor), &quot;window&quot;,
+// or &quot;page&quot;.
+function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
+  if (!includeWidgets &amp;&amp; lineObj.widgets) { for (var i = 0; i &lt; lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) {
+    var size = widgetHeight(lineObj.widgets[i])
+    rect.top += size; rect.bottom += size
+  } } }
+  if (context == &quot;line&quot;) { return rect }
+  if (!context) { context = &quot;local&quot; }
+  var yOff = heightAtLine(lineObj)
+  if (context == &quot;local&quot;) { yOff += paddingTop(cm.display) }
+  else { yOff -= cm.display.viewOffset }
+  if (context == &quot;page&quot; || context == &quot;window&quot;) {
+    var lOff = cm.display.lineSpace.getBoundingClientRect()
+    yOff += lOff.top + (context == &quot;window&quot; ? 0 : pageScrollY())
+    var xOff = lOff.left + (context == &quot;window&quot; ? 0 : pageScrollX())
+    rect.left += xOff; rect.right += xOff
+  }
+  rect.top += yOff; rect.bottom += yOff
+  return rect
+}
</ins><span class="cx"> 
</span><del>-      on(te, &quot;paste&quot;, function(e) {
-        if (handlePaste(e, cm)) return true;
</del><ins>+// Coverts a box from &quot;div&quot; coords to another coordinate system.
+// Context may be &quot;window&quot;, &quot;page&quot;, &quot;div&quot;, or &quot;local&quot;./null.
+function fromCoordSystem(cm, coords, context) {
+  if (context == &quot;div&quot;) { return coords }
+  var left = coords.left, top = coords.top
+  // First move into &quot;page&quot; coordinate system
+  if (context == &quot;page&quot;) {
+    left -= pageScrollX()
+    top -= pageScrollY()
+  } else if (context == &quot;local&quot; || !context) {
+    var localBox = cm.display.sizer.getBoundingClientRect()
+    left += localBox.left
+    top += localBox.top
+  }
</ins><span class="cx"> 
</span><del>-        cm.state.pasteIncoming = true;
-        input.fastPoll();
-      });
</del><ins>+  var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect()
+  return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
+}
</ins><span class="cx"> 
</span><del>-      function prepareCopyCut(e) {
-        if (cm.somethingSelected()) {
-          lastCopied = cm.getSelections();
-          if (input.inaccurateSelection) {
-            input.prevInput = &quot;&quot;;
-            input.inaccurateSelection = false;
-            te.value = lastCopied.join(&quot;\n&quot;);
-            selectInput(te);
-          }
-        } else if (!cm.options.lineWiseCopyCut) {
-          return;
-        } else {
-          var ranges = copyableRanges(cm);
-          lastCopied = ranges.text;
-          if (e.type == &quot;cut&quot;) {
-            cm.setSelections(ranges.ranges, null, sel_dontScroll);
-          } else {
-            input.prevInput = &quot;&quot;;
-            te.value = ranges.text.join(&quot;\n&quot;);
-            selectInput(te);
-          }
-        }
-        if (e.type == &quot;cut&quot;) cm.state.cutIncoming = true;
-      }
-      on(te, &quot;cut&quot;, prepareCopyCut);
-      on(te, &quot;copy&quot;, prepareCopyCut);
</del><ins>+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)
+}
</ins><span class="cx"> 
</span><del>-      on(display.scroller, &quot;paste&quot;, function(e) {
-        if (eventInWidget(display, e)) return;
-        cm.state.pasteIncoming = true;
-        input.focus();
-      });
</del><ins>+// 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 ? &quot;right&quot; : &quot;left&quot;, 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) &amp;&amp; partPos &amp;&amp; part.level &lt; order[partPos - 1].level) {
+      part = order[--partPos]
+      ch = bidiRight(part) - (part.level % 2 ? 0 : 1)
+      right = true
+    } else if (ch == bidiRight(part) &amp;&amp; partPos &lt; order.length - 1 &amp;&amp; part.level &lt; order[partPos + 1].level) {
+      part = order[++partPos]
+      ch = bidiLeft(part) - part.level % 2
+      right = false
+    }
+    if (right &amp;&amp; ch == part.to &amp;&amp; ch &gt; 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
+}
</ins><span class="cx"> 
</span><del>-      // Prevent normal selection in the editor (we handle our own)
-      on(display.lineSpace, &quot;selectstart&quot;, function(e) {
-        if (!eventInWidget(display, e)) e_preventDefault(e);
-      });
</del><ins>+// 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}
+}
</ins><span class="cx"> 
</span><del>-      on(te, &quot;compositionstart&quot;, function() {
-        var start = cm.getCursor(&quot;from&quot;);
-        input.composing = {
-          start: start,
-          range: cm.markText(start, cm.getCursor(&quot;to&quot;), {className: &quot;CodeMirror-composing&quot;})
-        };
-      });
-      on(te, &quot;compositionend&quot;, function() {
-        if (input.composing) {
-          input.poll();
-          input.composing.range.clear();
-          input.composing = null;
-        }
-      });
-    },
</del><ins>+// 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 &gt; 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
+}
</ins><span class="cx"> 
</span><del>-    prepareSelection: function() {
-      // Redraw the selection and/or cursor
-      var cm = this.cm, display = cm.display, doc = cm.doc;
-      var result = prepareSelection(cm);
</del><ins>+// Compute the character position closest to the given coordinates.
+// Input must be lineSpace-local (&quot;div&quot; coordinate system).
+function coordsChar(cm, x, y) {
+  var doc = cm.doc
+  y += cm.display.viewOffset
+  if (y &lt; 0) { return PosWithInfo(doc.first, 0, true, -1) }
+  var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1
+  if (lineN &gt; last)
+    { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1) }
+  if (x &lt; 0) { x = 0 }
</ins><span class="cx"> 
</span><del>-      // Move the hidden textarea near the cursor to prevent scrolling artifacts
-      if (cm.options.moveInputWithCursor) {
-        var headPos = cursorCoords(cm, doc.sel.primary().head, &quot;div&quot;);
-        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));
-      }
</del><ins>+  var lineObj = getLine(doc, lineN)
+  for (;;) {
+    var found = coordsCharInner(cm, lineObj, lineN, x, y)
+    var merged = collapsedSpanAtEnd(lineObj)
+    var mergedPos = merged &amp;&amp; merged.find(0, true)
+    if (merged &amp;&amp; (found.ch &gt; mergedPos.from.ch || found.ch == mergedPos.from.ch &amp;&amp; found.xRel &gt; 0))
+      { lineN = lineNo(lineObj = mergedPos.to.line) }
+    else
+      { return found }
+  }
+}
</ins><span class="cx"> 
</span><del>-      return result;
-    },
</del><ins>+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)
</ins><span class="cx"> 
</span><del>-    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 + &quot;px&quot;;
-        this.wrapper.style.left = drawn.teLeft + &quot;px&quot;;
-      }
-    },
</del><ins>+  function getX(ch) {
+    var sp = cursorCoords(cm, Pos(lineNo, ch), &quot;line&quot;, lineObj, preparedMeasure)
+    wrongLine = true
+    if (innerOff &gt; sp.bottom) { return sp.left - adjust }
+    else if (innerOff &lt; sp.top) { return sp.left + adjust }
+    else { wrongLine = false }
+    return sp.left
+  }
</ins><span class="cx"> 
</span><del>-    // 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 = &quot;&quot;;
-        var range = doc.sel.primary();
-        minimal = hasCopyEvent &amp;&amp;
-          (range.to().line - range.from().line &gt; 100 || (selected = cm.getSelection()).length &gt; 1000);
-        var content = minimal ? &quot;-&quot; : selected || cm.getSelection();
-        this.textarea.value = content;
-        if (cm.state.focused) selectInput(this.textarea);
-        if (ie &amp;&amp; ie_version &gt;= 9) this.hasSelection = content;
-      } else if (!typing) {
-        this.prevInput = this.textarea.value = &quot;&quot;;
-        if (ie &amp;&amp; ie_version &gt;= 9) this.hasSelection = null;
</del><ins>+  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 &gt; 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 &lt;= 1) {
+      var ch = x &lt; fromX || x - fromX &lt;= 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 &amp;&amp; !bidi &amp;&amp; !/\s/.test(lineObj.text.charAt(ch)) &amp;&amp; xDiff &gt; 0 &amp;&amp;
+          ch &lt; lineObj.text.length &amp;&amp; preparedMeasure.view.measure.heights.length &gt; 1) {
+        var charSize = measureCharPrepared(cm, preparedMeasure, ch, &quot;right&quot;)
+        if (innerOff &lt;= charSize.bottom &amp;&amp; innerOff &gt;= charSize.top &amp;&amp; Math.abs(x - charSize.right) &lt; xDiff) {
+          outside = false
+          ch++
+          xDiff = x - charSize.right
+        }
</ins><span class="cx">       }
</span><del>-      this.inaccurateSelection = minimal;
-    },
</del><ins>+      while (isExtendingChar(lineObj.text.charAt(ch))) { ++ch }
+      var pos = PosWithInfo(lineNo, ch, outside, xDiff &lt; -1 ? -1 : xDiff &gt; 1 ? 1 : 0)
+      return pos
+    }
+    var step = Math.ceil(dist / 2), middle = from + step
+    if (bidi) {
+      middle = from
+      for (var i = 0; i &lt; step; ++i) { middle = moveVisually(lineObj, middle, 1) }
+    }
+    var middleX = getX(middle)
+    if (middleX &gt; x) {to = middle; toX = middleX; if (toOutside = wrongLine) { toX += 1000; } dist = step}
+    else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step}
+  }
+}
</ins><span class="cx"> 
</span><del>-    getField: function() { return this.textarea; },
</del><ins>+var measureText
+// Compute the default text height.
+function textHeight(display) {
+  if (display.cachedTextHeight != null) { return display.cachedTextHeight }
+  if (measureText == null) {
+    measureText = elt(&quot;pre&quot;)
+    // Measure a bunch of lines, for browsers that compute
+    // fractional heights.
+    for (var i = 0; i &lt; 49; ++i) {
+      measureText.appendChild(document.createTextNode(&quot;x&quot;))
+      measureText.appendChild(elt(&quot;br&quot;))
+    }
+    measureText.appendChild(document.createTextNode(&quot;x&quot;))
+  }
+  removeChildrenAndAdd(display.measure, measureText)
+  var height = measureText.offsetHeight / 50
+  if (height &gt; 3) { display.cachedTextHeight = height }
+  removeChildren(display.measure)
+  return height || 1
+}
</ins><span class="cx"> 
</span><del>-    supportsTouch: function() { return false; },
</del><ins>+// Compute the default character width.
+function charWidth(display) {
+  if (display.cachedCharWidth != null) { return display.cachedCharWidth }
+  var anchor = elt(&quot;span&quot;, &quot;xxxxxxxxxx&quot;)
+  var pre = elt(&quot;pre&quot;, [anchor])
+  removeChildrenAndAdd(display.measure, pre)
+  var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10
+  if (width &gt; 2) { display.cachedCharWidth = width }
+  return width || 10
+}
</ins><span class="cx"> 
</span><del>-    focus: function() {
-      if (this.cm.options.readOnly != &quot;nocursor&quot; &amp;&amp; (!mobile || activeElt() != this.textarea)) {
-        try { this.textarea.focus(); }
-        catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
-      }
-    },
</del><ins>+// 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}
+}
</ins><span class="cx"> 
</span><del>-    blur: function() { this.textarea.blur(); },
</del><ins>+// 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
+}
</ins><span class="cx"> 
</span><del>-    resetPosition: function() {
-      this.wrapper.style.top = this.wrapper.style.left = 0;
-    },
</del><ins>+// 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 &amp;&amp; Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3)
+  return function (line) {
+    if (lineIsHidden(cm.doc, line)) { return 0 }
</ins><span class="cx"> 
</span><del>-    receivedFocus: function() { this.slowPoll(); },
</del><ins>+    var widgetsHeight = 0
+    if (line.widgets) { for (var i = 0; i &lt; line.widgets.length; i++) {
+      if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height }
+    } }
</ins><span class="cx"> 
</span><del>-    // 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();
-      });
-    },
</del><ins>+    if (wrapping)
+      { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
+    else
+      { return widgetsHeight + th }
+  }
+}
</ins><span class="cx"> 
</span><del>-    // 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 &amp;&amp; !missed) {missed = true; input.polling.set(60, p);}
-        else {input.pollingFast = false; input.slowPoll();}
-      }
-      input.polling.set(20, p);
-    },
</del><ins>+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) }
+  })
+}
</ins><span class="cx"> 
</span><del>-    // 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) &amp;&amp; !prevInput &amp;&amp; !this.composing) ||
-          isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq)
-        return false;
</del><ins>+// 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 &amp;&amp; e_target(e).getAttribute(&quot;cm-not-content&quot;) == &quot;true&quot;) { return null }
</ins><span class="cx"> 
</span><del>-      var text = input.value;
-      // If nothing changed, bail.
-      if (text == prevInput &amp;&amp; !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 &amp;&amp; ie_version &gt;= 9 &amp;&amp; this.hasSelection === text ||
-          mac &amp;&amp; /[\uf700-\uf7ff]/.test(text)) {
-        cm.display.input.reset();
-        return false;
-      }
</del><ins>+  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 &amp;&amp; coords.xRel == 1 &amp;&amp; (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
+}
</ins><span class="cx"> 
</span><del>-      if (cm.doc.sel == cm.display.selForContextMenu) {
-        var first = text.charCodeAt(0);
-        if (first == 0x200b &amp;&amp; !prevInput) prevInput = &quot;\u200b&quot;;
-        if (first == 0x21da) { this.reset(); return this.cm.execCommand(&quot;undo&quot;); }
-      }
-      // Find the part of the input that is actually new
-      var same = 0, l = Math.min(prevInput.length, text.length);
-      while (same &lt; l &amp;&amp; prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
</del><ins>+// Find the view element corresponding to a given line. Return null
+// when the line isn't visible.
+function findViewIndex(cm, n) {
+  if (n &gt;= cm.display.viewTo) { return null }
+  n -= cm.display.viewFrom
+  if (n &lt; 0) { return null }
+  var view = cm.display.view
+  for (var i = 0; i &lt; view.length; i++) {
+    n -= view[i].size
+    if (n &lt; 0) { return i }
+  }
+}
</ins><span class="cx"> 
</span><del>-      var self = this;
-      runInOp(cm, function() {
-        applyTextInput(cm, text.slice(same), prevInput.length - same,
-                       null, self.composing ? &quot;*compose&quot; : null);
</del><ins>+function updateSelection(cm) {
+  cm.display.input.showSelection(cm.display.input.prepareSelection())
+}
</ins><span class="cx"> 
</span><del>-        // Don't leave long text in the textarea, since it makes further polling slow
-        if (text.length &gt; 1000 || text.indexOf(&quot;\n&quot;) &gt; -1) input.value = self.prevInput = &quot;&quot;;
-        else self.prevInput = text;
</del><ins>+function prepareSelection(cm, primary) {
+  var doc = cm.doc, result = {}
+  var curFragment = result.cursors = document.createDocumentFragment()
+  var selFragment = result.selection = document.createDocumentFragment()
</ins><span class="cx"> 
</span><del>-        if (self.composing) {
-          self.composing.range.clear();
-          self.composing.range = cm.markText(self.composing.start, cm.getCursor(&quot;to&quot;),
-                                             {className: &quot;CodeMirror-composing&quot;});
-        }
-      });
-      return true;
-    },
</del><ins>+  for (var i = 0; i &lt; doc.sel.ranges.length; i++) {
+    if (primary === false &amp;&amp; i == doc.sel.primIndex) { continue }
+    var range = doc.sel.ranges[i]
+    if (range.from().line &gt;= cm.display.viewTo || range.to().line &lt; 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
+}
</ins><span class="cx"> 
</span><del>-    ensurePolled: function() {
-      if (this.pollingFast &amp;&amp; this.poll()) this.pollingFast = false;
-    },
</del><ins>+// Draws a cursor for the given range
+function drawSelectionCursor(cm, head, output) {
+  var pos = cursorCoords(cm, head, &quot;div&quot;, null, null, !cm.options.singleCursorHeightPerLine)
</ins><span class="cx"> 
</span><del>-    onKeyPress: function() {
-      if (ie &amp;&amp; ie_version &gt;= 9) this.hasSelection = null;
-      this.fastPoll();
-    },
</del><ins>+  var cursor = output.appendChild(elt(&quot;div&quot;, &quot;\u00a0&quot;, &quot;CodeMirror-cursor&quot;))
+  cursor.style.left = pos.left + &quot;px&quot;
+  cursor.style.top = pos.top + &quot;px&quot;
+  cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + &quot;px&quot;
</ins><span class="cx"> 
</span><del>-    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.
</del><ins>+  if (pos.other) {
+    // Secondary cursor, shown when on a 'jump' in bi-directional text
+    var otherCursor = output.appendChild(elt(&quot;div&quot;, &quot;\u00a0&quot;, &quot;CodeMirror-cursor CodeMirror-secondarycursor&quot;))
+    otherCursor.style.display = &quot;&quot;
+    otherCursor.style.left = pos.other.left + &quot;px&quot;
+    otherCursor.style.top = pos.other.top + &quot;px&quot;
+    otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + &quot;px&quot;
+  }
+}
</ins><span class="cx"> 
</span><del>-      // 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 &amp;&amp; cm.doc.sel.contains(pos) == -1)
-        operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
</del><ins>+// 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
</ins><span class="cx"> 
</span><del>-      var oldCSS = te.style.cssText;
-      input.wrapper.style.position = &quot;absolute&quot;;
-      te.style.cssText = &quot;position: fixed; width: 30px; height: 30px; top: &quot; + (e.clientY - 5) +
-        &quot;px; left: &quot; + (e.clientX - 5) + &quot;px; z-index: 1000; background: &quot; +
-        (ie ? &quot;rgba(255, 255, 255, .05)&quot; : &quot;transparent&quot;) +
-        &quot;; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);&quot;;
-      if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
-      display.input.focus();
-      if (webkit) window.scrollTo(null, oldScrollY);
-      display.input.reset();
-      // Adds &quot;Select all&quot; to context menu in FF
-      if (!cm.somethingSelected()) te.value = input.prevInput = &quot; &quot;;
-      input.contextMenuPending = true;
-      display.selForContextMenu = cm.doc.sel;
-      clearTimeout(display.detectingSelectAll);
</del><ins>+  function add(left, top, width, bottom) {
+    if (top &lt; 0) { top = 0 }
+    top = Math.round(top)
+    bottom = Math.round(bottom)
+    fragment.appendChild(elt(&quot;div&quot;, null, &quot;CodeMirror-selected&quot;, (&quot;position: absolute; left: &quot; + left + &quot;px;\n                             top: &quot; + top + &quot;px; width: &quot; + (width == null ? rightSide - left : width) + &quot;px;\n                             height: &quot; + (bottom - top) + &quot;px&quot;)))
+  }
</ins><span class="cx"> 
</span><del>-      // 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 = &quot;\u200b&quot; + (selected ? te.value : &quot;&quot;);
-          te.value = &quot;\u21da&quot;; // Used to catch context-menu undo
-          te.value = extval;
-          input.prevInput = selected ? &quot;&quot; : &quot;\u200b&quot;;
-          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.position = &quot;relative&quot;;
-        te.style.cssText = oldCSS;
-        if (ie &amp;&amp; ie_version &lt; 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
</del><ins>+  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), &quot;div&quot;, lineObj, bias)
+    }
</ins><span class="cx"> 
</span><del>-        // Try to detect the user choosing select-all
-        if (te.selectionStart != null) {
-          if (!ie || (ie &amp;&amp; ie_version &lt; 9)) prepareSelectAllHack();
-          var i = 0, poll = function() {
-            if (display.selForContextMenu == cm.doc.sel &amp;&amp; te.selectionStart == 0 &amp;&amp;
-                te.selectionEnd &gt; 0 &amp;&amp; input.prevInput == &quot;\u200b&quot;)
-              operation(cm, commands.selectAll)(cm);
-            else if (i++ &lt; 10) display.detectingSelectAll = setTimeout(poll, 500);
-            else display.input.reset();
-          };
-          display.detectingSelectAll = setTimeout(poll, 200);
-        }
</del><ins>+    iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) {
+      var leftPos = coords(from, &quot;left&quot;), rightPos, left, right
+      if (from == to) {
+        rightPos = leftPos
+        left = right = leftPos.left
+      } else {
+        rightPos = coords(to - 1, &quot;right&quot;)
+        if (dir == &quot;rtl&quot;) { var tmp = leftPos; leftPos = rightPos; rightPos = tmp }
+        left = leftPos.left
+        right = rightPos.right
</ins><span class="cx">       }
</span><ins>+      if (fromArg == null &amp;&amp; from == 0) { left = leftSide }
+      if (rightPos.top - leftPos.top &gt; 3) { // Different lines, draw top part
+        add(left, leftPos.top, null, leftPos.bottom)
+        left = leftSide
+        if (leftPos.bottom &lt; rightPos.top) { add(left, leftPos.bottom, null, rightPos.top) }
+      }
+      if (toArg == null &amp;&amp; to == lineLen) { right = rightSide }
+      if (!start || leftPos.top &lt; start.top || leftPos.top == start.top &amp;&amp; leftPos.left &lt; start.left)
+        { start = leftPos }
+      if (!end || rightPos.bottom &gt; end.bottom || rightPos.bottom == end.bottom &amp;&amp; rightPos.right &gt; end.right)
+        { end = rightPos }
+      if (left &lt; leftSide + 1) { left = leftSide }
+      add(left, rightPos.top, right - left, rightPos.bottom)
+    })
+    return {start: start, end: end}
+  }
</ins><span class="cx"> 
</span><del>-      if (ie &amp;&amp; ie_version &gt;= 9) prepareSelectAllHack();
-      if (captureRightClick) {
-        e_stop(e);
-        var mouseup = function() {
-          off(window, &quot;mouseup&quot;, mouseup);
-          setTimeout(rehide, 20);
-        };
-        on(window, &quot;mouseup&quot;, mouseup);
</del><ins>+  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 &lt; rightStart.top - 2) {
+        add(leftEnd.right, leftEnd.top, null, leftEnd.bottom)
+        add(leftSide, rightStart.top, rightStart.left, rightStart.bottom)
</ins><span class="cx">       } else {
</span><del>-        setTimeout(rehide, 50);
</del><ins>+        add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom)
</ins><span class="cx">       }
</span><del>-    },
</del><ins>+    }
+    if (leftEnd.bottom &lt; rightStart.top)
+      { add(leftSide, leftEnd.bottom, null, rightStart.top) }
+  }
</ins><span class="cx"> 
</span><del>-    setUneditable: nothing,
</del><ins>+  output.appendChild(fragment)
+}
</ins><span class="cx"> 
</span><del>-    needsContentAttribute: false
-  }, TextareaInput.prototype);
</del><ins>+// Cursor-blinking
+function restartBlink(cm) {
+  if (!cm.state.focused) { return }
+  var display = cm.display
+  clearInterval(display.blinker)
+  var on = true
+  display.cursorDiv.style.visibility = &quot;&quot;
+  if (cm.options.cursorBlinkRate &gt; 0)
+    { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? &quot;&quot; : &quot;hidden&quot;; },
+      cm.options.cursorBlinkRate) }
+  else if (cm.options.cursorBlinkRate &lt; 0)
+    { display.cursorDiv.style.visibility = &quot;hidden&quot; }
+}
</ins><span class="cx"> 
</span><del>-  // CONTENTEDITABLE INPUT STYLE
</del><ins>+function ensureFocus(cm) {
+  if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm) }
+}
</ins><span class="cx"> 
</span><del>-  function ContentEditableInput(cm) {
-    this.cm = cm;
-    this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
-    this.polling = new Delayed();
-    this.gracePeriod = false;
</del><ins>+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 == &quot;nocursor&quot;) { return }
+  if (!cm.state.focused) {
+    signal(cm, &quot;focus&quot;, cm, e)
+    cm.state.focused = true
+    addClass(cm.display.wrapper, &quot;CodeMirror-focused&quot;)
+    // 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 &amp;&amp; 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()
</ins><span class="cx">   }
</span><ins>+  restartBlink(cm)
+}
+function onBlur(cm, e) {
+  if (cm.state.delayingBlurEvent) { return }
</ins><span class="cx"> 
</span><del>-  ContentEditableInput.prototype = copyObj({
-    init: function(display) {
-      var input = this, cm = input.cm;
-      var div = input.div = display.lineDiv;
-      div.contentEditable = &quot;true&quot;;
-      disableBrowserMagic(div);
</del><ins>+  if (cm.state.focused) {
+    signal(cm, &quot;blur&quot;, cm, e)
+    cm.state.focused = false
+    rmClass(cm.display.wrapper, &quot;CodeMirror-focused&quot;)
+  }
+  clearInterval(cm.display.blinker)
+  setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false } }, 150)
+}
</ins><span class="cx"> 
</span><del>-      on(div, &quot;paste&quot;, function(e) { handlePaste(e, cm); })
</del><ins>+// 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 &amp;&amp; (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
+  var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft
+  var gutterW = display.gutters.offsetWidth, left = comp + &quot;px&quot;
+  for (var i = 0; i &lt; 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 &lt; align.length; j++)
+      { align[j].style.left = left } }
+  } }
+  if (cm.options.fixedGutter)
+    { display.gutters.style.left = (comp + gutterW) + &quot;px&quot; }
+}
</ins><span class="cx"> 
</span><del>-      on(div, &quot;compositionstart&quot;, 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 &gt; -1 &amp;&amp; found &lt;= prim.head.ch)
-          input.composing.sel = simpleSelection(Pos(prim.head.line, found),
-                                                Pos(prim.head.line, found + data.length));
-      });
-      on(div, &quot;compositionupdate&quot;, function(e) {
-        input.composing.data = e.data;
-      });
-      on(div, &quot;compositionend&quot;, function(e) {
-        var ours = input.composing;
-        if (!ours) return;
-        if (e.data != ours.startData &amp;&amp; !/\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);
-      });
</del><ins>+// 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(&quot;div&quot;, [elt(&quot;div&quot;, last)],
+                                               &quot;CodeMirror-linenumber CodeMirror-gutter-elt&quot;))
+    var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW
+    display.lineGutter.style.width = &quot;&quot;
+    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 + &quot;px&quot;
+    updateGutterSpace(cm)
+    return true
+  }
+  return false
+}
</ins><span class="cx"> 
</span><del>-      on(div, &quot;touchstart&quot;, function() {
-        input.forceCompositionEnd();
-      });
</del><ins>+// 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 &lt; display.view.length; i++) {
+    var cur = display.view[i], height = (void 0)
+    if (cur.hidden) { continue }
+    if (ie &amp;&amp; ie_version &lt; 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 &lt; 2) { height = textHeight(display) }
+    if (diff &gt; .001 || diff &lt; -.001) {
+      updateLineHeight(cur.line, height)
+      updateWidgetHeight(cur.line)
+      if (cur.rest) { for (var j = 0; j &lt; cur.rest.length; j++)
+        { updateWidgetHeight(cur.rest[j]) } }
+    }
+  }
+}
</ins><span class="cx"> 
</span><del>-      on(div, &quot;input&quot;, function() {
-        if (input.composing) return;
-        if (!input.pollContent())
-          runInOp(input.cm, function() {regChange(cm);});
-      });
</del><ins>+// Read and store the height of line widgets associated with the
+// given line.
+function updateWidgetHeight(line) {
+  if (line.widgets) { for (var i = 0; i &lt; line.widgets.length; ++i)
+    { line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight } }
+}
</ins><span class="cx"> 
</span><del>-      function onCopyCut(e) {
-        if (cm.somethingSelected()) {
-          lastCopied = cm.getSelections();
-          if (e.type == &quot;cut&quot;) cm.replaceSelection(&quot;&quot;, null, &quot;cut&quot;);
-        } else if (!cm.options.lineWiseCopyCut) {
-          return;
-        } else {
-          var ranges = copyableRanges(cm);
-          lastCopied = ranges.text;
-          if (e.type == &quot;cut&quot;) {
-            cm.operation(function() {
-              cm.setSelections(ranges.ranges, 0, sel_dontScroll);
-              cm.replaceSelection(&quot;&quot;, null, &quot;cut&quot;);
-            });
-          }
-        }
-        // iOS exposes the clipboard API, but seems to discard content inserted into it
-        if (e.clipboardData &amp;&amp; !ios) {
-          e.preventDefault();
-          e.clipboardData.clearData();
-          e.clipboardData.setData(&quot;text/plain&quot;, lastCopied.join(&quot;\n&quot;));
-        } 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.join(&quot;\n&quot;);
-          var hadFocus = document.activeElement;
-          selectInput(te);
-          setTimeout(function() {
-            cm.display.lineSpace.removeChild(kludge);
-            hadFocus.focus();
-          }, 50);
-        }
-      }
-      on(div, &quot;copy&quot;, onCopyCut);
-      on(div, &quot;cut&quot;, onCopyCut);
-    },
</del><ins>+// 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 &amp;&amp; viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop
+  top = Math.floor(top - paddingTop(display))
+  var bottom = viewport &amp;&amp; viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight
</ins><span class="cx"> 
</span><del>-    prepareSelection: function() {
-      var result = prepareSelection(this.cm, false);
-      result.focus = this.cm.state.focused;
-      return result;
-    },
</del><ins>+  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 &amp;&amp; viewport.ensure) {
+    var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line
+    if (ensureFrom &lt; from) {
+      from = ensureFrom
+      to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)
+    } else if (Math.min(ensureTo, doc.lastLine()) &gt;= to) {
+      from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight)
+      to = ensureTo
+    }
+  }
+  return {from: from, to: Math.max(to, from + 1)}
+}
</ins><span class="cx"> 
</span><del>-    showSelection: function(info) {
-      if (!info || !this.cm.display.view.length) return;
-      if (info.focus) this.showPrimarySelection();
-      this.showMultipleSelections(info);
-    },
</del><ins>+// Sync the scrollable area and scrollbars, ensure the viewport
+// covers the visible area.
+function setScrollTop(cm, val) {
+  if (Math.abs(cm.doc.scrollTop - val) &lt; 2) { return }
+  cm.doc.scrollTop = val
+  if (!gecko) { updateDisplaySimple(cm, {top: val}) }
+  if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val }
+  cm.display.scrollbars.setScrollTop(val)
+  if (gecko) { updateDisplaySimple(cm) }
+  startWorker(cm, 100)
+}
+// Sync scroller and scrollbar, ensure the gutter elements are
+// aligned.
+function setScrollLeft(cm, val, isScroller) {
+  if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) &lt; 2) { return }
+  val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)
+  cm.doc.scrollLeft = val
+  alignHorizontally(cm)
+  if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val }
+  cm.display.scrollbars.setScrollLeft(val)
+}
</ins><span class="cx"> 
</span><del>-    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 &amp;&amp; !curAnchor.bad &amp;&amp; curFocus &amp;&amp; !curFocus.bad &amp;&amp;
-          cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &amp;&amp;
-          cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
-        return;
</del><ins>+// Since the delta values reported on mouse wheel events are
+// unstandardized between browsers and even browser versions, and
+// generally horribly unpredictable, this code starts by measuring
+// the scroll effect that the first few mouse wheel events have,
+// and, from that, detects the way it can convert deltas to pixel
+// offsets afterwards.
+//
+// The reason we want to know the amount a wheel event will scroll
+// is that it gives us a chance to update the display before the
+// actual scrolling happens, reducing flickering.
</ins><span class="cx"> 
</span><del>-      var start = posToDOM(this.cm, prim.from());
-      var end = posToDOM(this.cm, prim.to());
-      if (!start &amp;&amp; !end) return;
</del><ins>+var wheelSamples = 0;
+var wheelPixelsPerUnit = null;
+// Fill in a browser-detected starting value on browsers where we
+// know one. These don't have to be accurate -- the result of them
+// being wrong would just be a slight flicker on the first wheel
+// scroll (if it is large enough).
+if (ie) { wheelPixelsPerUnit = -.53 }
+else if (gecko) { wheelPixelsPerUnit = 15 }
+else if (chrome) { wheelPixelsPerUnit = -.7 }
+else if (safari) { wheelPixelsPerUnit = -1/3 }
</ins><span class="cx"> 
</span><del>-      var view = this.cm.display.view;
-      var old = sel.rangeCount &amp;&amp; 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]};
-      }
</del><ins>+function wheelEventDelta(e) {
+  var dx = e.wheelDeltaX, dy = e.wheelDeltaY
+  if (dx == null &amp;&amp; e.detail &amp;&amp; e.axis == e.HORIZONTAL_AXIS) { dx = e.detail }
+  if (dy == null &amp;&amp; e.detail &amp;&amp; e.axis == e.VERTICAL_AXIS) { dy = e.detail }
+  else if (dy == null) { dy = e.wheelDelta }
+  return {x: dx, y: dy}
+}
+function wheelEventPixels(e) {
+  var delta = wheelEventDelta(e)
+  delta.x *= wheelPixelsPerUnit
+  delta.y *= wheelPixelsPerUnit
+  return delta
+}
</ins><span class="cx"> 
</span><del>-      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) {
-        sel.removeAllRanges();
-        sel.addRange(rng);
-        if (old &amp;&amp; sel.anchorNode == null) sel.addRange(old);
-        else if (gecko) this.startGracePeriod();
-      }
-      this.rememberSelection();
-    },
</del><ins>+function onScrollWheel(cm, e) {
+  var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y
</ins><span class="cx"> 
</span><del>-    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);
-    },
</del><ins>+  var display = cm.display, scroll = display.scroller
+  // Quit if there's nothing to scroll here
+  var canScrollX = scroll.scrollWidth &gt; scroll.clientWidth
+  var canScrollY = scroll.scrollHeight &gt; scroll.clientHeight
+  if (!(dx &amp;&amp; canScrollX || dy &amp;&amp; canScrollY)) { return }
</ins><span class="cx"> 
</span><del>-    showMultipleSelections: function(info) {
-      removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
-      removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
-    },
</del><ins>+  // Webkit browsers on OS X abort momentum scrolls when the target
+  // of the scroll event is removed from the scrollable element.
+  // This hack (see related code in patchDisplay) makes sure the
+  // element is kept around.
+  if (dy &amp;&amp; mac &amp;&amp; webkit) {
+    outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
+      for (var i = 0; i &lt; view.length; i++) {
+        if (view[i].node == cur) {
+          cm.display.currentWheelTarget = cur
+          break outer
+        }
+      }
+    }
+  }
</ins><span class="cx"> 
</span><del>-    rememberSelection: function() {
-      var sel = window.getSelection();
-      this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
-      this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
-    },
</del><ins>+  // On some browsers, horizontal scrolling will cause redraws to
+  // happen before the gutter has been realigned, causing it to
+  // wriggle around in a most unseemly way. When we have an
+  // estimated pixels/delta value, we just handle horizontal
+  // scrolling entirely here. It'll be slightly off from native, but
+  // better than glitching out.
+  if (dx &amp;&amp; !gecko &amp;&amp; !presto &amp;&amp; wheelPixelsPerUnit != null) {
+    if (dy &amp;&amp; canScrollY)
+      { setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))) }
+    setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)))
+    // Only prevent default scrolling if vertical scrolling is
+    // actually possible. Otherwise, it causes vertical scroll
+    // jitter on OSX trackpads when deltaX is small and deltaY
+    // is large (issue #3579)
+    if (!dy || (dy &amp;&amp; canScrollY))
+      { e_preventDefault(e) }
+    display.wheelStartX = null // Abort measurement, if in progress
+    return
+  }
</ins><span class="cx"> 
</span><del>-    selectionInEditor: function() {
-      var sel = window.getSelection();
-      if (!sel.rangeCount) return false;
-      var node = sel.getRangeAt(0).commonAncestorContainer;
-      return contains(this.div, node);
-    },
</del><ins>+  // 'Project' the visible viewport to cover the area that is being
+  // scrolled into view (if we know enough to estimate it).
+  if (dy &amp;&amp; wheelPixelsPerUnit != null) {
+    var pixels = dy * wheelPixelsPerUnit
+    var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight
+    if (pixels &lt; 0) { top = Math.max(0, top + pixels - 50) }
+    else { bot = Math.min(cm.doc.height, bot + pixels + 50) }
+    updateDisplaySimple(cm, {top: top, bottom: bot})
+  }
</ins><span class="cx"> 
</span><del>-    focus: function() {
-      if (this.cm.options.readOnly != &quot;nocursor&quot;) this.div.focus();
-    },
-    blur: function() { this.div.blur(); },
-    getField: function() { return this.div; },
</del><ins>+  if (wheelSamples &lt; 20) {
+    if (display.wheelStartX == null) {
+      display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop
+      display.wheelDX = dx; display.wheelDY = dy
+      setTimeout(function () {
+        if (display.wheelStartX == null) { return }
+        var movedX = scroll.scrollLeft - display.wheelStartX
+        var movedY = scroll.scrollTop - display.wheelStartY
+        var sample = (movedY &amp;&amp; display.wheelDY &amp;&amp; movedY / display.wheelDY) ||
+          (movedX &amp;&amp; display.wheelDX &amp;&amp; movedX / display.wheelDX)
+        display.wheelStartX = display.wheelStartY = null
+        if (!sample) { return }
+        wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1)
+        ++wheelSamples
+      }, 200)
+    } else {
+      display.wheelDX += dx; display.wheelDY += dy
+    }
+  }
+}
</ins><span class="cx"> 
</span><del>-    supportsTouch: function() { return true; },
</del><ins>+// SCROLLBARS
</ins><span class="cx"> 
</span><del>-    receivedFocus: function() {
-      var input = this;
-      if (this.selectionInEditor())
-        this.pollSelection();
-      else
-        runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
</del><ins>+// 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
+  }
+}
</ins><span class="cx"> 
</span><del>-      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);
-    },
</del><ins>+var NativeScrollbars = function(place, scroll, cm) {
+  this.cm = cm
+  var vert = this.vert = elt(&quot;div&quot;, [elt(&quot;div&quot;, null, null, &quot;min-width: 1px&quot;)], &quot;CodeMirror-vscrollbar&quot;)
+  var horiz = this.horiz = elt(&quot;div&quot;, [elt(&quot;div&quot;, null, null, &quot;height: 100%; min-height: 1px&quot;)], &quot;CodeMirror-hscrollbar&quot;)
+  place(vert); place(horiz)
</ins><span class="cx"> 
</span><del>-    selectionChanged: function() {
-      var sel = window.getSelection();
-      return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
-        sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
-    },
</del><ins>+  on(vert, &quot;scroll&quot;, function () {
+    if (vert.clientHeight) { scroll(vert.scrollTop, &quot;vertical&quot;) }
+  })
+  on(horiz, &quot;scroll&quot;, function () {
+    if (horiz.clientWidth) { scroll(horiz.scrollLeft, &quot;horizontal&quot;) }
+  })
</ins><span class="cx"> 
</span><del>-    pollSelection: function() {
-      if (!this.composing &amp;&amp; !this.gracePeriod &amp;&amp; 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 &amp;&amp; head) runInOp(cm, function() {
-          setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
-          if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
-        });
-      }
-    },
</del><ins>+  this.checkedZeroWidth = false
+  // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
+  if (ie &amp;&amp; ie_version &lt; 8) { this.horiz.style.minHeight = this.vert.style.minWidth = &quot;18px&quot; }
+};
</ins><span class="cx"> 
</span><del>-    pollContent: function() {
-      var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
-      var from = sel.from(), to = sel.to();
-      if (from.line &lt; display.viewFrom || to.line &gt; display.viewTo - 1) return false;
</del><ins>+NativeScrollbars.prototype.update = function (measure) {
+  var needsH = measure.scrollWidth &gt; measure.clientWidth + 1
+  var needsV = measure.scrollHeight &gt; measure.clientHeight + 1
+  var sWidth = measure.nativeBarWidth
</ins><span class="cx"> 
</span><del>-      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;
-      }
</del><ins>+  if (needsV) {
+    this.vert.style.display = &quot;block&quot;
+    this.vert.style.bottom = needsH ? sWidth + &quot;px&quot; : &quot;0&quot;
+    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) + &quot;px&quot;
+  } else {
+    this.vert.style.display = &quot;&quot;
+    this.vert.firstChild.style.height = &quot;0&quot;
+  }
</ins><span class="cx"> 
</span><del>-      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 &gt; 1 &amp;&amp; oldText.length &gt; 1) {
-        if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
-        else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
-        else break;
-      }
</del><ins>+  if (needsH) {
+    this.horiz.style.display = &quot;block&quot;
+    this.horiz.style.right = needsV ? sWidth + &quot;px&quot; : &quot;0&quot;
+    this.horiz.style.left = measure.barLeft + &quot;px&quot;
+    var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0)
+    this.horiz.firstChild.style.width =
+      (measure.scrollWidth - measure.clientWidth + totalWidth) + &quot;px&quot;
+  } else {
+    this.horiz.style.display = &quot;&quot;
+    this.horiz.firstChild.style.width = &quot;0&quot;
+  }
</ins><span class="cx"> 
</span><del>-      var cutFront = 0, cutEnd = 0;
-      var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
-      while (cutFront &lt; maxCutFront &amp;&amp; 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 &lt; maxCutEnd &amp;&amp;
-             newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
-        ++cutEnd;
</del><ins>+  if (!this.checkedZeroWidth &amp;&amp; measure.clientHeight &gt; 0) {
+    if (sWidth == 0) { this.zeroWidthHack() }
+    this.checkedZeroWidth = true
+  }
</ins><span class="cx"> 
</span><del>-      newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
-      newText[0] = newText[0].slice(cutFront);
</del><ins>+  return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
+};
</ins><span class="cx"> 
</span><del>-      var chFrom = Pos(fromLine, cutFront);
-      var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
-      if (newText.length &gt; 1 || newText[0] || cmp(chFrom, chTo)) {
-        replaceRange(cm.doc, newText, chFrom, chTo, &quot;+input&quot;);
-        return true;
-      }
-    },
</del><ins>+NativeScrollbars.prototype.setScrollLeft = function (pos) {
+  if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos }
+  if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz) }
+};
</ins><span class="cx"> 
</span><del>-    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 (composing.data &amp;&amp; composing.data != composing.startData)
-        operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
-    },
</del><ins>+NativeScrollbars.prototype.setScrollTop = function (pos) {
+  if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos }
+  if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert) }
+};
</ins><span class="cx"> 
</span><del>-    setUneditable: function(node) {
-      node.setAttribute(&quot;contenteditable&quot;, &quot;false&quot;);
-    },
</del><ins>+NativeScrollbars.prototype.zeroWidthHack = function () {
+  var w = mac &amp;&amp; !mac_geMountainLion ? &quot;12px&quot; : &quot;18px&quot;
+  this.horiz.style.height = this.vert.style.width = w
+  this.horiz.style.pointerEvents = this.vert.style.pointerEvents = &quot;none&quot;
+  this.disableHoriz = new Delayed
+  this.disableVert = new Delayed
+};
</ins><span class="cx"> 
</span><del>-    onKeyPress: function(e) {
-      e.preventDefault();
-      operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
-    },
</del><ins>+NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay) {
+  bar.style.pointerEvents = &quot;auto&quot;
+  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 = &quot;none&quot; }
+    else { delay.set(1000, maybeDisable) }
+  }
+  delay.set(1000, maybeDisable)
+};
</ins><span class="cx"> 
</span><del>-    onContextMenu: nothing,
-    resetPosition: nothing,
</del><ins>+NativeScrollbars.prototype.clear = function () {
+  var parent = this.horiz.parentNode
+  parent.removeChild(this.horiz)
+  parent.removeChild(this.vert)
+};
</ins><span class="cx"> 
</span><del>-    needsContentAttribute: true
-  }, ContentEditableInput.prototype);
</del><ins>+var NullScrollbars = function () {};
</ins><span class="cx"> 
</span><del>-  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);
</del><ins>+NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
+NullScrollbars.prototype.setScrollLeft = function () {};
+NullScrollbars.prototype.setScrollTop = function () {};
+NullScrollbars.prototype.clear = function () {};
</ins><span class="cx"> 
</span><del>-    var order = getOrder(line), side = &quot;left&quot;;
-    if (order) {
-      var partPos = getBidiPartAt(order, pos.ch);
-      side = partPos % 2 ? &quot;right&quot; : &quot;left&quot;;
-    }
-    var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
-    result.offset = result.collapse == &quot;right&quot; ? result.end : result.start;
-    return result;
</del><ins>+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 &lt; 4 &amp;&amp; startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
+    if (startWidth != cm.display.barWidth &amp;&amp; cm.options.lineWrapping)
+      { updateHeightsInViewport(cm) }
+    updateScrollbarsInner(cm, measureForScrollbars(cm))
+    startWidth = cm.display.barWidth; startHeight = cm.display.barHeight
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
</del><ins>+// 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)
</ins><span class="cx"> 
</span><del>-  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;
-    } else {
-      for (lineNode = node;; lineNode = lineNode.parentNode) {
-        if (!lineNode || lineNode == cm.display.lineDiv) return null;
-        if (lineNode.parentNode &amp;&amp; lineNode.parentNode == cm.display.lineDiv) break;
-      }
-    }
-    for (var i = 0; i &lt; cm.display.view.length; i++) {
-      var lineView = cm.display.view[i];
-      if (lineView.node == lineNode)
-        return locateNodeInLineView(lineView, node, offset);
-    }
</del><ins>+  d.sizer.style.paddingRight = (d.barWidth = sizes.right) + &quot;px&quot;
+  d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + &quot;px&quot;
+  d.heightForcer.style.borderBottom = sizes.bottom + &quot;px solid transparent&quot;
+
+  if (sizes.right &amp;&amp; sizes.bottom) {
+    d.scrollbarFiller.style.display = &quot;block&quot;
+    d.scrollbarFiller.style.height = sizes.bottom + &quot;px&quot;
+    d.scrollbarFiller.style.width = sizes.right + &quot;px&quot;
+  } else { d.scrollbarFiller.style.display = &quot;&quot; }
+  if (sizes.bottom &amp;&amp; cm.options.coverGutterNextToScrollbar &amp;&amp; cm.options.fixedGutter) {
+    d.gutterFiller.style.display = &quot;block&quot;
+    d.gutterFiller.style.height = sizes.bottom + &quot;px&quot;
+    d.gutterFiller.style.width = measure.gutterWidth + &quot;px&quot;
+  } else { d.gutterFiller.style.display = &quot;&quot; }
+}
+
+var scrollbarModel = {&quot;native&quot;: NativeScrollbars, &quot;null&quot;: 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) }
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  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);
-      }
-    }
</del><ins>+  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, &quot;mousedown&quot;, function () {
+      if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0) }
+    })
+    node.setAttribute(&quot;cm-not-content&quot;, &quot;true&quot;)
+  }, function (pos, axis) {
+    if (axis == &quot;horizontal&quot;) { setScrollLeft(cm, pos) }
+    else { setScrollTop(cm, pos) }
+  }, cm)
+  if (cm.display.scrollbars.addClass)
+    { addClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
+}
</ins><span class="cx"> 
</span><del>-    var textNode = node.nodeType == 3 ? node : null, topNode = node;
-    if (!textNode &amp;&amp; node.childNodes.length == 1 &amp;&amp; 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;
</del><ins>+// SCROLLING THINGS INTO VIEW
</ins><span class="cx"> 
</span><del>-    function find(textNode, topNode, offset) {
-      for (var i = -1; i &lt; (maps ? maps.length : 0); i++) {
-        var map = i &lt; 0 ? measure.map : maps[i];
-        for (var j = 0; j &lt; map.length; j += 3) {
-          var curNode = map[j + 2];
-          if (curNode == textNode || curNode == topNode) {
-            var line = lineNo(i &lt; 0 ? lineView.line : lineView.rest[i]);
-            var ch = map[j] + offset;
-            if (offset &lt; 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);
</del><ins>+// 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, coords) {
+  if (signalDOMEvent(cm, &quot;scrollCursorIntoView&quot;)) { return }
</ins><span class="cx"> 
</span><del>-    // 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;
-    }
</del><ins>+  var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null
+  if (coords.top + box.top &lt; 0) { doScroll = true }
+  else if (coords.bottom + box.top &gt; (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false }
+  if (doScroll != null &amp;&amp; !phantom) {
+    var scrollNode = elt(&quot;div&quot;, &quot;\u200b&quot;, null, (&quot;position: absolute;\n                         top: &quot; + (coords.top - display.viewOffset - paddingTop(cm.display)) + &quot;px;\n                         height: &quot; + (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + &quot;px;\n                         left: &quot; + (coords.left) + &quot;px; width: 2px;&quot;))
+    cm.display.lineSpace.appendChild(scrollNode)
+    scrollNode.scrollIntoView(doScroll)
+    cm.display.lineSpace.removeChild(scrollNode)
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  function domTextBetween(cm, from, to, fromLine, toLine) {
-    var text = &quot;&quot;, 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(&quot;cm-text&quot;);
-        if (cmText != null) {
-          if (cmText == &quot;&quot;) cmText = node.textContent.replace(/\u200b/g, &quot;&quot;);
-          text += cmText;
-          return;
-        }
-        var markerID = node.getAttribute(&quot;cm-marker&quot;), range;
-        if (markerID) {
-          var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
-          if (found.length &amp;&amp; (range = found[0].find()))
-            text += getBetween(cm.doc, range.from, range.to).join(lineSep);
-          return;
-        }
-        if (node.getAttribute(&quot;contenteditable&quot;) == &quot;false&quot;) return;
-        for (var i = 0; i &lt; 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;
-      }
</del><ins>+// 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 coords
+  for (var limit = 0; limit &lt; 5; limit++) {
+    var changed = false
+    coords = cursorCoords(cm, pos)
+    var endCoords = !end || end == pos ? coords : cursorCoords(cm, end)
+    var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
+                                       Math.min(coords.top, endCoords.top) - margin,
+                                       Math.max(coords.left, endCoords.left),
+                                       Math.max(coords.bottom, endCoords.bottom) + margin)
+    var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft
+    if (scrollPos.scrollTop != null) {
+      setScrollTop(cm, scrollPos.scrollTop)
+      if (Math.abs(cm.doc.scrollTop - startTop) &gt; 1) { changed = true }
</ins><span class="cx">     }
</span><del>-    for (;;) {
-      walk(from);
-      if (from == to) break;
-      from = from.nextSibling;
</del><ins>+    if (scrollPos.scrollLeft != null) {
+      setScrollLeft(cm, scrollPos.scrollLeft)
+      if (Math.abs(cm.doc.scrollLeft - startLeft) &gt; 1) { changed = true }
</ins><span class="cx">     }
</span><del>-    return text;
</del><ins>+    if (!changed) { break }
</ins><span class="cx">   }
</span><ins>+  return coords
+}
</ins><span class="cx"> 
</span><del>-  CodeMirror.inputStyles = {&quot;textarea&quot;: TextareaInput, &quot;contenteditable&quot;: ContentEditableInput};
</del><ins>+// Scroll a given set of coordinates into view (immediately).
+function scrollIntoView(cm, x1, y1, x2, y2) {
+  var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2)
+  if (scrollPos.scrollTop != null) { setScrollTop(cm, scrollPos.scrollTop) }
+  if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft) }
+}
</ins><span class="cx"> 
</span><del>-  // SELECTION / CURSOR
</del><ins>+// 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, x1, y1, x2, y2) {
+  var display = cm.display, snapMargin = textHeight(cm.display)
+  if (y1 &lt; 0) { y1 = 0 }
+  var screentop = cm.curOp &amp;&amp; cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop
+  var screen = displayHeight(cm), result = {}
+  if (y2 - y1 &gt; screen) { y2 = y1 + screen }
+  var docBottom = cm.doc.height + paddingVert(display)
+  var atTop = y1 &lt; snapMargin, atBottom = y2 &gt; docBottom - snapMargin
+  if (y1 &lt; screentop) {
+    result.scrollTop = atTop ? 0 : y1
+  } else if (y2 &gt; screentop + screen) {
+    var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen)
+    if (newTop != screentop) { result.scrollTop = newTop }
+  }
</ins><span class="cx"> 
</span><del>-  // 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;
</del><ins>+  var screenleft = cm.curOp &amp;&amp; cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft
+  var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0)
+  var tooWide = x2 - x1 &gt; screenw
+  if (tooWide) { x2 = x1 + screenw }
+  if (x1 &lt; 10)
+    { result.scrollLeft = 0 }
+  else if (x1 &lt; screenleft)
+    { result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)) }
+  else if (x2 &gt; screenw + screenleft - 3)
+    { result.scrollLeft = x2 + (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 addToScrollPos(cm, left, top) {
+  if (left != null || top != null) { resolveScrollToPos(cm) }
+  if (left != null)
+    { cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left }
+  if (top != null)
+    { 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(), from = cur, to = cur
+  if (!cm.options.lineWrapping) {
+    from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur
+    to = Pos(cur.line, cur.ch + 1)
</ins><span class="cx">   }
</span><ins>+  cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}
+}
</ins><span class="cx"> 
</span><del>-  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 &lt; 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 &lt; 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 &lt; 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 &lt; this.ranges.length; i++) {
-        var range = this.ranges[i];
-        if (cmp(end, range.from()) &gt;= 0 &amp;&amp; cmp(pos, range.to()) &lt;= 0)
-          return i;
-      }
-      return -1;
-    }
-  };
</del><ins>+// 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)
+    var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
+                                  Math.min(from.top, to.top) - range.margin,
+                                  Math.max(from.right, to.right),
+                                  Math.max(from.bottom, to.bottom) + range.margin)
+    cm.scrollTo(sPos.scrollLeft, sPos.scrollTop)
+  }
+}
</ins><span class="cx"> 
</span><del>-  function Range(anchor, head) {
-    this.anchor = anchor; this.head = head;
</del><ins>+// 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
</ins><span class="cx">   }
</span><ins>+  pushOperation(cm.curOp)
+}
</ins><span class="cx"> 
</span><del>-  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 &amp;&amp; this.head.ch == this.anchor.ch;
-    }
-  };
</del><ins>+// 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 &lt; group.ops.length; i++)
+      { group.ops[i].cm.curOp = null }
+    endOperations(group)
+  })
+}
</ins><span class="cx"> 
</span><del>-  // 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 &lt; ranges.length; i++) {
-      var cur = ranges[i], prev = ranges[i - 1];
-      if (cmp(prev.to(), cur.from()) &gt;= 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 &lt;= primIndex) --primIndex;
-        ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
-      }
-    }
-    return new Selection(ranges, primIndex);
</del><ins>+// 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 &lt; ops.length; i++) // Read DOM
+    { endOperation_R1(ops[i]) }
+  for (var i$1 = 0; i$1 &lt; ops.length; i$1++) // Write DOM (maybe)
+    { endOperation_W1(ops[i$1]) }
+  for (var i$2 = 0; i$2 &lt; ops.length; i$2++) // Read DOM
+    { endOperation_R2(ops[i$2]) }
+  for (var i$3 = 0; i$3 &lt; ops.length; i$3++) // Write DOM (maybe)
+    { endOperation_W2(ops[i$3]) }
+  for (var i$4 = 0; i$4 &lt; 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 &amp;&amp; (op.scrollToPos.from.line &lt; display.viewFrom ||
+                       op.scrollToPos.to.line &gt;= display.viewTo) ||
+    display.maxLineChanged &amp;&amp; cm.options.lineWrapping
+  op.update = op.mustUpdate &amp;&amp;
+    new DisplayUpdate(cm, op.mustUpdate &amp;&amp; {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate)
+}
+
+function endOperation_W1(op) {
+  op.updatedDisplay = op.mustUpdate &amp;&amp; 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 &amp;&amp; !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))
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  function simpleSelection(anchor, head) {
-    return new Selection([new Range(anchor, head || anchor)], 0);
</del><ins>+  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 + &quot;px&quot;
+    if (op.maxScrollLeft &lt; cm.doc.scrollLeft)
+      { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) }
+    cm.display.maxLineChanged = false
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // 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 &lt; doc.first) return Pos(doc.first, 0);
-    var last = doc.first + doc.size - 1;
-    if (pos.line &gt; last) return Pos(last, getLine(doc, last).text.length);
-    return clipToLen(pos, getLine(doc, pos.line).text.length);
</del><ins>+  var takeFocus = op.focus &amp;&amp; op.focus == activeElt() &amp;&amp; (!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 &amp;&amp; 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 &amp;&amp; (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 &amp;&amp; (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
</ins><span class="cx">   }
</span><del>-  function clipToLen(pos, linelen) {
-    var ch = pos.ch;
-    if (ch == null || ch &gt; linelen) return Pos(pos.line, linelen);
-    else if (ch &lt; 0) return Pos(pos.line, 0);
-    else return pos;
</del><ins>+  if (op.scrollLeft != null &amp;&amp; (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)
</ins><span class="cx">   }
</span><del>-  function isLine(doc, l) {return l &gt;= doc.first &amp;&amp; l &lt; doc.first + doc.size;}
-  function clipPosArray(doc, array) {
-    for (var out = [], i = 0; i &lt; array.length; i++) out[i] = clipPos(doc, array[i]);
-    return out;
</del><ins>+  // 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 &amp;&amp; cm.state.focused) { maybeScrollWindow(cm, coords) }
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // SELECTION UPDATES
</del><ins>+  // 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 &lt; hidden.length; ++i)
+    { if (!hidden[i].lines.length) { signal(hidden[i], &quot;hide&quot;) } } }
+  if (unhidden) { for (var i$1 = 0; i$1 &lt; unhidden.length; ++i$1)
+    { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], &quot;unhide&quot;) } } }
</ins><span class="cx"> 
</span><del>-  // The 'scroll' parameter given to many of these indicated whether
-  // the new cursor position should be scrolled into view after
-  // modifying the selection.
</del><ins>+  if (display.wrapper.offsetHeight)
+    { doc.scrollTop = cm.display.scroller.scrollTop }
</ins><span class="cx"> 
</span><del>-  // 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 &amp;&amp; doc.cm.display.shift || doc.extend) {
-      var anchor = range.anchor;
-      if (other) {
-        var posBefore = cmp(head, anchor) &lt; 0;
-        if (posBefore != (cmp(other, anchor) &lt; 0)) {
-          anchor = head;
-          head = other;
-        } else if (posBefore != (cmp(head, other) &lt; 0)) {
-          head = other;
-        }
-      }
-      return new Range(anchor, head);
-    } else {
-      return new Range(other || head, head);
-    }
-  }
</del><ins>+  // Fire change events, and delayed event handlers
+  if (op.changeObjs)
+    { signal(cm, &quot;changes&quot;, cm, op.changeObjs) }
+  if (op.update)
+    { op.update.finish() }
+}
</ins><span class="cx"> 
</span><del>-  // 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);
</del><ins>+// 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) }
</ins><span class="cx">   }
</span><del>-
-  // 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 &lt; 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);
</del><ins>+}
+// 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) }
</ins><span class="cx">   }
</span><del>-
-  // 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);
</del><ins>+}
+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) }
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // Reset the selection to a single range.
-  function setSimpleSelection(doc, anchor, head, options) {
-    setSelection(doc, simpleSelection(anchor, head), options);
-  }
</del><ins>+// 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 }
</ins><span class="cx"> 
</span><del>-  // Give beforeSelectionChange handlers a change to influence a
-  // selection update.
-  function filterSelectionChange(doc, sel) {
-    var obj = {
-      ranges: sel.ranges,
-      update: function(ranges) {
-        this.ranges = [];
-        for (var i = 0; i &lt; ranges.length; i++)
-          this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
-                                     clipPos(doc, ranges[i].head));
-      }
-    };
-    signal(doc, &quot;beforeSelectionChange&quot;, doc, obj);
-    if (doc.cm) signal(doc.cm, &quot;beforeSelectionChange&quot;, doc.cm, obj);
-    if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
-    else return sel;
-  }
</del><ins>+  var display = cm.display
+  if (lendiff &amp;&amp; to &lt; display.viewTo &amp;&amp;
+      (display.updateLineNumbers == null || display.updateLineNumbers &gt; from))
+    { display.updateLineNumbers = from }
</ins><span class="cx"> 
</span><del>-  function setSelectionReplaceHistory(doc, sel, options) {
-    var done = doc.history.done, last = lst(done);
-    if (last &amp;&amp; last.ranges) {
-      done[done.length - 1] = sel;
-      setSelectionNoUndo(doc, sel, options);
</del><ins>+  cm.curOp.viewChanged = true
+
+  if (from &gt;= display.viewTo) { // Change after
+    if (sawCollapsedSpans &amp;&amp; visualLineNo(cm.doc, from) &lt; display.viewTo)
+      { resetView(cm) }
+  } else if (to &lt;= display.viewFrom) { // Change before
+    if (sawCollapsedSpans &amp;&amp; visualLineEndNo(cm.doc, to + lendiff) &gt; display.viewFrom) {
+      resetView(cm)
</ins><span class="cx">     } else {
</span><del>-      setSelection(doc, sel, options);
</del><ins>+      display.viewFrom += lendiff
+      display.viewTo += lendiff
</ins><span class="cx">     }
</span><ins>+  } else if (from &lt;= display.viewFrom &amp;&amp; to &gt;= display.viewTo) { // Full overlap
+    resetView(cm)
+  } else if (from &lt;= 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 &gt;= 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 &amp;&amp; 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)
+    }
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // 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);
</del><ins>+  var ext = display.externalMeasured
+  if (ext) {
+    if (to &lt; ext.lineN)
+      { ext.lineN += lendiff }
+    else if (from &lt; ext.lineN + ext.size)
+      { display.externalMeasured = null }
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  function setSelectionNoUndo(doc, sel, options) {
-    if (hasHandler(doc, &quot;beforeSelectionChange&quot;) || doc.cm &amp;&amp; hasHandler(doc.cm, &quot;beforeSelectionChange&quot;))
-      sel = filterSelectionChange(doc, sel);
</del><ins>+// Register a change to a single line. Type must be one of &quot;text&quot;,
+// &quot;gutter&quot;, &quot;class&quot;, &quot;widget&quot;
+function regLineChange(cm, line, type) {
+  cm.curOp.viewChanged = true
+  var display = cm.display, ext = cm.display.externalMeasured
+  if (ext &amp;&amp; line &gt;= ext.lineN &amp;&amp; line &lt; ext.lineN + ext.size)
+    { display.externalMeasured = null }
</ins><span class="cx"> 
</span><del>-    var bias = options &amp;&amp; options.bias ||
-      (cmp(sel.primary().head, doc.sel.primary().head) &lt; 0 ? -1 : 1);
-    setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
</del><ins>+  if (line &lt; display.viewFrom || line &gt;= 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) }
+}
</ins><span class="cx"> 
</span><del>-    if (!(options &amp;&amp; options.scroll === false) &amp;&amp; doc.cm)
-      ensureCursorVisible(doc.cm);
-  }
</del><ins>+// Clear the view.
+function resetView(cm) {
+  cm.display.viewFrom = cm.display.viewTo = cm.doc.first
+  cm.display.view = []
+  cm.display.viewOffset = 0
+}
</ins><span class="cx"> 
</span><del>-  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);
</del><ins>+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 &lt; index; i++)
+    { n += view[i].size }
+  if (n != oldN) {
+    if (dir &gt; 0) {
+      if (index == view.length - 1) { return null }
+      diff = (n + view[index].size) - oldN
+      index++
+    } else {
+      diff = n - oldN
</ins><span class="cx">     }
</span><del>-    signalLater(doc, &quot;cursorActivity&quot;, doc);
</del><ins>+    oldN += diff; newN += diff
</ins><span class="cx">   }
</span><ins>+  while (visualLineNo(cm.doc, newN) != newN) {
+    if (index == (dir &lt; 0 ? 0 : view.length - 1)) { return null }
+    newN += dir * view[index - (dir &lt; 0 ? 1 : 0)].size
+    index += dir
+  }
+  return {index: index, lineN: newN}
+}
</ins><span class="cx"> 
</span><del>-  // 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);
</del><ins>+// 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 &gt;= display.viewTo || to &lt;= display.viewFrom) {
+    display.view = buildViewArray(cm, from, to)
+    display.viewFrom = from
+  } else {
+    if (display.viewFrom &gt; from)
+      { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view) }
+    else if (display.viewFrom &lt; from)
+      { display.view = display.view.slice(findViewIndex(cm, from)) }
+    display.viewFrom = from
+    if (display.viewTo &lt; to)
+      { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)) }
+    else if (display.viewTo &gt; to)
+      { display.view = display.view.slice(0, findViewIndex(cm, to)) }
</ins><span class="cx">   }
</span><ins>+  display.viewTo = to
+}
</ins><span class="cx"> 
</span><del>-  // Return a selection that does not partially select any atomic
-  // ranges.
-  function skipAtomicInSelection(doc, sel, bias, mayClear) {
-    var out;
-    for (var i = 0; i &lt; sel.ranges.length; i++) {
-      var range = sel.ranges[i];
-      var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
-      var newHead = skipAtomic(doc, range.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;
</del><ins>+// 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 &lt; view.length; i++) {
+    var lineView = view[i]
+    if (!lineView.hidden &amp;&amp; (!lineView.node || lineView.changes)) { ++dirty }
</ins><span class="cx">   }
</span><ins>+  return dirty
+}
</ins><span class="cx"> 
</span><del>-  // Ensure a given position is not inside an atomic range.
-  function skipAtomic(doc, pos, bias, mayClear) {
-    var flipped = false, curPos = pos;
-    var dir = bias || 1;
-    doc.cantEdit = false;
-    search: for (;;) {
-      var line = getLine(doc, curPos.line);
-      if (line.markedSpans) {
-        for (var i = 0; i &lt; line.markedSpans.length; ++i) {
-          var sp = line.markedSpans[i], m = sp.marker;
-          if ((sp.from == null || (m.inclusiveLeft ? sp.from &lt;= curPos.ch : sp.from &lt; curPos.ch)) &amp;&amp;
-              (sp.to == null || (m.inclusiveRight ? sp.to &gt;= curPos.ch : sp.to &gt; curPos.ch))) {
-            if (mayClear) {
-              signal(m, &quot;beforeCursorEnter&quot;);
-              if (m.explicitlyCleared) {
-                if (!line.markedSpans) break;
-                else {--i; continue;}
-              }
-            }
-            if (!m.atomic) continue;
-            var newPos = m.find(dir &lt; 0 ? -1 : 1);
-            if (cmp(newPos, curPos) == 0) {
-              newPos.ch += dir;
-              if (newPos.ch &lt; 0) {
-                if (newPos.line &gt; doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
-                else newPos = null;
-              } else if (newPos.ch &gt; line.text.length) {
-                if (newPos.line &lt; doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
-                else newPos = null;
-              }
-              if (!newPos) {
-                if (flipped) {
-                  // Driven in a corner -- no valid cursor position found at all
-                  // -- try again *with* clearing, if we didn't already
-                  if (!mayClear) return skipAtomic(doc, pos, bias, true);
-                  // Otherwise, turn off editing until further notice, and return the start of the doc
-                  doc.cantEdit = true;
-                  return Pos(doc.first, 0);
-                }
-                flipped = true; newPos = pos; dir = -dir;
-              }
-            }
-            curPos = newPos;
-            continue search;
-          }
-        }
-      }
-      return curPos;
</del><ins>+// HIGHLIGHT WORKER
+
+function startWorker(cm, time) {
+  if (cm.doc.mode.startState &amp;&amp; cm.doc.frontier &lt; cm.display.viewTo)
+    { cm.state.highlight.set(time, bind(highlightWorker, cm)) }
+}
+
+function highlightWorker(cm) {
+  var doc = cm.doc
+  if (doc.frontier &lt; doc.first) { doc.frontier = doc.first }
+  if (doc.frontier &gt;= 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 &gt;= cm.display.viewFrom) { // Visible
+      var oldStyles = line.styles, tooLong = line.text.length &gt; 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 &amp;&amp; (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass)
+      for (var i = 0; !ischange &amp;&amp; i &lt; 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 &lt;= cm.options.maxHighlightLength)
+        { processLine(cm, line.text, state) }
+      line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null
</ins><span class="cx">     }
</span><del>-  }
</del><ins>+    ++doc.frontier
+    if (+new Date &gt; end) {
+      startWorker(cm, cm.options.workDelay)
+      return true
+    }
+  })
+  if (changedLines.length) { runInOp(cm, function () {
+    for (var i = 0; i &lt; changedLines.length; i++)
+      { regLineChange(cm, changedLines[i], &quot;text&quot;) }
+  }) }
+}
</ins><span class="cx"> 
</span><del>-  // SELECTION DRAWING
</del><ins>+// DISPLAY DRAWING
</ins><span class="cx"> 
</span><del>-  function updateSelection(cm) {
-    cm.display.input.showSelection(cm.display.input.prepareSelection());
</del><ins>+var DisplayUpdate = function(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 () {
+    var this$1 = this;
+
+  for (var i = 0; i &lt; this.events.length; i++)
+    { signal.apply(null, this$1.events[i]) }
+};
+
+function maybeClipScrollbars(cm) {
+  var display = cm.display
+  if (!display.scrollbarsClipped &amp;&amp; display.scroller.offsetWidth) {
+    display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth
+    display.heightForcer.style.height = scrollGap(cm) + &quot;px&quot;
+    display.sizer.style.marginBottom = -display.nativeBarWidth + &quot;px&quot;
+    display.sizer.style.borderRightWidth = scrollGap(cm) + &quot;px&quot;
+    display.scrollbarsClipped = true
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  function prepareSelection(cm, primary) {
-    var doc = cm.doc, result = {};
-    var curFragment = result.cursors = document.createDocumentFragment();
-    var selFragment = result.selection = document.createDocumentFragment();
</del><ins>+// 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
</ins><span class="cx"> 
</span><del>-    for (var i = 0; i &lt; doc.sel.ranges.length; i++) {
-      if (primary === false &amp;&amp; i == doc.sel.primIndex) continue;
-      var range = doc.sel.ranges[i];
-      var collapsed = range.empty();
-      if (collapsed || cm.options.showCursorWhenSelecting)
-        drawSelectionCursor(cm, range.head, curFragment);
-      if (!collapsed)
-        drawSelectionRange(cm, range, selFragment);
-    }
-    return result;
</del><ins>+  if (update.editorIsHidden) {
+    resetView(cm)
+    return false
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // Draws a cursor for the given range
-  function drawSelectionCursor(cm, head, output) {
-    var pos = cursorCoords(cm, head, &quot;div&quot;, null, null, !cm.options.singleCursorHeightPerLine);
</del><ins>+  // Bail out if the visible area is already rendered and nothing changed.
+  if (!update.force &amp;&amp;
+      update.visible.from &gt;= display.viewFrom &amp;&amp; update.visible.to &lt;= display.viewTo &amp;&amp;
+      (display.updateLineNumbers == null || display.updateLineNumbers &gt;= display.viewTo) &amp;&amp;
+      display.renderedView == display.view &amp;&amp; countDirtyView(cm) == 0)
+    { return false }
</ins><span class="cx"> 
</span><del>-    var cursor = output.appendChild(elt(&quot;div&quot;, &quot;\u00a0&quot;, &quot;CodeMirror-cursor&quot;));
-    cursor.style.left = pos.left + &quot;px&quot;;
-    cursor.style.top = pos.top + &quot;px&quot;;
-    cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + &quot;px&quot;;
</del><ins>+  if (maybeUpdateLineNumberWidth(cm)) {
+    resetView(cm)
+    update.dims = getDimensions(cm)
+  }
</ins><span class="cx"> 
</span><del>-    if (pos.other) {
-      // Secondary cursor, shown when on a 'jump' in bi-directional text
-      var otherCursor = output.appendChild(elt(&quot;div&quot;, &quot;\u00a0&quot;, &quot;CodeMirror-cursor CodeMirror-secondarycursor&quot;));
-      otherCursor.style.display = &quot;&quot;;
-      otherCursor.style.left = pos.other.left + &quot;px&quot;;
-      otherCursor.style.top = pos.other.top + &quot;px&quot;;
-      otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + &quot;px&quot;;
-    }
</del><ins>+  // Compute a suitable new viewport (from &amp; 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 &lt; from &amp;&amp; from - display.viewFrom &lt; 20) { from = Math.max(doc.first, display.viewFrom) }
+  if (display.viewTo &gt; to &amp;&amp; display.viewTo - to &lt; 20) { to = Math.min(end, display.viewTo) }
+  if (sawCollapsedSpans) {
+    from = visualLineNo(cm.doc, from)
+    to = visualLineEndNo(cm.doc, to)
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // 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;
</del><ins>+  var different = from != display.viewFrom || to != display.viewTo ||
+    display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth
+  adjustView(cm, from, to)
</ins><span class="cx"> 
</span><del>-    function add(left, top, width, bottom) {
-      if (top &lt; 0) top = 0;
-      top = Math.round(top);
-      bottom = Math.round(bottom);
-      fragment.appendChild(elt(&quot;div&quot;, null, &quot;CodeMirror-selected&quot;, &quot;position: absolute; left: &quot; + left +
-                               &quot;px; top: &quot; + top + &quot;px; width: &quot; + (width == null ? rightSide - left : width) +
-                               &quot;px; height: &quot; + (bottom - top) + &quot;px&quot;));
-    }
</del><ins>+  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 + &quot;px&quot;
</ins><span class="cx"> 
</span><del>-    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), &quot;div&quot;, lineObj, bias);
-      }
</del><ins>+  var toUpdate = countDirtyView(cm)
+  if (!different &amp;&amp; toUpdate == 0 &amp;&amp; !update.force &amp;&amp; display.renderedView == display.view &amp;&amp;
+      (display.updateLineNumbers == null || display.updateLineNumbers &gt;= display.viewTo))
+    { return false }
</ins><span class="cx"> 
</span><del>-      iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
-        var leftPos = coords(from, &quot;left&quot;), rightPos, left, right;
-        if (from == to) {
-          rightPos = leftPos;
-          left = right = leftPos.left;
-        } else {
-          rightPos = coords(to - 1, &quot;right&quot;);
-          if (dir == &quot;rtl&quot;) { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
-          left = leftPos.left;
-          right = rightPos.right;
-        }
-        if (fromArg == null &amp;&amp; from == 0) left = leftSide;
-        if (rightPos.top - leftPos.top &gt; 3) { // Different lines, draw top part
-          add(left, leftPos.top, null, leftPos.bottom);
-          left = leftSide;
-          if (leftPos.bottom &lt; rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
-        }
-        if (toArg == null &amp;&amp; to == lineLen) right = rightSide;
-        if (!start || leftPos.top &lt; start.top || leftPos.top == start.top &amp;&amp; leftPos.left &lt; start.left)
-          start = leftPos;
-        if (!end || rightPos.bottom &gt; end.bottom || rightPos.bottom == end.bottom &amp;&amp; rightPos.right &gt; end.right)
-          end = rightPos;
-        if (left &lt; leftSide + 1) left = leftSide;
-        add(left, rightPos.top, right - left, rightPos.bottom);
-      });
-      return {start: start, end: end};
-    }
</del><ins>+  // 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 &gt; 4) { display.lineDiv.style.display = &quot;none&quot; }
+  patchDisplay(cm, display.updateLineNumbers, update.dims)
+  if (toUpdate &gt; 4) { display.lineDiv.style.display = &quot;&quot; }
+  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 &amp;&amp; activeElt() != focused &amp;&amp; focused.offsetHeight) { focused.focus() }
</ins><span class="cx"> 
</span><del>-    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 &lt; 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 &lt; rightStart.top)
-        add(leftSide, leftEnd.bottom, null, rightStart.top);
-    }
</del><ins>+  // 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
</ins><span class="cx"> 
</span><del>-    output.appendChild(fragment);
</del><ins>+  if (different) {
+    display.lastWrapHeight = update.wrapperHeight
+    display.lastWrapWidth = update.wrapperWidth
+    startWorker(cm, 400)
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // Cursor-blinking
-  function restartBlink(cm) {
-    if (!cm.state.focused) return;
-    var display = cm.display;
-    clearInterval(display.blinker);
-    var on = true;
-    display.cursorDiv.style.visibility = &quot;&quot;;
-    if (cm.options.cursorBlinkRate &gt; 0)
-      display.blinker = setInterval(function() {
-        display.cursorDiv.style.visibility = (on = !on) ? &quot;&quot; : &quot;hidden&quot;;
-      }, cm.options.cursorBlinkRate);
-    else if (cm.options.cursorBlinkRate &lt; 0)
-      display.cursorDiv.style.visibility = &quot;hidden&quot;;
</del><ins>+  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 &amp;&amp; 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 &gt;= cm.display.viewFrom &amp;&amp; update.visible.to &lt;= cm.display.viewTo)
+        { break }
+    }
+    if (!updateDisplayIfNeeded(cm, update)) { break }
+    updateHeightsInViewport(cm)
+    var barMeasure = measureForScrollbars(cm)
+    updateSelection(cm)
+    updateScrollbars(cm, barMeasure)
+    setDocumentHeight(cm, barMeasure)
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // HIGHLIGHT WORKER
</del><ins>+  update.signal(cm, &quot;update&quot;, cm)
+  if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
+    update.signal(cm, &quot;viewportChange&quot;, cm, cm.display.viewFrom, cm.display.viewTo)
+    cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo
+  }
+}
</ins><span class="cx"> 
</span><del>-  function startWorker(cm, time) {
-    if (cm.doc.mode.startState &amp;&amp; cm.doc.frontier &lt; cm.display.viewTo)
-      cm.state.highlight.set(time, bind(highlightWorker, cm));
</del><ins>+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()
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  function highlightWorker(cm) {
-    var doc = cm.doc;
-    if (doc.frontier &lt; doc.first) doc.frontier = doc.first;
-    if (doc.frontier &gt;= cm.display.viewTo) return;
-    var end = +new Date + cm.options.workTime;
-    var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
-    var changedLines = [];
</del><ins>+// 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
</ins><span class="cx"> 
</span><del>-    doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
-      if (doc.frontier &gt;= cm.display.viewFrom) { // Visible
-        var oldStyles = line.styles;
-        var highlighted = highlightLine(cm, line, 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 &amp;&amp; (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
-        for (var i = 0; !ischange &amp;&amp; i &lt; oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
-        if (ischange) changedLines.push(doc.frontier);
-        line.stateAfter = copyState(doc.mode, state);
-      } else {
-        processLine(cm, line.text, state);
-        line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
-      }
-      ++doc.frontier;
-      if (+new Date &gt; end) {
-        startWorker(cm, cm.options.workDelay);
-        return true;
-      }
-    });
-    if (changedLines.length) runInOp(cm, function() {
-      for (var i = 0; i &lt; changedLines.length; i++)
-        regLineChange(cm, changedLines[i], &quot;text&quot;);
-    });
</del><ins>+  function rm(node) {
+    var next = node.nextSibling
+    // Works around a throw-scroll bug in OS X Webkit
+    if (webkit &amp;&amp; mac &amp;&amp; cm.display.currentWheelTarget == node)
+      { node.style.display = &quot;none&quot; }
+    else
+      { node.parentNode.removeChild(node) }
+    return next
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // 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 &gt; lim; --search) {
-      if (search &lt;= doc.first) return doc.first;
-      var line = getLine(doc, search - 1);
-      if (line.stateAfter &amp;&amp; (!precise || search &lt;= doc.frontier)) return search;
-      var indented = countColumn(line.text, null, cm.options.tabSize);
-      if (minline == null || minindent &gt; indented) {
-        minline = search - 1;
-        minindent = indented;
</del><ins>+  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 &lt; 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 &amp;&amp; updateNumbersFrom != null &amp;&amp;
+        updateNumbersFrom &lt;= lineN &amp;&amp; lineView.lineNumber
+      if (lineView.changes) {
+        if (indexOf(lineView.changes, &quot;gutter&quot;) &gt; -1) { updateNumber = false }
+        updateLineForChanges(cm, lineView, lineN, dims)
</ins><span class="cx">       }
</span><ins>+      if (updateNumber) {
+        removeChildren(lineView.lineNumber)
+        lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)))
+      }
+      cur = lineView.node.nextSibling
</ins><span class="cx">     }
</span><del>-    return minline;
</del><ins>+    lineN += lineView.size
</ins><span class="cx">   }
</span><ins>+  while (cur) { cur = rm(cur) }
+}
</ins><span class="cx"> 
</span><del>-  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 &gt; doc.first &amp;&amp; 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 &gt;= display.viewFrom &amp;&amp; pos &lt; display.viewTo;
-      line.stateAfter = save ? copyState(doc.mode, state) : null;
-      ++pos;
-    });
-    if (precise) doc.frontier = pos;
-    return state;
-  }
</del><ins>+function updateGutterSpace(cm) {
+  var width = cm.display.gutters.offsetWidth
+  cm.display.sizer.style.marginLeft = width + &quot;px&quot;
+}
</ins><span class="cx"> 
</span><del>-  // POSITION MEASUREMENT
</del><ins>+function setDocumentHeight(cm, measure) {
+  cm.display.sizer.style.minHeight = measure.docHeight + &quot;px&quot;
+  cm.display.heightForcer.style.top = measure.docHeight + &quot;px&quot;
+  cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + &quot;px&quot;
+}
</ins><span class="cx"> 
</span><del>-  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(&quot;pre&quot;, &quot;x&quot;));
-    var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
-    var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
-    if (!isNaN(data.left) &amp;&amp; !isNaN(data.right)) display.cachedPaddingH = data;
-    return data;
</del><ins>+// 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)
+  var i = 0
+  for (; i &lt; specs.length; ++i) {
+    var gutterClass = specs[i]
+    var gElt = gutters.appendChild(elt(&quot;div&quot;, null, &quot;CodeMirror-gutter &quot; + gutterClass))
+    if (gutterClass == &quot;CodeMirror-linenumbers&quot;) {
+      cm.display.lineGutter = gElt
+      gElt.style.width = (cm.display.lineNumWidth || 1) + &quot;px&quot;
+    }
</ins><span class="cx">   }
</span><ins>+  gutters.style.display = i ? &quot;&quot; : &quot;none&quot;
+  updateGutterSpace(cm)
+}
</ins><span class="cx"> 
</span><del>-  function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
-  function displayWidth(cm) {
-    return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
</del><ins>+// Make sure the gutters options contains the element
+// &quot;CodeMirror-linenumbers&quot; when the lineNumbers option is true.
+function setGuttersForLineNumbers(options) {
+  var found = indexOf(options.gutters, &quot;CodeMirror-linenumbers&quot;)
+  if (found == -1 &amp;&amp; options.lineNumbers) {
+    options.gutters = options.gutters.concat([&quot;CodeMirror-linenumbers&quot;])
+  } else if (found &gt; -1 &amp;&amp; !options.lineNumbers) {
+    options.gutters = options.gutters.slice(0)
+    options.gutters.splice(found, 1)
</ins><span class="cx">   }
</span><del>-  function displayHeight(cm) {
-    return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
-  }
</del><ins>+}
</ins><span class="cx"> 
</span><del>-  // 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 &amp;&amp; displayWidth(cm);
-    if (!lineView.measure.heights || wrapping &amp;&amp; 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 &lt; rects.length - 1; i++) {
-          var cur = rects[i], next = rects[i + 1];
-          if (Math.abs(cur.bottom - next.bottom) &gt; 2)
-            heights.push((cur.bottom + next.top) / 2 - rect.top);
-        }
-      }
-      heights.push(rect.bottom - rect.top);
</del><ins>+// 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) {
+    var this$1 = this;
+
+    if (other == this) { return true }
+    if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
+    for (var i = 0; i &lt; this.ranges.length; i++) {
+      var here = this$1.ranges[i], there = other.ranges[i]
+      if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) { return false }
</ins><span class="cx">     }
</span><del>-  }
</del><ins>+    return true
+  },
+  deepCopy: function() {
+    var this$1 = this;
</ins><span class="cx"> 
</span><del>-  // 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 &lt; 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 &lt; lineView.rest.length; i++)
-      if (lineNo(lineView.rest[i]) &gt; lineN)
-        return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
-  }
</del><ins>+    var out = []
+    for (var i = 0; i &lt; this.ranges.length; i++)
+      { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)) }
+    return new Selection(out, this.primIndex)
+  },
+  somethingSelected: function() {
+    var this$1 = this;
</ins><span class="cx"> 
</span><del>-  // 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;
-  }
</del><ins>+    for (var i = 0; i &lt; this.ranges.length; i++)
+      { if (!this$1.ranges[i].empty()) { return true } }
+    return false
+  },
+  contains: function(pos, end) {
+    var this$1 = this;
</ins><span class="cx"> 
</span><del>-  // 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);
</del><ins>+    if (!end) { end = pos }
+    for (var i = 0; i &lt; this.ranges.length; i++) {
+      var range = this$1.ranges[i]
+      if (cmp(end, range.from()) &gt;= 0 &amp;&amp; cmp(pos, range.to()) &lt;= 0)
+        { return i }
+    }
+    return -1
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // Find a line view that corresponds to the given line number.
-  function findViewForLine(cm, lineN) {
-    if (lineN &gt;= cm.display.viewFrom &amp;&amp; lineN &lt; cm.display.viewTo)
-      return cm.display.view[findViewIndex(cm, lineN)];
-    var ext = cm.display.externalMeasured;
-    if (ext &amp;&amp; lineN &gt;= ext.lineN &amp;&amp; lineN &lt; ext.lineN + ext.size)
-      return ext;
</del><ins>+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 &amp;&amp; this.head.ch == this.anchor.ch
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // 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 &amp;&amp; !view.text) {
-      view = null;
-    } else if (view &amp;&amp; view.changes) {
-      updateLineForChanges(cm, view, lineN, getDimensions(cm));
-      cm.curOp.forceUpdate = true;
</del><ins>+// 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 &lt; ranges.length; i++) {
+    var cur = ranges[i], prev = ranges[i - 1]
+    if (cmp(prev.to(), cur.from()) &gt;= 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 &lt;= primIndex) { --primIndex }
+      ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to))
</ins><span class="cx">     }
</span><del>-    if (!view)
-      view = updateExternalMeasurement(cm, line);
</del><ins>+  }
+  return new Selection(ranges, primIndex)
+}
</ins><span class="cx"> 
</span><del>-    var info = mapFromLineView(view, line, lineN);
-    return {
-      line: line, view: view, rect: null,
-      map: info.map, cache: info.cache, before: info.before,
-      hasHeights: false
-    };
</del><ins>+function simpleSelection(anchor, head) {
+  return new Selection([new Range(anchor, head || anchor)], 0)
+}
+
+// Compute the position of the end of a change (its 'to' property
+// refers to the pre-change end).
+function changeEnd(change) {
+  if (!change.text) { return change.to }
+  return Pos(change.from.line + change.text.length - 1,
+             lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
+}
+
+// Adjust a position to refer to the post-change position of the
+// same text, or the end of the change if the change covers it.
+function adjustForChange(pos, change) {
+  if (cmp(pos, change.from) &lt; 0) { return pos }
+  if (cmp(pos, change.to) &lt;= 0) { return changeEnd(change) }
+
+  var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch
+  if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch }
+  return Pos(line, ch)
+}
+
+function computeSelAfterChange(doc, change) {
+  var out = []
+  for (var i = 0; i &lt; doc.sel.ranges.length; i++) {
+    var range = doc.sel.ranges[i]
+    out.push(new Range(adjustForChange(range.anchor, change),
+                       adjustForChange(range.head, change)))
</ins><span class="cx">   }
</span><ins>+  return normalizeSelection(out, doc.sel.primIndex)
+}
</ins><span class="cx"> 
</span><del>-  // 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 || &quot;&quot;), found;
-    if (prepared.cache.hasOwnProperty(key)) {
-      found = prepared.cache[key];
</del><ins>+function offsetPos(pos, old, nw) {
+  if (pos.line == old.line)
+    { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
+  else
+    { return Pos(nw.line + (pos.line - old.line), pos.ch) }
+}
+
+// Used by replaceSelections to allow moving the selection to the
+// start or around the replaced test. Hint may be &quot;start&quot; or &quot;around&quot;.
+function computeReplacedSel(doc, changes, hint) {
+  var out = []
+  var oldPrev = Pos(doc.first, 0), newPrev = oldPrev
+  for (var i = 0; i &lt; changes.length; i++) {
+    var change = changes[i]
+    var from = offsetPos(change.from, oldPrev, newPrev)
+    var to = offsetPos(changeEnd(change), oldPrev, newPrev)
+    oldPrev = change.to
+    newPrev = to
+    if (hint == &quot;around&quot;) {
+      var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) &lt; 0
+      out[i] = new Range(inv ? to : from, inv ? from : to)
</ins><span class="cx">     } else {
</span><del>-      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;
</del><ins>+      out[i] = new Range(from, from)
</ins><span class="cx">     }
</span><del>-    return {left: found.left, right: found.right,
-            top: varHeight ? found.rtop : found.top,
-            bottom: varHeight ? found.rbottom : found.bottom};
</del><span class="cx">   }
</span><ins>+  return new Selection(out, doc.sel.primIndex)
+}
</ins><span class="cx"> 
</span><del>-  var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
</del><ins>+// Used to get the editor into a consistent state again when options change.
</ins><span class="cx"> 
</span><del>-  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 &lt; map.length; i += 3) {
-      var mStart = map[i], mEnd = map[i + 1];
-      if (ch &lt; mStart) {
-        start = 0; end = 1;
-        collapse = &quot;left&quot;;
-      } else if (ch &lt; mEnd) {
-        start = ch - mStart;
-        end = start + 1;
-      } else if (i == map.length - 3 || ch == mEnd &amp;&amp; map[i + 3] &gt; ch) {
-        end = mEnd - mStart;
-        start = end - 1;
-        if (ch &gt;= mEnd) collapse = &quot;right&quot;;
-      }
-      if (start != null) {
-        node = map[i + 2];
-        if (mStart == mEnd &amp;&amp; bias == (node.insertLeft ? &quot;left&quot; : &quot;right&quot;))
-          collapse = bias;
-        if (bias == &quot;left&quot; &amp;&amp; start == 0)
-          while (i &amp;&amp; map[i - 2] == map[i - 3] &amp;&amp; map[i - 1].insertLeft) {
-            node = map[(i -= 3) + 2];
-            collapse = &quot;left&quot;;
-          }
-        if (bias == &quot;right&quot; &amp;&amp; start == mEnd - mStart)
-          while (i &lt; map.length - 3 &amp;&amp; map[i + 3] == map[i + 4] &amp;&amp; !map[i + 5].insertLeft) {
-            node = map[(i += 3) + 2];
-            collapse = &quot;right&quot;;
-          }
-        break;
-      }
-    }
-    return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
-  }
</del><ins>+function loadMode(cm) {
+  cm.doc.mode = getMode(cm.options, cm.doc.modeOption)
+  resetModeState(cm)
+}
</ins><span class="cx"> 
</span><del>-  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;
</del><ins>+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) }
+}
</ins><span class="cx"> 
</span><del>-    var rect;
-    if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
-      for (var i = 0; i &lt; 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
-        while (start &amp;&amp; isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
-        while (place.coverStart + end &lt; place.coverEnd &amp;&amp; isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
-        if (ie &amp;&amp; ie_version &lt; 9 &amp;&amp; start == 0 &amp;&amp; end == place.coverEnd - place.coverStart) {
-          rect = node.parentNode.getBoundingClientRect();
-        } else if (ie &amp;&amp; cm.options.lineWrapping) {
-          var rects = range(node, start, end).getClientRects();
-          if (rects.length)
-            rect = rects[bias == &quot;right&quot; ? 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 = &quot;right&quot;;
-      }
-      if (ie &amp;&amp; ie_version &lt; 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
-    } else { // If it is a widget, simply get the box for the whole widget.
-      if (start &gt; 0) collapse = bias = &quot;right&quot;;
-      var rects;
-      if (cm.options.lineWrapping &amp;&amp; (rects = node.getClientRects()).length &gt; 1)
-        rect = rects[bias == &quot;right&quot; ? rects.length - 1 : 0];
-      else
-        rect = node.getBoundingClientRect();
-    }
-    if (ie &amp;&amp; ie_version &lt; 9 &amp;&amp; !start &amp;&amp; (!rect || !rect.left &amp;&amp; !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;
-    }
</del><ins>+// DOCUMENT DATA STRUCTURE
</ins><span class="cx"> 
</span><del>-    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 &lt; heights.length - 1; i++)
-      if (mid &lt; heights[i]) break;
-    var top = i ? heights[i - 1] : 0, bot = heights[i];
-    var result = {left: (collapse == &quot;right&quot; ? rect.right : rect.left) - prepared.rect.left,
-                  right: (collapse == &quot;left&quot; ? rect.left : rect.right) - prepared.rect.left,
-                  top: top, bottom: bot};
-    if (!rect.left &amp;&amp; !rect.right) result.bogus = true;
-    if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
</del><ins>+// By default, updates that start and end at the beginning of a line
+// are treated specially, in order to make the association of line
+// widgets and marker elements with the text behave more intuitive.
+function isWholeLineUpdate(doc, change) {
+  return change.from.ch == 0 &amp;&amp; change.to.ch == 0 &amp;&amp; lst(change.text) == &quot;&quot; &amp;&amp;
+    (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
+}
</ins><span class="cx"> 
</span><del>-    return result;
</del><ins>+// Perform a change on the document data structure.
+function updateDoc(doc, change, markedSpans, estimateHeight) {
+  function spansFor(n) {return markedSpans ? markedSpans[n] : null}
+  function update(line, text, spans) {
+    updateLine(line, text, spans, estimateHeight)
+    signalLater(line, &quot;change&quot;, line, change)
</ins><span class="cx">   }
</span><del>-
-  // 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};
</del><ins>+  function linesFor(start, end) {
+    var result = []
+    for (var i = start; i &lt; end; ++i)
+      { result.push(new Line(text[i], spansFor(i), estimateHeight)) }
+    return result
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  function clearLineMeasurementCacheFor(lineView) {
-    if (lineView.measure) {
-      lineView.measure.cache = {};
-      lineView.measure.heights = null;
-      if (lineView.rest) for (var i = 0; i &lt; lineView.rest.length; i++)
-        lineView.measure.caches[i] = {};
</del><ins>+  var from = change.from, to = change.to, text = change.text
+  var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line)
+  var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line
+
+  // Adjust the line structure
+  if (change.full) {
+    doc.insert(0, linesFor(0, text.length))
+    doc.remove(text.length, doc.size - text.length)
+  } else if (isWholeLineUpdate(doc, change)) {
+    // This is a whole-line replace. Treated specially to make
+    // sure line objects move the way they are supposed to.
+    var added = linesFor(0, text.length - 1)
+    update(lastLine, lastLine.text, lastSpans)
+    if (nlines) { doc.remove(from.line, nlines) }
+    if (added.length) { doc.insert(from.line, added) }
+  } else if (firstLine == lastLine) {
+    if (text.length == 1) {
+      update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans)
+    } else {
+      var added$1 = linesFor(1, text.length - 1)
+      added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight))
+      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
+      doc.insert(from.line + 1, added$1)
</ins><span class="cx">     }
</span><ins>+  } else if (text.length == 1) {
+    update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0))
+    doc.remove(from.line + 1, nlines)
+  } else {
+    update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
+    update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans)
+    var added$2 = linesFor(1, text.length - 1)
+    if (nlines &gt; 1) { doc.remove(from.line + 1, nlines - 1) }
+    doc.insert(from.line + 1, added$2)
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  function clearLineMeasurementCache(cm) {
-    cm.display.externalMeasure = null;
-    removeChildren(cm.display.lineMeasure);
-    for (var i = 0; i &lt; cm.display.view.length; i++)
-      clearLineMeasurementCacheFor(cm.display.view[i]);
-  }
</del><ins>+  signalLater(doc, &quot;change&quot;, doc, change)
+}
</ins><span class="cx"> 
</span><del>-  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;
</del><ins>+// Call f for all linked documents.
+function linkedDocs(doc, f, sharedHistOnly) {
+  function propagate(doc, skip, sharedHist) {
+    if (doc.linked) { for (var i = 0; i &lt; doc.linked.length; ++i) {
+      var rel = doc.linked[i]
+      if (rel.doc == skip) { continue }
+      var shared = sharedHist &amp;&amp; rel.sharedHist
+      if (sharedHistOnly &amp;&amp; !shared) { continue }
+      f(rel.doc, shared)
+      propagate(rel.doc, doc, shared)
+    } }
</ins><span class="cx">   }
</span><ins>+  propagate(doc, null, true)
+}
</ins><span class="cx"> 
</span><del>-  function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
-  function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
</del><ins>+// Attach a document to an editor.
+function attachDoc(cm, doc) {
+  if (doc.cm) { throw new Error(&quot;This document is already in use.&quot;) }
+  cm.doc = doc
+  doc.cm = cm
+  estimateLineHeights(cm)
+  loadMode(cm)
+  if (!cm.options.lineWrapping) { findMaxLine(cm) }
+  cm.options.mode = doc.modeOption
+  regChange(cm)
+}
</ins><span class="cx"> 
</span><del>-  // Converts a {top, bottom, left, right} box from line-local
-  // coordinates into another coordinate system. Context may be one of
-  // &quot;line&quot;, &quot;div&quot; (display.lineDiv), &quot;local&quot;/null (editor), &quot;window&quot;,
-  // or &quot;page&quot;.
-  function intoCoordSystem(cm, lineObj, rect, context) {
-    if (lineObj.widgets) for (var i = 0; i &lt; lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
-      var size = widgetHeight(lineObj.widgets[i]);
-      rect.top += size; rect.bottom += size;
-    }
-    if (context == &quot;line&quot;) return rect;
-    if (!context) context = &quot;local&quot;;
-    var yOff = heightAtLine(lineObj);
-    if (context == &quot;local&quot;) yOff += paddingTop(cm.display);
-    else yOff -= cm.display.viewOffset;
-    if (context == &quot;page&quot; || context == &quot;window&quot;) {
-      var lOff = cm.display.lineSpace.getBoundingClientRect();
-      yOff += lOff.top + (context == &quot;window&quot; ? 0 : pageScrollY());
-      var xOff = lOff.left + (context == &quot;window&quot; ? 0 : pageScrollX());
-      rect.left += xOff; rect.right += xOff;
-    }
-    rect.top += yOff; rect.bottom += yOff;
-    return rect;
-  }
</del><ins>+function History(startGen) {
+  // Arrays of change events and selections. Doing something adds an
+  // event to done and clears undo. Undoing moves events from done
+  // to undone, redoing moves them in the other direction.
+  this.done = []; this.undone = []
+  this.undoDepth = Infinity
+  // Used to track when changes can be merged into a single undo
+  // event
+  this.lastModTime = this.lastSelTime = 0
+  this.lastOp = this.lastSelOp = null
+  this.lastOrigin = this.lastSelOrigin = null
+  // Used by the isClean() method
+  this.generation = this.maxGeneration = startGen || 1
+}
</ins><span class="cx"> 
</span><del>-  // Coverts a box from &quot;div&quot; coords to another coordinate system.
-  // Context may be &quot;window&quot;, &quot;page&quot;, &quot;div&quot;, or &quot;local&quot;/null.
-  function fromCoordSystem(cm, coords, context) {
-    if (context == &quot;div&quot;) return coords;
-    var left = coords.left, top = coords.top;
-    // First move into &quot;page&quot; coordinate system
-    if (context == &quot;page&quot;) {
-      left -= pageScrollX();
-      top -= pageScrollY();
-    } else if (context == &quot;local&quot; || !context) {
-      var localBox = cm.display.sizer.getBoundingClientRect();
-      left += localBox.left;
-      top += localBox.top;
-    }
</del><ins>+// Create a history change event from an updateDoc-style change
+// object.
+function historyChangeFromChange(doc, change) {
+  var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}
+  attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1)
+  linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true)
+  return histChange
+}
</ins><span class="cx"> 
</span><del>-    var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
-    return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
</del><ins>+// Pop all selection events off the end of a history array. Stop at
+// a change event.
+function clearSelectionEvents(array) {
+  while (array.length) {
+    var last = lst(array)
+    if (last.ranges) { array.pop() }
+    else { break }
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  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);
</del><ins>+// Find the top change event in the history. Pop off selection
+// events that are in the way.
+function lastChangeEvent(hist, force) {
+  if (force) {
+    clearSelectionEvents(hist.done)
+    return lst(hist.done)
+  } else if (hist.done.length &amp;&amp; !lst(hist.done).ranges) {
+    return lst(hist.done)
+  } else if (hist.done.length &gt; 1 &amp;&amp; !hist.done[hist.done.length - 2].ranges) {
+    hist.done.pop()
+    return lst(hist.done)
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // 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 ? &quot;right&quot; : &quot;left&quot;, varHeight);
-      if (right) m.left = m.right; else m.right = m.left;
-      return intoCoordSystem(cm, lineObj, m, context);
</del><ins>+// Register a change in the history. Merges changes that are within
+// a single operation, or are close together with an origin that
+// allows merging (starting with &quot;+&quot;) into a single event.
+function addChangeToHistory(doc, change, selAfter, opId) {
+  var hist = doc.history
+  hist.undone.length = 0
+  var time = +new Date, cur
+  var last
+
+  if ((hist.lastOp == opId ||
+       hist.lastOrigin == change.origin &amp;&amp; change.origin &amp;&amp;
+       ((change.origin.charAt(0) == &quot;+&quot; &amp;&amp; doc.cm &amp;&amp; hist.lastModTime &gt; time - doc.cm.options.historyEventDelay) ||
+        change.origin.charAt(0) == &quot;*&quot;)) &amp;&amp;
+      (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
+    // Merge this change into the last event
+    last = lst(cur.changes)
+    if (cmp(change.from, change.to) == 0 &amp;&amp; cmp(change.from, last.to) == 0) {
+      // Optimized case for simple insertion -- don't want to add
+      // new changesets for every character typed
+      last.to = changeEnd(change)
+    } else {
+      // Add new sub-event
+      cur.changes.push(historyChangeFromChange(doc, change))
</ins><span class="cx">     }
</span><del>-    function getBidi(ch, partPos) {
-      var part = order[partPos], right = part.level % 2;
-      if (ch == bidiLeft(part) &amp;&amp; partPos &amp;&amp; part.level &lt; order[partPos - 1].level) {
-        part = order[--partPos];
-        ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
-        right = true;
-      } else if (ch == bidiRight(part) &amp;&amp; partPos &lt; order.length - 1 &amp;&amp; part.level &lt; order[partPos + 1].level) {
-        part = order[++partPos];
-        ch = bidiLeft(part) - part.level % 2;
-        right = false;
-      }
-      if (right &amp;&amp; ch == part.to &amp;&amp; ch &gt; part.from) return get(ch - 1);
-      return get(ch, right);
</del><ins>+  } else {
+    // Can not be merged, start a new event.
+    var before = lst(hist.done)
+    if (!before || !before.ranges)
+      { pushSelectionToHistory(doc.sel, hist.done) }
+    cur = {changes: [historyChangeFromChange(doc, change)],
+           generation: hist.generation}
+    hist.done.push(cur)
+    while (hist.done.length &gt; hist.undoDepth) {
+      hist.done.shift()
+      if (!hist.done[0].ranges) { hist.done.shift() }
</ins><span class="cx">     }
</span><del>-    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;
</del><span class="cx">   }
</span><ins>+  hist.done.push(selAfter)
+  hist.generation = ++hist.maxGeneration
+  hist.lastModTime = hist.lastSelTime = time
+  hist.lastOp = hist.lastSelOp = opId
+  hist.lastOrigin = hist.lastSelOrigin = change.origin
</ins><span class="cx"> 
</span><del>-  // 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};
-  }
</del><ins>+  if (!last) { signal(doc, &quot;historyAdded&quot;) }
+}
</ins><span class="cx"> 
</span><del>-  // 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 &gt; 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;
</del><ins>+function selectionEventCanBeMerged(doc, origin, prev, sel) {
+  var ch = origin.charAt(0)
+  return ch == &quot;*&quot; ||
+    ch == &quot;+&quot; &amp;&amp;
+    prev.ranges.length == sel.ranges.length &amp;&amp;
+    prev.somethingSelected() == sel.somethingSelected() &amp;&amp;
+    new Date - doc.history.lastSelTime &lt;= (doc.cm ? doc.cm.options.historyEventDelay : 500)
+}
+
+// Called whenever the selection changes, sets the new selection as
+// the pending selection in the history, and pushes the old pending
+// selection into the 'done' array when it was significantly
+// different (in number of selected ranges, emptiness, or time).
+function addSelectionToHistory(doc, sel, opId, options) {
+  var hist = doc.history, origin = options &amp;&amp; options.origin
+
+  // A new event is started when the previous origin does not match
+  // the current, or the origins don't allow matching. Origins
+  // starting with * are always merged, those starting with + are
+  // merged when similar and close together in time.
+  if (opId == hist.lastSelOp ||
+      (origin &amp;&amp; hist.lastSelOrigin == origin &amp;&amp;
+       (hist.lastModTime == hist.lastSelTime &amp;&amp; hist.lastOrigin == origin ||
+        selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
+    { hist.done[hist.done.length - 1] = sel }
+  else
+    { pushSelectionToHistory(sel, hist.done) }
+
+  hist.lastSelTime = +new Date
+  hist.lastSelOrigin = origin
+  hist.lastSelOp = opId
+  if (options &amp;&amp; options.clearRedo !== false)
+    { clearSelectionEvents(hist.undone) }
+}
+
+function pushSelectionToHistory(sel, dest) {
+  var top = lst(dest)
+  if (!(top &amp;&amp; top.ranges &amp;&amp; top.equals(sel)))
+    { dest.push(sel) }
+}
+
+// Used to store marked span information in the history.
+function attachLocalSpans(doc, change, from, to) {
+  var existing = change[&quot;spans_&quot; + doc.id], n = 0
+  doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
+    if (line.markedSpans)
+      { (existing || (existing = change[&quot;spans_&quot; + doc.id] = {}))[n] = line.markedSpans }
+    ++n
+  })
+}
+
+// When un/re-doing restores text containing marked spans, those
+// that have been explicitly cleared should not be restored.
+function removeClearedSpans(spans) {
+  if (!spans) { return null }
+  var out
+  for (var i = 0; i &lt; spans.length; ++i) {
+    if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i) } }
+    else if (out) { out.push(spans[i]) }
</ins><span class="cx">   }
</span><ins>+  return !out ? spans : out.length ? out : null
+}
</ins><span class="cx"> 
</span><del>-  // Compute the character position closest to the given coordinates.
-  // Input must be lineSpace-local (&quot;div&quot; coordinate system).
-  function coordsChar(cm, x, y) {
-    var doc = cm.doc;
-    y += cm.display.viewOffset;
-    if (y &lt; 0) return PosWithInfo(doc.first, 0, true, -1);
-    var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
-    if (lineN &gt; last)
-      return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
-    if (x &lt; 0) x = 0;
</del><ins>+// Retrieve and filter the old marked spans stored in a change event.
+function getOldSpans(doc, change) {
+  var found = change[&quot;spans_&quot; + doc.id]
+  if (!found) { return null }
+  var nw = []
+  for (var i = 0; i &lt; change.text.length; ++i)
+    { nw.push(removeClearedSpans(found[i])) }
+  return nw
+}
</ins><span class="cx"> 
</span><del>-    var lineObj = getLine(doc, lineN);
-    for (;;) {
-      var found = coordsCharInner(cm, lineObj, lineN, x, y);
-      var merged = collapsedSpanAtEnd(lineObj);
-      var mergedPos = merged &amp;&amp; merged.find(0, true);
-      if (merged &amp;&amp; (found.ch &gt; mergedPos.from.ch || found.ch == mergedPos.from.ch &amp;&amp; found.xRel &gt; 0))
-        lineN = lineNo(lineObj = mergedPos.to.line);
-      else
-        return found;
</del><ins>+// Used for un/re-doing changes from the history. Combines the
+// result of computing the existing spans with the set of spans that
+// existed in the history (so that deleting around a span and then
+// undoing brings back the span).
+function mergeOldSpans(doc, change) {
+  var old = getOldSpans(doc, change)
+  var stretched = stretchSpansOverChange(doc, change)
+  if (!old) { return stretched }
+  if (!stretched) { return old }
+
+  for (var i = 0; i &lt; old.length; ++i) {
+    var oldCur = old[i], stretchCur = stretched[i]
+    if (oldCur &amp;&amp; stretchCur) {
+      spans: for (var j = 0; j &lt; stretchCur.length; ++j) {
+        var span = stretchCur[j]
+        for (var k = 0; k &lt; oldCur.length; ++k)
+          { if (oldCur[k].marker == span.marker) { continue spans } }
+        oldCur.push(span)
+      }
+    } else if (stretchCur) {
+      old[i] = stretchCur
</ins><span class="cx">     }
</span><span class="cx">   }
</span><ins>+  return old
+}
</ins><span class="cx"> 
</span><del>-  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), &quot;line&quot;, lineObj, preparedMeasure);
-      wrongLine = true;
-      if (innerOff &gt; sp.bottom) return sp.left - adjust;
-      else if (innerOff &lt; sp.top) return sp.left + adjust;
-      else wrongLine = false;
-      return sp.left;
</del><ins>+// Used both to provide a JSON-safe object in .getHistory, and, when
+// detaching a document, to split the history in two
+function copyHistoryArray(events, newGroup, instantiateSel) {
+  var copy = []
+  for (var i = 0; i &lt; events.length; ++i) {
+    var event = events[i]
+    if (event.ranges) {
+      copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event)
+      continue
</ins><span class="cx">     }
</span><ins>+    var changes = event.changes, newChanges = []
+    copy.push({changes: newChanges})
+    for (var j = 0; j &lt; changes.length; ++j) {
+      var change = changes[j], m = (void 0)
+      newChanges.push({from: change.from, to: change.to, text: change.text})
+      if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
+        if (indexOf(newGroup, Number(m[1])) &gt; -1) {
+          lst(newChanges)[prop] = change[prop]
+          delete change[prop]
+        }
+      } } }
+    }
+  }
+  return copy
+}
</ins><span class="cx"> 
</span><del>-    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;
</del><ins>+// The 'scroll' parameter given to many of these indicated whether
+// the new cursor position should be scrolled into view after
+// modifying the selection.
</ins><span class="cx"> 
</span><del>-    if (x &gt; 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 &lt;= 1) {
-        var ch = x &lt; fromX || x - fromX &lt;= toX - x ? from : to;
-        var xDiff = x - (ch == from ? fromX : toX);
-        while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
-        var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
-                              xDiff &lt; -1 ? -1 : xDiff &gt; 1 ? 1 : 0);
-        return pos;
</del><ins>+// 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 &amp;&amp; doc.cm.display.shift || doc.extend) {
+    var anchor = range.anchor
+    if (other) {
+      var posBefore = cmp(head, anchor) &lt; 0
+      if (posBefore != (cmp(other, anchor) &lt; 0)) {
+        anchor = head
+        head = other
+      } else if (posBefore != (cmp(head, other) &lt; 0)) {
+        head = other
</ins><span class="cx">       }
</span><del>-      var step = Math.ceil(dist / 2), middle = from + step;
-      if (bidi) {
-        middle = from;
-        for (var i = 0; i &lt; step; ++i) middle = moveVisually(lineObj, middle, 1);
-      }
-      var middleX = getX(middle);
-      if (middleX &gt; x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
-      else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
</del><span class="cx">     }
</span><ins>+    return new Range(anchor, head)
+  } else {
+    return new Range(other || head, head)
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  var measureText;
-  // Compute the default text height.
-  function textHeight(display) {
-    if (display.cachedTextHeight != null) return display.cachedTextHeight;
-    if (measureText == null) {
-      measureText = elt(&quot;pre&quot;);
-      // Measure a bunch of lines, for browsers that compute
-      // fractional heights.
-      for (var i = 0; i &lt; 49; ++i) {
-        measureText.appendChild(document.createTextNode(&quot;x&quot;));
-        measureText.appendChild(elt(&quot;br&quot;));
-      }
-      measureText.appendChild(document.createTextNode(&quot;x&quot;));
-    }
-    removeChildrenAndAdd(display.measure, measureText);
-    var height = measureText.offsetHeight / 50;
-    if (height &gt; 3) display.cachedTextHeight = height;
-    removeChildren(display.measure);
-    return height || 1;
</del><ins>+// 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) {
+  var out = []
+  for (var i = 0; i &lt; 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) {
+      var this$1 = this;
+
+      this.ranges = []
+      for (var i = 0; i &lt; ranges.length; i++)
+        { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
+                                   clipPos(doc, ranges[i].head)) }
+    },
+    origin: options &amp;&amp; options.origin
</ins><span class="cx">   }
</span><ins>+  signal(doc, &quot;beforeSelectionChange&quot;, doc, obj)
+  if (doc.cm) { signal(doc.cm, &quot;beforeSelectionChange&quot;, doc.cm, obj) }
+  if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
+  else { return sel }
+}
</ins><span class="cx"> 
</span><del>-  // Compute the default character width.
-  function charWidth(display) {
-    if (display.cachedCharWidth != null) return display.cachedCharWidth;
-    var anchor = elt(&quot;span&quot;, &quot;xxxxxxxxxx&quot;);
-    var pre = elt(&quot;pre&quot;, [anchor]);
-    removeChildrenAndAdd(display.measure, pre);
-    var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
-    if (width &gt; 2) display.cachedCharWidth = width;
-    return width || 10;
</del><ins>+function setSelectionReplaceHistory(doc, sel, options) {
+  var done = doc.history.done, last = lst(done)
+  if (last &amp;&amp; last.ranges) {
+    done[done.length - 1] = sel
+    setSelectionNoUndo(doc, sel, options)
+  } else {
+    setSelection(doc, sel, options)
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // OPERATIONS
</del><ins>+// 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)
+}
</ins><span class="cx"> 
</span><del>-  // 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.
</del><ins>+function setSelectionNoUndo(doc, sel, options) {
+  if (hasHandler(doc, &quot;beforeSelectionChange&quot;) || doc.cm &amp;&amp; hasHandler(doc.cm, &quot;beforeSelectionChange&quot;))
+    { sel = filterSelectionChange(doc, sel, options) }
</ins><span class="cx"> 
</span><del>-  var operationGroup = null;
</del><ins>+  var bias = options &amp;&amp; options.bias ||
+    (cmp(sel.primary().head, doc.sel.primary().head) &lt; 0 ? -1 : 1)
+  setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true))
</ins><span class="cx"> 
</span><del>-  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: []
-      };
</del><ins>+  if (!(options &amp;&amp; options.scroll === false) &amp;&amp; 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, &quot;cursorActivity&quot;, 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 &lt; sel.ranges.length; i++) {
+    var range = sel.ranges[i]
+    var old = sel.ranges.length == doc.sel.ranges.length &amp;&amp; doc.sel.ranges[i]
+    var newAnchor = skipAtomic(doc, range.anchor, old &amp;&amp; old.anchor, bias, mayClear)
+    var newHead = skipAtomic(doc, range.head, old &amp;&amp; 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)
</ins><span class="cx">     }
</span><span class="cx">   }
</span><ins>+  return out ? normalizeSelection(out, sel.primIndex) : sel
+}
</ins><span class="cx"> 
</span><del>-  function fireCallbacksForOps(group) {
-    // Calls delayed callbacks and cursorActivity handlers until no
-    // new ones appear
-    var callbacks = group.delayedCallbacks, i = 0;
-    do {
-      for (; i &lt; callbacks.length; i++)
-        callbacks[i].call(null);
-      for (var j = 0; j &lt; group.ops.length; j++) {
-        var op = group.ops[j];
-        if (op.cursorActivityHandlers)
-          while (op.cursorActivityCalled &lt; op.cursorActivityHandlers.length)
-            op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
</del><ins>+function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
+  var line = getLine(doc, pos.line)
+  if (line.markedSpans) { for (var i = 0; i &lt; line.markedSpans.length; ++i) {
+    var sp = line.markedSpans[i], m = sp.marker
+    if ((sp.from == null || (m.inclusiveLeft ? sp.from &lt;= pos.ch : sp.from &lt; pos.ch)) &amp;&amp;
+        (sp.to == null || (m.inclusiveRight ? sp.to &gt;= pos.ch : sp.to &gt; pos.ch))) {
+      if (mayClear) {
+        signal(m, &quot;beforeCursorEnter&quot;)
+        if (m.explicitlyCleared) {
+          if (!line.markedSpans) { break }
+          else {--i; continue}
+        }
</ins><span class="cx">       }
</span><del>-    } while (i &lt; callbacks.length);
-  }
</del><ins>+      if (!m.atomic) { continue }
</ins><span class="cx"> 
</span><del>-  // Finish an operation, updating the display and signalling delayed events
-  function endOperation(cm) {
-    var op = cm.curOp, group = op.ownsGroup;
-    if (!group) return;
</del><ins>+      if (oldPos) {
+        var near = m.find(dir &lt; 0 ? 1 : -1), diff = (void 0)
+        if (dir &lt; 0 ? m.inclusiveRight : m.inclusiveLeft)
+          { near = movePos(doc, near, -dir, near &amp;&amp; near.line == pos.line ? line : null) }
+        if (near &amp;&amp; near.line == pos.line &amp;&amp; (diff = cmp(near, oldPos)) &amp;&amp; (dir &lt; 0 ? diff &lt; 0 : diff &gt; 0))
+          { return skipAtomicInner(doc, near, pos, dir, mayClear) }
+      }
</ins><span class="cx"> 
</span><del>-    try { fireCallbacksForOps(group); }
-    finally {
-      operationGroup = null;
-      for (var i = 0; i &lt; group.ops.length; i++)
-        group.ops[i].cm.curOp = null;
-      endOperations(group);
</del><ins>+      var far = m.find(dir &lt; 0 ? -1 : 1)
+      if (dir &lt; 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
</ins><span class="cx">     }
</span><ins>+  } }
+  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 &amp;&amp; skipAtomicInner(doc, pos, oldPos, dir, true)) ||
+      skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
+      (!mayClear &amp;&amp; skipAtomicInner(doc, pos, oldPos, -dir, true))
+  if (!found) {
+    doc.cantEdit = true
+    return Pos(doc.first, 0)
</ins><span class="cx">   }
</span><ins>+  return found
+}
</ins><span class="cx"> 
</span><del>-  // 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 &lt; ops.length; i++) // Read DOM
-      endOperation_R1(ops[i]);
-    for (var i = 0; i &lt; ops.length; i++) // Write DOM (maybe)
-      endOperation_W1(ops[i]);
-    for (var i = 0; i &lt; ops.length; i++) // Read DOM
-      endOperation_R2(ops[i]);
-    for (var i = 0; i &lt; ops.length; i++) // Write DOM (maybe)
-      endOperation_W2(ops[i]);
-    for (var i = 0; i &lt; ops.length; i++) // Read DOM
-      endOperation_finish(ops[i]);
</del><ins>+function movePos(doc, pos, dir, line) {
+  if (dir &lt; 0 &amp;&amp; pos.ch == 0) {
+    if (pos.line &gt; doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
+    else { return null }
+  } else if (dir &gt; 0 &amp;&amp; pos.ch == (line || getLine(doc, pos.line)).text.length) {
+    if (pos.line &lt; doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
+    else { return null }
+  } else {
+    return new Pos(pos.line, pos.ch + dir)
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  function endOperation_R1(op) {
-    var cm = op.cm, display = cm.display;
-    maybeClipScrollbars(cm);
-    if (op.updateMaxLine) findMaxLine(cm);
</del><ins>+function selectAll(cm) {
+  cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll)
+}
</ins><span class="cx"> 
</span><del>-    op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
-      op.scrollToPos &amp;&amp; (op.scrollToPos.from.line &lt; display.viewFrom ||
-                         op.scrollToPos.to.line &gt;= display.viewTo) ||
-      display.maxLineChanged &amp;&amp; cm.options.lineWrapping;
-    op.update = op.mustUpdate &amp;&amp;
-      new DisplayUpdate(cm, op.mustUpdate &amp;&amp; {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
-  }
</del><ins>+// UPDATING
</ins><span class="cx"> 
</span><del>-  function endOperation_W1(op) {
-    op.updatedDisplay = op.mustUpdate &amp;&amp; updateDisplayIfNeeded(op.cm, op.update);
</del><ins>+// Allow &quot;beforeChange&quot; event handlers to influence a change
+function filterChange(doc, change, update) {
+  var obj = {
+    canceled: false,
+    from: change.from,
+    to: change.to,
+    text: change.text,
+    origin: change.origin,
+    cancel: function () { return obj.canceled = true; }
</ins><span class="cx">   }
</span><ins>+  if (update) { obj.update = function (from, to, text, origin) {
+    if (from) { obj.from = clipPos(doc, from) }
+    if (to) { obj.to = clipPos(doc, to) }
+    if (text) { obj.text = text }
+    if (origin !== undefined) { obj.origin = origin }
+  } }
+  signal(doc, &quot;beforeChange&quot;, doc, obj)
+  if (doc.cm) { signal(doc.cm, &quot;beforeChange&quot;, doc.cm, obj) }
</ins><span class="cx"> 
</span><del>-  function endOperation_R2(op) {
-    var cm = op.cm, display = cm.display;
-    if (op.updatedDisplay) updateHeightsInViewport(cm);
</del><ins>+  if (obj.canceled) { return null }
+  return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
+}
</ins><span class="cx"> 
</span><del>-    op.barMeasure = measureForScrollbars(cm);
</del><ins>+// Apply a change to a document, and add it to the document's
+// history, and propagating it to all linked documents.
+function makeChange(doc, change, ignoreReadOnly) {
+  if (doc.cm) {
+    if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
+    if (doc.cm.state.suppressEdits) { return }
+  }
</ins><span class="cx"> 
</span><del>-    // 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 &amp;&amp; !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));
-    }
</del><ins>+  if (hasHandler(doc, &quot;beforeChange&quot;) || doc.cm &amp;&amp; hasHandler(doc.cm, &quot;beforeChange&quot;)) {
+    change = filterChange(doc, change, true)
+    if (!change) { return }
+  }
</ins><span class="cx"> 
</span><del>-    if (op.updatedDisplay || op.selectionChanged)
-      op.preparedSelection = display.input.prepareSelection();
</del><ins>+  // Possibly split or suppress the update based on the presence
+  // of read-only spans in its range.
+  var split = sawReadOnlySpans &amp;&amp; !ignoreReadOnly &amp;&amp; removeReadOnlyRanges(doc, change.from, change.to)
+  if (split) {
+    for (var i = split.length - 1; i &gt;= 0; --i)
+      { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [&quot;&quot;] : change.text}) }
+  } else {
+    makeChangeInner(doc, change)
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  function endOperation_W2(op) {
-    var cm = op.cm;
</del><ins>+function makeChangeInner(doc, change) {
+  if (change.text.length == 1 &amp;&amp; change.text[0] == &quot;&quot; &amp;&amp; cmp(change.from, change.to) == 0) { return }
+  var selAfter = computeSelAfterChange(doc, change)
+  addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN)
</ins><span class="cx"> 
</span><del>-    if (op.adjustWidthTo != null) {
-      cm.display.sizer.style.minWidth = op.adjustWidthTo + &quot;px&quot;;
-      if (op.maxScrollLeft &lt; cm.doc.scrollLeft)
-        setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
-      cm.display.maxLineChanged = false;
</del><ins>+  makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change))
+  var rebased = []
+
+  linkedDocs(doc, function (doc, sharedHist) {
+    if (!sharedHist &amp;&amp; indexOf(rebased, doc.history) == -1) {
+      rebaseHist(doc.history, change)
+      rebased.push(doc.history)
</ins><span class="cx">     }
</span><ins>+    makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change))
+  })
+}
</ins><span class="cx"> 
</span><del>-    if (op.preparedSelection)
-      cm.display.input.showSelection(op.preparedSelection);
-    if (op.updatedDisplay)
-      setDocumentHeight(cm, op.barMeasure);
-    if (op.updatedDisplay || op.startHeight != cm.doc.height)
-      updateScrollbars(cm, op.barMeasure);
</del><ins>+// Revert a change stored in a document's history.
+function makeChangeFromHistory(doc, type, allowSelectionOnly) {
+  if (doc.cm &amp;&amp; doc.cm.state.suppressEdits &amp;&amp; !allowSelectionOnly) { return }
</ins><span class="cx"> 
</span><del>-    if (op.selectionChanged) restartBlink(cm);
</del><ins>+  var hist = doc.history, event, selAfter = doc.sel
+  var source = type == &quot;undo&quot; ? hist.done : hist.undone, dest = type == &quot;undo&quot; ? hist.undone : hist.done
</ins><span class="cx"> 
</span><del>-    if (cm.state.focused &amp;&amp; op.updateInput)
-      cm.display.input.reset(op.typing);
-    if (op.focus &amp;&amp; op.focus == activeElt()) ensureFocus(op.cm);
</del><ins>+  // Verify that there is a useable event (so that ctrl-z won't
+  // needlessly clear selection events)
+  var i = 0
+  for (; i &lt; source.length; i++) {
+    event = source[i]
+    if (allowSelectionOnly ? event.ranges &amp;&amp; !event.equals(doc.sel) : !event.ranges)
+      { break }
</ins><span class="cx">   }
</span><ins>+  if (i == source.length) { return }
+  hist.lastOrigin = hist.lastSelOrigin = null
</ins><span class="cx"> 
</span><del>-  function endOperation_finish(op) {
-    var cm = op.cm, display = cm.display, doc = cm.doc;
</del><ins>+  for (;;) {
+    event = source.pop()
+    if (event.ranges) {
+      pushSelectionToHistory(event, dest)
+      if (allowSelectionOnly &amp;&amp; !event.equals(doc.sel)) {
+        setSelection(doc, event, {clearRedo: false})
+        return
+      }
+      selAfter = event
+    }
+    else { break }
+  }
</ins><span class="cx"> 
</span><del>-    if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
</del><ins>+  // Build up a reverse change object to add to the opposite history
+  // stack (redo when undoing, and vice versa).
+  var antiChanges = []
+  pushSelectionToHistory(selAfter, dest)
+  dest.push({changes: antiChanges, generation: hist.generation})
+  hist.generation = event.generation || ++hist.maxGeneration
</ins><span class="cx"> 
</span><del>-    // Abort mouse wheel delta measurement, when scrolling explicitly
-    if (display.wheelStartX != null &amp;&amp; (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
-      display.wheelStartX = display.wheelStartY = null;
</del><ins>+  var filter = hasHandler(doc, &quot;beforeChange&quot;) || doc.cm &amp;&amp; hasHandler(doc.cm, &quot;beforeChange&quot;)
</ins><span class="cx"> 
</span><del>-    // Propagate the scroll position to the actual DOM scroller
-    if (op.scrollTop != null &amp;&amp; (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;
</del><ins>+  var loop = function ( i ) {
+    var change = event.changes[i]
+    change.origin = type
+    if (filter &amp;&amp; !filterChange(doc, change, false)) {
+      source.length = 0
+      return {}
</ins><span class="cx">     }
</span><del>-    if (op.scrollLeft != null &amp;&amp; (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
-      doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), 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 &amp;&amp; cm.state.focused) maybeScrollWindow(cm, coords);
-    }
</del><span class="cx"> 
</span><del>-    // 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 &lt; hidden.length; ++i)
-      if (!hidden[i].lines.length) signal(hidden[i], &quot;hide&quot;);
-    if (unhidden) for (var i = 0; i &lt; unhidden.length; ++i)
-      if (unhidden[i].lines.length) signal(unhidden[i], &quot;unhide&quot;);
</del><ins>+    antiChanges.push(historyChangeFromChange(doc, change))
</ins><span class="cx"> 
</span><del>-    if (display.wrapper.offsetHeight)
-      doc.scrollTop = cm.display.scroller.scrollTop;
</del><ins>+    var after = i ? computeSelAfterChange(doc, change) : lst(source)
+    makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change))
+    if (!i &amp;&amp; doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}) }
+    var rebased = []
</ins><span class="cx"> 
</span><del>-    // Fire change events, and delayed event handlers
-    if (op.changeObjs)
-      signal(cm, &quot;changes&quot;, cm, op.changeObjs);
-    if (op.update)
-      op.update.finish();
</del><ins>+    // Propagate to the linked documents
+    linkedDocs(doc, function (doc, sharedHist) {
+      if (!sharedHist &amp;&amp; indexOf(rebased, doc.history) == -1) {
+        rebaseHist(doc.history, change)
+        rebased.push(doc.history)
+      }
+      makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change))
+    })
+  };
+
+  for (var i$1 = event.changes.length - 1; i$1 &gt;= 0; --i$1) {
+    var returned = loop( i$1 );
+
+    if ( returned ) return returned.v;
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // Run the given function in an operation
-  function runInOp(cm, f) {
-    if (cm.curOp) return f();
-    startOperation(cm);
-    try { return f(); }
-    finally { endOperation(cm); }
</del><ins>+// Sub-views need their line numbers shifted when text is added
+// above or below them in the parent document.
+function shiftDoc(doc, distance) {
+  if (distance == 0) { return }
+  doc.first += distance
+  doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
+    Pos(range.anchor.line + distance, range.anchor.ch),
+    Pos(range.head.line + distance, range.head.ch)
+  ); }), doc.sel.primIndex)
+  if (doc.cm) {
+    regChange(doc.cm, doc.first, doc.first - distance, distance)
+    for (var d = doc.cm.display, l = d.viewFrom; l &lt; d.viewTo; l++)
+      { regLineChange(doc.cm, l, &quot;gutter&quot;) }
</ins><span class="cx">   }
</span><del>-  // 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); }
-    };
</del><ins>+}
+
+// More lower-level change function, handling only a single document
+// (not linked ones).
+function makeChangeSingleDoc(doc, change, selAfter, spans) {
+  if (doc.cm &amp;&amp; !doc.cm.curOp)
+    { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
+
+  if (change.to.line &lt; doc.first) {
+    shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line))
+    return
</ins><span class="cx">   }
</span><del>-  // 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); }
-    };
</del><ins>+  if (change.from.line &gt; doc.lastLine()) { return }
+
+  // Clip the change to the size of this doc
+  if (change.from.line &lt; doc.first) {
+    var shift = change.text.length - 1 - (doc.first - change.from.line)
+    shiftDoc(doc, shift)
+    change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
+              text: [lst(change.text)], origin: change.origin}
</ins><span class="cx">   }
</span><del>-  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); }
-    };
</del><ins>+  var last = doc.lastLine()
+  if (change.to.line &gt; last) {
+    change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
+              text: [change.text[0]], origin: change.origin}
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // VIEW TRACKING
</del><ins>+  change.removed = getBetween(doc, change.from, change.to)
</ins><span class="cx"> 
</span><del>-  // 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);
-  }
</del><ins>+  if (!selAfter) { selAfter = computeSelAfterChange(doc, change) }
+  if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans) }
+  else { updateDoc(doc, change, spans) }
+  setSelectionNoUndo(doc, selAfter, sel_dontScroll)
+}
</ins><span class="cx"> 
</span><del>-  // Create a range of LineView objects for the given lines.
-  function buildViewArray(cm, from, to) {
-    var array = [], nextPos;
-    for (var pos = from; pos &lt; to; pos = nextPos) {
-      var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
-      nextPos = pos + view.size;
-      array.push(view);
-    }
-    return array;
</del><ins>+// Handle the interaction of a change to a document with the editor
+// that this document is part of.
+function makeChangeSingleDocInEditor(cm, change, spans) {
+  var doc = cm.doc, display = cm.display, from = change.from, to = change.to
+
+  var recomputeMaxLength = false, checkWidthStart = from.line
+  if (!cm.options.lineWrapping) {
+    checkWidthStart = lineNo(visualLine(getLine(doc, from.line)))
+    doc.iter(checkWidthStart, to.line + 1, function (line) {
+      if (line == display.maxLine) {
+        recomputeMaxLength = true
+        return true
+      }
+    })
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // 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;
</del><ins>+  if (doc.sel.contains(change.from, change.to) &gt; -1)
+    { signalCursorActivity(cm) }
</ins><span class="cx"> 
</span><del>-    var display = cm.display;
-    if (lendiff &amp;&amp; to &lt; display.viewTo &amp;&amp;
-        (display.updateLineNumbers == null || display.updateLineNumbers &gt; from))
-      display.updateLineNumbers = from;
</del><ins>+  updateDoc(doc, change, spans, estimateHeight(cm))
</ins><span class="cx"> 
</span><del>-    cm.curOp.viewChanged = true;
-
-    if (from &gt;= display.viewTo) { // Change after
-      if (sawCollapsedSpans &amp;&amp; visualLineNo(cm.doc, from) &lt; display.viewTo)
-        resetView(cm);
-    } else if (to &lt;= display.viewFrom) { // Change before
-      if (sawCollapsedSpans &amp;&amp; visualLineEndNo(cm.doc, to + lendiff) &gt; display.viewFrom) {
-        resetView(cm);
-      } else {
-        display.viewFrom += lendiff;
-        display.viewTo += lendiff;
</del><ins>+  if (!cm.options.lineWrapping) {
+    doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
+      var len = lineLength(line)
+      if (len &gt; display.maxLineLength) {
+        display.maxLine = line
+        display.maxLineLength = len
+        display.maxLineChanged = true
+        recomputeMaxLength = false
</ins><span class="cx">       }
</span><del>-    } else if (from &lt;= display.viewFrom &amp;&amp; to &gt;= display.viewTo) { // Full overlap
-      resetView(cm);
-    } else if (from &lt;= 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 &gt;= 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 &amp;&amp; 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);
-      }
-    }
</del><ins>+    })
+    if (recomputeMaxLength) { cm.curOp.updateMaxLine = true }
+  }
</ins><span class="cx"> 
</span><del>-    var ext = display.externalMeasured;
-    if (ext) {
-      if (to &lt; ext.lineN)
-        ext.lineN += lendiff;
-      else if (from &lt; ext.lineN + ext.size)
-        display.externalMeasured = null;
</del><ins>+  // Adjust frontier, schedule worker
+  doc.frontier = Math.min(doc.frontier, from.line)
+  startWorker(cm, 400)
+
+  var lendiff = change.text.length - (to.line - from.line) - 1
+  // Remember that these lines changed, for updating the display
+  if (change.full)
+    { regChange(cm) }
+  else if (from.line == to.line &amp;&amp; change.text.length == 1 &amp;&amp; !isWholeLineUpdate(cm.doc, change))
+    { regLineChange(cm, from.line, &quot;text&quot;) }
+  else
+    { regChange(cm, from.line, to.line + 1, lendiff) }
+
+  var changesHandler = hasHandler(cm, &quot;changes&quot;), changeHandler = hasHandler(cm, &quot;change&quot;)
+  if (changeHandler || changesHandler) {
+    var obj = {
+      from: from, to: to,
+      text: change.text,
+      removed: change.removed,
+      origin: change.origin
</ins><span class="cx">     }
</span><ins>+    if (changeHandler) { signalLater(cm, &quot;change&quot;, cm, obj) }
+    if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj) }
</ins><span class="cx">   }
</span><ins>+  cm.display.selForContextMenu = null
+}
</ins><span class="cx"> 
</span><del>-  // Register a change to a single line. Type must be one of &quot;text&quot;,
-  // &quot;gutter&quot;, &quot;class&quot;, &quot;widget&quot;
-  function regLineChange(cm, line, type) {
-    cm.curOp.viewChanged = true;
-    var display = cm.display, ext = cm.display.externalMeasured;
-    if (ext &amp;&amp; line &gt;= ext.lineN &amp;&amp; line &lt; ext.lineN + ext.size)
-      display.externalMeasured = null;
</del><ins>+function replaceRange(doc, code, from, to, origin) {
+  if (!to) { to = from }
+  if (cmp(to, from) &lt; 0) { var tmp = to; to = from; from = tmp }
+  if (typeof code == &quot;string&quot;) { code = doc.splitLines(code) }
+  makeChange(doc, {from: from, to: to, text: code, origin: origin})
+}
</ins><span class="cx"> 
</span><del>-    if (line &lt; display.viewFrom || line &gt;= 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);
-  }
</del><ins>+// Rebasing/resetting history to deal with externally-sourced changes
</ins><span class="cx"> 
</span><del>-  // Clear the view.
-  function resetView(cm) {
-    cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
-    cm.display.view = [];
-    cm.display.viewOffset = 0;
</del><ins>+function rebaseHistSelSingle(pos, from, to, diff) {
+  if (to &lt; pos.line) {
+    pos.line += diff
+  } else if (from &lt; pos.line) {
+    pos.line = from
+    pos.ch = 0
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // Find the view element corresponding to a given line. Return null
-  // when the line isn't visible.
-  function findViewIndex(cm, n) {
-    if (n &gt;= cm.display.viewTo) return null;
-    n -= cm.display.viewFrom;
-    if (n &lt; 0) return null;
-    var view = cm.display.view;
-    for (var i = 0; i &lt; view.length; i++) {
-      n -= view[i].size;
-      if (n &lt; 0) return i;
</del><ins>+// Tries to rebase an array of history events given a change in the
+// document. If the change touches the same lines as the event, the
+// event, and everything 'behind' it, is discarded. If the change is
+// before the event, the event's positions are updated. Uses a
+// copy-on-write scheme for the positions, to avoid having to
+// reallocate them all on every rebase, but also avoid problems with
+// shared position objects being unsafely updated.
+function rebaseHistArray(array, from, to, diff) {
+  for (var i = 0; i &lt; array.length; ++i) {
+    var sub = array[i], ok = true
+    if (sub.ranges) {
+      if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true }
+      for (var j = 0; j &lt; sub.ranges.length; j++) {
+        rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff)
+        rebaseHistSelSingle(sub.ranges[j].head, from, to, diff)
+      }
+      continue
</ins><span class="cx">     }
</span><del>-  }
-
-  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 &lt; index; i++)
-      n += view[i].size;
-    if (n != oldN) {
-      if (dir &gt; 0) {
-        if (index == view.length - 1) return null;
-        diff = (n + view[index].size) - oldN;
-        index++;
-      } else {
-        diff = n - oldN;
</del><ins>+    for (var j$1 = 0; j$1 &lt; sub.changes.length; ++j$1) {
+      var cur = sub.changes[j$1]
+      if (to &lt; cur.from.line) {
+        cur.from = Pos(cur.from.line + diff, cur.from.ch)
+        cur.to = Pos(cur.to.line + diff, cur.to.ch)
+      } else if (from &lt;= cur.to.line) {
+        ok = false
+        break
</ins><span class="cx">       }
</span><del>-      oldN += diff; newN += diff;
</del><span class="cx">     }
</span><del>-    while (visualLineNo(cm.doc, newN) != newN) {
-      if (index == (dir &lt; 0 ? 0 : view.length - 1)) return null;
-      newN += dir * view[index - (dir &lt; 0 ? 1 : 0)].size;
-      index += dir;
</del><ins>+    if (!ok) {
+      array.splice(0, i + 1)
+      i = 0
</ins><span class="cx">     }
</span><del>-    return {index: index, lineN: newN};
</del><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // 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 &gt;= display.viewTo || to &lt;= display.viewFrom) {
-      display.view = buildViewArray(cm, from, to);
-      display.viewFrom = from;
-    } else {
-      if (display.viewFrom &gt; from)
-        display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
-      else if (display.viewFrom &lt; from)
-        display.view = display.view.slice(findViewIndex(cm, from));
-      display.viewFrom = from;
-      if (display.viewTo &lt; to)
-        display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
-      else if (display.viewTo &gt; to)
-        display.view = display.view.slice(0, findViewIndex(cm, to));
-    }
-    display.viewTo = to;
</del><ins>+function rebaseHist(hist, change) {
+  var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1
+  rebaseHistArray(hist.done, from, to, diff)
+  rebaseHistArray(hist.undone, from, to, diff)
+}
+
+// Utility for applying a change to a line by handle or number,
+// returning the number and optionally registering the line as
+// changed.
+function changeLine(doc, handle, changeType, op) {
+  var no = handle, line = handle
+  if (typeof handle == &quot;number&quot;) { line = getLine(doc, clipLine(doc, handle)) }
+  else { no = lineNo(handle) }
+  if (no == null) { return null }
+  if (op(line, no) &amp;&amp; doc.cm) { regLineChange(doc.cm, no, changeType) }
+  return line
+}
+
+// The document is represented as a BTree consisting of leaves, with
+// chunk of lines in them, and branches, with up to ten leaves or
+// other branch nodes below them. The top node is always a branch
+// node, and is the document object itself (meaning it has
+// additional methods and properties).
+//
+// All nodes have parent links. The tree is used both to go from
+// line numbers to line objects, and to go from objects to numbers.
+// It also indexes by height, and is used to convert between height
+// and line object, and to find the total height of the document.
+//
+// See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
+
+function LeafChunk(lines) {
+  var this$1 = this;
+
+  this.lines = lines
+  this.parent = null
+  var height = 0
+  for (var i = 0; i &lt; lines.length; ++i) {
+    lines[i].parent = this$1
+    height += lines[i].height
</ins><span class="cx">   }
</span><ins>+  this.height = height
+}
</ins><span class="cx"> 
</span><del>-  // 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 &lt; view.length; i++) {
-      var lineView = view[i];
-      if (!lineView.hidden &amp;&amp; (!lineView.node || lineView.changes)) ++dirty;
</del><ins>+LeafChunk.prototype = {
+  chunkSize: function() { return this.lines.length },
+  // Remove the n lines at offset 'at'.
+  removeInner: function(at, n) {
+    var this$1 = this;
+
+    for (var i = at, e = at + n; i &lt; e; ++i) {
+      var line = this$1.lines[i]
+      this$1.height -= line.height
+      cleanUpLine(line)
+      signalLater(line, &quot;delete&quot;)
</ins><span class="cx">     }
</span><del>-    return dirty;
</del><ins>+    this.lines.splice(at, n)
+  },
+  // Helper used to collapse a small branch into a single leaf.
+  collapse: function(lines) {
+    lines.push.apply(lines, this.lines)
+  },
+  // Insert the given array of lines at offset 'at', count them as
+  // having the given height.
+  insertInner: function(at, lines, height) {
+    var this$1 = this;
+
+    this.height += height
+    this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at))
+    for (var i = 0; i &lt; lines.length; ++i) { lines[i].parent = this$1 }
+  },
+  // Used to iterate over a part of the tree.
+  iterN: function(at, n, op) {
+    var this$1 = this;
+
+    for (var e = at + n; at &lt; e; ++at)
+      { if (op(this$1.lines[at])) { return true } }
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // EVENT HANDLERS
</del><ins>+function BranchChunk(children) {
+  var this$1 = this;
</ins><span class="cx"> 
</span><del>-  // Attach the necessary event handlers when initializing the editor
-  function registerEventHandlers(cm) {
-    var d = cm.display;
-    on(d.scroller, &quot;mousedown&quot;, operation(cm, onMouseDown));
-    // Older IE's will not fire a second mousedown for a double click
-    if (ie &amp;&amp; ie_version &lt; 11)
-      on(d.scroller, &quot;dblclick&quot;, 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, &quot;dblclick&quot;, function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
-    // Some browsers fire contextmenu *after* opening the menu, at
-    // which point we can't mess with it anymore. Context menu is
-    // handled in onMouseDown for these browsers.
-    if (!captureRightClick) on(d.scroller, &quot;contextmenu&quot;, function(e) {onContextMenu(cm, e);});
</del><ins>+  this.children = children
+  var size = 0, height = 0
+  for (var i = 0; i &lt; children.length; ++i) {
+    var ch = children[i]
+    size += ch.chunkSize(); height += ch.height
+    ch.parent = this$1
+  }
+  this.size = size
+  this.height = height
+  this.parent = null
+}
</ins><span class="cx"> 
</span><del>-    // Used to suppress mouse event handling when a touch happens
-    var touchFinished, prevTouch = {end: 0};
-    function finishTouch() {
-      if (d.activeTouch) {
-        touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
-        prevTouch = d.activeTouch;
-        prevTouch.end = +new Date;
-      }
-    };
-    function isMouseLikeTouchEvent(e) {
-      if (e.touches.length != 1) return false;
-      var touch = e.touches[0];
-      return touch.radiusX &lt;= 1 &amp;&amp; touch.radiusY &lt;= 1;
</del><ins>+BranchChunk.prototype = {
+  chunkSize: function() { return this.size },
+  removeInner: function(at, n) {
+    var this$1 = this;
+
+    this.size -= n
+    for (var i = 0; i &lt; this.children.length; ++i) {
+      var child = this$1.children[i], sz = child.chunkSize()
+      if (at &lt; sz) {
+        var rm = Math.min(n, sz - at), oldHeight = child.height
+        child.removeInner(at, rm)
+        this$1.height -= oldHeight - child.height
+        if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null }
+        if ((n -= rm) == 0) { break }
+        at = 0
+      } else { at -= sz }
</ins><span class="cx">     }
</span><del>-    function farAway(touch, other) {
-      if (other.left == null) return true;
-      var dx = other.left - touch.left, dy = other.top - touch.top;
-      return dx * dx + dy * dy &gt; 20 * 20;
</del><ins>+    // If the result is smaller than 25 lines, ensure that it is a
+    // single leaf node.
+    if (this.size - n &lt; 25 &amp;&amp;
+        (this.children.length &gt; 1 || !(this.children[0] instanceof LeafChunk))) {
+      var lines = []
+      this.collapse(lines)
+      this.children = [new LeafChunk(lines)]
+      this.children[0].parent = this
</ins><span class="cx">     }
</span><del>-    on(d.scroller, &quot;touchstart&quot;, function(e) {
-      if (!isMouseLikeTouchEvent(e)) {
-        clearTimeout(touchFinished);
-        var now = +new Date;
-        d.activeTouch = {start: now, moved: false,
-                         prev: now - prevTouch.end &lt;= 300 ? prevTouch : null};
-        if (e.touches.length == 1) {
-          d.activeTouch.left = e.touches[0].pageX;
-          d.activeTouch.top = e.touches[0].pageY;
</del><ins>+  },
+  collapse: function(lines) {
+    var this$1 = this;
+
+    for (var i = 0; i &lt; this.children.length; ++i) { this$1.children[i].collapse(lines) }
+  },
+  insertInner: function(at, lines, height) {
+    var this$1 = this;
+
+    this.size += lines.length
+    this.height += height
+    for (var i = 0; i &lt; this.children.length; ++i) {
+      var child = this$1.children[i], sz = child.chunkSize()
+      if (at &lt;= sz) {
+        child.insertInner(at, lines, height)
+        if (child.lines &amp;&amp; child.lines.length &gt; 50) {
+          // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
+          // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
+          var remaining = child.lines.length % 25 + 25
+          for (var pos = remaining; pos &lt; child.lines.length;) {
+            var leaf = new LeafChunk(child.lines.slice(pos, pos += 25))
+            child.height -= leaf.height
+            this$1.children.splice(++i, 0, leaf)
+            leaf.parent = this$1
+          }
+          child.lines = child.lines.slice(0, remaining)
+          this$1.maybeSpill()
</ins><span class="cx">         }
</span><ins>+        break
</ins><span class="cx">       }
</span><del>-    });
-    on(d.scroller, &quot;touchmove&quot;, function() {
-      if (d.activeTouch) d.activeTouch.moved = true;
-    });
-    on(d.scroller, &quot;touchend&quot;, function(e) {
-      var touch = d.activeTouch;
-      if (touch &amp;&amp; !eventInWidget(d, e) &amp;&amp; touch.left != null &amp;&amp;
-          !touch.moved &amp;&amp; new Date - touch.start &lt; 300) {
-        var pos = cm.coordsChar(d.activeTouch, &quot;page&quot;), range;
-        if (!touch.prev || farAway(touch, touch.prev)) // Single tap
-          range = new Range(pos, pos);
-        else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
-          range = cm.findWordAt(pos);
-        else // Triple tap
-          range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
-        cm.setSelection(range.anchor, range.head);
-        cm.focus();
-        e_preventDefault(e);
</del><ins>+      at -= sz
+    }
+  },
+  // When a node has grown, check whether it should be split.
+  maybeSpill: function() {
+    if (this.children.length &lt;= 10) { return }
+    var me = this
+    do {
+      var spilled = me.children.splice(me.children.length - 5, 5)
+      var sibling = new BranchChunk(spilled)
+      if (!me.parent) { // Become the parent node
+        var copy = new BranchChunk(me.children)
+        copy.parent = me
+        me.children = [copy, sibling]
+        me = copy
+     } else {
+        me.size -= sibling.size
+        me.height -= sibling.height
+        var myIndex = indexOf(me.parent.children, me)
+        me.parent.children.splice(myIndex + 1, 0, sibling)
</ins><span class="cx">       }
</span><del>-      finishTouch();
-    });
-    on(d.scroller, &quot;touchcancel&quot;, finishTouch);
</del><ins>+      sibling.parent = me.parent
+    } while (me.children.length &gt; 10)
+    me.parent.maybeSpill()
+  },
+  iterN: function(at, n, op) {
+    var this$1 = this;
</ins><span class="cx"> 
</span><del>-    // Sync scrolling between fake scrollbars and real scrollable
-    // area, ensure viewport is updated when scrolling.
-    on(d.scroller, &quot;scroll&quot;, function() {
-      if (d.scroller.clientHeight) {
-        setScrollTop(cm, d.scroller.scrollTop);
-        setScrollLeft(cm, d.scroller.scrollLeft, true);
-        signal(cm, &quot;scroll&quot;, cm);
-      }
-    });
</del><ins>+    for (var i = 0; i &lt; this.children.length; ++i) {
+      var child = this$1.children[i], sz = child.chunkSize()
+      if (at &lt; sz) {
+        var used = Math.min(n, sz - at)
+        if (child.iterN(at, used, op)) { return true }
+        if ((n -= used) == 0) { break }
+        at = 0
+      } else { at -= sz }
+    }
+  }
+}
</ins><span class="cx"> 
</span><del>-    // Listen to wheel events in order to try and update the viewport on time.
-    on(d.scroller, &quot;mousewheel&quot;, function(e){onScrollWheel(cm, e);});
-    on(d.scroller, &quot;DOMMouseScroll&quot;, function(e){onScrollWheel(cm, e);});
</del><ins>+// Line widgets are block elements displayed above or below a line.
</ins><span class="cx"> 
</span><del>-    // Prevent wrapper from ever scrolling
-    on(d.wrapper, &quot;scroll&quot;, function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
</del><ins>+function LineWidget(doc, node, options) {
+  var this$1 = this;
</ins><span class="cx"> 
</span><del>-    d.dragFunctions = {
-      enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
-      over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
-      start: function(e){onDragStart(cm, e);},
-      drop: operation(cm, onDrop),
-      leave: function() {clearDragCursor(cm);}
-    };
</del><ins>+  if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
+    { this$1[opt] = options[opt] } } }
+  this.doc = doc
+  this.node = node
+}
+eventMixin(LineWidget)
</ins><span class="cx"> 
</span><del>-    var inp = d.input.getField();
-    on(inp, &quot;keyup&quot;, function(e) { onKeyUp.call(cm, e); });
-    on(inp, &quot;keydown&quot;, operation(cm, onKeyDown));
-    on(inp, &quot;keypress&quot;, operation(cm, onKeyPress));
-    on(inp, &quot;focus&quot;, bind(onFocus, cm));
-    on(inp, &quot;blur&quot;, bind(onBlur, cm));
-  }
</del><ins>+function adjustScrollWhenAboveVisible(cm, line, diff) {
+  if (heightAtLine(line) &lt; ((cm.curOp &amp;&amp; cm.curOp.scrollTop) || cm.doc.scrollTop))
+    { addToScrollPos(cm, null, diff) }
+}
</ins><span class="cx"> 
</span><del>-  function dragDropChanged(cm, value, old) {
-    var wasOn = old &amp;&amp; old != CodeMirror.Init;
-    if (!value != !wasOn) {
-      var funcs = cm.display.dragFunctions;
-      var toggle = value ? on : off;
-      toggle(cm.display.scroller, &quot;dragstart&quot;, funcs.start);
-      toggle(cm.display.scroller, &quot;dragenter&quot;, funcs.enter);
-      toggle(cm.display.scroller, &quot;dragover&quot;, funcs.over);
-      toggle(cm.display.scroller, &quot;dragleave&quot;, funcs.leave);
-      toggle(cm.display.scroller, &quot;drop&quot;, funcs.drop);
</del><ins>+LineWidget.prototype.clear = function() {
+  var this$1 = this;
+
+  var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line)
+  if (no == null || !ws) { return }
+  for (var i = 0; i &lt; ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1) } }
+  if (!ws.length) { line.widgets = null }
+  var height = widgetHeight(this)
+  updateLineHeight(line, Math.max(0, line.height - height))
+  if (cm) { runInOp(cm, function () {
+    adjustScrollWhenAboveVisible(cm, line, -height)
+    regLineChange(cm, no, &quot;widget&quot;)
+  }) }
+}
+LineWidget.prototype.changed = function() {
+  var oldH = this.height, cm = this.doc.cm, line = this.line
+  this.height = null
+  var diff = widgetHeight(this) - oldH
+  if (!diff) { return }
+  updateLineHeight(line, line.height + diff)
+  if (cm) { runInOp(cm, function () {
+    cm.curOp.forceUpdate = true
+    adjustScrollWhenAboveVisible(cm, line, diff)
+  }) }
+}
+
+function addLineWidget(doc, handle, node, options) {
+  var widget = new LineWidget(doc, node, options)
+  var cm = doc.cm
+  if (cm &amp;&amp; widget.noHScroll) { cm.display.alignWidgets = true }
+  changeLine(doc, handle, &quot;widget&quot;, function (line) {
+    var widgets = line.widgets || (line.widgets = [])
+    if (widget.insertAt == null) { widgets.push(widget) }
+    else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget) }
+    widget.line = line
+    if (cm &amp;&amp; !lineIsHidden(doc, line)) {
+      var aboveVisible = heightAtLine(line) &lt; doc.scrollTop
+      updateLineHeight(line, line.height + widgetHeight(widget))
+      if (aboveVisible) { addToScrollPos(cm, null, widget.height) }
+      cm.curOp.forceUpdate = true
</ins><span class="cx">     }
</span><ins>+    return true
+  })
+  return widget
+}
+
+// TEXTMARKERS
+
+// Created with markText and setBookmark methods. A TextMarker is a
+// handle that can be used to clear or find a marked position in the
+// document. Line objects hold arrays (markedSpans) containing
+// {from, to, marker} object pointing to such marker objects, and
+// indicating that such a marker is present on that line. Multiple
+// lines may point to the same marker when it spans across lines.
+// The spans will have null for their from/to properties when the
+// marker continues beyond the start/end of the line. Markers have
+// links back to the lines they currently touch.
+
+// Collapsed markers have unique ids, in order to be able to order
+// them, which is needed for uniquely determining an outer marker
+// when they overlap (they may nest, but not partially overlap).
+var nextMarkerId = 0
+
+function TextMarker(doc, type) {
+  this.lines = []
+  this.type = type
+  this.doc = doc
+  this.id = ++nextMarkerId
+}
+eventMixin(TextMarker)
+
+// Clear the marker.
+TextMarker.prototype.clear = function() {
+  var this$1 = this;
+
+  if (this.explicitlyCleared) { return }
+  var cm = this.doc.cm, withOp = cm &amp;&amp; !cm.curOp
+  if (withOp) { startOperation(cm) }
+  if (hasHandler(this, &quot;clear&quot;)) {
+    var found = this.find()
+    if (found) { signalLater(this, &quot;clear&quot;, found.from, found.to) }
</ins><span class="cx">   }
</span><ins>+  var min = null, max = null
+  for (var i = 0; i &lt; this.lines.length; ++i) {
+    var line = this$1.lines[i]
+    var span = getMarkedSpanFor(line.markedSpans, this$1)
+    if (cm &amp;&amp; !this$1.collapsed) { regLineChange(cm, lineNo(line), &quot;text&quot;) }
+    else if (cm) {
+      if (span.to != null) { max = lineNo(line) }
+      if (span.from != null) { min = lineNo(line) }
+    }
+    line.markedSpans = removeMarkedSpan(line.markedSpans, span)
+    if (span.from == null &amp;&amp; this$1.collapsed &amp;&amp; !lineIsHidden(this$1.doc, line) &amp;&amp; cm)
+      { updateLineHeight(line, textHeight(cm.display)) }
+  }
+  if (cm &amp;&amp; this.collapsed &amp;&amp; !cm.options.lineWrapping) { for (var i$1 = 0; i$1 &lt; this.lines.length; ++i$1) {
+    var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual)
+    if (len &gt; cm.display.maxLineLength) {
+      cm.display.maxLine = visual
+      cm.display.maxLineLength = len
+      cm.display.maxLineChanged = true
+    }
+  } }
</ins><span class="cx"> 
</span><del>-  // Called when the window resizes
-  function onResize(cm) {
-    var d = cm.display;
-    if (d.lastWrapHeight == d.wrapper.clientHeight &amp;&amp; d.lastWrapWidth == d.wrapper.clientWidth)
-      return;
-    // Might be a text scaling operation, clear size caches.
-    d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
-    d.scrollbarsClipped = false;
-    cm.setSize();
</del><ins>+  if (min != null &amp;&amp; cm &amp;&amp; this.collapsed) { regChange(cm, min, max + 1) }
+  this.lines.length = 0
+  this.explicitlyCleared = true
+  if (this.atomic &amp;&amp; this.doc.cantEdit) {
+    this.doc.cantEdit = false
+    if (cm) { reCheckSelection(cm.doc) }
</ins><span class="cx">   }
</span><ins>+  if (cm) { signalLater(cm, &quot;markerCleared&quot;, cm, this) }
+  if (withOp) { endOperation(cm) }
+  if (this.parent) { this.parent.clear() }
+}
</ins><span class="cx"> 
</span><del>-  // MOUSE EVENTS
</del><ins>+// Find the position of the marker in the document. Returns a {from,
+// to} object by default. Side can be passed to get a specific side
+// -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
+// Pos objects returned contain a line object, rather than a line
+// number (used to prevent looking up the same line twice).
+TextMarker.prototype.find = function(side, lineObj) {
+  var this$1 = this;
</ins><span class="cx"> 
</span><del>-  // 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 &amp;&amp; n.getAttribute(&quot;cm-ignore-events&quot;) == &quot;true&quot;) ||
-          (n.parentNode == display.sizer &amp;&amp; n != display.mover))
-        return true;
</del><ins>+  if (side == null &amp;&amp; this.type == &quot;bookmark&quot;) { side = 1 }
+  var from, to
+  for (var i = 0; i &lt; this.lines.length; ++i) {
+    var line = this$1.lines[i]
+    var span = getMarkedSpanFor(line.markedSpans, this$1)
+    if (span.from != null) {
+      from = Pos(lineObj ? line : lineNo(line), span.from)
+      if (side == -1) { return from }
</ins><span class="cx">     }
</span><ins>+    if (span.to != null) {
+      to = Pos(lineObj ? line : lineNo(line), span.to)
+      if (side == 1) { return to }
+    }
</ins><span class="cx">   }
</span><ins>+  return from &amp;&amp; {from: from, to: to}
+}
</ins><span class="cx"> 
</span><del>-  // 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 &amp;&amp; e_target(e).getAttribute(&quot;cm-not-content&quot;) == &quot;true&quot;) return null;
</del><ins>+// Signals that the marker's widget changed, and surrounding layout
+// should be recomputed.
+TextMarker.prototype.changed = function() {
+  var pos = this.find(-1, true), widget = this, cm = this.doc.cm
+  if (!pos || !cm) { return }
+  runInOp(cm, function () {
+    var line = pos.line, lineN = lineNo(pos.line)
+    var view = findViewForLine(cm, lineN)
+    if (view) {
+      clearLineMeasurementCacheFor(view)
+      cm.curOp.selectionChanged = cm.curOp.forceUpdate = true
+    }
+    cm.curOp.updateMaxLine = true
+    if (!lineIsHidden(widget.doc, line) &amp;&amp; widget.height != null) {
+      var oldHeight = widget.height
+      widget.height = null
+      var dHeight = widgetHeight(widget) - oldHeight
+      if (dHeight)
+        { updateLineHeight(line, line.height + dHeight) }
+    }
+  })
+}
</ins><span class="cx"> 
</span><del>-    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 &amp;&amp; coords.xRel == 1 &amp;&amp; (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;
</del><ins>+TextMarker.prototype.attachLine = function(line) {
+  if (!this.lines.length &amp;&amp; this.doc.cm) {
+    var op = this.doc.cm.curOp
+    if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
+      { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this) }
</ins><span class="cx">   }
</span><ins>+  this.lines.push(line)
+}
+TextMarker.prototype.detachLine = function(line) {
+  this.lines.splice(indexOf(this.lines, line), 1)
+  if (!this.lines.length &amp;&amp; this.doc.cm) {
+    var op = this.doc.cm.curOp
+    ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this)
+  }
+}
</ins><span class="cx"> 
</span><del>-  // A mouse down can be a single click, double click, triple click,
-  // start of selection drag, start of text drag, new cursor
-  // (ctrl-click), rectangle drag (alt-drag), or xwin
-  // middle-click-paste. Or it might be a click on something we should
-  // not interfere with, such as a scrollbar or widget.
-  function onMouseDown(e) {
-    var cm = this, display = cm.display;
-    if (display.activeTouch &amp;&amp; display.input.supportsTouch() || signalDOMEvent(cm, e)) return;
-    display.shift = e.shiftKey;
</del><ins>+// Create a marker, wire it up to the right lines, and
+function markText(doc, from, to, options, type) {
+  // Shared markers (across linked documents) are handled separately
+  // (markTextShared will call out to this again, once per
+  // document).
+  if (options &amp;&amp; options.shared) { return markTextShared(doc, from, to, options, type) }
+  // Ensure we are in an operation.
+  if (doc.cm &amp;&amp; !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
</ins><span class="cx"> 
</span><del>-    if (eventInWidget(display, e)) {
-      if (!webkit) {
-        // Briefly turn off draggability, to allow widgets to do
-        // normal dragging things.
-        display.scroller.draggable = false;
-        setTimeout(function(){display.scroller.draggable = true;}, 100);
-      }
-      return;
-    }
-    if (clickInGutter(cm, e)) return;
-    var start = posFromMouse(cm, e);
-    window.focus();
</del><ins>+  var marker = new TextMarker(doc, type), diff = cmp(from, to)
+  if (options) { copyObj(options, marker, false) }
+  // Don't connect empty markers unless clearWhenEmpty is false
+  if (diff &gt; 0 || diff == 0 &amp;&amp; marker.clearWhenEmpty !== false)
+    { return marker }
+  if (marker.replacedWith) {
+    // Showing up as a widget implies collapsed (widget replaces text)
+    marker.collapsed = true
+    marker.widgetNode = elt(&quot;span&quot;, [marker.replacedWith], &quot;CodeMirror-widget&quot;)
+    if (!options.handleMouseEvents) { marker.widgetNode.setAttribute(&quot;cm-ignore-events&quot;, &quot;true&quot;) }
+    if (options.insertLeft) { marker.widgetNode.insertLeft = true }
+  }
+  if (marker.collapsed) {
+    if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
+        from.line != to.line &amp;&amp; conflictingCollapsedRange(doc, to.line, from, to, marker))
+      { throw new Error(&quot;Inserting collapsed marker partially overlapping an existing one&quot;) }
+    seeCollapsedSpans()
+  }
</ins><span class="cx"> 
</span><del>-    switch (e_button(e)) {
-    case 1:
-      // #3261: make sure, that we're not starting a second selection
-      if (cm.state.selectingText)
-        cm.state.selectingText(e);
-      else if (start)
-        leftButtonDown(cm, e, start);
-      else if (e_target(e) == display.scroller)
-        e_preventDefault(e);
-      break;
-    case 2:
-      if (webkit) cm.state.lastMiddleDown = +new Date;
-      if (start) extendSelection(cm.doc, start);
-      setTimeout(function() {display.input.focus();}, 20);
-      e_preventDefault(e);
-      break;
-    case 3:
-      if (captureRightClick) onContextMenu(cm, e);
-      else delayBlurEvent(cm);
-      break;
-    }
</del><ins>+  if (marker.addToHistory)
+    { addChangeToHistory(doc, {from: from, to: to, origin: &quot;markText&quot;}, doc.sel, NaN) }
+
+  var curLine = from.line, cm = doc.cm, updateMaxLine
+  doc.iter(curLine, to.line + 1, function (line) {
+    if (cm &amp;&amp; marker.collapsed &amp;&amp; !cm.options.lineWrapping &amp;&amp; visualLine(line) == cm.display.maxLine)
+      { updateMaxLine = true }
+    if (marker.collapsed &amp;&amp; curLine != from.line) { updateLineHeight(line, 0) }
+    addMarkedSpan(line, new MarkedSpan(marker,
+                                       curLine == from.line ? from.ch : null,
+                                       curLine == to.line ? to.ch : null))
+    ++curLine
+  })
+  // lineIsHidden depends on the presence of the spans, so needs a second pass
+  if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
+    if (lineIsHidden(doc, line)) { updateLineHeight(line, 0) }
+  }) }
+
+  if (marker.clearOnEnter) { on(marker, &quot;beforeCursorEnter&quot;, function () { return marker.clear(); }) }
+
+  if (marker.readOnly) {
+    seeReadOnlySpans()
+    if (doc.history.done.length || doc.history.undone.length)
+      { doc.clearHistory() }
</ins><span class="cx">   }
</span><ins>+  if (marker.collapsed) {
+    marker.id = ++nextMarkerId
+    marker.atomic = true
+  }
+  if (cm) {
+    // Sync editor state
+    if (updateMaxLine) { cm.curOp.updateMaxLine = true }
+    if (marker.collapsed)
+      { regChange(cm, from.line, to.line + 1) }
+    else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
+      { for (var i = from.line; i &lt;= to.line; i++) { regLineChange(cm, i, &quot;text&quot;) } }
+    if (marker.atomic) { reCheckSelection(cm.doc) }
+    signalLater(cm, &quot;markerAdded&quot;, cm, marker)
+  }
+  return marker
+}
</ins><span class="cx"> 
</span><del>-  var lastClick, lastDoubleClick;
-  function leftButtonDown(cm, e, start) {
-    if (ie) setTimeout(bind(ensureFocus, cm), 0);
-    else cm.curOp.focus = activeElt();
</del><ins>+// SHARED TEXTMARKERS
</ins><span class="cx"> 
</span><del>-    var now = +new Date, type;
-    if (lastDoubleClick &amp;&amp; lastDoubleClick.time &gt; now - 400 &amp;&amp; cmp(lastDoubleClick.pos, start) == 0) {
-      type = &quot;triple&quot;;
-    } else if (lastClick &amp;&amp; lastClick.time &gt; now - 400 &amp;&amp; cmp(lastClick.pos, start) == 0) {
-      type = &quot;double&quot;;
-      lastDoubleClick = {time: now, pos: start};
-    } else {
-      type = &quot;single&quot;;
-      lastClick = {time: now, pos: start};
</del><ins>+// A shared marker spans multiple linked documents. It is
+// implemented as a meta-marker-object controlling multiple normal
+// markers.
+function SharedTextMarker(markers, primary) {
+  var this$1 = this;
+
+  this.markers = markers
+  this.primary = primary
+  for (var i = 0; i &lt; markers.length; ++i)
+    { markers[i].parent = this$1 }
+}
+eventMixin(SharedTextMarker)
+
+SharedTextMarker.prototype.clear = function() {
+  var this$1 = this;
+
+  if (this.explicitlyCleared) { return }
+  this.explicitlyCleared = true
+  for (var i = 0; i &lt; this.markers.length; ++i)
+    { this$1.markers[i].clear() }
+  signalLater(this, &quot;clear&quot;)
+}
+SharedTextMarker.prototype.find = function(side, lineObj) {
+  return this.primary.find(side, lineObj)
+}
+
+function markTextShared(doc, from, to, options, type) {
+  options = copyObj(options)
+  options.shared = false
+  var markers = [markText(doc, from, to, options, type)], primary = markers[0]
+  var widget = options.widgetNode
+  linkedDocs(doc, function (doc) {
+    if (widget) { options.widgetNode = widget.cloneNode(true) }
+    markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type))
+    for (var i = 0; i &lt; doc.linked.length; ++i)
+      { if (doc.linked[i].isParent) { return } }
+    primary = lst(markers)
+  })
+  return new SharedTextMarker(markers, primary)
+}
+
+function findSharedMarkers(doc) {
+  return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
+}
+
+function copySharedMarkers(doc, markers) {
+  for (var i = 0; i &lt; markers.length; i++) {
+    var marker = markers[i], pos = marker.find()
+    var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to)
+    if (cmp(mFrom, mTo)) {
+      var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type)
+      marker.markers.push(subMark)
+      subMark.parent = marker
</ins><span class="cx">     }
</span><del>-
-    var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
-    if (cm.options.dragDrop &amp;&amp; dragAndDrop &amp;&amp; !isReadOnly(cm) &amp;&amp;
-        type == &quot;single&quot; &amp;&amp; (contained = sel.contains(start)) &gt; -1 &amp;&amp;
-        (cmp((contained = sel.ranges[contained]).from(), start) &lt; 0 || start.xRel &gt; 0) &amp;&amp;
-        (cmp(contained.to(), start) &gt; 0 || start.xRel &lt; 0))
-      leftButtonStartDrag(cm, e, start, modifier);
-    else
-      leftButtonSelect(cm, e, start, type, modifier);
</del><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // Start a text drag. When it ends, see if any dragging actually
-  // happen, and treat as a click if it didn't.
-  function leftButtonStartDrag(cm, e, start, modifier) {
-    var display = cm.display, startTime = +new Date;
-    var dragEnd = operation(cm, function(e2) {
-      if (webkit) display.scroller.draggable = false;
-      cm.state.draggingText = false;
-      off(document, &quot;mouseup&quot;, dragEnd);
-      off(display.scroller, &quot;drop&quot;, dragEnd);
-      if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) &lt; 10) {
-        e_preventDefault(e2);
-        if (!modifier &amp;&amp; +new Date - 200 &lt; startTime)
-          extendSelection(cm.doc, start);
-        // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
-        if (webkit || ie &amp;&amp; ie_version == 9)
-          setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
-        else
-          display.input.focus();
</del><ins>+function detachSharedMarkers(markers) {
+  var loop = function ( i ) {
+    var marker = markers[i], linked = [marker.primary.doc]
+    linkedDocs(marker.primary.doc, function (d) { return linked.push(d); })
+    for (var j = 0; j &lt; marker.markers.length; j++) {
+      var subMarker = marker.markers[j]
+      if (indexOf(linked, subMarker.doc) == -1) {
+        subMarker.parent = null
+        marker.markers.splice(j--, 1)
</ins><span class="cx">       }
</span><del>-    });
-    // Let the drag handler handle this.
-    if (webkit) display.scroller.draggable = true;
-    cm.state.draggingText = dragEnd;
-    // IE's approach to draggable
-    if (display.scroller.dragDrop) display.scroller.dragDrop();
-    on(document, &quot;mouseup&quot;, dragEnd);
-    on(display.scroller, &quot;drop&quot;, dragEnd);
-  }
</del><ins>+    }
+  };
</ins><span class="cx"> 
</span><del>-  // Normal selection, as opposed to text dragging.
-  function leftButtonSelect(cm, e, start, type, addNew) {
-    var display = cm.display, doc = cm.doc;
-    e_preventDefault(e);
</del><ins>+  for (var i = 0; i &lt; markers.length; i++) loop( i );
+}
</ins><span class="cx"> 
</span><del>-    var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
-    if (addNew &amp;&amp; !e.shiftKey) {
-      ourIndex = doc.sel.contains(start);
-      if (ourIndex &gt; -1)
-        ourRange = ranges[ourIndex];
-      else
-        ourRange = new Range(start, start);
-    } else {
-      ourRange = doc.sel.primary();
-      ourIndex = doc.sel.primIndex;
</del><ins>+var nextDocId = 0
+var Doc = function(text, mode, firstLine, lineSep) {
+  if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep) }
+  if (firstLine == null) { firstLine = 0 }
+
+  BranchChunk.call(this, [new LeafChunk([new Line(&quot;&quot;, null)])])
+  this.first = firstLine
+  this.scrollTop = this.scrollLeft = 0
+  this.cantEdit = false
+  this.cleanGeneration = 1
+  this.frontier = firstLine
+  var start = Pos(firstLine, 0)
+  this.sel = simpleSelection(start)
+  this.history = new History(null)
+  this.id = ++nextDocId
+  this.modeOption = mode
+  this.lineSep = lineSep
+  this.extend = false
+
+  if (typeof text == &quot;string&quot;) { text = this.splitLines(text) }
+  updateDoc(this, {from: start, to: start, text: text})
+  setSelection(this, simpleSelection(start), sel_dontScroll)
+}
+
+Doc.prototype = createObj(BranchChunk.prototype, {
+  constructor: Doc,
+  // Iterate over the document. Supports two forms -- with only one
+  // argument, it calls that for each line in the document. With
+  // three, it iterates over the range given by the first two (with
+  // the second being non-inclusive).
+  iter: function(from, to, op) {
+    if (op) { this.iterN(from - this.first, to - from, op) }
+    else { this.iterN(this.first, this.first + this.size, from) }
+  },
+
+  // Non-public interface for adding and removing lines.
+  insert: function(at, lines) {
+    var height = 0
+    for (var i = 0; i &lt; lines.length; ++i) { height += lines[i].height }
+    this.insertInner(at - this.first, lines, height)
+  },
+  remove: function(at, n) { this.removeInner(at - this.first, n) },
+
+  // From here, the methods are part of the public interface. Most
+  // are also available from CodeMirror (editor) instances.
+
+  getValue: function(lineSep) {
+    var lines = getLines(this, this.first, this.first + this.size)
+    if (lineSep === false) { return lines }
+    return lines.join(lineSep || this.lineSeparator())
+  },
+  setValue: docMethodOp(function(code) {
+    var top = Pos(this.first, 0), last = this.first + this.size - 1
+    makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
+                      text: this.splitLines(code), origin: &quot;setValue&quot;, full: true}, true)
+    setSelection(this, simpleSelection(top))
+  }),
+  replaceRange: function(code, from, to, origin) {
+    from = clipPos(this, from)
+    to = to ? clipPos(this, to) : from
+    replaceRange(this, code, from, to, origin)
+  },
+  getRange: function(from, to, lineSep) {
+    var lines = getBetween(this, clipPos(this, from), clipPos(this, to))
+    if (lineSep === false) { return lines }
+    return lines.join(lineSep || this.lineSeparator())
+  },
+
+  getLine: function(line) {var l = this.getLineHandle(line); return l &amp;&amp; l.text},
+
+  getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
+  getLineNumber: function(line) {return lineNo(line)},
+
+  getLineHandleVisualStart: function(line) {
+    if (typeof line == &quot;number&quot;) { line = getLine(this, line) }
+    return visualLine(line)
+  },
+
+  lineCount: function() {return this.size},
+  firstLine: function() {return this.first},
+  lastLine: function() {return this.first + this.size - 1},
+
+  clipPos: function(pos) {return clipPos(this, pos)},
+
+  getCursor: function(start) {
+    var range = this.sel.primary(), pos
+    if (start == null || start == &quot;head&quot;) { pos = range.head }
+    else if (start == &quot;anchor&quot;) { pos = range.anchor }
+    else if (start == &quot;end&quot; || start == &quot;to&quot; || start === false) { pos = range.to() }
+    else { pos = range.from() }
+    return pos
+  },
+  listSelections: function() { return this.sel.ranges },
+  somethingSelected: function() {return this.sel.somethingSelected()},
+
+  setCursor: docMethodOp(function(line, ch, options) {
+    setSimpleSelection(this, clipPos(this, typeof line == &quot;number&quot; ? Pos(line, ch || 0) : line), null, options)
+  }),
+  setSelection: docMethodOp(function(anchor, head, options) {
+    setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options)
+  }),
+  extendSelection: docMethodOp(function(head, other, options) {
+    extendSelection(this, clipPos(this, head), other &amp;&amp; clipPos(this, other), options)
+  }),
+  extendSelections: docMethodOp(function(heads, options) {
+    extendSelections(this, clipPosArray(this, heads), options)
+  }),
+  extendSelectionsBy: docMethodOp(function(f, options) {
+    var heads = map(this.sel.ranges, f)
+    extendSelections(this, clipPosArray(this, heads), options)
+  }),
+  setSelections: docMethodOp(function(ranges, primary, options) {
+    var this$1 = this;
+
+    if (!ranges.length) { return }
+    var out = []
+    for (var i = 0; i &lt; ranges.length; i++)
+      { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
+                         clipPos(this$1, ranges[i].head)) }
+    if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex) }
+    setSelection(this, normalizeSelection(out, primary), options)
+  }),
+  addSelection: docMethodOp(function(anchor, head, options) {
+    var ranges = this.sel.ranges.slice(0)
+    ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)))
+    setSelection(this, normalizeSelection(ranges, ranges.length - 1), options)
+  }),
+
+  getSelection: function(lineSep) {
+    var this$1 = this;
+
+    var ranges = this.sel.ranges, lines
+    for (var i = 0; i &lt; ranges.length; i++) {
+      var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
+      lines = lines ? lines.concat(sel) : sel
</ins><span class="cx">     }
</span><ins>+    if (lineSep === false) { return lines }
+    else { return lines.join(lineSep || this.lineSeparator()) }
+  },
+  getSelections: function(lineSep) {
+    var this$1 = this;
</ins><span class="cx"> 
</span><del>-    if (e.altKey) {
-      type = &quot;rect&quot;;
-      if (!addNew) ourRange = new Range(start, start);
-      start = posFromMouse(cm, e, true, true);
-      ourIndex = -1;
-    } else if (type == &quot;double&quot;) {
-      var word = cm.findWordAt(start);
-      if (cm.display.shift || doc.extend)
-        ourRange = extendRange(doc, ourRange, word.anchor, word.head);
-      else
-        ourRange = word;
-    } else if (type == &quot;triple&quot;) {
-      var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
-      if (cm.display.shift || doc.extend)
-        ourRange = extendRange(doc, ourRange, line.anchor, line.head);
-      else
-        ourRange = line;
-    } else {
-      ourRange = extendRange(doc, ourRange, start);
</del><ins>+    var parts = [], ranges = this.sel.ranges
+    for (var i = 0; i &lt; ranges.length; i++) {
+      var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
+      if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()) }
+      parts[i] = sel
</ins><span class="cx">     }
</span><ins>+    return parts
+  },
+  replaceSelection: function(code, collapse, origin) {
+    var dup = []
+    for (var i = 0; i &lt; this.sel.ranges.length; i++)
+      { dup[i] = code }
+    this.replaceSelections(dup, collapse, origin || &quot;+input&quot;)
+  },
+  replaceSelections: docMethodOp(function(code, collapse, origin) {
+    var this$1 = this;
</ins><span class="cx"> 
</span><del>-    if (!addNew) {
-      ourIndex = 0;
-      setSelection(doc, new Selection([ourRange], 0), sel_mouse);
-      startSel = doc.sel;
-    } else if (ourIndex == -1) {
-      ourIndex = ranges.length;
-      setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
-                   {scroll: false, origin: &quot;*mouse&quot;});
-    } else if (ranges.length &gt; 1 &amp;&amp; ranges[ourIndex].empty() &amp;&amp; type == &quot;single&quot; &amp;&amp; !e.shiftKey) {
-      setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0));
-      startSel = doc.sel;
-    } else {
-      replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
</del><ins>+    var changes = [], sel = this.sel
+    for (var i = 0; i &lt; sel.ranges.length; i++) {
+      var range = sel.ranges[i]
+      changes[i] = {from: range.from(), to: range.to(), text: this$1.splitLines(code[i]), origin: origin}
</ins><span class="cx">     }
</span><ins>+    var newSel = collapse &amp;&amp; collapse != &quot;end&quot; &amp;&amp; computeReplacedSel(this, changes, collapse)
+    for (var i$1 = changes.length - 1; i$1 &gt;= 0; i$1--)
+      { makeChange(this$1, changes[i$1]) }
+    if (newSel) { setSelectionReplaceHistory(this, newSel) }
+    else if (this.cm) { ensureCursorVisible(this.cm) }
+  }),
+  undo: docMethodOp(function() {makeChangeFromHistory(this, &quot;undo&quot;)}),
+  redo: docMethodOp(function() {makeChangeFromHistory(this, &quot;redo&quot;)}),
+  undoSelection: docMethodOp(function() {makeChangeFromHistory(this, &quot;undo&quot;, true)}),
+  redoSelection: docMethodOp(function() {makeChangeFromHistory(this, &quot;redo&quot;, true)}),
</ins><span class="cx"> 
</span><del>-    var lastPos = start;
-    function extendTo(pos) {
-      if (cmp(lastPos, pos) == 0) return;
-      lastPos = pos;
</del><ins>+  setExtending: function(val) {this.extend = val},
+  getExtending: function() {return this.extend},
</ins><span class="cx"> 
</span><del>-      if (type == &quot;rect&quot;) {
-        var ranges = [], tabSize = cm.options.tabSize;
-        var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
-        var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
-        var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
-        for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
-             line &lt;= end; line++) {
-          var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
-          if (left == right)
-            ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
-          else if (text.length &gt; leftPos)
-            ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
-        }
-        if (!ranges.length) ranges.push(new Range(start, start));
-        setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
-                     {origin: &quot;*mouse&quot;, scroll: false});
-        cm.scrollIntoView(pos);
-      } else {
-        var oldRange = ourRange;
-        var anchor = oldRange.anchor, head = pos;
-        if (type != &quot;single&quot;) {
-          if (type == &quot;double&quot;)
-            var range = cm.findWordAt(pos);
-          else
-            var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
-          if (cmp(range.anchor, anchor) &gt; 0) {
-            head = range.head;
-            anchor = minPos(oldRange.from(), range.anchor);
-          } else {
-            head = range.anchor;
-            anchor = maxPos(oldRange.to(), range.head);
-          }
-        }
-        var ranges = startSel.ranges.slice(0);
-        ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
-        setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
-      }
-    }
</del><ins>+  historySize: function() {
+    var hist = this.history, done = 0, undone = 0
+    for (var i = 0; i &lt; hist.done.length; i++) { if (!hist.done[i].ranges) { ++done } }
+    for (var i$1 = 0; i$1 &lt; hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone } }
+    return {undo: done, redo: undone}
+  },
+  clearHistory: function() {this.history = new History(this.history.maxGeneration)},
</ins><span class="cx"> 
</span><del>-    var editorSize = display.wrapper.getBoundingClientRect();
-    // Used to ensure timeout re-tries don't fire when another extend
-    // happened in the meantime (clearTimeout isn't reliable -- at
-    // least on Chrome, the timeouts still happen even when cleared,
-    // if the clear happens after their scheduled firing time).
-    var counter = 0;
</del><ins>+  markClean: function() {
+    this.cleanGeneration = this.changeGeneration(true)
+  },
+  changeGeneration: function(forceSplit) {
+    if (forceSplit)
+      { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null }
+    return this.history.generation
+  },
+  isClean: function (gen) {
+    return this.history.generation == (gen || this.cleanGeneration)
+  },
</ins><span class="cx"> 
</span><del>-    function extend(e) {
-      var curCount = ++counter;
-      var cur = posFromMouse(cm, e, true, type == &quot;rect&quot;);
-      if (!cur) return;
-      if (cmp(cur, lastPos) != 0) {
-        cm.curOp.focus = activeElt();
-        extendTo(cur);
-        var visible = visibleLines(display, doc);
-        if (cur.line &gt;= visible.to || cur.line &lt; visible.from)
-          setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
-      } else {
-        var outside = e.clientY &lt; editorSize.top ? -20 : e.clientY &gt; editorSize.bottom ? 20 : 0;
-        if (outside) setTimeout(operation(cm, function() {
-          if (counter != curCount) return;
-          display.scroller.scrollTop += outside;
-          extend(e);
-        }), 50);
</del><ins>+  getHistory: function() {
+    return {done: copyHistoryArray(this.history.done),
+            undone: copyHistoryArray(this.history.undone)}
+  },
+  setHistory: function(histData) {
+    var hist = this.history = new History(this.history.maxGeneration)
+    hist.done = copyHistoryArray(histData.done.slice(0), null, true)
+    hist.undone = copyHistoryArray(histData.undone.slice(0), null, true)
+  },
+
+  setGutterMarker: docMethodOp(function(line, gutterID, value) {
+    return changeLine(this, line, &quot;gutter&quot;, function (line) {
+      var markers = line.gutterMarkers || (line.gutterMarkers = {})
+      markers[gutterID] = value
+      if (!value &amp;&amp; isEmpty(markers)) { line.gutterMarkers = null }
+      return true
+    })
+  }),
+
+  clearGutter: docMethodOp(function(gutterID) {
+    var this$1 = this;
+
+    var i = this.first
+    this.iter(function (line) {
+      if (line.gutterMarkers &amp;&amp; line.gutterMarkers[gutterID]) {
+        changeLine(this$1, line, &quot;gutter&quot;, function () {
+          line.gutterMarkers[gutterID] = null
+          if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null }
+          return true
+        })
</ins><span class="cx">       }
</span><del>-    }
</del><ins>+      ++i
+    })
+  }),
</ins><span class="cx"> 
</span><del>-    function done(e) {
-      cm.state.selectingText = false;
-      counter = Infinity;
-      e_preventDefault(e);
-      display.input.focus();
-      off(document, &quot;mousemove&quot;, move);
-      off(document, &quot;mouseup&quot;, up);
-      doc.history.lastSelOrigin = null;
</del><ins>+  lineInfo: function(line) {
+    var n
+    if (typeof line == &quot;number&quot;) {
+      if (!isLine(this, line)) { return null }
+      n = line
+      line = getLine(this, line)
+      if (!line) { return null }
+    } else {
+      n = lineNo(line)
+      if (n == null) { return null }
</ins><span class="cx">     }
</span><ins>+    return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
+            textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
+            widgets: line.widgets}
+  },
</ins><span class="cx"> 
</span><del>-    var move = operation(cm, function(e) {
-      if (!e_button(e)) done(e);
-      else extend(e);
-    });
-    var up = operation(cm, done);
-    cm.state.selectingText = up;
-    on(document, &quot;mousemove&quot;, move);
-    on(document, &quot;mouseup&quot;, up);
-  }
</del><ins>+  addLineClass: docMethodOp(function(handle, where, cls) {
+    return changeLine(this, handle, where == &quot;gutter&quot; ? &quot;gutter&quot; : &quot;class&quot;, function (line) {
+      var prop = where == &quot;text&quot; ? &quot;textClass&quot;
+               : where == &quot;background&quot; ? &quot;bgClass&quot;
+               : where == &quot;gutter&quot; ? &quot;gutterClass&quot; : &quot;wrapClass&quot;
+      if (!line[prop]) { line[prop] = cls }
+      else if (classTest(cls).test(line[prop])) { return false }
+      else { line[prop] += &quot; &quot; + cls }
+      return true
+    })
+  }),
+  removeLineClass: docMethodOp(function(handle, where, cls) {
+    return changeLine(this, handle, where == &quot;gutter&quot; ? &quot;gutter&quot; : &quot;class&quot;, function (line) {
+      var prop = where == &quot;text&quot; ? &quot;textClass&quot;
+               : where == &quot;background&quot; ? &quot;bgClass&quot;
+               : where == &quot;gutter&quot; ? &quot;gutterClass&quot; : &quot;wrapClass&quot;
+      var cur = line[prop]
+      if (!cur) { return false }
+      else if (cls == null) { line[prop] = null }
+      else {
+        var found = cur.match(classTest(cls))
+        if (!found) { return false }
+        var end = found.index + found[0].length
+        line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? &quot;&quot; : &quot; &quot;) + cur.slice(end) || null
+      }
+      return true
+    })
+  }),
</ins><span class="cx"> 
</span><del>-  // Determines whether an event happened in the gutter, and fires the
-  // handlers for the corresponding event.
-  function gutterEvent(cm, e, type, prevent, signalfn) {
-    try { var mX = e.clientX, mY = e.clientY; }
-    catch(e) { return false; }
-    if (mX &gt;= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
-    if (prevent) e_preventDefault(e);
</del><ins>+  addLineWidget: docMethodOp(function(handle, node, options) {
+    return addLineWidget(this, handle, node, options)
+  }),
+  removeLineWidget: function(widget) { widget.clear() },
</ins><span class="cx"> 
</span><del>-    var display = cm.display;
-    var lineBox = display.lineDiv.getBoundingClientRect();
</del><ins>+  markText: function(from, to, options) {
+    return markText(this, clipPos(this, from), clipPos(this, to), options, options &amp;&amp; options.type || &quot;range&quot;)
+  },
+  setBookmark: function(pos, options) {
+    var realOpts = {replacedWith: options &amp;&amp; (options.nodeType == null ? options.widget : options),
+                    insertLeft: options &amp;&amp; options.insertLeft,
+                    clearWhenEmpty: false, shared: options &amp;&amp; options.shared,
+                    handleMouseEvents: options &amp;&amp; options.handleMouseEvents}
+    pos = clipPos(this, pos)
+    return markText(this, pos, pos, realOpts, &quot;bookmark&quot;)
+  },
+  findMarksAt: function(pos) {
+    pos = clipPos(this, pos)
+    var markers = [], spans = getLine(this, pos.line).markedSpans
+    if (spans) { for (var i = 0; i &lt; spans.length; ++i) {
+      var span = spans[i]
+      if ((span.from == null || span.from &lt;= pos.ch) &amp;&amp;
+          (span.to == null || span.to &gt;= pos.ch))
+        { markers.push(span.marker.parent || span.marker) }
+    } }
+    return markers
+  },
+  findMarks: function(from, to, filter) {
+    from = clipPos(this, from); to = clipPos(this, to)
+    var found = [], lineNo = from.line
+    this.iter(from.line, to.line + 1, function (line) {
+      var spans = line.markedSpans
+      if (spans) { for (var i = 0; i &lt; spans.length; i++) {
+        var span = spans[i]
+        if (!(span.to != null &amp;&amp; lineNo == from.line &amp;&amp; from.ch &gt;= span.to ||
+              span.from == null &amp;&amp; lineNo != from.line ||
+              span.from != null &amp;&amp; lineNo == to.line &amp;&amp; span.from &gt;= to.ch) &amp;&amp;
+            (!filter || filter(span.marker)))
+          { found.push(span.marker.parent || span.marker) }
+      } }
+      ++lineNo
+    })
+    return found
+  },
+  getAllMarks: function() {
+    var markers = []
+    this.iter(function (line) {
+      var sps = line.markedSpans
+      if (sps) { for (var i = 0; i &lt; sps.length; ++i)
+        { if (sps[i].from != null) { markers.push(sps[i].marker) } } }
+    })
+    return markers
+  },
</ins><span class="cx"> 
</span><del>-    if (mY &gt; lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
-    mY -= lineBox.top - display.viewOffset;
</del><ins>+  posFromIndex: function(off) {
+    var ch, lineNo = this.first, sepSize = this.lineSeparator().length
+    this.iter(function (line) {
+      var sz = line.text.length + sepSize
+      if (sz &gt; off) { ch = off; return true }
+      off -= sz
+      ++lineNo
+    })
+    return clipPos(this, Pos(lineNo, ch))
+  },
+  indexFromPos: function (coords) {
+    coords = clipPos(this, coords)
+    var index = coords.ch
+    if (coords.line &lt; this.first || coords.ch &lt; 0) { return 0 }
+    var sepSize = this.lineSeparator().length
+    this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
+      index += line.text.length + sepSize
+    })
+    return index
+  },
</ins><span class="cx"> 
</span><del>-    for (var i = 0; i &lt; cm.options.gutters.length; ++i) {
-      var g = display.gutters.childNodes[i];
-      if (g &amp;&amp; g.getBoundingClientRect().right &gt;= mX) {
-        var line = lineAtHeight(cm.doc, mY);
-        var gutter = cm.options.gutters[i];
-        signalfn(cm, type, cm, line, gutter, e);
-        return e_defaultPrevented(e);
-      }
</del><ins>+  copy: function(copyHistory) {
+    var doc = new Doc(getLines(this, this.first, this.first + this.size),
+                      this.modeOption, this.first, this.lineSep)
+    doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft
+    doc.sel = this.sel
+    doc.extend = false
+    if (copyHistory) {
+      doc.history.undoDepth = this.history.undoDepth
+      doc.setHistory(this.getHistory())
</ins><span class="cx">     }
</span><del>-  }
</del><ins>+    return doc
+  },
</ins><span class="cx"> 
</span><del>-  function clickInGutter(cm, e) {
-    return gutterEvent(cm, e, &quot;gutterClick&quot;, true, signalLater);
-  }
</del><ins>+  linkedDoc: function(options) {
+    if (!options) { options = {} }
+    var from = this.first, to = this.first + this.size
+    if (options.from != null &amp;&amp; options.from &gt; from) { from = options.from }
+    if (options.to != null &amp;&amp; options.to &lt; to) { to = options.to }
+    var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep)
+    if (options.sharedHist) { copy.history = this.history
+    ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist})
+    copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]
+    copySharedMarkers(copy, findSharedMarkers(this))
+    return copy
+  },
+  unlinkDoc: function(other) {
+    var this$1 = this;
</ins><span class="cx"> 
</span><del>-  // Kludge to work around strange IE behavior where it'll sometimes
-  // re-fire a series of drag-related events right after the drop (#1551)
-  var lastDrop = 0;
</del><ins>+    if (other instanceof CodeMirror) { other = other.doc }
+    if (this.linked) { for (var i = 0; i &lt; this.linked.length; ++i) {
+      var link = this$1.linked[i]
+      if (link.doc != other) { continue }
+      this$1.linked.splice(i, 1)
+      other.unlinkDoc(this$1)
+      detachSharedMarkers(findSharedMarkers(this$1))
+      break
+    } }
+    // If the histories were shared, split them again
+    if (other.history == this.history) {
+      var splitIds = [other.id]
+      linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true)
+      other.history = new History(null)
+      other.history.done = copyHistoryArray(this.history.done, splitIds)
+      other.history.undone = copyHistoryArray(this.history.undone, splitIds)
+    }
+  },
+  iterLinkedDocs: function(f) {linkedDocs(this, f)},
</ins><span class="cx"> 
</span><del>-  function onDrop(e) {
-    var cm = this;
-    clearDragCursor(cm);
-    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
-      return;
-    e_preventDefault(e);
-    if (ie) lastDrop = +new Date;
-    var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
-    if (!pos || isReadOnly(cm)) return;
-    // Might be a file drop, in which case we simply extract the text
-    // and insert it.
-    if (files &amp;&amp; files.length &amp;&amp; window.FileReader &amp;&amp; window.File) {
-      var n = files.length, text = Array(n), read = 0;
-      var loadFile = function(file, i) {
-        var reader = new FileReader;
-        reader.onload = operation(cm, function() {
-          text[i] = reader.result;
-          if (++read == n) {
-            pos = clipPos(cm.doc, pos);
-            var change = {from: pos, to: pos,
-                          text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
-                          origin: &quot;paste&quot;};
-            makeChange(cm.doc, change);
-            setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
-          }
-        });
-        reader.readAsText(file);
-      };
-      for (var i = 0; i &lt; n; ++i) loadFile(files[i], i);
-    } else { // Normal drop
-      // Don't do a replace if the drop happened inside of the selected text.
-      if (cm.state.draggingText &amp;&amp; cm.doc.sel.contains(pos) &gt; -1) {
-        cm.state.draggingText(e);
-        // Ensure the editor is re-focused
-        setTimeout(function() {cm.display.input.focus();}, 20);
-        return;
-      }
-      try {
-        var text = e.dataTransfer.getData(&quot;Text&quot;);
-        if (text) {
-          if (cm.state.draggingText &amp;&amp; !(mac ? e.altKey : e.ctrlKey))
-            var selected = cm.listSelections();
-          setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
-          if (selected) for (var i = 0; i &lt; selected.length; ++i)
-            replaceRange(cm.doc, &quot;&quot;, selected[i].anchor, selected[i].head, &quot;drag&quot;);
-          cm.replaceSelection(text, &quot;around&quot;, &quot;paste&quot;);
-          cm.display.input.focus();
</del><ins>+  getMode: function() {return this.mode},
+  getEditor: function() {return this.cm},
+
+  splitLines: function(str) {
+    if (this.lineSep) { return str.split(this.lineSep) }
+    return splitLinesAuto(str)
+  },
+  lineSeparator: function() { return this.lineSep || &quot;\n&quot; }
+})
+
+// Public alias.
+Doc.prototype.eachLine = Doc.prototype.iter
+
+// Kludge to work around strange IE behavior where it'll sometimes
+// re-fire a series of drag-related events right after the drop (#1551)
+var lastDrop = 0
+
+function onDrop(e) {
+  var cm = this
+  clearDragCursor(cm)
+  if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
+    { return }
+  e_preventDefault(e)
+  if (ie) { lastDrop = +new Date }
+  var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files
+  if (!pos || cm.isReadOnly()) { return }
+  // Might be a file drop, in which case we simply extract the text
+  // and insert it.
+  if (files &amp;&amp; files.length &amp;&amp; window.FileReader &amp;&amp; window.File) {
+    var n = files.length, text = Array(n), read = 0
+    var loadFile = function (file, i) {
+      if (cm.options.allowDropFileTypes &amp;&amp;
+          indexOf(cm.options.allowDropFileTypes, file.type) == -1)
+        { return }
+
+      var reader = new FileReader
+      reader.onload = operation(cm, function () {
+        var content = reader.result
+        if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = &quot;&quot; }
+        text[i] = content
+        if (++read == n) {
+          pos = clipPos(cm.doc, pos)
+          var change = {from: pos, to: pos,
+                        text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
+                        origin: &quot;paste&quot;}
+          makeChange(cm.doc, change)
+          setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)))
</ins><span class="cx">         }
</span><ins>+      })
+      reader.readAsText(file)
+    }
+    for (var i = 0; i &lt; n; ++i) { loadFile(files[i], i) }
+  } else { // Normal drop
+    // Don't do a replace if the drop happened inside of the selected text.
+    if (cm.state.draggingText &amp;&amp; cm.doc.sel.contains(pos) &gt; -1) {
+      cm.state.draggingText(e)
+      // Ensure the editor is re-focused
+      setTimeout(function () { return cm.display.input.focus(); }, 20)
+      return
+    }
+    try {
+      var text$1 = e.dataTransfer.getData(&quot;Text&quot;)
+      if (text$1) {
+        var selected
+        if (cm.state.draggingText &amp;&amp; !cm.state.draggingText.copy)
+          { selected = cm.listSelections() }
+        setSelectionNoUndo(cm.doc, simpleSelection(pos, pos))
+        if (selected) { for (var i$1 = 0; i$1 &lt; selected.length; ++i$1)
+          { replaceRange(cm.doc, &quot;&quot;, selected[i$1].anchor, selected[i$1].head, &quot;drag&quot;) } }
+        cm.replaceSelection(text$1, &quot;around&quot;, &quot;paste&quot;)
+        cm.display.input.focus()
</ins><span class="cx">       }
</span><del>-      catch(e){}
</del><span class="cx">     }
</span><ins>+    catch(e){}
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  function onDragStart(cm, e) {
-    if (ie &amp;&amp; (!cm.state.draggingText || +new Date - lastDrop &lt; 100)) { e_stop(e); return; }
-    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
</del><ins>+function onDragStart(cm, e) {
+  if (ie &amp;&amp; (!cm.state.draggingText || +new Date - lastDrop &lt; 100)) { e_stop(e); return }
+  if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
</ins><span class="cx"> 
</span><del>-    e.dataTransfer.setData(&quot;Text&quot;, cm.getSelection());
</del><ins>+  e.dataTransfer.setData(&quot;Text&quot;, cm.getSelection())
+  e.dataTransfer.effectAllowed = &quot;copyMove&quot;
</ins><span class="cx"> 
</span><del>-    // Use dummy image instead of default browsers image.
-    // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
-    if (e.dataTransfer.setDragImage &amp;&amp; !safari) {
-      var img = elt(&quot;img&quot;, null, null, &quot;position: fixed; left: 0; top: 0;&quot;);
-      img.src = &quot;data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==&quot;;
-      if (presto) {
-        img.width = img.height = 1;
-        cm.display.wrapper.appendChild(img);
-        // Force a relayout, or Opera won't use our image for some obscure reason
-        img._top = img.offsetTop;
-      }
-      e.dataTransfer.setDragImage(img, 0, 0);
-      if (presto) img.parentNode.removeChild(img);
</del><ins>+  // Use dummy image instead of default browsers image.
+  // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
+  if (e.dataTransfer.setDragImage &amp;&amp; !safari) {
+    var img = elt(&quot;img&quot;, null, null, &quot;position: fixed; left: 0; top: 0;&quot;)
+    img.src = &quot;data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==&quot;
+    if (presto) {
+      img.width = img.height = 1
+      cm.display.wrapper.appendChild(img)
+      // Force a relayout, or Opera won't use our image for some obscure reason
+      img._top = img.offsetTop
</ins><span class="cx">     }
</span><ins>+    e.dataTransfer.setDragImage(img, 0, 0)
+    if (presto) { img.parentNode.removeChild(img) }
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  function onDragOver(cm, e) {
-    var pos = posFromMouse(cm, e);
-    if (!pos) return;
-    var frag = document.createDocumentFragment();
-    drawSelectionCursor(cm, pos, frag);
-    if (!cm.display.dragCursor) {
-      cm.display.dragCursor = elt(&quot;div&quot;, null, &quot;CodeMirror-cursors CodeMirror-dragcursors&quot;);
-      cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
-    }
-    removeChildrenAndAdd(cm.display.dragCursor, frag);
</del><ins>+function onDragOver(cm, e) {
+  var pos = posFromMouse(cm, e)
+  if (!pos) { return }
+  var frag = document.createDocumentFragment()
+  drawSelectionCursor(cm, pos, frag)
+  if (!cm.display.dragCursor) {
+    cm.display.dragCursor = elt(&quot;div&quot;, null, &quot;CodeMirror-cursors CodeMirror-dragcursors&quot;)
+    cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv)
</ins><span class="cx">   }
</span><ins>+  removeChildrenAndAdd(cm.display.dragCursor, frag)
+}
</ins><span class="cx"> 
</span><del>-  function clearDragCursor(cm) {
-    if (cm.display.dragCursor) {
-      cm.display.lineSpace.removeChild(cm.display.dragCursor);
-      cm.display.dragCursor = null;
-    }
</del><ins>+function clearDragCursor(cm) {
+  if (cm.display.dragCursor) {
+    cm.display.lineSpace.removeChild(cm.display.dragCursor)
+    cm.display.dragCursor = null
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // SCROLL EVENTS
</del><ins>+// These must be handled carefully, because naively registering a
+// handler for each editor will cause the editors to never be
+// garbage collected.
</ins><span class="cx"> 
</span><del>-  // Sync the scrollable area and scrollbars, ensure the viewport
-  // covers the visible area.
-  function setScrollTop(cm, val) {
-    if (Math.abs(cm.doc.scrollTop - val) &lt; 2) return;
-    cm.doc.scrollTop = val;
-    if (!gecko) updateDisplaySimple(cm, {top: val});
-    if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
-    cm.display.scrollbars.setScrollTop(val);
-    if (gecko) updateDisplaySimple(cm);
-    startWorker(cm, 100);
</del><ins>+function forEachCodeMirror(f) {
+  if (!document.body.getElementsByClassName) { return }
+  var byClass = document.body.getElementsByClassName(&quot;CodeMirror&quot;)
+  for (var i = 0; i &lt; byClass.length; i++) {
+    var cm = byClass[i].CodeMirror
+    if (cm) { f(cm) }
</ins><span class="cx">   }
</span><del>-  // Sync scroller and scrollbar, ensure the gutter elements are
-  // aligned.
-  function setScrollLeft(cm, val, isScroller) {
-    if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) &lt; 2) return;
-    val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
-    cm.doc.scrollLeft = val;
-    alignHorizontally(cm);
-    if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
-    cm.display.scrollbars.setScrollLeft(val);
-  }
</del><ins>+}
</ins><span class="cx"> 
</span><del>-  // Since the delta values reported on mouse wheel events are
-  // unstandardized between browsers and even browser versions, and
-  // generally horribly unpredictable, this code starts by measuring
-  // the scroll effect that the first few mouse wheel events have,
-  // and, from that, detects the way it can convert deltas to pixel
-  // offsets afterwards.
-  //
-  // The reason we want to know the amount a wheel event will scroll
-  // is that it gives us a chance to update the display before the
-  // actual scrolling happens, reducing flickering.
</del><ins>+var globalsRegistered = false
+function ensureGlobalHandlers() {
+  if (globalsRegistered) { return }
+  registerGlobalHandlers()
+  globalsRegistered = true
+}
+function registerGlobalHandlers() {
+  // When the window resizes, we need to refresh active editors.
+  var resizeTimer
+  on(window, &quot;resize&quot;, function () {
+    if (resizeTimer == null) { resizeTimer = setTimeout(function () {
+      resizeTimer = null
+      forEachCodeMirror(onResize)
+    }, 100) }
+  })
+  // When the window loses focus, we want to show the editor as blurred
+  on(window, &quot;blur&quot;, function () { return forEachCodeMirror(onBlur); })
+}
+// Called when the window resizes
+function onResize(cm) {
+  var d = cm.display
+  if (d.lastWrapHeight == d.wrapper.clientHeight &amp;&amp; d.lastWrapWidth == d.wrapper.clientWidth)
+    { return }
+  // Might be a text scaling operation, clear size caches.
+  d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
+  d.scrollbarsClipped = false
+  cm.setSize()
+}
</ins><span class="cx"> 
</span><del>-  var wheelSamples = 0, wheelPixelsPerUnit = null;
-  // Fill in a browser-detected starting value on browsers where we
-  // know one. These don't have to be accurate -- the result of them
-  // being wrong would just be a slight flicker on the first wheel
-  // scroll (if it is large enough).
-  if (ie) wheelPixelsPerUnit = -.53;
-  else if (gecko) wheelPixelsPerUnit = 15;
-  else if (chrome) wheelPixelsPerUnit = -.7;
-  else if (safari) wheelPixelsPerUnit = -1/3;
</del><ins>+var keyNames = {
+  3: &quot;Enter&quot;, 8: &quot;Backspace&quot;, 9: &quot;Tab&quot;, 13: &quot;Enter&quot;, 16: &quot;Shift&quot;, 17: &quot;Ctrl&quot;, 18: &quot;Alt&quot;,
+  19: &quot;Pause&quot;, 20: &quot;CapsLock&quot;, 27: &quot;Esc&quot;, 32: &quot;Space&quot;, 33: &quot;PageUp&quot;, 34: &quot;PageDown&quot;, 35: &quot;End&quot;,
+  36: &quot;Home&quot;, 37: &quot;Left&quot;, 38: &quot;Up&quot;, 39: &quot;Right&quot;, 40: &quot;Down&quot;, 44: &quot;PrintScrn&quot;, 45: &quot;Insert&quot;,
+  46: &quot;Delete&quot;, 59: &quot;;&quot;, 61: &quot;=&quot;, 91: &quot;Mod&quot;, 92: &quot;Mod&quot;, 93: &quot;Mod&quot;,
+  106: &quot;*&quot;, 107: &quot;=&quot;, 109: &quot;-&quot;, 110: &quot;.&quot;, 111: &quot;/&quot;, 127: &quot;Delete&quot;,
+  173: &quot;-&quot;, 186: &quot;;&quot;, 187: &quot;=&quot;, 188: &quot;,&quot;, 189: &quot;-&quot;, 190: &quot;.&quot;, 191: &quot;/&quot;, 192: &quot;`&quot;, 219: &quot;[&quot;, 220: &quot;\\&quot;,
+  221: &quot;]&quot;, 222: &quot;'&quot;, 63232: &quot;Up&quot;, 63233: &quot;Down&quot;, 63234: &quot;Left&quot;, 63235: &quot;Right&quot;, 63272: &quot;Delete&quot;,
+  63273: &quot;Home&quot;, 63275: &quot;End&quot;, 63276: &quot;PageUp&quot;, 63277: &quot;PageDown&quot;, 63302: &quot;Insert&quot;
+}
</ins><span class="cx"> 
</span><del>-  var wheelEventDelta = function(e) {
-    var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
-    if (dx == null &amp;&amp; e.detail &amp;&amp; e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
-    if (dy == null &amp;&amp; e.detail &amp;&amp; e.axis == e.VERTICAL_AXIS) dy = e.detail;
-    else if (dy == null) dy = e.wheelDelta;
-    return {x: dx, y: dy};
-  };
-  CodeMirror.wheelEventPixels = function(e) {
-    var delta = wheelEventDelta(e);
-    delta.x *= wheelPixelsPerUnit;
-    delta.y *= wheelPixelsPerUnit;
-    return delta;
-  };
</del><ins>+// Number keys
+for (var i = 0; i &lt; 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i) }
+// Alphabetic keys
+for (var i$1 = 65; i$1 &lt;= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1) }
+// Function keys
+for (var i$2 = 1; i$2 &lt;= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = &quot;F&quot; + i$2 }
</ins><span class="cx"> 
</span><del>-  function onScrollWheel(cm, e) {
-    var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
</del><ins>+var keyMap = {}
</ins><span class="cx"> 
</span><del>-    var display = cm.display, scroll = display.scroller;
-    // Quit if there's nothing to scroll here
-    if (!(dx &amp;&amp; scroll.scrollWidth &gt; scroll.clientWidth ||
-          dy &amp;&amp; scroll.scrollHeight &gt; scroll.clientHeight)) return;
</del><ins>+keyMap.basic = {
+  &quot;Left&quot;: &quot;goCharLeft&quot;, &quot;Right&quot;: &quot;goCharRight&quot;, &quot;Up&quot;: &quot;goLineUp&quot;, &quot;Down&quot;: &quot;goLineDown&quot;,
+  &quot;End&quot;: &quot;goLineEnd&quot;, &quot;Home&quot;: &quot;goLineStartSmart&quot;, &quot;PageUp&quot;: &quot;goPageUp&quot;, &quot;PageDown&quot;: &quot;goPageDown&quot;,
+  &quot;Delete&quot;: &quot;delCharAfter&quot;, &quot;Backspace&quot;: &quot;delCharBefore&quot;, &quot;Shift-Backspace&quot;: &quot;delCharBefore&quot;,
+  &quot;Tab&quot;: &quot;defaultTab&quot;, &quot;Shift-Tab&quot;: &quot;indentAuto&quot;,
+  &quot;Enter&quot;: &quot;newlineAndIndent&quot;, &quot;Insert&quot;: &quot;toggleOverwrite&quot;,
+  &quot;Esc&quot;: &quot;singleSelection&quot;
+}
+// Note that the save and find-related commands aren't defined by
+// default. User code or addons can define them. Unknown commands
+// are simply ignored.
+keyMap.pcDefault = {
+  &quot;Ctrl-A&quot;: &quot;selectAll&quot;, &quot;Ctrl-D&quot;: &quot;deleteLine&quot;, &quot;Ctrl-Z&quot;: &quot;undo&quot;, &quot;Shift-Ctrl-Z&quot;: &quot;redo&quot;, &quot;Ctrl-Y&quot;: &quot;redo&quot;,
+  &quot;Ctrl-Home&quot;: &quot;goDocStart&quot;, &quot;Ctrl-End&quot;: &quot;goDocEnd&quot;, &quot;Ctrl-Up&quot;: &quot;goLineUp&quot;, &quot;Ctrl-Down&quot;: &quot;goLineDown&quot;,
+  &quot;Ctrl-Left&quot;: &quot;goGroupLeft&quot;, &quot;Ctrl-Right&quot;: &quot;goGroupRight&quot;, &quot;Alt-Left&quot;: &quot;goLineStart&quot;, &quot;Alt-Right&quot;: &quot;goLineEnd&quot;,
+  &quot;Ctrl-Backspace&quot;: &quot;delGroupBefore&quot;, &quot;Ctrl-Delete&quot;: &quot;delGroupAfter&quot;, &quot;Ctrl-S&quot;: &quot;save&quot;, &quot;Ctrl-F&quot;: &quot;find&quot;,
+  &quot;Ctrl-G&quot;: &quot;findNext&quot;, &quot;Shift-Ctrl-G&quot;: &quot;findPrev&quot;, &quot;Shift-Ctrl-F&quot;: &quot;replace&quot;, &quot;Shift-Ctrl-R&quot;: &quot;replaceAll&quot;,
+  &quot;Ctrl-[&quot;: &quot;indentLess&quot;, &quot;Ctrl-]&quot;: &quot;indentMore&quot;,
+  &quot;Ctrl-U&quot;: &quot;undoSelection&quot;, &quot;Shift-Ctrl-U&quot;: &quot;redoSelection&quot;, &quot;Alt-U&quot;: &quot;redoSelection&quot;,
+  fallthrough: &quot;basic&quot;
+}
+// Very basic readline/emacs-style bindings, which are standard on Mac.
+keyMap.emacsy = {
+  &quot;Ctrl-F&quot;: &quot;goCharRight&quot;, &quot;Ctrl-B&quot;: &quot;goCharLeft&quot;, &quot;Ctrl-P&quot;: &quot;goLineUp&quot;, &quot;Ctrl-N&quot;: &quot;goLineDown&quot;,
+  &quot;Alt-F&quot;: &quot;goWordRight&quot;, &quot;Alt-B&quot;: &quot;goWordLeft&quot;, &quot;Ctrl-A&quot;: &quot;goLineStart&quot;, &quot;Ctrl-E&quot;: &quot;goLineEnd&quot;,
+  &quot;Ctrl-V&quot;: &quot;goPageDown&quot;, &quot;Shift-Ctrl-V&quot;: &quot;goPageUp&quot;, &quot;Ctrl-D&quot;: &quot;delCharAfter&quot;, &quot;Ctrl-H&quot;: &quot;delCharBefore&quot;,
+  &quot;Alt-D&quot;: &quot;delWordAfter&quot;, &quot;Alt-Backspace&quot;: &quot;delWordBefore&quot;, &quot;Ctrl-K&quot;: &quot;killLine&quot;, &quot;Ctrl-T&quot;: &quot;transposeChars&quot;,
+  &quot;Ctrl-O&quot;: &quot;openLine&quot;
+}
+keyMap.macDefault = {
+  &quot;Cmd-A&quot;: &quot;selectAll&quot;, &quot;Cmd-D&quot;: &quot;deleteLine&quot;, &quot;Cmd-Z&quot;: &quot;undo&quot;, &quot;Shift-Cmd-Z&quot;: &quot;redo&quot;, &quot;Cmd-Y&quot;: &quot;redo&quot;,
+  &quot;Cmd-Home&quot;: &quot;goDocStart&quot;, &quot;Cmd-Up&quot;: &quot;goDocStart&quot;, &quot;Cmd-End&quot;: &quot;goDocEnd&quot;, &quot;Cmd-Down&quot;: &quot;goDocEnd&quot;, &quot;Alt-Left&quot;: &quot;goGroupLeft&quot;,
+  &quot;Alt-Right&quot;: &quot;goGroupRight&quot;, &quot;Cmd-Left&quot;: &quot;goLineLeft&quot;, &quot;Cmd-Right&quot;: &quot;goLineRight&quot;, &quot;Alt-Backspace&quot;: &quot;delGroupBefore&quot;,
+  &quot;Ctrl-Alt-Backspace&quot;: &quot;delGroupAfter&quot;, &quot;Alt-Delete&quot;: &quot;delGroupAfter&quot;, &quot;Cmd-S&quot;: &quot;save&quot;, &quot;Cmd-F&quot;: &quot;find&quot;,
+  &quot;Cmd-G&quot;: &quot;findNext&quot;, &quot;Shift-Cmd-G&quot;: &quot;findPrev&quot;, &quot;Cmd-Alt-F&quot;: &quot;replace&quot;, &quot;Shift-Cmd-Alt-F&quot;: &quot;replaceAll&quot;,
+  &quot;Cmd-[&quot;: &quot;indentLess&quot;, &quot;Cmd-]&quot;: &quot;indentMore&quot;, &quot;Cmd-Backspace&quot;: &quot;delWrappedLineLeft&quot;, &quot;Cmd-Delete&quot;: &quot;delWrappedLineRight&quot;,
+  &quot;Cmd-U&quot;: &quot;undoSelection&quot;, &quot;Shift-Cmd-U&quot;: &quot;redoSelection&quot;, &quot;Ctrl-Up&quot;: &quot;goDocStart&quot;, &quot;Ctrl-Down&quot;: &quot;goDocEnd&quot;,
+  fallthrough: [&quot;basic&quot;, &quot;emacsy&quot;]
+}
+keyMap[&quot;default&quot;] = mac ? keyMap.macDefault : keyMap.pcDefault
</ins><span class="cx"> 
</span><del>-    // Webkit browsers on OS X abort momentum scrolls when the target
-    // of the scroll event is removed from the scrollable element.
-    // This hack (see related code in patchDisplay) makes sure the
-    // element is kept around.
-    if (dy &amp;&amp; mac &amp;&amp; webkit) {
-      outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
-        for (var i = 0; i &lt; view.length; i++) {
-          if (view[i].node == cur) {
-            cm.display.currentWheelTarget = cur;
-            break outer;
-          }
-        }
-      }
-    }
</del><ins>+// KEYMAP DISPATCH
</ins><span class="cx"> 
</span><del>-    // On some browsers, horizontal scrolling will cause redraws to
-    // happen before the gutter has been realigned, causing it to
-    // wriggle around in a most unseemly way. When we have an
-    // estimated pixels/delta value, we just handle horizontal
-    // scrolling entirely here. It'll be slightly off from native, but
-    // better than glitching out.
-    if (dx &amp;&amp; !gecko &amp;&amp; !presto &amp;&amp; wheelPixelsPerUnit != null) {
-      if (dy)
-        setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
-      setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
-      e_preventDefault(e);
-      display.wheelStartX = null; // Abort measurement, if in progress
-      return;
-    }
</del><ins>+function normalizeKeyName(name) {
+  var parts = name.split(/-(?!$)/)
+  name = parts[parts.length - 1]
+  var alt, ctrl, shift, cmd
+  for (var i = 0; i &lt; parts.length - 1; i++) {
+    var mod = parts[i]
+    if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true }
+    else if (/^a(lt)?$/i.test(mod)) { alt = true }
+    else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true }
+    else if (/^s(hift)?$/i.test(mod)) { shift = true }
+    else { throw new Error(&quot;Unrecognized modifier name: &quot; + mod) }
+  }
+  if (alt) { name = &quot;Alt-&quot; + name }
+  if (ctrl) { name = &quot;Ctrl-&quot; + name }
+  if (cmd) { name = &quot;Cmd-&quot; + name }
+  if (shift) { name = &quot;Shift-&quot; + name }
+  return name
+}
</ins><span class="cx"> 
</span><del>-    // 'Project' the visible viewport to cover the area that is being
-    // scrolled into view (if we know enough to estimate it).
-    if (dy &amp;&amp; wheelPixelsPerUnit != null) {
-      var pixels = dy * wheelPixelsPerUnit;
-      var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
-      if (pixels &lt; 0) top = Math.max(0, top + pixels - 50);
-      else bot = Math.min(cm.doc.height, bot + pixels + 50);
-      updateDisplaySimple(cm, {top: top, bottom: bot});
-    }
</del><ins>+// This is a kludge to keep keymaps mostly working as raw objects
+// (backwards compatibility) while at the same time support features
+// like normalization and multi-stroke key bindings. It compiles a
+// new normalized keymap, and then updates the old object to reflect
+// this.
+function normalizeKeyMap(keymap) {
+  var copy = {}
+  for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
+    var value = keymap[keyname]
+    if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
+    if (value == &quot;...&quot;) { delete keymap[keyname]; continue }
</ins><span class="cx"> 
</span><del>-    if (wheelSamples &lt; 20) {
-      if (display.wheelStartX == null) {
-        display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
-        display.wheelDX = dx; display.wheelDY = dy;
-        setTimeout(function() {
-          if (display.wheelStartX == null) return;
-          var movedX = scroll.scrollLeft - display.wheelStartX;
-          var movedY = scroll.scrollTop - display.wheelStartY;
-          var sample = (movedY &amp;&amp; display.wheelDY &amp;&amp; movedY / display.wheelDY) ||
-            (movedX &amp;&amp; display.wheelDX &amp;&amp; movedX / display.wheelDX);
-          display.wheelStartX = display.wheelStartY = null;
-          if (!sample) return;
-          wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
-          ++wheelSamples;
-        }, 200);
</del><ins>+    var keys = map(keyname.split(&quot; &quot;), normalizeKeyName)
+    for (var i = 0; i &lt; keys.length; i++) {
+      var val = (void 0), name = (void 0)
+      if (i == keys.length - 1) {
+        name = keys.join(&quot; &quot;)
+        val = value
</ins><span class="cx">       } else {
</span><del>-        display.wheelDX += dx; display.wheelDY += dy;
</del><ins>+        name = keys.slice(0, i + 1).join(&quot; &quot;)
+        val = &quot;...&quot;
</ins><span class="cx">       }
</span><ins>+      var prev = copy[name]
+      if (!prev) { copy[name] = val }
+      else if (prev != val) { throw new Error(&quot;Inconsistent bindings for &quot; + name) }
</ins><span class="cx">     }
</span><del>-  }
</del><ins>+    delete keymap[keyname]
+  } }
+  for (var prop in copy) { keymap[prop] = copy[prop] }
+  return keymap
+}
</ins><span class="cx"> 
</span><del>-  // KEY EVENTS
</del><ins>+function lookupKey(key, map, handle, context) {
+  map = getKeyMap(map)
+  var found = map.call ? map.call(key, context) : map[key]
+  if (found === false) { return &quot;nothing&quot; }
+  if (found === &quot;...&quot;) { return &quot;multi&quot; }
+  if (found != null &amp;&amp; handle(found)) { return &quot;handled&quot; }
</ins><span class="cx"> 
</span><del>-  // Run a handler that was bound to a key.
-  function doHandleBinding(cm, bound, dropShift) {
-    if (typeof bound == &quot;string&quot;) {
-      bound = commands[bound];
-      if (!bound) return false;
</del><ins>+  if (map.fallthrough) {
+    if (Object.prototype.toString.call(map.fallthrough) != &quot;[object Array]&quot;)
+      { return lookupKey(key, map.fallthrough, handle, context) }
+    for (var i = 0; i &lt; map.fallthrough.length; i++) {
+      var result = lookupKey(key, map.fallthrough[i], handle, context)
+      if (result) { return result }
</ins><span class="cx">     }
</span><del>-    // Ensure previous input has been read, so that the handler sees a
-    // consistent view of the document
-    cm.display.input.ensurePolled();
-    var prevShift = cm.display.shift, done = false;
-    try {
-      if (isReadOnly(cm)) cm.state.suppressEdits = true;
-      if (dropShift) cm.display.shift = false;
-      done = bound(cm) != Pass;
-    } finally {
-      cm.display.shift = prevShift;
-      cm.state.suppressEdits = false;
-    }
-    return done;
</del><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  function lookupKeyForEditor(cm, name, handle) {
-    for (var i = 0; i &lt; cm.state.keyMaps.length; i++) {
-      var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
-      if (result) return result;
</del><ins>+// Modifier key presses don't count as 'real' key presses for the
+// purpose of keymap fallthrough.
+function isModifierKey(value) {
+  var name = typeof value == &quot;string&quot; ? value : keyNames[value.keyCode]
+  return name == &quot;Ctrl&quot; || name == &quot;Alt&quot; || name == &quot;Shift&quot; || name == &quot;Mod&quot;
+}
+
+// Look up the name of a key as indicated by an event object.
+function keyName(event, noShift) {
+  if (presto &amp;&amp; event.keyCode == 34 &amp;&amp; event[&quot;char&quot;]) { return false }
+  var base = keyNames[event.keyCode], name = base
+  if (name == null || event.altGraphKey) { return false }
+  if (event.altKey &amp;&amp; base != &quot;Alt&quot;) { name = &quot;Alt-&quot; + name }
+  if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) &amp;&amp; base != &quot;Ctrl&quot;) { name = &quot;Ctrl-&quot; + name }
+  if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) &amp;&amp; base != &quot;Cmd&quot;) { name = &quot;Cmd-&quot; + name }
+  if (!noShift &amp;&amp; event.shiftKey &amp;&amp; base != &quot;Shift&quot;) { name = &quot;Shift-&quot; + name }
+  return name
+}
+
+function getKeyMap(val) {
+  return typeof val == &quot;string&quot; ? keyMap[val] : val
+}
+
+// Helper for deleting text near the selection(s), used to implement
+// backspace, delete, and similar functionality.
+function deleteNearSelection(cm, compute) {
+  var ranges = cm.doc.sel.ranges, kill = []
+  // Build up a set of ranges to kill first, merging overlapping
+  // ranges.
+  for (var i = 0; i &lt; ranges.length; i++) {
+    var toKill = compute(ranges[i])
+    while (kill.length &amp;&amp; cmp(toKill.from, lst(kill).to) &lt;= 0) {
+      var replaced = kill.pop()
+      if (cmp(replaced.from, toKill.from) &lt; 0) {
+        toKill.from = replaced.from
+        break
+      }
</ins><span class="cx">     }
</span><del>-    return (cm.options.extraKeys &amp;&amp; lookupKey(name, cm.options.extraKeys, handle, cm))
-      || lookupKey(name, cm.options.keyMap, handle, cm);
</del><ins>+    kill.push(toKill)
</ins><span class="cx">   }
</span><ins>+  // Next, remove those actual ranges.
+  runInOp(cm, function () {
+    for (var i = kill.length - 1; i &gt;= 0; i--)
+      { replaceRange(cm.doc, &quot;&quot;, kill[i].from, kill[i].to, &quot;+delete&quot;) }
+    ensureCursorVisible(cm)
+  })
+}
</ins><span class="cx"> 
</span><del>-  var stopSeq = new Delayed;
-  function dispatchKey(cm, name, e, handle) {
-    var seq = cm.state.keySeq;
-    if (seq) {
-      if (isModifierKey(name)) return &quot;handled&quot;;
-      stopSeq.set(50, function() {
-        if (cm.state.keySeq == seq) {
-          cm.state.keySeq = null;
-          cm.display.input.reset();
</del><ins>+// Commands are parameter-less actions that can be performed on an
+// editor, mostly used for keybindings.
+var commands = {
+  selectAll: selectAll,
+  singleSelection: function (cm) { return cm.setSelection(cm.getCursor(&quot;anchor&quot;), cm.getCursor(&quot;head&quot;), sel_dontScroll); },
+  killLine: function (cm) { return deleteNearSelection(cm, function (range) {
+    if (range.empty()) {
+      var len = getLine(cm.doc, range.head.line).text.length
+      if (range.head.ch == len &amp;&amp; range.head.line &lt; cm.lastLine())
+        { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
+      else
+        { return {from: range.head, to: Pos(range.head.line, len)} }
+    } else {
+      return {from: range.from(), to: range.to()}
+    }
+  }); },
+  deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
+    from: Pos(range.from().line, 0),
+    to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
+  }); }); },
+  delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
+    from: Pos(range.from().line, 0), to: range.from()
+  }); }); },
+  delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
+    var top = cm.charCoords(range.head, &quot;div&quot;).top + 5
+    var leftPos = cm.coordsChar({left: 0, top: top}, &quot;div&quot;)
+    return {from: leftPos, to: range.from()}
+  }); },
+  delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
+    var top = cm.charCoords(range.head, &quot;div&quot;).top + 5
+    var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, &quot;div&quot;)
+    return {from: range.from(), to: rightPos }
+  }); },
+  undo: function (cm) { return cm.undo(); },
+  redo: function (cm) { return cm.redo(); },
+  undoSelection: function (cm) { return cm.undoSelection(); },
+  redoSelection: function (cm) { return cm.redoSelection(); },
+  goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
+  goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
+  goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
+    {origin: &quot;+move&quot;, bias: 1}
+  ); },
+  goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
+    {origin: &quot;+move&quot;, bias: 1}
+  ); },
+  goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
+    {origin: &quot;+move&quot;, bias: -1}
+  ); },
+  goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
+    var top = cm.charCoords(range.head, &quot;div&quot;).top + 5
+    return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, &quot;div&quot;)
+  }, sel_move); },
+  goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
+    var top = cm.charCoords(range.head, &quot;div&quot;).top + 5
+    return cm.coordsChar({left: 0, top: top}, &quot;div&quot;)
+  }, sel_move); },
+  goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
+    var top = cm.charCoords(range.head, &quot;div&quot;).top + 5
+    var pos = cm.coordsChar({left: 0, top: top}, &quot;div&quot;)
+    if (pos.ch &lt; cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
+    return pos
+  }, sel_move); },
+  goLineUp: function (cm) { return cm.moveV(-1, &quot;line&quot;); },
+  goLineDown: function (cm) { return cm.moveV(1, &quot;line&quot;); },
+  goPageUp: function (cm) { return cm.moveV(-1, &quot;page&quot;); },
+  goPageDown: function (cm) { return cm.moveV(1, &quot;page&quot;); },
+  goCharLeft: function (cm) { return cm.moveH(-1, &quot;char&quot;); },
+  goCharRight: function (cm) { return cm.moveH(1, &quot;char&quot;); },
+  goColumnLeft: function (cm) { return cm.moveH(-1, &quot;column&quot;); },
+  goColumnRight: function (cm) { return cm.moveH(1, &quot;column&quot;); },
+  goWordLeft: function (cm) { return cm.moveH(-1, &quot;word&quot;); },
+  goGroupRight: function (cm) { return cm.moveH(1, &quot;group&quot;); },
+  goGroupLeft: function (cm) { return cm.moveH(-1, &quot;group&quot;); },
+  goWordRight: function (cm) { return cm.moveH(1, &quot;word&quot;); },
+  delCharBefore: function (cm) { return cm.deleteH(-1, &quot;char&quot;); },
+  delCharAfter: function (cm) { return cm.deleteH(1, &quot;char&quot;); },
+  delWordBefore: function (cm) { return cm.deleteH(-1, &quot;word&quot;); },
+  delWordAfter: function (cm) { return cm.deleteH(1, &quot;word&quot;); },
+  delGroupBefore: function (cm) { return cm.deleteH(-1, &quot;group&quot;); },
+  delGroupAfter: function (cm) { return cm.deleteH(1, &quot;group&quot;); },
+  indentAuto: function (cm) { return cm.indentSelection(&quot;smart&quot;); },
+  indentMore: function (cm) { return cm.indentSelection(&quot;add&quot;); },
+  indentLess: function (cm) { return cm.indentSelection(&quot;subtract&quot;); },
+  insertTab: function (cm) { return cm.replaceSelection(&quot;\t&quot;); },
+  insertSoftTab: function (cm) {
+    var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize
+    for (var i = 0; i &lt; ranges.length; i++) {
+      var pos = ranges[i].from()
+      var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize)
+      spaces.push(spaceStr(tabSize - col % tabSize))
+    }
+    cm.replaceSelections(spaces)
+  },
+  defaultTab: function (cm) {
+    if (cm.somethingSelected()) { cm.indentSelection(&quot;add&quot;) }
+    else { cm.execCommand(&quot;insertTab&quot;) }
+  },
+  // Swap the two chars left and right of each selection's head.
+  // Move cursor behind the two swapped characters afterwards.
+  //
+  // Doesn't consider line feeds a character.
+  // Doesn't scan more than one line above to find a character.
+  // Doesn't do anything on an empty line.
+  // Doesn't do anything with non-empty selections.
+  transposeChars: function (cm) { return runInOp(cm, function () {
+    var ranges = cm.listSelections(), newSel = []
+    for (var i = 0; i &lt; ranges.length; i++) {
+      if (!ranges[i].empty()) { continue }
+      var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text
+      if (line) {
+        if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1) }
+        if (cur.ch &gt; 0) {
+          cur = new Pos(cur.line, cur.ch + 1)
+          cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
+                          Pos(cur.line, cur.ch - 2), cur, &quot;+transpose&quot;)
+        } else if (cur.line &gt; cm.doc.first) {
+          var prev = getLine(cm.doc, cur.line - 1).text
+          if (prev) {
+            cur = new Pos(cur.line, 1)
+            cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
+                            prev.charAt(prev.length - 1),
+                            Pos(cur.line - 1, prev.length - 1), cur, &quot;+transpose&quot;)
+          }
</ins><span class="cx">         }
</span><del>-      });
-      name = seq + &quot; &quot; + name;
</del><ins>+      }
+      newSel.push(new Range(cur, cur))
</ins><span class="cx">     }
</span><del>-    var result = lookupKeyForEditor(cm, name, handle);
</del><ins>+    cm.setSelections(newSel)
+  }); },
+  newlineAndIndent: function (cm) { return runInOp(cm, function () {
+    var sels = cm.listSelections()
+    for (var i = sels.length - 1; i &gt;= 0; i--)
+      { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, &quot;+input&quot;) }
+    sels = cm.listSelections()
+    for (var i$1 = 0; i$1 &lt; sels.length; i$1++)
+      { cm.indentLine(sels[i$1].from().line, null, true) }
+    ensureCursorVisible(cm)
+  }); },
+  openLine: function (cm) { return cm.replaceSelection(&quot;\n&quot;, &quot;start&quot;); },
+  toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
+}
</ins><span class="cx"> 
</span><del>-    if (result == &quot;multi&quot;)
-      cm.state.keySeq = name;
-    if (result == &quot;handled&quot;)
-      signalLater(cm, &quot;keyHandled&quot;, cm, name, e);
</del><span class="cx"> 
</span><del>-    if (result == &quot;handled&quot; || result == &quot;multi&quot;) {
-      e_preventDefault(e);
-      restartBlink(cm);
-    }
-
-    if (seq &amp;&amp; !result &amp;&amp; /\'$/.test(name)) {
-      e_preventDefault(e);
-      return true;
-    }
-    return !!result;
</del><ins>+function lineStart(cm, lineN) {
+  var line = getLine(cm.doc, lineN)
+  var visual = visualLine(line)
+  if (visual != line) { lineN = lineNo(visual) }
+  var order = getOrder(visual)
+  var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual)
+  return Pos(lineN, ch)
+}
+function lineEnd(cm, lineN) {
+  var merged, line = getLine(cm.doc, lineN)
+  while (merged = collapsedSpanAtEnd(line)) {
+    line = merged.find(1, true).line
+    lineN = null
</ins><span class="cx">   }
</span><ins>+  var order = getOrder(line)
+  var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line)
+  return Pos(lineN == null ? lineNo(line) : lineN, ch)
+}
+function lineStartSmart(cm, pos) {
+  var start = lineStart(cm, pos.line)
+  var line = getLine(cm.doc, start.line)
+  var order = getOrder(line)
+  if (!order || order[0].level == 0) {
+    var firstNonWS = Math.max(0, line.text.search(/\S/))
+    var inWS = pos.line == start.line &amp;&amp; pos.ch &lt;= firstNonWS &amp;&amp; pos.ch
+    return Pos(start.line, inWS ? 0 : firstNonWS)
+  }
+  return start
+}
</ins><span class="cx"> 
</span><del>-  // Handle a key from the keydown event.
-  function handleKeyBinding(cm, e) {
-    var name = keyName(e, true);
-    if (!name) return false;
-
-    if (e.shiftKey &amp;&amp; !cm.state.keySeq) {
-      // First try to resolve full name (including 'Shift-'). Failing
-      // that, see if there is a cursor-motion command (starting with
-      // 'go') bound to the keyname without 'Shift-'.
-      return dispatchKey(cm, &quot;Shift-&quot; + name, e, function(b) {return doHandleBinding(cm, b, true);})
-          || dispatchKey(cm, name, e, function(b) {
-               if (typeof b == &quot;string&quot; ? /^go[A-Z]/.test(b) : b.motion)
-                 return doHandleBinding(cm, b);
-             });
-    } else {
-      return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
-    }
</del><ins>+// Run a handler that was bound to a key.
+function doHandleBinding(cm, bound, dropShift) {
+  if (typeof bound == &quot;string&quot;) {
+    bound = commands[bound]
+    if (!bound) { return false }
</ins><span class="cx">   }
</span><ins>+  // Ensure previous input has been read, so that the handler sees a
+  // consistent view of the document
+  cm.display.input.ensurePolled()
+  var prevShift = cm.display.shift, done = false
+  try {
+    if (cm.isReadOnly()) { cm.state.suppressEdits = true }
+    if (dropShift) { cm.display.shift = false }
+    done = bound(cm) != Pass
+  } finally {
+    cm.display.shift = prevShift
+    cm.state.suppressEdits = false
+  }
+  return done
+}
</ins><span class="cx"> 
</span><del>-  // Handle a key from the keypress event
-  function handleCharBinding(cm, e, ch) {
-    return dispatchKey(cm, &quot;'&quot; + ch + &quot;'&quot;, e,
-                       function(b) { return doHandleBinding(cm, b, true); });
</del><ins>+function lookupKeyForEditor(cm, name, handle) {
+  for (var i = 0; i &lt; cm.state.keyMaps.length; i++) {
+    var result = lookupKey(name, cm.state.keyMaps[i], handle, cm)
+    if (result) { return result }
</ins><span class="cx">   }
</span><ins>+  return (cm.options.extraKeys &amp;&amp; lookupKey(name, cm.options.extraKeys, handle, cm))
+    || lookupKey(name, cm.options.keyMap, handle, cm)
+}
</ins><span class="cx"> 
</span><del>-  var lastStoppedKey = null;
-  function onKeyDown(e) {
-    var cm = this;
-    cm.curOp.focus = activeElt();
-    if (signalDOMEvent(cm, e)) return;
-    // IE does strange things with escape.
-    if (ie &amp;&amp; ie_version &lt; 11 &amp;&amp; e.keyCode == 27) e.returnValue = false;
-    var code = e.keyCode;
-    cm.display.shift = code == 16 || e.shiftKey;
-    var handled = handleKeyBinding(cm, e);
-    if (presto) {
-      lastStoppedKey = handled ? code : null;
-      // Opera has no cut event... we try to at least catch the key combo
-      if (!handled &amp;&amp; code == 88 &amp;&amp; !hasCopyEvent &amp;&amp; (mac ? e.metaKey : e.ctrlKey))
-        cm.replaceSelection(&quot;&quot;, null, &quot;cut&quot;);
-    }
-
-    // Turn mouse into crosshair when Alt is held on Mac.
-    if (code == 18 &amp;&amp; !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
-      showCrossHair(cm);
</del><ins>+var stopSeq = new Delayed
+function dispatchKey(cm, name, e, handle) {
+  var seq = cm.state.keySeq
+  if (seq) {
+    if (isModifierKey(name)) { return &quot;handled&quot; }
+    stopSeq.set(50, function () {
+      if (cm.state.keySeq == seq) {
+        cm.state.keySeq = null
+        cm.display.input.reset()
+      }
+    })
+    name = seq + &quot; &quot; + name
</ins><span class="cx">   }
</span><ins>+  var result = lookupKeyForEditor(cm, name, handle)
</ins><span class="cx"> 
</span><del>-  function showCrossHair(cm) {
-    var lineDiv = cm.display.lineDiv;
-    addClass(lineDiv, &quot;CodeMirror-crosshair&quot;);
</del><ins>+  if (result == &quot;multi&quot;)
+    { cm.state.keySeq = name }
+  if (result == &quot;handled&quot;)
+    { signalLater(cm, &quot;keyHandled&quot;, cm, name, e) }
</ins><span class="cx"> 
</span><del>-    function up(e) {
-      if (e.keyCode == 18 || !e.altKey) {
-        rmClass(lineDiv, &quot;CodeMirror-crosshair&quot;);
-        off(document, &quot;keyup&quot;, up);
-        off(document, &quot;mouseover&quot;, up);
-      }
-    }
-    on(document, &quot;keyup&quot;, up);
-    on(document, &quot;mouseover&quot;, up);
</del><ins>+  if (result == &quot;handled&quot; || result == &quot;multi&quot;) {
+    e_preventDefault(e)
+    restartBlink(cm)
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  function onKeyUp(e) {
-    if (e.keyCode == 16) this.doc.sel.shift = false;
-    signalDOMEvent(this, e);
</del><ins>+  if (seq &amp;&amp; !result &amp;&amp; /\'$/.test(name)) {
+    e_preventDefault(e)
+    return true
</ins><span class="cx">   }
</span><ins>+  return !!result
+}
</ins><span class="cx"> 
</span><del>-  function onKeyPress(e) {
-    var cm = this;
-    if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey &amp;&amp; !e.altKey || mac &amp;&amp; e.metaKey) return;
-    var keyCode = e.keyCode, charCode = e.charCode;
-    if (presto &amp;&amp; keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
-    if ((presto &amp;&amp; (!e.which || e.which &lt; 10)) &amp;&amp; handleKeyBinding(cm, e)) return;
-    var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
-    if (handleCharBinding(cm, e, ch)) return;
-    cm.display.input.onKeyPress(e);
</del><ins>+// Handle a key from the keydown event.
+function handleKeyBinding(cm, e) {
+  var name = keyName(e, true)
+  if (!name) { return false }
+
+  if (e.shiftKey &amp;&amp; !cm.state.keySeq) {
+    // First try to resolve full name (including 'Shift-'). Failing
+    // that, see if there is a cursor-motion command (starting with
+    // 'go') bound to the keyname without 'Shift-'.
+    return dispatchKey(cm, &quot;Shift-&quot; + name, e, function (b) { return doHandleBinding(cm, b, true); })
+        || dispatchKey(cm, name, e, function (b) {
+             if (typeof b == &quot;string&quot; ? /^go[A-Z]/.test(b) : b.motion)
+               { return doHandleBinding(cm, b) }
+           })
+  } else {
+    return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // FOCUS/BLUR EVENTS
</del><ins>+// Handle a key from the keypress event
+function handleCharBinding(cm, e, ch) {
+  return dispatchKey(cm, &quot;'&quot; + ch + &quot;'&quot;, e, function (b) { return doHandleBinding(cm, b, true); })
+}
</ins><span class="cx"> 
</span><del>-  function delayBlurEvent(cm) {
-    cm.state.delayingBlurEvent = true;
-    setTimeout(function() {
-      if (cm.state.delayingBlurEvent) {
-        cm.state.delayingBlurEvent = false;
-        onBlur(cm);
-      }
-    }, 100);
</del><ins>+var lastStoppedKey = null
+function onKeyDown(e) {
+  var cm = this
+  cm.curOp.focus = activeElt()
+  if (signalDOMEvent(cm, e)) { return }
+  // IE does strange things with escape.
+  if (ie &amp;&amp; ie_version &lt; 11 &amp;&amp; e.keyCode == 27) { e.returnValue = false }
+  var code = e.keyCode
+  cm.display.shift = code == 16 || e.shiftKey
+  var handled = handleKeyBinding(cm, e)
+  if (presto) {
+    lastStoppedKey = handled ? code : null
+    // Opera has no cut event... we try to at least catch the key combo
+    if (!handled &amp;&amp; code == 88 &amp;&amp; !hasCopyEvent &amp;&amp; (mac ? e.metaKey : e.ctrlKey))
+      { cm.replaceSelection(&quot;&quot;, null, &quot;cut&quot;) }
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  function onFocus(cm) {
-    if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
</del><ins>+  // Turn mouse into crosshair when Alt is held on Mac.
+  if (code == 18 &amp;&amp; !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
+    { showCrossHair(cm) }
+}
</ins><span class="cx"> 
</span><del>-    if (cm.options.readOnly == &quot;nocursor&quot;) return;
-    if (!cm.state.focused) {
-      signal(cm, &quot;focus&quot;, cm);
-      cm.state.focused = true;
-      addClass(cm.display.wrapper, &quot;CodeMirror-focused&quot;);
-      // 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 &amp;&amp; cm.display.selForContextMenu != cm.doc.sel) {
-        cm.display.input.reset();
-        if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
-      }
-      cm.display.input.receivedFocus();
</del><ins>+function showCrossHair(cm) {
+  var lineDiv = cm.display.lineDiv
+  addClass(lineDiv, &quot;CodeMirror-crosshair&quot;)
+
+  function up(e) {
+    if (e.keyCode == 18 || !e.altKey) {
+      rmClass(lineDiv, &quot;CodeMirror-crosshair&quot;)
+      off(document, &quot;keyup&quot;, up)
+      off(document, &quot;mouseover&quot;, up)
</ins><span class="cx">     }
</span><del>-    restartBlink(cm);
</del><span class="cx">   }
</span><del>-  function onBlur(cm) {
-    if (cm.state.delayingBlurEvent) return;
</del><ins>+  on(document, &quot;keyup&quot;, up)
+  on(document, &quot;mouseover&quot;, up)
+}
</ins><span class="cx"> 
</span><del>-    if (cm.state.focused) {
-      signal(cm, &quot;blur&quot;, cm);
-      cm.state.focused = false;
-      rmClass(cm.display.wrapper, &quot;CodeMirror-focused&quot;);
</del><ins>+function onKeyUp(e) {
+  if (e.keyCode == 16) { this.doc.sel.shift = false }
+  signalDOMEvent(this, e)
+}
+
+function onKeyPress(e) {
+  var cm = this
+  if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey &amp;&amp; !e.altKey || mac &amp;&amp; e.metaKey) { return }
+  var keyCode = e.keyCode, charCode = e.charCode
+  if (presto &amp;&amp; keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
+  if ((presto &amp;&amp; (!e.which || e.which &lt; 10)) &amp;&amp; handleKeyBinding(cm, e)) { return }
+  var ch = String.fromCharCode(charCode == null ? keyCode : charCode)
+  // Some browsers fire keypress events for backspace
+  if (ch == &quot;\x08&quot;) { return }
+  if (handleCharBinding(cm, e, ch)) { return }
+  cm.display.input.onKeyPress(e)
+}
+
+// A mouse down can be a single click, double click, triple click,
+// start of selection drag, start of text drag, new cursor
+// (ctrl-click), rectangle drag (alt-drag), or xwin
+// middle-click-paste. Or it might be a click on something we should
+// not interfere with, such as a scrollbar or widget.
+function onMouseDown(e) {
+  var cm = this, display = cm.display
+  if (signalDOMEvent(cm, e) || display.activeTouch &amp;&amp; display.input.supportsTouch()) { return }
+  display.input.ensurePolled()
+  display.shift = e.shiftKey
+
+  if (eventInWidget(display, e)) {
+    if (!webkit) {
+      // Briefly turn off draggability, to allow widgets to do
+      // normal dragging things.
+      display.scroller.draggable = false
+      setTimeout(function () { return display.scroller.draggable = true; }, 100)
</ins><span class="cx">     }
</span><del>-    clearInterval(cm.display.blinker);
-    setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
</del><ins>+    return
</ins><span class="cx">   }
</span><ins>+  if (clickInGutter(cm, e)) { return }
+  var start = posFromMouse(cm, e)
+  window.focus()
</ins><span class="cx"> 
</span><del>-  // CONTEXT MENU HANDLING
-
-  // To make the context menu work, we need to briefly unhide the
-  // textarea (making it as unobtrusive as possible) to let the
-  // right-click take effect on it.
-  function onContextMenu(cm, e) {
-    if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
-    cm.display.input.onContextMenu(e);
</del><ins>+  switch (e_button(e)) {
+  case 1:
+    // #3261: make sure, that we're not starting a second selection
+    if (cm.state.selectingText)
+      { cm.state.selectingText(e) }
+    else if (start)
+      { leftButtonDown(cm, e, start) }
+    else if (e_target(e) == display.scroller)
+      { e_preventDefault(e) }
+    break
+  case 2:
+    if (webkit) { cm.state.lastMiddleDown = +new Date }
+    if (start) { extendSelection(cm.doc, start) }
+    setTimeout(function () { return display.input.focus(); }, 20)
+    e_preventDefault(e)
+    break
+  case 3:
+    if (captureRightClick) { onContextMenu(cm, e) }
+    else { delayBlurEvent(cm) }
+    break
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  function contextMenuInGutter(cm, e) {
-    if (!hasHandler(cm, &quot;gutterContextMenu&quot;)) return false;
-    return gutterEvent(cm, e, &quot;gutterContextMenu&quot;, false, signal);
</del><ins>+var lastClick;
+var lastDoubleClick;
+function leftButtonDown(cm, e, start) {
+  if (ie) { setTimeout(bind(ensureFocus, cm), 0) }
+  else { cm.curOp.focus = activeElt() }
+
+  var now = +new Date, type
+  if (lastDoubleClick &amp;&amp; lastDoubleClick.time &gt; now - 400 &amp;&amp; cmp(lastDoubleClick.pos, start) == 0) {
+    type = &quot;triple&quot;
+  } else if (lastClick &amp;&amp; lastClick.time &gt; now - 400 &amp;&amp; cmp(lastClick.pos, start) == 0) {
+    type = &quot;double&quot;
+    lastDoubleClick = {time: now, pos: start}
+  } else {
+    type = &quot;single&quot;
+    lastClick = {time: now, pos: start}
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // UPDATING
</del><ins>+  var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained
+  if (cm.options.dragDrop &amp;&amp; dragAndDrop &amp;&amp; !cm.isReadOnly() &amp;&amp;
+      type == &quot;single&quot; &amp;&amp; (contained = sel.contains(start)) &gt; -1 &amp;&amp;
+      (cmp((contained = sel.ranges[contained]).from(), start) &lt; 0 || start.xRel &gt; 0) &amp;&amp;
+      (cmp(contained.to(), start) &gt; 0 || start.xRel &lt; 0))
+    { leftButtonStartDrag(cm, e, start, modifier) }
+  else
+    { leftButtonSelect(cm, e, start, type, modifier) }
+}
</ins><span class="cx"> 
</span><del>-  // Compute the position of the end of a change (its 'to' property
-  // refers to the pre-change end).
-  var changeEnd = CodeMirror.changeEnd = function(change) {
-    if (!change.text) return change.to;
-    return Pos(change.from.line + change.text.length - 1,
-               lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
-  };
</del><ins>+// Start a text drag. When it ends, see if any dragging actually
+// happen, and treat as a click if it didn't.
+function leftButtonStartDrag(cm, e, start, modifier) {
+  var display = cm.display, startTime = +new Date
+  var dragEnd = operation(cm, function (e2) {
+    if (webkit) { display.scroller.draggable = false }
+    cm.state.draggingText = false
+    off(document, &quot;mouseup&quot;, dragEnd)
+    off(display.scroller, &quot;drop&quot;, dragEnd)
+    if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) &lt; 10) {
+      e_preventDefault(e2)
+      if (!modifier &amp;&amp; +new Date - 200 &lt; startTime)
+        { extendSelection(cm.doc, start) }
+      // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
+      if (webkit || ie &amp;&amp; ie_version == 9)
+        { setTimeout(function () {document.body.focus(); display.input.focus()}, 20) }
+      else
+        { display.input.focus() }
+    }
+  })
+  // Let the drag handler handle this.
+  if (webkit) { display.scroller.draggable = true }
+  cm.state.draggingText = dragEnd
+  dragEnd.copy = mac ? e.altKey : e.ctrlKey
+  // IE's approach to draggable
+  if (display.scroller.dragDrop) { display.scroller.dragDrop() }
+  on(document, &quot;mouseup&quot;, dragEnd)
+  on(display.scroller, &quot;drop&quot;, dragEnd)
+}
</ins><span class="cx"> 
</span><del>-  // Adjust a position to refer to the post-change position of the
-  // same text, or the end of the change if the change covers it.
-  function adjustForChange(pos, change) {
-    if (cmp(pos, change.from) &lt; 0) return pos;
-    if (cmp(pos, change.to) &lt;= 0) return changeEnd(change);
</del><ins>+// Normal selection, as opposed to text dragging.
+function leftButtonSelect(cm, e, start, type, addNew) {
+  var display = cm.display, doc = cm.doc
+  e_preventDefault(e)
</ins><span class="cx"> 
</span><del>-    var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
-    if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
-    return Pos(line, ch);
</del><ins>+  var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges
+  if (addNew &amp;&amp; !e.shiftKey) {
+    ourIndex = doc.sel.contains(start)
+    if (ourIndex &gt; -1)
+      { ourRange = ranges[ourIndex] }
+    else
+      { ourRange = new Range(start, start) }
+  } else {
+    ourRange = doc.sel.primary()
+    ourIndex = doc.sel.primIndex
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  function computeSelAfterChange(doc, change) {
-    var out = [];
-    for (var i = 0; i &lt; doc.sel.ranges.length; i++) {
-      var range = doc.sel.ranges[i];
-      out.push(new Range(adjustForChange(range.anchor, change),
-                         adjustForChange(range.head, change)));
-    }
-    return normalizeSelection(out, doc.sel.primIndex);
</del><ins>+  if (chromeOS ? e.shiftKey &amp;&amp; e.metaKey : e.altKey) {
+    type = &quot;rect&quot;
+    if (!addNew) { ourRange = new Range(start, start) }
+    start = posFromMouse(cm, e, true, true)
+    ourIndex = -1
+  } else if (type == &quot;double&quot;) {
+    var word = cm.findWordAt(start)
+    if (cm.display.shift || doc.extend)
+      { ourRange = extendRange(doc, ourRange, word.anchor, word.head) }
+    else
+      { ourRange = word }
+  } else if (type == &quot;triple&quot;) {
+    var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)))
+    if (cm.display.shift || doc.extend)
+      { ourRange = extendRange(doc, ourRange, line.anchor, line.head) }
+    else
+      { ourRange = line }
+  } else {
+    ourRange = extendRange(doc, ourRange, start)
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  function offsetPos(pos, old, nw) {
-    if (pos.line == old.line)
-      return Pos(nw.line, pos.ch - old.ch + nw.ch);
-    else
-      return Pos(nw.line + (pos.line - old.line), pos.ch);
</del><ins>+  if (!addNew) {
+    ourIndex = 0
+    setSelection(doc, new Selection([ourRange], 0), sel_mouse)
+    startSel = doc.sel
+  } else if (ourIndex == -1) {
+    ourIndex = ranges.length
+    setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
+                 {scroll: false, origin: &quot;*mouse&quot;})
+  } else if (ranges.length &gt; 1 &amp;&amp; ranges[ourIndex].empty() &amp;&amp; type == &quot;single&quot; &amp;&amp; !e.shiftKey) {
+    setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
+                 {scroll: false, origin: &quot;*mouse&quot;})
+    startSel = doc.sel
+  } else {
+    replaceOneSelection(doc, ourIndex, ourRange, sel_mouse)
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // Used by replaceSelections to allow moving the selection to the
-  // start or around the replaced test. Hint may be &quot;start&quot; or &quot;around&quot;.
-  function computeReplacedSel(doc, changes, hint) {
-    var out = [];
-    var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
-    for (var i = 0; i &lt; changes.length; i++) {
-      var change = changes[i];
-      var from = offsetPos(change.from, oldPrev, newPrev);
-      var to = offsetPos(changeEnd(change), oldPrev, newPrev);
-      oldPrev = change.to;
-      newPrev = to;
-      if (hint == &quot;around&quot;) {
-        var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) &lt; 0;
-        out[i] = new Range(inv ? to : from, inv ? from : to);
-      } else {
-        out[i] = new Range(from, from);
</del><ins>+  var lastPos = start
+  function extendTo(pos) {
+    if (cmp(lastPos, pos) == 0) { return }
+    lastPos = pos
+
+    if (type == &quot;rect&quot;) {
+      var ranges = [], tabSize = cm.options.tabSize
+      var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize)
+      var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize)
+      var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol)
+      for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
+           line &lt;= end; line++) {
+        var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize)
+        if (left == right)
+          { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))) }
+        else if (text.length &gt; leftPos)
+          { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))) }
</ins><span class="cx">       }
</span><ins>+      if (!ranges.length) { ranges.push(new Range(start, start)) }
+      setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
+                   {origin: &quot;*mouse&quot;, scroll: false})
+      cm.scrollIntoView(pos)
+    } else {
+      var oldRange = ourRange
+      var anchor = oldRange.anchor, head = pos
+      if (type != &quot;single&quot;) {
+        var range
+        if (type == &quot;double&quot;)
+          { range = cm.findWordAt(pos) }
+        else
+          { range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))) }
+        if (cmp(range.anchor, anchor) &gt; 0) {
+          head = range.head
+          anchor = minPos(oldRange.from(), range.anchor)
+        } else {
+          head = range.anchor
+          anchor = maxPos(oldRange.to(), range.head)
+        }
+      }
+      var ranges$1 = startSel.ranges.slice(0)
+      ranges$1[ourIndex] = new Range(clipPos(doc, anchor), head)
+      setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse)
</ins><span class="cx">     }
</span><del>-    return new Selection(out, doc.sel.primIndex);
</del><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // Allow &quot;beforeChange&quot; event handlers to influence a change
-  function filterChange(doc, change, update) {
-    var obj = {
-      canceled: false,
-      from: change.from,
-      to: change.to,
-      text: change.text,
-      origin: change.origin,
-      cancel: function() { this.canceled = true; }
-    };
-    if (update) obj.update = function(from, to, text, origin) {
-      if (from) this.from = clipPos(doc, from);
-      if (to) this.to = clipPos(doc, to);
-      if (text) this.text = text;
-      if (origin !== undefined) this.origin = origin;
-    };
-    signal(doc, &quot;beforeChange&quot;, doc, obj);
-    if (doc.cm) signal(doc.cm, &quot;beforeChange&quot;, doc.cm, obj);
</del><ins>+  var editorSize = display.wrapper.getBoundingClientRect()
+  // Used to ensure timeout re-tries don't fire when another extend
+  // happened in the meantime (clearTimeout isn't reliable -- at
+  // least on Chrome, the timeouts still happen even when cleared,
+  // if the clear happens after their scheduled firing time).
+  var counter = 0
</ins><span class="cx"> 
</span><del>-    if (obj.canceled) return null;
-    return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
</del><ins>+  function extend(e) {
+    var curCount = ++counter
+    var cur = posFromMouse(cm, e, true, type == &quot;rect&quot;)
+    if (!cur) { return }
+    if (cmp(cur, lastPos) != 0) {
+      cm.curOp.focus = activeElt()
+      extendTo(cur)
+      var visible = visibleLines(display, doc)
+      if (cur.line &gt;= visible.to || cur.line &lt; visible.from)
+        { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e) }}), 150) }
+    } else {
+      var outside = e.clientY &lt; editorSize.top ? -20 : e.clientY &gt; editorSize.bottom ? 20 : 0
+      if (outside) { setTimeout(operation(cm, function () {
+        if (counter != curCount) { return }
+        display.scroller.scrollTop += outside
+        extend(e)
+      }), 50) }
+    }
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // Apply a change to a document, and add it to the document's
-  // history, and propagating it to all linked documents.
-  function makeChange(doc, change, ignoreReadOnly) {
-    if (doc.cm) {
-      if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
-      if (doc.cm.state.suppressEdits) return;
-    }
</del><ins>+  function done(e) {
+    cm.state.selectingText = false
+    counter = Infinity
+    e_preventDefault(e)
+    display.input.focus()
+    off(document, &quot;mousemove&quot;, move)
+    off(document, &quot;mouseup&quot;, up)
+    doc.history.lastSelOrigin = null
+  }
</ins><span class="cx"> 
</span><del>-    if (hasHandler(doc, &quot;beforeChange&quot;) || doc.cm &amp;&amp; hasHandler(doc.cm, &quot;beforeChange&quot;)) {
-      change = filterChange(doc, change, true);
-      if (!change) return;
-    }
</del><ins>+  var move = operation(cm, function (e) {
+    if (!e_button(e)) { done(e) }
+    else { extend(e) }
+  })
+  var up = operation(cm, done)
+  cm.state.selectingText = up
+  on(document, &quot;mousemove&quot;, move)
+  on(document, &quot;mouseup&quot;, up)
+}
</ins><span class="cx"> 
</span><del>-    // Possibly split or suppress the update based on the presence
-    // of read-only spans in its range.
-    var split = sawReadOnlySpans &amp;&amp; !ignoreReadOnly &amp;&amp; removeReadOnlyRanges(doc, change.from, change.to);
-    if (split) {
-      for (var i = split.length - 1; i &gt;= 0; --i)
-        makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [&quot;&quot;] : change.text});
-    } else {
-      makeChangeInner(doc, change);
</del><ins>+
+// Determines whether an event happened in the gutter, and fires the
+// handlers for the corresponding event.
+function gutterEvent(cm, e, type, prevent) {
+  var mX, mY
+  try { mX = e.clientX; mY = e.clientY }
+  catch(e) { return false }
+  if (mX &gt;= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
+  if (prevent) { e_preventDefault(e) }
+
+  var display = cm.display
+  var lineBox = display.lineDiv.getBoundingClientRect()
+
+  if (mY &gt; lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
+  mY -= lineBox.top - display.viewOffset
+
+  for (var i = 0; i &lt; cm.options.gutters.length; ++i) {
+    var g = display.gutters.childNodes[i]
+    if (g &amp;&amp; g.getBoundingClientRect().right &gt;= mX) {
+      var line = lineAtHeight(cm.doc, mY)
+      var gutter = cm.options.gutters[i]
+      signal(cm, type, cm, line, gutter, e)
+      return e_defaultPrevented(e)
</ins><span class="cx">     }
</span><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  function makeChangeInner(doc, change) {
-    if (change.text.length == 1 &amp;&amp; change.text[0] == &quot;&quot; &amp;&amp; cmp(change.from, change.to) == 0) return;
-    var selAfter = computeSelAfterChange(doc, change);
-    addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
</del><ins>+function clickInGutter(cm, e) {
+  return gutterEvent(cm, e, &quot;gutterClick&quot;, true)
+}
</ins><span class="cx"> 
</span><del>-    makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
-    var rebased = [];
</del><ins>+// CONTEXT MENU HANDLING
</ins><span class="cx"> 
</span><del>-    linkedDocs(doc, function(doc, sharedHist) {
-      if (!sharedHist &amp;&amp; indexOf(rebased, doc.history) == -1) {
-        rebaseHist(doc.history, change);
-        rebased.push(doc.history);
-      }
-      makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
-    });
</del><ins>+// To make the context menu work, we need to briefly unhide the
+// textarea (making it as unobtrusive as possible) to let the
+// right-click take effect on it.
+function onContextMenu(cm, e) {
+  if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
+  if (signalDOMEvent(cm, e, &quot;contextmenu&quot;)) { return }
+  cm.display.input.onContextMenu(e)
+}
+
+function contextMenuInGutter(cm, e) {
+  if (!hasHandler(cm, &quot;gutterContextMenu&quot;)) { return false }
+  return gutterEvent(cm, e, &quot;gutterContextMenu&quot;, false)
+}
+
+function themeChanged(cm) {
+  cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, &quot;&quot;) +
+    cm.options.theme.replace(/(^|\s)\s*/g, &quot; cm-s-&quot;)
+  clearCaches(cm)
+}
+
+var Init = {toString: function(){return &quot;CodeMirror.Init&quot;}}
+
+var defaults = {}
+var optionHandlers = {}
+
+function defineOptions(CodeMirror) {
+  var optionHandlers = CodeMirror.optionHandlers
+
+  function option(name, deflt, handle, notOnInit) {
+    CodeMirror.defaults[name] = deflt
+    if (handle) { optionHandlers[name] =
+      notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old) }} : handle }
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // Revert a change stored in a document's history.
-  function makeChangeFromHistory(doc, type, allowSelectionOnly) {
-    if (doc.cm &amp;&amp; doc.cm.state.suppressEdits) return;
</del><ins>+  CodeMirror.defineOption = option
</ins><span class="cx"> 
</span><del>-    var hist = doc.history, event, selAfter = doc.sel;
-    var source = type == &quot;undo&quot; ? hist.done : hist.undone, dest = type == &quot;undo&quot; ? hist.undone : hist.done;
</del><ins>+  // Passed to option handlers when there is no old value.
+  CodeMirror.Init = Init
</ins><span class="cx"> 
</span><del>-    // Verify that there is a useable event (so that ctrl-z won't
-    // needlessly clear selection events)
-    for (var i = 0; i &lt; source.length; i++) {
-      event = source[i];
-      if (allowSelectionOnly ? event.ranges &amp;&amp; !event.equals(doc.sel) : !event.ranges)
-        break;
-    }
-    if (i == source.length) return;
-    hist.lastOrigin = hist.lastSelOrigin = null;
</del><ins>+  // These two are, on init, called from the constructor because they
+  // have to be initialized before the editor can start at all.
+  option(&quot;value&quot;, &quot;&quot;, function (cm, val) { return cm.setValue(val); }, true)
+  option(&quot;mode&quot;, null, function (cm, val) {
+    cm.doc.modeOption = val
+    loadMode(cm)
+  }, true)
</ins><span class="cx"> 
</span><del>-    for (;;) {
-      event = source.pop();
-      if (event.ranges) {
-        pushSelectionToHistory(event, dest);
-        if (allowSelectionOnly &amp;&amp; !event.equals(doc.sel)) {
-          setSelection(doc, event, {clearRedo: false});
-          return;
-        }
-        selAfter = event;
</del><ins>+  option(&quot;indentUnit&quot;, 2, loadMode, true)
+  option(&quot;indentWithTabs&quot;, false)
+  option(&quot;smartIndent&quot;, true)
+  option(&quot;tabSize&quot;, 4, function (cm) {
+    resetModeState(cm)
+    clearCaches(cm)
+    regChange(cm)
+  }, true)
+  option(&quot;lineSeparator&quot;, null, function (cm, val) {
+    cm.doc.lineSep = val
+    if (!val) { return }
+    var newBreaks = [], lineNo = cm.doc.first
+    cm.doc.iter(function (line) {
+      for (var pos = 0;;) {
+        var found = line.text.indexOf(val, pos)
+        if (found == -1) { break }
+        pos = found + val.length
+        newBreaks.push(Pos(lineNo, found))
</ins><span class="cx">       }
</span><del>-      else break;
-    }
</del><ins>+      lineNo++
+    })
+    for (var i = newBreaks.length - 1; i &gt;= 0; i--)
+      { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) }
+  })
+  option(&quot;specialChars&quot;, /[\u0000-\u001f\u007f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
+    cm.state.specialChars = new RegExp(val.source + (val.test(&quot;\t&quot;) ? &quot;&quot; : &quot;|\t&quot;), &quot;g&quot;)
+    if (old != Init) { cm.refresh() }
+  })
+  option(&quot;specialCharPlaceholder&quot;, defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true)
+  option(&quot;electricChars&quot;, true)
+  option(&quot;inputStyle&quot;, mobile ? &quot;contenteditable&quot; : &quot;textarea&quot;, function () {
+    throw new Error(&quot;inputStyle can not (yet) be changed in a running editor&quot;) // FIXME
+  }, true)
+  option(&quot;spellcheck&quot;, false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true)
+  option(&quot;rtlMoveVisually&quot;, !windows)
+  option(&quot;wholeLineUpdateBefore&quot;, true)
</ins><span class="cx"> 
</span><del>-    // Build up a reverse change object to add to the opposite history
-    // stack (redo when undoing, and vice versa).
-    var antiChanges = [];
-    pushSelectionToHistory(selAfter, dest);
-    dest.push({changes: antiChanges, generation: hist.generation});
-    hist.generation = event.generation || ++hist.maxGeneration;
</del><ins>+  option(&quot;theme&quot;, &quot;default&quot;, function (cm) {
+    themeChanged(cm)
+    guttersChanged(cm)
+  }, true)
+  option(&quot;keyMap&quot;, &quot;default&quot;, function (cm, val, old) {
+    var next = getKeyMap(val)
+    var prev = old != Init &amp;&amp; getKeyMap(old)
+    if (prev &amp;&amp; prev.detach) { prev.detach(cm, next) }
+    if (next.attach) { next.attach(cm, prev || null) }
+  })
+  option(&quot;extraKeys&quot;, null)
</ins><span class="cx"> 
</span><del>-    var filter = hasHandler(doc, &quot;beforeChange&quot;) || doc.cm &amp;&amp; hasHandler(doc.cm, &quot;beforeChange&quot;);
</del><ins>+  option(&quot;lineWrapping&quot;, false, wrappingChanged, true)
+  option(&quot;gutters&quot;, [], function (cm) {
+    setGuttersForLineNumbers(cm.options)
+    guttersChanged(cm)
+  }, true)
+  option(&quot;fixedGutter&quot;, true, function (cm, val) {
+    cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + &quot;px&quot; : &quot;0&quot;
+    cm.refresh()
+  }, true)
+  option(&quot;coverGutterNextToScrollbar&quot;, false, function (cm) { return updateScrollbars(cm); }, true)
+  option(&quot;scrollbarStyle&quot;, &quot;native&quot;, function (cm) {
+    initScrollbars(cm)
+    updateScrollbars(cm)
+    cm.display.scrollbars.setScrollTop(cm.doc.scrollTop)
+    cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)
+  }, true)
+  option(&quot;lineNumbers&quot;, false, function (cm) {
+    setGuttersForLineNumbers(cm.options)
+    guttersChanged(cm)
+  }, true)
+  option(&quot;firstLineNumber&quot;, 1, guttersChanged, true)
+  option(&quot;lineNumberFormatter&quot;, function (integer) { return integer; }, guttersChanged, true)
+  option(&quot;showCursorWhenSelecting&quot;, false, updateSelection, true)
</ins><span class="cx"> 
</span><del>-    for (var i = event.changes.length - 1; i &gt;= 0; --i) {
-      var change = event.changes[i];
-      change.origin = type;
-      if (filter &amp;&amp; !filterChange(doc, change, false)) {
-        source.length = 0;
-        return;
-      }
</del><ins>+  option(&quot;resetSelectionOnContextMenu&quot;, true)
+  option(&quot;lineWiseCopyCut&quot;, true)
</ins><span class="cx"> 
</span><del>-      antiChanges.push(historyChangeFromChange(doc, change));
</del><ins>+  option(&quot;readOnly&quot;, false, function (cm, val) {
+    if (val == &quot;nocursor&quot;) {
+      onBlur(cm)
+      cm.display.input.blur()
+      cm.display.disabled = true
+    } else {
+      cm.display.disabled = false
+    }
+    cm.display.input.readOnlyChanged(val)
+  })
+  option(&quot;disableInput&quot;, false, function (cm, val) {if (!val) { cm.display.input.reset() }}, true)
+  option(&quot;dragDrop&quot;, true, dragDropChanged)
+  option(&quot;allowDropFileTypes&quot;, null)
</ins><span class="cx"> 
</span><del>-      var after = i ? computeSelAfterChange(doc, change) : lst(source);
-      makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
-      if (!i &amp;&amp; doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
-      var rebased = [];
</del><ins>+  option(&quot;cursorBlinkRate&quot;, 530)
+  option(&quot;cursorScrollMargin&quot;, 0)
+  option(&quot;cursorHeight&quot;, 1, updateSelection, true)
+  option(&quot;singleCursorHeightPerLine&quot;, true, updateSelection, true)
+  option(&quot;workTime&quot;, 100)
+  option(&quot;workDelay&quot;, 100)
+  option(&quot;flattenSpans&quot;, true, resetModeState, true)
+  option(&quot;addModeClass&quot;, false, resetModeState, true)
+  option(&quot;pollInterval&quot;, 100)
+  option(&quot;undoDepth&quot;, 200, function (cm, val) { return cm.doc.history.undoDepth = val; })
+  option(&quot;historyEventDelay&quot;, 1250)
+  option(&quot;viewportMargin&quot;, 10, function (cm) { return cm.refresh(); }, true)
+  option(&quot;maxHighlightLength&quot;, 10000, resetModeState, true)
+  option(&quot;moveInputWithCursor&quot;, true, function (cm, val) {
+    if (!val) { cm.display.input.resetPosition() }
+  })
</ins><span class="cx"> 
</span><del>-      // Propagate to the linked documents
-      linkedDocs(doc, function(doc, sharedHist) {
-        if (!sharedHist &amp;&amp; indexOf(rebased, doc.history) == -1) {
-          rebaseHist(doc.history, change);
-          rebased.push(doc.history);
-        }
-        makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
-      });
-    }
</del><ins>+  option(&quot;tabindex&quot;, null, function (cm, val) { return cm.display.input.getField().tabIndex = val || &quot;&quot;; })
+  option(&quot;autofocus&quot;, null)
+}
+
+function guttersChanged(cm) {
+  updateGutters(cm)
+  regChange(cm)
+  alignHorizontally(cm)
+}
+
+function dragDropChanged(cm, value, old) {
+  var wasOn = old &amp;&amp; old != Init
+  if (!value != !wasOn) {
+    var funcs = cm.display.dragFunctions
+    var toggle = value ? on : off
+    toggle(cm.display.scroller, &quot;dragstart&quot;, funcs.start)
+    toggle(cm.display.scroller, &quot;dragenter&quot;, funcs.enter)
+    toggle(cm.display.scroller, &quot;dragover&quot;, funcs.over)
+    toggle(cm.display.scroller, &quot;dragleave&quot;, funcs.leave)
+    toggle(cm.display.scroller, &quot;drop&quot;, funcs.drop)
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // Sub-views need their line numbers shifted when text is added
-  // above or below them in the parent document.
-  function shiftDoc(doc, distance) {
-    if (distance == 0) return;
-    doc.first += distance;
-    doc.sel = new Selection(map(doc.sel.ranges, function(range) {
-      return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
-                       Pos(range.head.line + distance, range.head.ch));
-    }), doc.sel.primIndex);
-    if (doc.cm) {
-      regChange(doc.cm, doc.first, doc.first - distance, distance);
-      for (var d = doc.cm.display, l = d.viewFrom; l &lt; d.viewTo; l++)
-        regLineChange(doc.cm, l, &quot;gutter&quot;);
-    }
</del><ins>+function wrappingChanged(cm) {
+  if (cm.options.lineWrapping) {
+    addClass(cm.display.wrapper, &quot;CodeMirror-wrap&quot;)
+    cm.display.sizer.style.minWidth = &quot;&quot;
+    cm.display.sizerWidth = null
+  } else {
+    rmClass(cm.display.wrapper, &quot;CodeMirror-wrap&quot;)
+    findMaxLine(cm)
</ins><span class="cx">   }
</span><ins>+  estimateLineHeights(cm)
+  regChange(cm)
+  clearCaches(cm)
+  setTimeout(function () { return updateScrollbars(cm); }, 100)
+}
</ins><span class="cx"> 
</span><del>-  // More lower-level change function, handling only a single document
-  // (not linked ones).
-  function makeChangeSingleDoc(doc, change, selAfter, spans) {
-    if (doc.cm &amp;&amp; !doc.cm.curOp)
-      return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
</del><ins>+// A CodeMirror instance represents an editor. This is the object
+// that user code is usually dealing with.
</ins><span class="cx"> 
</span><del>-    if (change.to.line &lt; doc.first) {
-      shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
-      return;
-    }
-    if (change.from.line &gt; doc.lastLine()) return;
</del><ins>+function CodeMirror(place, options) {
+  var this$1 = this;
</ins><span class="cx"> 
</span><del>-    // Clip the change to the size of this doc
-    if (change.from.line &lt; doc.first) {
-      var shift = change.text.length - 1 - (doc.first - change.from.line);
-      shiftDoc(doc, shift);
-      change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
-                text: [lst(change.text)], origin: change.origin};
-    }
-    var last = doc.lastLine();
-    if (change.to.line &gt; last) {
-      change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
-                text: [change.text[0]], origin: change.origin};
-    }
</del><ins>+  if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
</ins><span class="cx"> 
</span><del>-    change.removed = getBetween(doc, change.from, change.to);
</del><ins>+  this.options = options = options ? copyObj(options) : {}
+  // Determine effective options based on given values and defaults.
+  copyObj(defaults, options, false)
+  setGuttersForLineNumbers(options)
</ins><span class="cx"> 
</span><del>-    if (!selAfter) selAfter = computeSelAfterChange(doc, change);
-    if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
-    else updateDoc(doc, change, spans);
-    setSelectionNoUndo(doc, selAfter, sel_dontScroll);
-  }
</del><ins>+  var doc = options.value
+  if (typeof doc == &quot;string&quot;) { doc = new Doc(doc, options.mode, null, options.lineSeparator) }
+  this.doc = doc
</ins><span class="cx"> 
</span><del>-  // Handle the interaction of a change to a document with the editor
-  // that this document is part of.
-  function makeChangeSingleDocInEditor(cm, change, spans) {
-    var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
</del><ins>+  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 += &quot; CodeMirror-wrap&quot; }
+  initScrollbars(this)
</ins><span class="cx"> 
</span><del>-    var recomputeMaxLength = false, checkWidthStart = from.line;
-    if (!cm.options.lineWrapping) {
-      checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
-      doc.iter(checkWidthStart, to.line + 1, function(line) {
-        if (line == display.maxLine) {
-          recomputeMaxLength = true;
-          return true;
-        }
-      });
-    }
</del><ins>+  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
+  }
</ins><span class="cx"> 
</span><del>-    if (doc.sel.contains(change.from, change.to) &gt; -1)
-      signalCursorActivity(cm);
</del><ins>+  if (options.autofocus &amp;&amp; !mobile) { display.input.focus() }
</ins><span class="cx"> 
</span><del>-    updateDoc(doc, change, spans, estimateHeight(cm));
</del><ins>+  // Override magic textarea content restore that IE sometimes does
+  // on our hidden textarea on reload
+  if (ie &amp;&amp; ie_version &lt; 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20) }
</ins><span class="cx"> 
</span><del>-    if (!cm.options.lineWrapping) {
-      doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
-        var len = lineLength(line);
-        if (len &gt; display.maxLineLength) {
-          display.maxLine = line;
-          display.maxLineLength = len;
-          display.maxLineChanged = true;
-          recomputeMaxLength = false;
-        }
-      });
-      if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
-    }
</del><ins>+  registerEventHandlers(this)
+  ensureGlobalHandlers()
</ins><span class="cx"> 
</span><del>-    // Adjust frontier, schedule worker
-    doc.frontier = Math.min(doc.frontier, from.line);
-    startWorker(cm, 400);
</del><ins>+  startOperation(this)
+  this.curOp.forceUpdate = true
+  attachDoc(this, doc)
</ins><span class="cx"> 
</span><del>-    var lendiff = change.text.length - (to.line - from.line) - 1;
-    // Remember that these lines changed, for updating the display
-    if (change.full)
-      regChange(cm);
-    else if (from.line == to.line &amp;&amp; change.text.length == 1 &amp;&amp; !isWholeLineUpdate(cm.doc, change))
-      regLineChange(cm, from.line, &quot;text&quot;);
-    else
-      regChange(cm, from.line, to.line + 1, lendiff);
</del><ins>+  if ((options.autofocus &amp;&amp; !mobile) || this.hasFocus())
+    { setTimeout(bind(onFocus, this), 20) }
+  else
+    { onBlur(this) }
</ins><span class="cx"> 
</span><del>-    var changesHandler = hasHandler(cm, &quot;changes&quot;), changeHandler = hasHandler(cm, &quot;change&quot;);
-    if (changeHandler || changesHandler) {
-      var obj = {
-        from: from, to: to,
-        text: change.text,
-        removed: change.removed,
-        origin: change.origin
-      };
-      if (changeHandler) signalLater(cm, &quot;change&quot;, cm, obj);
-      if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
-    }
-    cm.display.selForContextMenu = null;
-  }
</del><ins>+  for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
+    { optionHandlers[opt](this$1, options[opt], Init) } }
+  maybeUpdateLineNumberWidth(this)
+  if (options.finishInit) { options.finishInit(this) }
+  for (var i = 0; i &lt; initHooks.length; ++i) { initHooks[i](this$1) }
+  endOperation(this)
+  // Suppress optimizelegibility in Webkit, since it breaks text
+  // measuring on line wrapping boundaries.
+  if (webkit &amp;&amp; options.lineWrapping &amp;&amp;
+      getComputedStyle(display.lineDiv).textRendering == &quot;optimizelegibility&quot;)
+    { display.lineDiv.style.textRendering = &quot;auto&quot; }
+}
</ins><span class="cx"> 
</span><del>-  function replaceRange(doc, code, from, to, origin) {
-    if (!to) to = from;
-    if (cmp(to, from) &lt; 0) { var tmp = to; to = from; from = tmp; }
-    if (typeof code == &quot;string&quot;) code = doc.splitLines(code);
-    makeChange(doc, {from: from, to: to, text: code, origin: origin});
-  }
</del><ins>+// The default configuration options.
+CodeMirror.defaults = defaults
+// Functions to run when options are changed.
+CodeMirror.optionHandlers = optionHandlers
</ins><span class="cx"> 
</span><del>-  // SCROLLING THINGS INTO VIEW
</del><ins>+// Attach the necessary event handlers when initializing the editor
+function registerEventHandlers(cm) {
+  var d = cm.display
+  on(d.scroller, &quot;mousedown&quot;, operation(cm, onMouseDown))
+  // Older IE's will not fire a second mousedown for a double click
+  if (ie &amp;&amp; ie_version &lt; 11)
+    { on(d.scroller, &quot;dblclick&quot;, 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, &quot;dblclick&quot;, function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }) }
+  // Some browsers fire contextmenu *after* opening the menu, at
+  // which point we can't mess with it anymore. Context menu is
+  // handled in onMouseDown for these browsers.
+  if (!captureRightClick) { on(d.scroller, &quot;contextmenu&quot;, function (e) { return onContextMenu(cm, e); }) }
</ins><span class="cx"> 
</span><del>-  // 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, coords) {
-    if (signalDOMEvent(cm, &quot;scrollCursorIntoView&quot;)) return;
-
-    var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
-    if (coords.top + box.top &lt; 0) doScroll = true;
-    else if (coords.bottom + box.top &gt; (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
-    if (doScroll != null &amp;&amp; !phantom) {
-      var scrollNode = elt(&quot;div&quot;, &quot;\u200b&quot;, null, &quot;position: absolute; top: &quot; +
-                           (coords.top - display.viewOffset - paddingTop(cm.display)) + &quot;px; height: &quot; +
-                           (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + &quot;px; left: &quot; +
-                           coords.left + &quot;px; width: 2px;&quot;);
-      cm.display.lineSpace.appendChild(scrollNode);
-      scrollNode.scrollIntoView(doScroll);
-      cm.display.lineSpace.removeChild(scrollNode);
</del><ins>+  // Used to suppress mouse event handling when a touch happens
+  var touchFinished, prevTouch = {end: 0}
+  function finishTouch() {
+    if (d.activeTouch) {
+      touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000)
+      prevTouch = d.activeTouch
+      prevTouch.end = +new Date
</ins><span class="cx">     }
</span><span class="cx">   }
</span><del>-
-  // 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;
-    for (var limit = 0; limit &lt; 5; limit++) {
-      var changed = false, coords = cursorCoords(cm, pos);
-      var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
-      var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
-                                         Math.min(coords.top, endCoords.top) - margin,
-                                         Math.max(coords.left, endCoords.left),
-                                         Math.max(coords.bottom, endCoords.bottom) + margin);
-      var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
-      if (scrollPos.scrollTop != null) {
-        setScrollTop(cm, scrollPos.scrollTop);
-        if (Math.abs(cm.doc.scrollTop - startTop) &gt; 1) changed = true;
</del><ins>+  function isMouseLikeTouchEvent(e) {
+    if (e.touches.length != 1) { return false }
+    var touch = e.touches[0]
+    return touch.radiusX &lt;= 1 &amp;&amp; touch.radiusY &lt;= 1
+  }
+  function farAway(touch, other) {
+    if (other.left == null) { return true }
+    var dx = other.left - touch.left, dy = other.top - touch.top
+    return dx * dx + dy * dy &gt; 20 * 20
+  }
+  on(d.scroller, &quot;touchstart&quot;, function (e) {
+    if (!signalDOMEvent(cm, e) &amp;&amp; !isMouseLikeTouchEvent(e)) {
+      d.input.ensurePolled()
+      clearTimeout(touchFinished)
+      var now = +new Date
+      d.activeTouch = {start: now, moved: false,
+                       prev: now - prevTouch.end &lt;= 300 ? prevTouch : null}
+      if (e.touches.length == 1) {
+        d.activeTouch.left = e.touches[0].pageX
+        d.activeTouch.top = e.touches[0].pageY
</ins><span class="cx">       }
</span><del>-      if (scrollPos.scrollLeft != null) {
-        setScrollLeft(cm, scrollPos.scrollLeft);
-        if (Math.abs(cm.doc.scrollLeft - startLeft) &gt; 1) changed = true;
-      }
-      if (!changed) break;
</del><span class="cx">     }
</span><del>-    return coords;
-  }
</del><ins>+  })
+  on(d.scroller, &quot;touchmove&quot;, function () {
+    if (d.activeTouch) { d.activeTouch.moved = true }
+  })
+  on(d.scroller, &quot;touchend&quot;, function (e) {
+    var touch = d.activeTouch
+    if (touch &amp;&amp; !eventInWidget(d, e) &amp;&amp; touch.left != null &amp;&amp;
+        !touch.moved &amp;&amp; new Date - touch.start &lt; 300) {
+      var pos = cm.coordsChar(d.activeTouch, &quot;page&quot;), range
+      if (!touch.prev || farAway(touch, touch.prev)) // Single tap
+        { range = new Range(pos, pos) }
+      else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
+        { range = cm.findWordAt(pos) }
+      else // Triple tap
+        { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
+      cm.setSelection(range.anchor, range.head)
+      cm.focus()
+      e_preventDefault(e)
+    }
+    finishTouch()
+  })
+  on(d.scroller, &quot;touchcancel&quot;, finishTouch)
</ins><span class="cx"> 
</span><del>-  // Scroll a given set of coordinates into view (immediately).
-  function scrollIntoView(cm, x1, y1, x2, y2) {
-    var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
-    if (scrollPos.scrollTop != null) setScrollTop(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, x1, y1, x2, y2) {
-    var display = cm.display, snapMargin = textHeight(cm.display);
-    if (y1 &lt; 0) y1 = 0;
-    var screentop = cm.curOp &amp;&amp; cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
-    var screen = displayHeight(cm), result = {};
-    if (y2 - y1 &gt; screen) y2 = y1 + screen;
-    var docBottom = cm.doc.height + paddingVert(display);
-    var atTop = y1 &lt; snapMargin, atBottom = y2 &gt; docBottom - snapMargin;
-    if (y1 &lt; screentop) {
-      result.scrollTop = atTop ? 0 : y1;
-    } else if (y2 &gt; screentop + screen) {
-      var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
-      if (newTop != screentop) result.scrollTop = newTop;
</del><ins>+  // Sync scrolling between fake scrollbars and real scrollable
+  // area, ensure viewport is updated when scrolling.
+  on(d.scroller, &quot;scroll&quot;, function () {
+    if (d.scroller.clientHeight) {
+      setScrollTop(cm, d.scroller.scrollTop)
+      setScrollLeft(cm, d.scroller.scrollLeft, true)
+      signal(cm, &quot;scroll&quot;, cm)
</ins><span class="cx">     }
</span><ins>+  })
</ins><span class="cx"> 
</span><del>-    var screenleft = cm.curOp &amp;&amp; cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
-    var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
-    var tooWide = x2 - x1 &gt; screenw;
-    if (tooWide) x2 = x1 + screenw;
-    if (x1 &lt; 10)
-      result.scrollLeft = 0;
-    else if (x1 &lt; screenleft)
-      result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
-    else if (x2 &gt; screenw + screenleft - 3)
-      result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
-    return result;
-  }
</del><ins>+  // Listen to wheel events in order to try and update the viewport on time.
+  on(d.scroller, &quot;mousewheel&quot;, function (e) { return onScrollWheel(cm, e); })
+  on(d.scroller, &quot;DOMMouseScroll&quot;, function (e) { return onScrollWheel(cm, e); })
</ins><span class="cx"> 
</span><del>-  // Store a relative adjustment to the scroll position in the current
-  // operation (to be applied when the operation finishes).
-  function addToScrollPos(cm, left, top) {
-    if (left != null || top != null) resolveScrollToPos(cm);
-    if (left != null)
-      cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
-    if (top != null)
-      cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
-  }
</del><ins>+  // Prevent wrapper from ever scrolling
+  on(d.wrapper, &quot;scroll&quot;, function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; })
</ins><span class="cx"> 
</span><del>-  // Make sure that at the end of the operation the current cursor is
-  // shown.
-  function ensureCursorVisible(cm) {
-    resolveScrollToPos(cm);
-    var cur = cm.getCursor(), from = cur, to = cur;
-    if (!cm.options.lineWrapping) {
-      from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
-      to = Pos(cur.line, cur.ch + 1);
-    }
-    cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
</del><ins>+  d.dragFunctions = {
+    enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e) }},
+    over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e) }},
+    start: function (e) { return onDragStart(cm, e); },
+    drop: operation(cm, onDrop),
+    leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm) }}
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // 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);
-      var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
-                                    Math.min(from.top, to.top) - range.margin,
-                                    Math.max(from.right, to.right),
-                                    Math.max(from.bottom, to.bottom) + range.margin);
-      cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
-    }
-  }
</del><ins>+  var inp = d.input.getField()
+  on(inp, &quot;keyup&quot;, function (e) { return onKeyUp.call(cm, e); })
+  on(inp, &quot;keydown&quot;, operation(cm, onKeyDown))
+  on(inp, &quot;keypress&quot;, operation(cm, onKeyPress))
+  on(inp, &quot;focus&quot;, function (e) { return onFocus(cm, e); })
+  on(inp, &quot;blur&quot;, function (e) { return onBlur(cm, e); })
+}
</ins><span class="cx"> 
</span><del>-  // API UTILITIES
</del><ins>+var initHooks = []
+CodeMirror.defineInitHook = function (f) { return initHooks.push(f); }
</ins><span class="cx"> 
</span><del>-  // Indent the given line. The how parameter can be &quot;smart&quot;,
-  // &quot;add&quot;/null, &quot;subtract&quot;, or &quot;prev&quot;. When aggressive is false
-  // (typically set to true for forced single-line indents), empty
-  // lines are not indented, and places where the mode returns Pass
-  // are left alone.
-  function indentLine(cm, n, how, aggressive) {
-    var doc = cm.doc, state;
-    if (how == null) how = &quot;add&quot;;
-    if (how == &quot;smart&quot;) {
-      // Fall back to &quot;prev&quot; when the mode doesn't have an indentation
-      // method.
-      if (!doc.mode.indent) how = &quot;prev&quot;;
-      else state = getStateBefore(cm, n);
-    }
</del><ins>+// Indent the given line. The how parameter can be &quot;smart&quot;,
+// &quot;add&quot;/null, &quot;subtract&quot;, or &quot;prev&quot;. When aggressive is false
+// (typically set to true for forced single-line indents), empty
+// lines are not indented, and places where the mode returns Pass
+// are left alone.
+function indentLine(cm, n, how, aggressive) {
+  var doc = cm.doc, state
+  if (how == null) { how = &quot;add&quot; }
+  if (how == &quot;smart&quot;) {
+    // Fall back to &quot;prev&quot; when the mode doesn't have an indentation
+    // method.
+    if (!doc.mode.indent) { how = &quot;prev&quot; }
+    else { state = getStateBefore(cm, n) }
+  }
</ins><span class="cx"> 
</span><del>-    var tabSize = cm.options.tabSize;
-    var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
-    if (line.stateAfter) line.stateAfter = null;
-    var curSpaceString = line.text.match(/^\s*/)[0], indentation;
-    if (!aggressive &amp;&amp; !/\S/.test(line.text)) {
-      indentation = 0;
-      how = &quot;not&quot;;
-    } else if (how == &quot;smart&quot;) {
-      indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
-      if (indentation == Pass || indentation &gt; 150) {
-        if (!aggressive) return;
-        how = &quot;prev&quot;;
-      }
</del><ins>+  var tabSize = cm.options.tabSize
+  var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize)
+  if (line.stateAfter) { line.stateAfter = null }
+  var curSpaceString = line.text.match(/^\s*/)[0], indentation
+  if (!aggressive &amp;&amp; !/\S/.test(line.text)) {
+    indentation = 0
+    how = &quot;not&quot;
+  } else if (how == &quot;smart&quot;) {
+    indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text)
+    if (indentation == Pass || indentation &gt; 150) {
+      if (!aggressive) { return }
+      how = &quot;prev&quot;
</ins><span class="cx">     }
</span><del>-    if (how == &quot;prev&quot;) {
-      if (n &gt; doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
-      else indentation = 0;
-    } else if (how == &quot;add&quot;) {
-      indentation = curSpace + cm.options.indentUnit;
-    } else if (how == &quot;subtract&quot;) {
-      indentation = curSpace - cm.options.indentUnit;
-    } else if (typeof how == &quot;number&quot;) {
-      indentation = curSpace + how;
-    }
-    indentation = Math.max(0, indentation);
</del><ins>+  }
+  if (how == &quot;prev&quot;) {
+    if (n &gt; doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize) }
+    else { indentation = 0 }
+  } else if (how == &quot;add&quot;) {
+    indentation = curSpace + cm.options.indentUnit
+  } else if (how == &quot;subtract&quot;) {
+    indentation = curSpace - cm.options.indentUnit
+  } else if (typeof how == &quot;number&quot;) {
+    indentation = curSpace + how
+  }
+  indentation = Math.max(0, indentation)
</ins><span class="cx"> 
</span><del>-    var indentString = &quot;&quot;, pos = 0;
-    if (cm.options.indentWithTabs)
-      for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += &quot;\t&quot;;}
-    if (pos &lt; indentation) indentString += spaceStr(indentation - pos);
</del><ins>+  var indentString = &quot;&quot;, pos = 0
+  if (cm.options.indentWithTabs)
+    { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += &quot;\t&quot;} }
+  if (pos &lt; indentation) { indentString += spaceStr(indentation - pos) }
</ins><span class="cx"> 
</span><del>-    if (indentString != curSpaceString) {
-      replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), &quot;+input&quot;);
-      line.stateAfter = null;
-      return true;
-    } else {
-      // Ensure that, if the cursor was in the whitespace at the start
-      // of the line, it is moved to the end of that space.
-      for (var i = 0; i &lt; doc.sel.ranges.length; i++) {
-        var range = doc.sel.ranges[i];
-        if (range.head.line == n &amp;&amp; range.head.ch &lt; curSpaceString.length) {
-          var pos = Pos(n, curSpaceString.length);
-          replaceOneSelection(doc, i, new Range(pos, pos));
-          break;
-        }
</del><ins>+  if (indentString != curSpaceString) {
+    replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), &quot;+input&quot;)
+    line.stateAfter = null
+    return true
+  } else {
+    // Ensure that, if the cursor was in the whitespace at the start
+    // of the line, it is moved to the end of that space.
+    for (var i$1 = 0; i$1 &lt; doc.sel.ranges.length; i$1++) {
+      var range = doc.sel.ranges[i$1]
+      if (range.head.line == n &amp;&amp; range.head.ch &lt; curSpaceString.length) {
+        var pos$1 = Pos(n, curSpaceString.length)
+        replaceOneSelection(doc, i$1, new Range(pos$1, pos$1))
+        break
</ins><span class="cx">       }
</span><span class="cx">     }
</span><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // Utility for applying a change to a line by handle or number,
-  // returning the number and optionally registering the line as
-  // changed.
-  function changeLine(doc, handle, changeType, op) {
-    var no = handle, line = handle;
-    if (typeof handle == &quot;number&quot;) line = getLine(doc, clipLine(doc, handle));
-    else no = lineNo(handle);
-    if (no == null) return null;
-    if (op(line, no) &amp;&amp; doc.cm) regLineChange(doc.cm, no, changeType);
-    return line;
-  }
</del><ins>+// 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
</ins><span class="cx"> 
</span><del>-  // Helper for deleting text near the selection(s), used to implement
-  // backspace, delete, and similar functionality.
-  function deleteNearSelection(cm, compute) {
-    var ranges = cm.doc.sel.ranges, kill = [];
-    // Build up a set of ranges to kill first, merging overlapping
-    // ranges.
-    for (var i = 0; i &lt; ranges.length; i++) {
-      var toKill = compute(ranges[i]);
-      while (kill.length &amp;&amp; cmp(toKill.from, lst(kill).to) &lt;= 0) {
-        var replaced = kill.pop();
-        if (cmp(replaced.from, toKill.from) &lt; 0) {
-          toKill.from = replaced.from;
-          break;
-        }
</del><ins>+function setLastCopied(newLastCopied) {
+  lastCopied = newLastCopied
+}
+
+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 == &quot;paste&quot;
+  var textLines = splitLinesAuto(inserted), multiPaste = null
+  // When pasing N lines into N selections, insert one line per selection
+  if (paste &amp;&amp; sel.ranges.length &gt; 1) {
+    if (lastCopied &amp;&amp; lastCopied.text.join(&quot;\n&quot;) == inserted) {
+      if (sel.ranges.length % lastCopied.text.length == 0) {
+        multiPaste = []
+        for (var i = 0; i &lt; lastCopied.text.length; i++)
+          { multiPaste.push(doc.splitLines(lastCopied.text[i])) }
</ins><span class="cx">       }
</span><del>-      kill.push(toKill);
</del><ins>+    } else if (textLines.length == sel.ranges.length) {
+      multiPaste = map(textLines, function (l) { return [l]; })
</ins><span class="cx">     }
</span><del>-    // Next, remove those actual ranges.
-    runInOp(cm, function() {
-      for (var i = kill.length - 1; i &gt;= 0; i--)
-        replaceRange(cm.doc, &quot;&quot;, kill[i].from, kill[i].to, &quot;+delete&quot;);
-      ensureCursorVisible(cm);
-    });
</del><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // Used for horizontal relative motion. Dir is -1 or 1 (left or
-  // right), unit can be &quot;char&quot;, &quot;column&quot; (like char, but doesn't
-  // cross line boundaries), &quot;word&quot; (across next word), or &quot;group&quot; (to
-  // the start of next group of word or non-word-non-whitespace
-  // chars). The visually param controls whether, in right-to-left
-  // text, direction 1 means to move towards the next index in the
-  // string, or towards the character to the right of the current
-  // position. The resulting position will have a hitSide=true
-  // property if it reached the end of the document.
-  function findPosH(doc, pos, dir, unit, visually) {
-    var line = pos.line, ch = pos.ch, origDir = dir;
-    var lineObj = getLine(doc, line);
-    var possible = true;
-    function findNextLine() {
-      var l = line + dir;
-      if (l &lt; doc.first || l &gt;= doc.first + doc.size) return (possible = false);
-      line = l;
-      return lineObj = getLine(doc, l);
</del><ins>+  var updateInput
+  // Normal behavior is to insert the new text into every selection
+  for (var i$1 = sel.ranges.length - 1; i$1 &gt;= 0; i$1--) {
+    var range = sel.ranges[i$1]
+    var from = range.from(), to = range.to()
+    if (range.empty()) {
+      if (deleted &amp;&amp; deleted &gt; 0) // Handle deletion
+        { from = Pos(from.line, from.ch - deleted) }
+      else if (cm.state.overwrite &amp;&amp; !paste) // Handle overwrite
+        { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)) }
+      else if (lastCopied &amp;&amp; lastCopied.lineWise &amp;&amp; lastCopied.text.join(&quot;\n&quot;) == inserted)
+        { from = to = Pos(from.line, 0) }
</ins><span class="cx">     }
</span><del>-    function moveOnce(boundToLine) {
-      var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
-      if (next == null) {
-        if (!boundToLine &amp;&amp; findNextLine()) {
-          if (visually) ch = (dir &lt; 0 ? lineRight : lineLeft)(lineObj);
-          else ch = dir &lt; 0 ? lineObj.text.length : 0;
-        } else return (possible = false);
-      } else ch = next;
-      return true;
-    }
</del><ins>+    updateInput = cm.curOp.updateInput
+    var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
+                       origin: origin || (paste ? &quot;paste&quot; : cm.state.cutIncoming ? &quot;cut&quot; : &quot;+input&quot;)}
+    makeChange(cm.doc, changeEvent)
+    signalLater(cm, &quot;inputRead&quot;, cm, changeEvent)
+  }
+  if (inserted &amp;&amp; !paste)
+    { triggerElectric(cm, inserted) }
</ins><span class="cx"> 
</span><del>-    if (unit == &quot;char&quot;) moveOnce();
-    else if (unit == &quot;column&quot;) moveOnce(true);
-    else if (unit == &quot;word&quot; || unit == &quot;group&quot;) {
-      var sawType = null, group = unit == &quot;group&quot;;
-      var helper = doc.cm &amp;&amp; doc.cm.getHelper(pos, &quot;wordChars&quot;);
-      for (var first = true;; first = false) {
-        if (dir &lt; 0 &amp;&amp; !moveOnce(!first)) break;
-        var cur = lineObj.text.charAt(ch) || &quot;\n&quot;;
-        var type = isWordChar(cur, helper) ? &quot;w&quot;
-          : group &amp;&amp; cur == &quot;\n&quot; ? &quot;n&quot;
-          : !group || /\s/.test(cur) ? null
-          : &quot;p&quot;;
-        if (group &amp;&amp; !first &amp;&amp; !type) type = &quot;s&quot;;
-        if (sawType &amp;&amp; sawType != type) {
-          if (dir &lt; 0) {dir = 1; moveOnce();}
-          break;
-        }
</del><ins>+  ensureCursorVisible(cm)
+  cm.curOp.updateInput = updateInput
+  cm.curOp.typing = true
+  cm.state.pasteIncoming = cm.state.cutIncoming = false
+}
</ins><span class="cx"> 
</span><del>-        if (type) sawType = type;
-        if (dir &gt; 0 &amp;&amp; !moveOnce(!first)) break;
-      }
-    }
-    var result = skipAtomic(doc, Pos(line, ch), origDir, true);
-    if (!possible) result.hitSide = true;
-    return result;
</del><ins>+function handlePaste(e, cm) {
+  var pasted = e.clipboardData &amp;&amp; e.clipboardData.getData(&quot;Text&quot;)
+  if (pasted) {
+    e.preventDefault()
+    if (!cm.isReadOnly() &amp;&amp; !cm.options.disableInput)
+      { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, &quot;paste&quot;); }) }
+    return true
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // For relative vertical movement. Dir may be -1 or 1. Unit can be
-  // &quot;page&quot; or &quot;line&quot;. The resulting position will have a hitSide=true
-  // property if it reached the end of the document.
-  function findPosV(cm, pos, dir, unit) {
-    var doc = cm.doc, x = pos.left, y;
-    if (unit == &quot;page&quot;) {
-      var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
-      y = pos.top + dir * (pageSize - (dir &lt; 0 ? 1.5 : .5) * textHeight(cm.display));
-    } else if (unit == &quot;line&quot;) {
-      y = dir &gt; 0 ? pos.bottom + 3 : pos.top - 3;
</del><ins>+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 &gt;= 0; i--) {
+    var range = sel.ranges[i]
+    if (range.head.ch &gt; 100 || (i &amp;&amp; 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 &lt; mode.electricChars.length; j++)
+        { if (inserted.indexOf(mode.electricChars.charAt(j)) &gt; -1) {
+          indented = indentLine(cm, range.head.line, &quot;smart&quot;)
+          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, &quot;smart&quot;) }
</ins><span class="cx">     }
</span><del>-    for (;;) {
-      var target = coordsChar(cm, x, y);
-      if (!target.outside) break;
-      if (dir &lt; 0 ? y &lt;= 0 : y &gt;= doc.height) { target.hitSide = true; break; }
-      y += dir * 5;
-    }
-    return target;
</del><ins>+    if (indented) { signalLater(cm, &quot;electricInput&quot;, cm, range.head.line) }
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // EDITOR METHODS
</del><ins>+function copyableRanges(cm) {
+  var text = [], ranges = []
+  for (var i = 0; i &lt; 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}
+}
</ins><span class="cx"> 
</span><del>-  // The publicly visible API. Note that methodOp(f) means
-  // 'wrap f in an operation, performed on its `this` parameter'.
</del><ins>+function disableBrowserMagic(field, spellcheck) {
+  field.setAttribute(&quot;autocorrect&quot;, &quot;off&quot;)
+  field.setAttribute(&quot;autocapitalize&quot;, &quot;off&quot;)
+  field.setAttribute(&quot;spellcheck&quot;, !!spellcheck)
+}
</ins><span class="cx"> 
</span><del>-  // This is not the complete set of editor methods. Most of the
-  // methods defined on the Doc type are also injected into
-  // CodeMirror.prototype, for backwards compatibility and
-  // convenience.
</del><ins>+function hiddenTextarea() {
+  var te = elt(&quot;textarea&quot;, null, null, &quot;position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none&quot;)
+  var div = elt(&quot;div&quot;, [te], null, &quot;overflow: hidden; position: relative; width: 3px; height: 0px;&quot;)
+  // 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 = &quot;1000px&quot; }
+  else { te.setAttribute(&quot;wrap&quot;, &quot;off&quot;) }
+  // If border: 0; -- iOS fails to open keyboard (issue #1287)
+  if (ios) { te.style.border = &quot;1px solid black&quot; }
+  disableBrowserMagic(te)
+  return div
+}
</ins><span class="cx"> 
</span><ins>+// The publicly visible API. Note that methodOp(f) means
+// 'wrap f in an operation, performed on its `this` parameter'.
+
+// This is not the complete set of editor methods. Most of the
+// methods defined on the Doc type are also injected into
+// CodeMirror.prototype, for backwards compatibility and
+// convenience.
+
+function addEditorMethods(CodeMirror) {
+  var optionHandlers = CodeMirror.optionHandlers
+
+  var helpers = CodeMirror.helpers = {}
+
</ins><span class="cx">   CodeMirror.prototype = {
</span><span class="cx">     constructor: CodeMirror,
</span><del>-    focus: function(){window.focus(); this.display.input.focus();},
</del><ins>+    focus: function(){window.focus(); this.display.input.focus()},
</ins><span class="cx"> 
</span><span class="cx">     setOption: function(option, value) {
</span><del>-      var options = this.options, old = options[option];
-      if (options[option] == value &amp;&amp; option != &quot;mode&quot;) return;
-      options[option] = value;
</del><ins>+      var options = this.options, old = options[option]
+      if (options[option] == value &amp;&amp; option != &quot;mode&quot;) { return }
+      options[option] = value
</ins><span class="cx">       if (optionHandlers.hasOwnProperty(option))
</span><del>-        operation(this, optionHandlers[option])(this, value, old);
</del><ins>+        { operation(this, optionHandlers[option])(this, value, old) }
+      signal(this, &quot;optionChange&quot;, this, option)
</ins><span class="cx">     },
</span><span class="cx"> 
</span><del>-    getOption: function(option) {return this.options[option];},
-    getDoc: function() {return this.doc;},
</del><ins>+    getOption: function(option) {return this.options[option]},
+    getDoc: function() {return this.doc},
</ins><span class="cx"> 
</span><span class="cx">     addKeyMap: function(map, bottom) {
</span><del>-      this.state.keyMaps[bottom ? &quot;push&quot; : &quot;unshift&quot;](getKeyMap(map));
</del><ins>+      this.state.keyMaps[bottom ? &quot;push&quot; : &quot;unshift&quot;](getKeyMap(map))
</ins><span class="cx">     },
</span><span class="cx">     removeKeyMap: function(map) {
</span><del>-      var maps = this.state.keyMaps;
</del><ins>+      var maps = this.state.keyMaps
</ins><span class="cx">       for (var i = 0; i &lt; maps.length; ++i)
</span><del>-        if (maps[i] == map || maps[i].name == map) {
-          maps.splice(i, 1);
-          return true;
-        }
</del><ins>+        { if (maps[i] == map || maps[i].name == map) {
+          maps.splice(i, 1)
+          return true
+        } }
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     addOverlay: methodOp(function(spec, options) {
</span><del>-      var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
-      if (mode.startState) throw new Error(&quot;Overlays may not be stateful.&quot;);
-      this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options &amp;&amp; options.opaque});
-      this.state.modeGen++;
-      regChange(this);
</del><ins>+      var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec)
+      if (mode.startState) { throw new Error(&quot;Overlays may not be stateful.&quot;) }
+      insertSorted(this.state.overlays,
+                   {mode: mode, modeSpec: spec, opaque: options &amp;&amp; options.opaque,
+                    priority: (options &amp;&amp; options.priority) || 0},
+                   function (overlay) { return overlay.priority; })
+      this.state.modeGen++
+      regChange(this)
</ins><span class="cx">     }),
</span><span class="cx">     removeOverlay: methodOp(function(spec) {
</span><del>-      var overlays = this.state.overlays;
</del><ins>+      var this$1 = this;
+
+      var overlays = this.state.overlays
</ins><span class="cx">       for (var i = 0; i &lt; overlays.length; ++i) {
</span><del>-        var cur = overlays[i].modeSpec;
</del><ins>+        var cur = overlays[i].modeSpec
</ins><span class="cx">         if (cur == spec || typeof spec == &quot;string&quot; &amp;&amp; cur.name == spec) {
</span><del>-          overlays.splice(i, 1);
-          this.state.modeGen++;
-          regChange(this);
-          return;
</del><ins>+          overlays.splice(i, 1)
+          this$1.state.modeGen++
+          regChange(this$1)
+          return
</ins><span class="cx">         }
</span><span class="cx">       }
</span><span class="cx">     }),
</span><span class="lines">@@ -4885,28 +7684,30 @@
</span><span class="cx"> 
</span><span class="cx">     indentLine: methodOp(function(n, dir, aggressive) {
</span><span class="cx">       if (typeof dir != &quot;string&quot; &amp;&amp; typeof dir != &quot;number&quot;) {
</span><del>-        if (dir == null) dir = this.options.smartIndent ? &quot;smart&quot; : &quot;prev&quot;;
-        else dir = dir ? &quot;add&quot; : &quot;subtract&quot;;
</del><ins>+        if (dir == null) { dir = this.options.smartIndent ? &quot;smart&quot; : &quot;prev&quot; }
+        else { dir = dir ? &quot;add&quot; : &quot;subtract&quot; }
</ins><span class="cx">       }
</span><del>-      if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
</del><ins>+      if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive) }
</ins><span class="cx">     }),
</span><span class="cx">     indentSelection: methodOp(function(how) {
</span><del>-      var ranges = this.doc.sel.ranges, end = -1;
</del><ins>+      var this$1 = this;
+
+      var ranges = this.doc.sel.ranges, end = -1
</ins><span class="cx">       for (var i = 0; i &lt; ranges.length; i++) {
</span><del>-        var range = ranges[i];
</del><ins>+        var range = ranges[i]
</ins><span class="cx">         if (!range.empty()) {
</span><del>-          var from = range.from(), to = range.to();
-          var start = Math.max(end, from.line);
-          end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
</del><ins>+          var from = range.from(), to = range.to()
+          var start = Math.max(end, from.line)
+          end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1
</ins><span class="cx">           for (var j = start; j &lt; end; ++j)
</span><del>-            indentLine(this, j, how);
-          var newRanges = this.doc.sel.ranges;
</del><ins>+            { indentLine(this$1, j, how) }
+          var newRanges = this$1.doc.sel.ranges
</ins><span class="cx">           if (from.ch == 0 &amp;&amp; ranges.length == newRanges.length &amp;&amp; newRanges[i].from().ch &gt; 0)
</span><del>-            replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
</del><ins>+            { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll) }
</ins><span class="cx">         } else if (range.head.line &gt; end) {
</span><del>-          indentLine(this, range.head.line, how, true);
-          end = range.head.line;
-          if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
</del><ins>+          indentLine(this$1, range.head.line, how, true)
+          end = range.head.line
+          if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1) }
</ins><span class="cx">         }
</span><span class="cx">       }
</span><span class="cx">     }),
</span><span class="lines">@@ -4914,178 +7715,144 @@
</span><span class="cx">     // Fetch the parser token for a given character. Useful for hacks
</span><span class="cx">     // that want to inspect the mode state (say, for completion).
</span><span class="cx">     getTokenAt: function(pos, precise) {
</span><del>-      return takeToken(this, pos, precise);
</del><ins>+      return takeToken(this, pos, precise)
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     getLineTokens: function(line, precise) {
</span><del>-      return takeToken(this, Pos(line), precise, true);
</del><ins>+      return takeToken(this, Pos(line), precise, true)
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     getTokenTypeAt: function(pos) {
</span><del>-      pos = clipPos(this.doc, pos);
-      var styles = getLineStyles(this, getLine(this.doc, pos.line));
-      var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
-      var type;
-      if (ch == 0) type = styles[2];
-      else for (;;) {
-        var mid = (before + after) &gt;&gt; 1;
-        if ((mid ? styles[mid * 2 - 1] : 0) &gt;= ch) after = mid;
-        else if (styles[mid * 2 + 1] &lt; ch) before = mid + 1;
-        else { type = styles[mid * 2 + 2]; break; }
-      }
-      var cut = type ? type.indexOf(&quot;cm-overlay &quot;) : -1;
-      return cut &lt; 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
</del><ins>+      pos = clipPos(this.doc, pos)
+      var styles = getLineStyles(this, getLine(this.doc, pos.line))
+      var before = 0, after = (styles.length - 1) / 2, ch = pos.ch
+      var type
+      if (ch == 0) { type = styles[2] }
+      else { for (;;) {
+        var mid = (before + after) &gt;&gt; 1
+        if ((mid ? styles[mid * 2 - 1] : 0) &gt;= ch) { after = mid }
+        else if (styles[mid * 2 + 1] &lt; ch) { before = mid + 1 }
+        else { type = styles[mid * 2 + 2]; break }
+      } }
+      var cut = type ? type.indexOf(&quot;overlay &quot;) : -1
+      return cut &lt; 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     getModeAt: function(pos) {
</span><del>-      var mode = this.doc.mode;
-      if (!mode.innerMode) return mode;
-      return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
</del><ins>+      var mode = this.doc.mode
+      if (!mode.innerMode) { return mode }
+      return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     getHelper: function(pos, type) {
</span><del>-      return this.getHelpers(pos, type)[0];
</del><ins>+      return this.getHelpers(pos, type)[0]
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     getHelpers: function(pos, type) {
</span><del>-      var found = [];
-      if (!helpers.hasOwnProperty(type)) return found;
-      var help = helpers[type], mode = this.getModeAt(pos);
</del><ins>+      var this$1 = this;
+
+      var found = []
+      if (!helpers.hasOwnProperty(type)) { return found }
+      var help = helpers[type], mode = this.getModeAt(pos)
</ins><span class="cx">       if (typeof mode[type] == &quot;string&quot;) {
</span><del>-        if (help[mode[type]]) found.push(help[mode[type]]);
</del><ins>+        if (help[mode[type]]) { found.push(help[mode[type]]) }
</ins><span class="cx">       } else if (mode[type]) {
</span><span class="cx">         for (var i = 0; i &lt; mode[type].length; i++) {
</span><del>-          var val = help[mode[type][i]];
-          if (val) found.push(val);
</del><ins>+          var val = help[mode[type][i]]
+          if (val) { found.push(val) }
</ins><span class="cx">         }
</span><span class="cx">       } else if (mode.helperType &amp;&amp; help[mode.helperType]) {
</span><del>-        found.push(help[mode.helperType]);
</del><ins>+        found.push(help[mode.helperType])
</ins><span class="cx">       } else if (help[mode.name]) {
</span><del>-        found.push(help[mode.name]);
</del><ins>+        found.push(help[mode.name])
</ins><span class="cx">       }
</span><del>-      for (var i = 0; i &lt; help._global.length; i++) {
-        var cur = help._global[i];
-        if (cur.pred(mode, this) &amp;&amp; indexOf(found, cur.val) == -1)
-          found.push(cur.val);
</del><ins>+      for (var i$1 = 0; i$1 &lt; help._global.length; i$1++) {
+        var cur = help._global[i$1]
+        if (cur.pred(mode, this$1) &amp;&amp; indexOf(found, cur.val) == -1)
+          { found.push(cur.val) }
</ins><span class="cx">       }
</span><del>-      return found;
</del><ins>+      return found
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     getStateAfter: function(line, precise) {
</span><del>-      var doc = this.doc;
-      line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
-      return getStateBefore(this, line + 1, precise);
</del><ins>+      var doc = this.doc
+      line = clipLine(doc, line == null ? doc.first + doc.size - 1: line)
+      return getStateBefore(this, line + 1, precise)
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     cursorCoords: function(start, mode) {
</span><del>-      var pos, range = this.doc.sel.primary();
-      if (start == null) pos = range.head;
-      else if (typeof start == &quot;object&quot;) pos = clipPos(this.doc, start);
-      else pos = start ? range.from() : range.to();
-      return cursorCoords(this, pos, mode || &quot;page&quot;);
</del><ins>+      var pos, range = this.doc.sel.primary()
+      if (start == null) { pos = range.head }
+      else if (typeof start == &quot;object&quot;) { pos = clipPos(this.doc, start) }
+      else { pos = start ? range.from() : range.to() }
+      return cursorCoords(this, pos, mode || &quot;page&quot;)
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     charCoords: function(pos, mode) {
</span><del>-      return charCoords(this, clipPos(this.doc, pos), mode || &quot;page&quot;);
</del><ins>+      return charCoords(this, clipPos(this.doc, pos), mode || &quot;page&quot;)
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     coordsChar: function(coords, mode) {
</span><del>-      coords = fromCoordSystem(this, coords, mode || &quot;page&quot;);
-      return coordsChar(this, coords.left, coords.top);
</del><ins>+      coords = fromCoordSystem(this, coords, mode || &quot;page&quot;)
+      return coordsChar(this, coords.left, coords.top)
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     lineAtHeight: function(height, mode) {
</span><del>-      height = fromCoordSystem(this, {top: height, left: 0}, mode || &quot;page&quot;).top;
-      return lineAtHeight(this.doc, height + this.display.viewOffset);
</del><ins>+      height = fromCoordSystem(this, {top: height, left: 0}, mode || &quot;page&quot;).top
+      return lineAtHeight(this.doc, height + this.display.viewOffset)
</ins><span class="cx">     },
</span><del>-    heightAtLine: function(line, mode) {
-      var end = false, lineObj;
</del><ins>+    heightAtLine: function(line, mode, includeWidgets) {
+      var end = false, lineObj
</ins><span class="cx">       if (typeof line == &quot;number&quot;) {
</span><del>-        var last = this.doc.first + this.doc.size - 1;
-        if (line &lt; this.doc.first) line = this.doc.first;
-        else if (line &gt; last) { line = last; end = true; }
-        lineObj = getLine(this.doc, line);
</del><ins>+        var last = this.doc.first + this.doc.size - 1
+        if (line &lt; this.doc.first) { line = this.doc.first }
+        else if (line &gt; last) { line = last; end = true }
+        lineObj = getLine(this.doc, line)
</ins><span class="cx">       } else {
</span><del>-        lineObj = line;
</del><ins>+        lineObj = line
</ins><span class="cx">       }
</span><del>-      return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || &quot;page&quot;).top +
-        (end ? this.doc.height - heightAtLine(lineObj) : 0);
</del><ins>+      return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || &quot;page&quot;, includeWidgets).top +
+        (end ? this.doc.height - heightAtLine(lineObj) : 0)
</ins><span class="cx">     },
</span><span class="cx"> 
</span><del>-    defaultTextHeight: function() { return textHeight(this.display); },
-    defaultCharWidth: function() { return charWidth(this.display); },
</del><ins>+    defaultTextHeight: function() { return textHeight(this.display) },
+    defaultCharWidth: function() { return charWidth(this.display) },
</ins><span class="cx"> 
</span><del>-    setGutterMarker: methodOp(function(line, gutterID, value) {
-      return changeLine(this.doc, line, &quot;gutter&quot;, function(line) {
-        var markers = line.gutterMarkers || (line.gutterMarkers = {});
-        markers[gutterID] = value;
-        if (!value &amp;&amp; isEmpty(markers)) line.gutterMarkers = null;
-        return true;
-      });
-    }),
</del><ins>+    getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
</ins><span class="cx"> 
</span><del>-    clearGutter: methodOp(function(gutterID) {
-      var cm = this, doc = cm.doc, i = doc.first;
-      doc.iter(function(line) {
-        if (line.gutterMarkers &amp;&amp; line.gutterMarkers[gutterID]) {
-          line.gutterMarkers[gutterID] = null;
-          regLineChange(cm, i, &quot;gutter&quot;);
-          if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
-        }
-        ++i;
-      });
-    }),
-
-    lineInfo: function(line) {
-      if (typeof line == &quot;number&quot;) {
-        if (!isLine(this.doc, line)) return null;
-        var n = line;
-        line = getLine(this.doc, line);
-        if (!line) return null;
-      } else {
-        var n = lineNo(line);
-        if (n == null) return null;
-      }
-      return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
-              textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
-              widgets: line.widgets};
-    },
-
-    getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
-
</del><span class="cx">     addWidget: function(pos, node, scroll, vert, horiz) {
</span><del>-      var display = this.display;
-      pos = cursorCoords(this, clipPos(this.doc, pos));
-      var top = pos.bottom, left = pos.left;
-      node.style.position = &quot;absolute&quot;;
-      node.setAttribute(&quot;cm-ignore-events&quot;, &quot;true&quot;);
-      this.display.input.setUneditable(node);
-      display.sizer.appendChild(node);
</del><ins>+      var display = this.display
+      pos = cursorCoords(this, clipPos(this.doc, pos))
+      var top = pos.bottom, left = pos.left
+      node.style.position = &quot;absolute&quot;
+      node.setAttribute(&quot;cm-ignore-events&quot;, &quot;true&quot;)
+      this.display.input.setUneditable(node)
+      display.sizer.appendChild(node)
</ins><span class="cx">       if (vert == &quot;over&quot;) {
</span><del>-        top = pos.top;
</del><ins>+        top = pos.top
</ins><span class="cx">       } else if (vert == &quot;above&quot; || vert == &quot;near&quot;) {
</span><span class="cx">         var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
</span><del>-        hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
</del><ins>+        hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth)
</ins><span class="cx">         // Default to positioning above (if specified and possible); otherwise default to positioning below
</span><span class="cx">         if ((vert == 'above' || pos.bottom + node.offsetHeight &gt; vspace) &amp;&amp; pos.top &gt; node.offsetHeight)
</span><del>-          top = pos.top - node.offsetHeight;
</del><ins>+          { top = pos.top - node.offsetHeight }
</ins><span class="cx">         else if (pos.bottom + node.offsetHeight &lt;= vspace)
</span><del>-          top = pos.bottom;
</del><ins>+          { top = pos.bottom }
</ins><span class="cx">         if (left + node.offsetWidth &gt; hspace)
</span><del>-          left = hspace - node.offsetWidth;
</del><ins>+          { left = hspace - node.offsetWidth }
</ins><span class="cx">       }
</span><del>-      node.style.top = top + &quot;px&quot;;
-      node.style.left = node.style.right = &quot;&quot;;
</del><ins>+      node.style.top = top + &quot;px&quot;
+      node.style.left = node.style.right = &quot;&quot;
</ins><span class="cx">       if (horiz == &quot;right&quot;) {
</span><del>-        left = display.sizer.clientWidth - node.offsetWidth;
-        node.style.right = &quot;0px&quot;;
</del><ins>+        left = display.sizer.clientWidth - node.offsetWidth
+        node.style.right = &quot;0px&quot;
</ins><span class="cx">       } else {
</span><del>-        if (horiz == &quot;left&quot;) left = 0;
-        else if (horiz == &quot;middle&quot;) left = (display.sizer.clientWidth - node.offsetWidth) / 2;
-        node.style.left = left + &quot;px&quot;;
</del><ins>+        if (horiz == &quot;left&quot;) { left = 0 }
+        else if (horiz == &quot;middle&quot;) { left = (display.sizer.clientWidth - node.offsetWidth) / 2 }
+        node.style.left = left + &quot;px&quot;
</ins><span class="cx">       }
</span><span class="cx">       if (scroll)
</span><del>-        scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
</del><ins>+        { scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight) }
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     triggerOnKeyDown: methodOp(onKeyDown),
</span><span class="lines">@@ -5094,3725 +7861,1251 @@
</span><span class="cx"> 
</span><span class="cx">     execCommand: function(cmd) {
</span><span class="cx">       if (commands.hasOwnProperty(cmd))
</span><del>-        return commands[cmd].call(null, this);
</del><ins>+        { return commands[cmd].call(null, this) }
</ins><span class="cx">     },
</span><span class="cx"> 
</span><del>-    triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
</del><ins>+    triggerElectric: methodOp(function(text) { triggerElectric(this, text) }),
</ins><span class="cx"> 
</span><span class="cx">     findPosH: function(from, amount, unit, visually) {
</span><del>-      var dir = 1;
-      if (amount &lt; 0) { dir = -1; amount = -amount; }
-      for (var i = 0, cur = clipPos(this.doc, from); i &lt; amount; ++i) {
-        cur = findPosH(this.doc, cur, dir, unit, visually);
-        if (cur.hitSide) break;
</del><ins>+      var this$1 = this;
+
+      var dir = 1
+      if (amount &lt; 0) { dir = -1; amount = -amount }
+      var cur = clipPos(this.doc, from)
+      for (var i = 0; i &lt; amount; ++i) {
+        cur = findPosH(this$1.doc, cur, dir, unit, visually)
+        if (cur.hitSide) { break }
</ins><span class="cx">       }
</span><del>-      return cur;
</del><ins>+      return cur
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     moveH: methodOp(function(dir, unit) {
</span><del>-      var cm = this;
-      cm.extendSelectionsBy(function(range) {
-        if (cm.display.shift || cm.doc.extend || range.empty())
-          return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
</del><ins>+      var this$1 = this;
+
+      this.extendSelectionsBy(function (range) {
+        if (this$1.display.shift || this$1.doc.extend || range.empty())
+          { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
</ins><span class="cx">         else
</span><del>-          return dir &lt; 0 ? range.from() : range.to();
-      }, sel_move);
</del><ins>+          { return dir &lt; 0 ? range.from() : range.to() }
+      }, sel_move)
</ins><span class="cx">     }),
</span><span class="cx"> 
</span><span class="cx">     deleteH: methodOp(function(dir, unit) {
</span><del>-      var sel = this.doc.sel, doc = this.doc;
</del><ins>+      var sel = this.doc.sel, doc = this.doc
</ins><span class="cx">       if (sel.somethingSelected())
</span><del>-        doc.replaceSelection(&quot;&quot;, null, &quot;+delete&quot;);
</del><ins>+        { doc.replaceSelection(&quot;&quot;, null, &quot;+delete&quot;) }
</ins><span class="cx">       else
</span><del>-        deleteNearSelection(this, function(range) {
-          var other = findPosH(doc, range.head, dir, unit, false);
-          return dir &lt; 0 ? {from: other, to: range.head} : {from: range.head, to: other};
-        });
</del><ins>+        { deleteNearSelection(this, function (range) {
+          var other = findPosH(doc, range.head, dir, unit, false)
+          return dir &lt; 0 ? {from: other, to: range.head} : {from: range.head, to: other}
+        }) }
</ins><span class="cx">     }),
</span><span class="cx"> 
</span><span class="cx">     findPosV: function(from, amount, unit, goalColumn) {
</span><del>-      var dir = 1, x = goalColumn;
-      if (amount &lt; 0) { dir = -1; amount = -amount; }
-      for (var i = 0, cur = clipPos(this.doc, from); i &lt; amount; ++i) {
-        var coords = cursorCoords(this, cur, &quot;div&quot;);
-        if (x == null) x = coords.left;
-        else coords.left = x;
-        cur = findPosV(this, coords, dir, unit);
-        if (cur.hitSide) break;
</del><ins>+      var this$1 = this;
+
+      var dir = 1, x = goalColumn
+      if (amount &lt; 0) { dir = -1; amount = -amount }
+      var cur = clipPos(this.doc, from)
+      for (var i = 0; i &lt; amount; ++i) {
+        var coords = cursorCoords(this$1, cur, &quot;div&quot;)
+        if (x == null) { x = coords.left }
+        else { coords.left = x }
+        cur = findPosV(this$1, coords, dir, unit)
+        if (cur.hitSide) { break }
</ins><span class="cx">       }
</span><del>-      return cur;
</del><ins>+      return cur
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     moveV: methodOp(function(dir, unit) {
</span><del>-      var cm = this, doc = this.doc, goals = [];
-      var collapse = !cm.display.shift &amp;&amp; !doc.extend &amp;&amp; doc.sel.somethingSelected();
-      doc.extendSelectionsBy(function(range) {
</del><ins>+      var this$1 = this;
+
+      var doc = this.doc, goals = []
+      var collapse = !this.display.shift &amp;&amp; !doc.extend &amp;&amp; doc.sel.somethingSelected()
+      doc.extendSelectionsBy(function (range) {
</ins><span class="cx">         if (collapse)
</span><del>-          return dir &lt; 0 ? range.from() : range.to();
-        var headPos = cursorCoords(cm, range.head, &quot;div&quot;);
-        if (range.goalColumn != null) headPos.left = range.goalColumn;
-        goals.push(headPos.left);
-        var pos = findPosV(cm, headPos, dir, unit);
</del><ins>+          { return dir &lt; 0 ? range.from() : range.to() }
+        var headPos = cursorCoords(this$1, range.head, &quot;div&quot;)
+        if (range.goalColumn != null) { headPos.left = range.goalColumn }
+        goals.push(headPos.left)
+        var pos = findPosV(this$1, headPos, dir, unit)
</ins><span class="cx">         if (unit == &quot;page&quot; &amp;&amp; range == doc.sel.primary())
</span><del>-          addToScrollPos(cm, null, charCoords(cm, pos, &quot;div&quot;).top - headPos.top);
-        return pos;
-      }, sel_move);
-      if (goals.length) for (var i = 0; i &lt; doc.sel.ranges.length; i++)
-        doc.sel.ranges[i].goalColumn = goals[i];
</del><ins>+          { addToScrollPos(this$1, null, charCoords(this$1, pos, &quot;div&quot;).top - headPos.top) }
+        return pos
+      }, sel_move)
+      if (goals.length) { for (var i = 0; i &lt; doc.sel.ranges.length; i++)
+        { doc.sel.ranges[i].goalColumn = goals[i] } }
</ins><span class="cx">     }),
</span><span class="cx"> 
</span><span class="cx">     // Find the word at the given position (as returned by coordsChar).
</span><span class="cx">     findWordAt: function(pos) {
</span><del>-      var doc = this.doc, line = getLine(doc, pos.line).text;
-      var start = pos.ch, end = pos.ch;
</del><ins>+      var doc = this.doc, line = getLine(doc, pos.line).text
+      var start = pos.ch, end = pos.ch
</ins><span class="cx">       if (line) {
</span><del>-        var helper = this.getHelper(pos, &quot;wordChars&quot;);
-        if ((pos.xRel &lt; 0 || end == line.length) &amp;&amp; start) --start; else ++end;
-        var startChar = line.charAt(start);
</del><ins>+        var helper = this.getHelper(pos, &quot;wordChars&quot;)
+        if ((pos.xRel &lt; 0 || end == line.length) &amp;&amp; start) { --start; } else { ++end }
+        var startChar = line.charAt(start)
</ins><span class="cx">         var check = isWordChar(startChar, helper)
</span><del>-          ? function(ch) { return isWordChar(ch, helper); }
-          : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
-          : function(ch) {return !/\s/.test(ch) &amp;&amp; !isWordChar(ch);};
-        while (start &gt; 0 &amp;&amp; check(line.charAt(start - 1))) --start;
-        while (end &lt; line.length &amp;&amp; check(line.charAt(end))) ++end;
</del><ins>+          ? function (ch) { return isWordChar(ch, helper); }
+          : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
+          : function (ch) { return (!/\s/.test(ch) &amp;&amp; !isWordChar(ch)); }
+        while (start &gt; 0 &amp;&amp; check(line.charAt(start - 1))) { --start }
+        while (end &lt; line.length &amp;&amp; check(line.charAt(end))) { ++end }
</ins><span class="cx">       }
</span><del>-      return new Range(Pos(pos.line, start), Pos(pos.line, end));
</del><ins>+      return new Range(Pos(pos.line, start), Pos(pos.line, end))
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     toggleOverwrite: function(value) {
</span><del>-      if (value != null &amp;&amp; value == this.state.overwrite) return;
</del><ins>+      if (value != null &amp;&amp; value == this.state.overwrite) { return }
</ins><span class="cx">       if (this.state.overwrite = !this.state.overwrite)
</span><del>-        addClass(this.display.cursorDiv, &quot;CodeMirror-overwrite&quot;);
</del><ins>+        { addClass(this.display.cursorDiv, &quot;CodeMirror-overwrite&quot;) }
</ins><span class="cx">       else
</span><del>-        rmClass(this.display.cursorDiv, &quot;CodeMirror-overwrite&quot;);
</del><ins>+        { rmClass(this.display.cursorDiv, &quot;CodeMirror-overwrite&quot;) }
</ins><span class="cx"> 
</span><del>-      signal(this, &quot;overwriteToggle&quot;, this, this.state.overwrite);
</del><ins>+      signal(this, &quot;overwriteToggle&quot;, this, this.state.overwrite)
</ins><span class="cx">     },
</span><del>-    hasFocus: function() { return this.display.input.getField() == activeElt(); },
</del><ins>+    hasFocus: function() { return this.display.input.getField() == activeElt() },
+    isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
</ins><span class="cx"> 
</span><span class="cx">     scrollTo: methodOp(function(x, y) {
</span><del>-      if (x != null || y != null) resolveScrollToPos(this);
-      if (x != null) this.curOp.scrollLeft = x;
-      if (y != null) this.curOp.scrollTop = y;
</del><ins>+      if (x != null || y != null) { resolveScrollToPos(this) }
+      if (x != null) { this.curOp.scrollLeft = x }
+      if (y != null) { this.curOp.scrollTop = y }
</ins><span class="cx">     }),
</span><span class="cx">     getScrollInfo: function() {
</span><del>-      var scroller = this.display.scroller;
</del><ins>+      var scroller = this.display.scroller
</ins><span class="cx">       return {left: scroller.scrollLeft, top: scroller.scrollTop,
</span><span class="cx">               height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
</span><span class="cx">               width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
</span><del>-              clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
</del><ins>+              clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     scrollIntoView: methodOp(function(range, margin) {
</span><span class="cx">       if (range == null) {
</span><del>-        range = {from: this.doc.sel.primary().head, to: null};
-        if (margin == null) margin = this.options.cursorScrollMargin;
</del><ins>+        range = {from: this.doc.sel.primary().head, to: null}
+        if (margin == null) { margin = this.options.cursorScrollMargin }
</ins><span class="cx">       } else if (typeof range == &quot;number&quot;) {
</span><del>-        range = {from: Pos(range, 0), to: null};
</del><ins>+        range = {from: Pos(range, 0), to: null}
</ins><span class="cx">       } else if (range.from == null) {
</span><del>-        range = {from: range, to: null};
</del><ins>+        range = {from: range, to: null}
</ins><span class="cx">       }
</span><del>-      if (!range.to) range.to = range.from;
-      range.margin = margin || 0;
</del><ins>+      if (!range.to) { range.to = range.from }
+      range.margin = margin || 0
</ins><span class="cx"> 
</span><span class="cx">       if (range.from.line != null) {
</span><del>-        resolveScrollToPos(this);
-        this.curOp.scrollToPos = range;
</del><ins>+        resolveScrollToPos(this)
+        this.curOp.scrollToPos = range
</ins><span class="cx">       } else {
</span><span class="cx">         var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
</span><span class="cx">                                       Math.min(range.from.top, range.to.top) - range.margin,
</span><span class="cx">                                       Math.max(range.from.right, range.to.right),
</span><del>-                                      Math.max(range.from.bottom, range.to.bottom) + range.margin);
-        this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
</del><ins>+                                      Math.max(range.from.bottom, range.to.bottom) + range.margin)
+        this.scrollTo(sPos.scrollLeft, sPos.scrollTop)
</ins><span class="cx">       }
</span><span class="cx">     }),
</span><span class="cx"> 
</span><span class="cx">     setSize: methodOp(function(width, height) {
</span><del>-      var cm = this;
-      function interpret(val) {
-        return typeof val == &quot;number&quot; || /^\d+$/.test(String(val)) ? val + &quot;px&quot; : val;
-      }
-      if (width != null) cm.display.wrapper.style.width = interpret(width);
-      if (height != null) cm.display.wrapper.style.height = interpret(height);
-      if (cm.options.lineWrapping) clearLineMeasurementCache(this);
-      var lineNo = cm.display.viewFrom;
-      cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
-        if (line.widgets) for (var i = 0; i &lt; line.widgets.length; i++)
-          if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, &quot;widget&quot;); break; }
-        ++lineNo;
-      });
-      cm.curOp.forceUpdate = true;
-      signal(cm, &quot;refresh&quot;, this);
</del><ins>+      var this$1 = this;
+
+      var interpret = function (val) { return typeof val == &quot;number&quot; || /^\d+$/.test(String(val)) ? val + &quot;px&quot; : val; }
+      if (width != null) { this.display.wrapper.style.width = interpret(width) }
+      if (height != null) { this.display.wrapper.style.height = interpret(height) }
+      if (this.options.lineWrapping) { clearLineMeasurementCache(this) }
+      var lineNo = this.display.viewFrom
+      this.doc.iter(lineNo, this.display.viewTo, function (line) {
+        if (line.widgets) { for (var i = 0; i &lt; line.widgets.length; i++)
+          { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, &quot;widget&quot;); break } } }
+        ++lineNo
+      })
+      this.curOp.forceUpdate = true
+      signal(this, &quot;refresh&quot;, this)
</ins><span class="cx">     }),
</span><span class="cx"> 
</span><del>-    operation: function(f){return runInOp(this, f);},
</del><ins>+    operation: function(f){return runInOp(this, f)},
</ins><span class="cx"> 
</span><span class="cx">     refresh: methodOp(function() {
</span><del>-      var oldHeight = this.display.cachedTextHeight;
-      regChange(this);
-      this.curOp.forceUpdate = true;
-      clearCaches(this);
-      this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
-      updateGutterSpace(this);
</del><ins>+      var oldHeight = this.display.cachedTextHeight
+      regChange(this)
+      this.curOp.forceUpdate = true
+      clearCaches(this)
+      this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop)
+      updateGutterSpace(this)
</ins><span class="cx">       if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) &gt; .5)
</span><del>-        estimateLineHeights(this);
-      signal(this, &quot;refresh&quot;, this);
</del><ins>+        { estimateLineHeights(this) }
+      signal(this, &quot;refresh&quot;, this)
</ins><span class="cx">     }),
</span><span class="cx"> 
</span><span class="cx">     swapDoc: methodOp(function(doc) {
</span><del>-      var old = this.doc;
-      old.cm = null;
-      attachDoc(this, doc);
-      clearCaches(this);
-      this.display.input.reset();
-      this.scrollTo(doc.scrollLeft, doc.scrollTop);
-      this.curOp.forceScroll = true;
-      signalLater(this, &quot;swapDoc&quot;, this, old);
-      return old;
</del><ins>+      var old = this.doc
+      old.cm = null
+      attachDoc(this, doc)
+      clearCaches(this)
+      this.display.input.reset()
+      this.scrollTo(doc.scrollLeft, doc.scrollTop)
+      this.curOp.forceScroll = true
+      signalLater(this, &quot;swapDoc&quot;, this, old)
+      return old
</ins><span class="cx">     }),
</span><span class="cx"> 
</span><del>-    getInputField: function(){return this.display.input.getField();},
-    getWrapperElement: function(){return this.display.wrapper;},
-    getScrollerElement: function(){return this.display.scroller;},
-    getGutterElement: function(){return this.display.gutters;}
-  };
-  eventMixin(CodeMirror);
-
-  // OPTION DEFAULTS
-
-  // The default configuration options.
-  var defaults = CodeMirror.defaults = {};
-  // Functions to run when options are changed.
-  var optionHandlers = CodeMirror.optionHandlers = {};
-
-  function option(name, deflt, handle, notOnInit) {
-    CodeMirror.defaults[name] = deflt;
-    if (handle) optionHandlers[name] =
-      notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
</del><ins>+    getInputField: function(){return this.display.input.getField()},
+    getWrapperElement: function(){return this.display.wrapper},
+    getScrollerElement: function(){return this.display.scroller},
+    getGutterElement: function(){return this.display.gutters}
</ins><span class="cx">   }
</span><ins>+  eventMixin(CodeMirror)
</ins><span class="cx"> 
</span><del>-  // Passed to option handlers when there is no old value.
-  var Init = CodeMirror.Init = {toString: function(){return &quot;CodeMirror.Init&quot;;}};
-
-  // These two are, on init, called from the constructor because they
-  // have to be initialized before the editor can start at all.
-  option(&quot;value&quot;, &quot;&quot;, function(cm, val) {
-    cm.setValue(val);
-  }, true);
-  option(&quot;mode&quot;, null, function(cm, val) {
-    cm.doc.modeOption = val;
-    loadMode(cm);
-  }, true);
-
-  option(&quot;indentUnit&quot;, 2, loadMode, true);
-  option(&quot;indentWithTabs&quot;, false);
-  option(&quot;smartIndent&quot;, true);
-  option(&quot;tabSize&quot;, 4, function(cm) {
-    resetModeState(cm);
-    clearCaches(cm);
-    regChange(cm);
-  }, true);
-  option(&quot;lineSeparator&quot;, null, function(cm, val) {
-    cm.doc.lineSep = val;
-    if (!val) return;
-    var newBreaks = [], lineNo = cm.doc.first;
-    cm.doc.iter(function(line) {
-      for (var pos = 0;;) {
-        var found = line.text.indexOf(val, pos);
-        if (found == -1) break;
-        pos = found + val.length;
-        newBreaks.push(Pos(lineNo, found));
-      }
-      lineNo++;
-    });
-    for (var i = newBreaks.length - 1; i &gt;= 0; i--)
-      replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
-  });
-  option(&quot;specialChars&quot;, /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
-    cm.state.specialChars = new RegExp(val.source + (val.test(&quot;\t&quot;) ? &quot;&quot; : &quot;|\t&quot;), &quot;g&quot;);
-    if (old != CodeMirror.Init) cm.refresh();
-  });
-  option(&quot;specialCharPlaceholder&quot;, defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
-  option(&quot;electricChars&quot;, true);
-  option(&quot;inputStyle&quot;, mobile ? &quot;contenteditable&quot; : &quot;textarea&quot;, function() {
-    throw new Error(&quot;inputStyle can not (yet) be changed in a running editor&quot;); // FIXME
-  }, true);
-  option(&quot;rtlMoveVisually&quot;, !windows);
-  option(&quot;wholeLineUpdateBefore&quot;, true);
-
-  option(&quot;theme&quot;, &quot;default&quot;, function(cm) {
-    themeChanged(cm);
-    guttersChanged(cm);
-  }, true);
-  option(&quot;keyMap&quot;, &quot;default&quot;, function(cm, val, old) {
-    var next = getKeyMap(val);
-    var prev = old != CodeMirror.Init &amp;&amp; getKeyMap(old);
-    if (prev &amp;&amp; prev.detach) prev.detach(cm, next);
-    if (next.attach) next.attach(cm, prev || null);
-  });
-  option(&quot;extraKeys&quot;, null);
-
-  option(&quot;lineWrapping&quot;, false, wrappingChanged, true);
-  option(&quot;gutters&quot;, [], function(cm) {
-    setGuttersForLineNumbers(cm.options);
-    guttersChanged(cm);
-  }, true);
-  option(&quot;fixedGutter&quot;, true, function(cm, val) {
-    cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + &quot;px&quot; : &quot;0&quot;;
-    cm.refresh();
-  }, true);
-  option(&quot;coverGutterNextToScrollbar&quot;, false, function(cm) {updateScrollbars(cm);}, true);
-  option(&quot;scrollbarStyle&quot;, &quot;native&quot;, function(cm) {
-    initScrollbars(cm);
-    updateScrollbars(cm);
-    cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
-    cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
-  }, true);
-  option(&quot;lineNumbers&quot;, false, function(cm) {
-    setGuttersForLineNumbers(cm.options);
-    guttersChanged(cm);
-  }, true);
-  option(&quot;firstLineNumber&quot;, 1, guttersChanged, true);
-  option(&quot;lineNumberFormatter&quot;, function(integer) {return integer;}, guttersChanged, true);
-  option(&quot;showCursorWhenSelecting&quot;, false, updateSelection, true);
-
-  option(&quot;resetSelectionOnContextMenu&quot;, true);
-  option(&quot;lineWiseCopyCut&quot;, true);
-
-  option(&quot;readOnly&quot;, false, function(cm, val) {
-    if (val == &quot;nocursor&quot;) {
-      onBlur(cm);
-      cm.display.input.blur();
-      cm.display.disabled = true;
-    } else {
-      cm.display.disabled = false;
-      if (!val) cm.display.input.reset();
-    }
-  });
-  option(&quot;disableInput&quot;, false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
-  option(&quot;dragDrop&quot;, true, dragDropChanged);
-
-  option(&quot;cursorBlinkRate&quot;, 530);
-  option(&quot;cursorScrollMargin&quot;, 0);
-  option(&quot;cursorHeight&quot;, 1, updateSelection, true);
-  option(&quot;singleCursorHeightPerLine&quot;, true, updateSelection, true);
-  option(&quot;workTime&quot;, 100);
-  option(&quot;workDelay&quot;, 100);
-  option(&quot;flattenSpans&quot;, true, resetModeState, true);
-  option(&quot;addModeClass&quot;, false, resetModeState, true);
-  option(&quot;pollInterval&quot;, 100);
-  option(&quot;undoDepth&quot;, 200, function(cm, val){cm.doc.history.undoDepth = val;});
-  option(&quot;historyEventDelay&quot;, 1250);
-  option(&quot;viewportMargin&quot;, 10, function(cm){cm.refresh();}, true);
-  option(&quot;maxHighlightLength&quot;, 10000, resetModeState, true);
-  option(&quot;moveInputWithCursor&quot;, true, function(cm, val) {
-    if (!val) cm.display.input.resetPosition();
-  });
-
-  option(&quot;tabindex&quot;, null, function(cm, val) {
-    cm.display.input.getField().tabIndex = val || &quot;&quot;;
-  });
-  option(&quot;autofocus&quot;, null);
-
-  // MODE DEFINITION AND QUERYING
-
-  // Known modes, by name and by MIME
-  var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.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.)
-  CodeMirror.defineMode = function(name, mode) {
-    if (!CodeMirror.defaults.mode &amp;&amp; name != &quot;null&quot;) CodeMirror.defaults.mode = name;
-    if (arguments.length &gt; 2)
-      mode.dependencies = Array.prototype.slice.call(arguments, 2);
-    modes[name] = mode;
-  };
-
-  CodeMirror.defineMIME = function(mime, spec) {
-    mimeModes[mime] = spec;
-  };
-
-  // Given a MIME type, a {name, ...options} config object, or a name
-  // string, return a mode config object.
-  CodeMirror.resolveMode = function(spec) {
-    if (typeof spec == &quot;string&quot; &amp;&amp; mimeModes.hasOwnProperty(spec)) {
-      spec = mimeModes[spec];
-    } else if (spec &amp;&amp; typeof spec.name == &quot;string&quot; &amp;&amp; mimeModes.hasOwnProperty(spec.name)) {
-      var found = mimeModes[spec.name];
-      if (typeof found == &quot;string&quot;) found = {name: found};
-      spec = createObj(found, spec);
-      spec.name = found.name;
-    } else if (typeof spec == &quot;string&quot; &amp;&amp; /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
-      return CodeMirror.resolveMode(&quot;application/xml&quot;);
-    }
-    if (typeof spec == &quot;string&quot;) return {name: spec};
-    else return spec || {name: &quot;null&quot;};
-  };
-
-  // Given a mode spec (anything that resolveMode accepts), find and
-  // initialize an actual mode object.
-  CodeMirror.getMode = function(options, spec) {
-    var spec = CodeMirror.resolveMode(spec);
-    var mfactory = modes[spec.name];
-    if (!mfactory) return CodeMirror.getMode(options, &quot;text/plain&quot;);
-    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[&quot;_&quot; + prop] = modeObj[prop];
-        modeObj[prop] = exts[prop];
-      }
-    }
-    modeObj.name = spec.name;
-    if (spec.helperType) modeObj.helperType = spec.helperType;
-    if (spec.modeProps) for (var prop in spec.modeProps)
-      modeObj[prop] = spec.modeProps[prop];
-
-    return modeObj;
-  };
-
-  // Minimal default mode.
-  CodeMirror.defineMode(&quot;null&quot;, function() {
-    return {token: function(stream) {stream.skipToEnd();}};
-  });
-  CodeMirror.defineMIME(&quot;text/plain&quot;, &quot;null&quot;);
-
-  // This can be used to attach properties to mode objects from
-  // outside the actual mode definition.
-  var modeExtensions = CodeMirror.modeExtensions = {};
-  CodeMirror.extendMode = function(mode, properties) {
-    var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
-    copyObj(properties, exts);
-  };
-
-  // EXTENSIONS
-
-  CodeMirror.defineExtension = function(name, func) {
-    CodeMirror.prototype[name] = func;
-  };
-  CodeMirror.defineDocExtension = function(name, func) {
-    Doc.prototype[name] = func;
-  };
-  CodeMirror.defineOption = option;
-
-  var initHooks = [];
-  CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
-
-  var helpers = CodeMirror.helpers = {};
</del><span class="cx">   CodeMirror.registerHelper = function(type, name, value) {
</span><del>-    if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
-    helpers[type][name] = value;
-  };
</del><ins>+    if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []} }
+    helpers[type][name] = value
+  }
</ins><span class="cx">   CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
</span><del>-    CodeMirror.registerHelper(type, name, value);
-    helpers[type]._global.push({pred: predicate, val: value});
-  };
</del><ins>+    CodeMirror.registerHelper(type, name, value)
+    helpers[type]._global.push({pred: predicate, val: value})
+  }
+}
</ins><span class="cx"> 
</span><del>-  // MODE STATE HANDLING
</del><ins>+// Used for horizontal relative motion. Dir is -1 or 1 (left or
+// right), unit can be &quot;char&quot;, &quot;column&quot; (like char, but doesn't
+// cross line boundaries), &quot;word&quot; (across next word), or &quot;group&quot; (to
+// the start of next group of word or non-word-non-whitespace
+// chars). The visually param controls whether, in right-to-left
+// text, direction 1 means to move towards the next index in the
+// string, or towards the character to the right of the current
+// position. The resulting position will have a hitSide=true
+// property if it reached the end of the document.
+function findPosH(doc, pos, dir, unit, visually) {
+  var line = pos.line, ch = pos.ch, origDir = dir
+  var lineObj = getLine(doc, line)
+  function findNextLine() {
+    var l = line + dir
+    if (l &lt; doc.first || l &gt;= doc.first + doc.size) { return false }
+    line = l
+    return lineObj = getLine(doc, l)
+  }
+  function moveOnce(boundToLine) {
+    var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true)
+    if (next == null) {
+      if (!boundToLine &amp;&amp; findNextLine()) {
+        if (visually) { ch = (dir &lt; 0 ? lineRight : lineLeft)(lineObj) }
+        else { ch = dir &lt; 0 ? lineObj.text.length : 0 }
+      } else { return false }
+    } else { ch = next }
+    return true
+  }
</ins><span class="cx"> 
</span><del>-  // Utility functions for working with state. Exported because nested
-  // modes need to do this for their inner modes.
-
-  var copyState = CodeMirror.copyState = function(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;
-  };
-
-  var startState = CodeMirror.startState = function(mode, a1, a2) {
-    return mode.startState ? mode.startState(a1, a2) : true;
-  };
-
-  // Given a mode and a state (for that mode), find the inner mode and
-  // state at the position that the state refers to.
-  CodeMirror.innerMode = function(mode, state) {
-    while (mode.innerMode) {
-      var info = mode.innerMode(state);
-      if (!info || info.mode == mode) break;
-      state = info.state;
-      mode = info.mode;
-    }
-    return info || {mode: mode, state: state};
-  };
-
-  // STANDARD COMMANDS
-
-  // Commands are parameter-less actions that can be performed on an
-  // editor, mostly used for keybindings.
-  var commands = CodeMirror.commands = {
-    selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
-    singleSelection: function(cm) {
-      cm.setSelection(cm.getCursor(&quot;anchor&quot;), cm.getCursor(&quot;head&quot;), sel_dontScroll);
-    },
-    killLine: function(cm) {
-      deleteNearSelection(cm, function(range) {
-        if (range.empty()) {
-          var len = getLine(cm.doc, range.head.line).text.length;
-          if (range.head.ch == len &amp;&amp; range.head.line &lt; cm.lastLine())
-            return {from: range.head, to: Pos(range.head.line + 1, 0)};
-          else
-            return {from: range.head, to: Pos(range.head.line, len)};
-        } else {
-          return {from: range.from(), to: range.to()};
-        }
-      });
-    },
-    deleteLine: function(cm) {
-      deleteNearSelection(cm, function(range) {
-        return {from: Pos(range.from().line, 0),
-                to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
-      });
-    },
-    delLineLeft: function(cm) {
-      deleteNearSelection(cm, function(range) {
-        return {from: Pos(range.from().line, 0), to: range.from()};
-      });
-    },
-    delWrappedLineLeft: function(cm) {
-      deleteNearSelection(cm, function(range) {
-        var top = cm.charCoords(range.head, &quot;div&quot;).top + 5;
-        var leftPos = cm.coordsChar({left: 0, top: top}, &quot;div&quot;);
-        return {from: leftPos, to: range.from()};
-      });
-    },
-    delWrappedLineRight: function(cm) {
-      deleteNearSelection(cm, function(range) {
-        var top = cm.charCoords(range.head, &quot;div&quot;).top + 5;
-        var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, &quot;div&quot;);
-        return {from: range.from(), to: rightPos };
-      });
-    },
-    undo: function(cm) {cm.undo();},
-    redo: function(cm) {cm.redo();},
-    undoSelection: function(cm) {cm.undoSelection();},
-    redoSelection: function(cm) {cm.redoSelection();},
-    goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
-    goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
-    goLineStart: function(cm) {
-      cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
-                            {origin: &quot;+move&quot;, bias: 1});
-    },
-    goLineStartSmart: function(cm) {
-      cm.extendSelectionsBy(function(range) {
-        return lineStartSmart(cm, range.head);
-      }, {origin: &quot;+move&quot;, bias: 1});
-    },
-    goLineEnd: function(cm) {
-      cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
-                            {origin: &quot;+move&quot;, bias: -1});
-    },
-    goLineRight: function(cm) {
-      cm.extendSelectionsBy(function(range) {
-        var top = cm.charCoords(range.head, &quot;div&quot;).top + 5;
-        return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, &quot;div&quot;);
-      }, sel_move);
-    },
-    goLineLeft: function(cm) {
-      cm.extendSelectionsBy(function(range) {
-        var top = cm.charCoords(range.head, &quot;div&quot;).top + 5;
-        return cm.coordsChar({left: 0, top: top}, &quot;div&quot;);
-      }, sel_move);
-    },
-    goLineLeftSmart: function(cm) {
-      cm.extendSelectionsBy(function(range) {
-        var top = cm.charCoords(range.head, &quot;div&quot;).top + 5;
-        var pos = cm.coordsChar({left: 0, top: top}, &quot;div&quot;);
-        if (pos.ch &lt; cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
-        return pos;
-      }, sel_move);
-    },
-    goLineUp: function(cm) {cm.moveV(-1, &quot;line&quot;);},
-    goLineDown: function(cm) {cm.moveV(1, &quot;line&quot;);},
-    goPageUp: function(cm) {cm.moveV(-1, &quot;page&quot;);},
-    goPageDown: function(cm) {cm.moveV(1, &quot;page&quot;);},
-    goCharLeft: function(cm) {cm.moveH(-1, &quot;char&quot;);},
-    goCharRight: function(cm) {cm.moveH(1, &quot;char&quot;);},
-    goColumnLeft: function(cm) {cm.moveH(-1, &quot;column&quot;);},
-    goColumnRight: function(cm) {cm.moveH(1, &quot;column&quot;);},
-    goWordLeft: function(cm) {cm.moveH(-1, &quot;word&quot;);},
-    goGroupRight: function(cm) {cm.moveH(1, &quot;group&quot;);},
-    goGroupLeft: function(cm) {cm.moveH(-1, &quot;group&quot;);},
-    goWordRight: function(cm) {cm.moveH(1, &quot;word&quot;);},
-    delCharBefore: function(cm) {cm.deleteH(-1, &quot;char&quot;);},
-    delCharAfter: function(cm) {cm.deleteH(1, &quot;char&quot;);},
-    delWordBefore: function(cm) {cm.deleteH(-1, &quot;word&quot;);},
-    delWordAfter: function(cm) {cm.deleteH(1, &quot;word&quot;);},
-    delGroupBefore: function(cm) {cm.deleteH(-1, &quot;group&quot;);},
-    delGroupAfter: function(cm) {cm.deleteH(1, &quot;group&quot;);},
-    indentAuto: function(cm) {cm.indentSelection(&quot;smart&quot;);},
-    indentMore: function(cm) {cm.indentSelection(&quot;add&quot;);},
-    indentLess: function(cm) {cm.indentSelection(&quot;subtract&quot;);},
-    insertTab: function(cm) {cm.replaceSelection(&quot;\t&quot;);},
-    insertSoftTab: function(cm) {
-      var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
-      for (var i = 0; i &lt; ranges.length; i++) {
-        var pos = ranges[i].from();
-        var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
-        spaces.push(new Array(tabSize - col % tabSize + 1).join(&quot; &quot;));
</del><ins>+  if (unit == &quot;char&quot;) {
+    moveOnce()
+  } else if (unit == &quot;column&quot;) {
+    moveOnce(true)
+  } else if (unit == &quot;word&quot; || unit == &quot;group&quot;) {
+    var sawType = null, group = unit == &quot;group&quot;
+    var helper = doc.cm &amp;&amp; doc.cm.getHelper(pos, &quot;wordChars&quot;)
+    for (var first = true;; first = false) {
+      if (dir &lt; 0 &amp;&amp; !moveOnce(!first)) { break }
+      var cur = lineObj.text.charAt(ch) || &quot;\n&quot;
+      var type = isWordChar(cur, helper) ? &quot;w&quot;
+        : group &amp;&amp; cur == &quot;\n&quot; ? &quot;n&quot;
+        : !group || /\s/.test(cur) ? null
+        : &quot;p&quot;
+      if (group &amp;&amp; !first &amp;&amp; !type) { type = &quot;s&quot; }
+      if (sawType &amp;&amp; sawType != type) {
+        if (dir &lt; 0) {dir = 1; moveOnce()}
+        break
</ins><span class="cx">       }
</span><del>-      cm.replaceSelections(spaces);
-    },
-    defaultTab: function(cm) {
-      if (cm.somethingSelected()) cm.indentSelection(&quot;add&quot;);
-      else cm.execCommand(&quot;insertTab&quot;);
-    },
-    transposeChars: function(cm) {
-      runInOp(cm, function() {
-        var ranges = cm.listSelections(), newSel = [];
-        for (var i = 0; i &lt; ranges.length; i++) {
-          var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
-          if (line) {
-            if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
-            if (cur.ch &gt; 0) {
-              cur = new Pos(cur.line, cur.ch + 1);
-              cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
-                              Pos(cur.line, cur.ch - 2), cur, &quot;+transpose&quot;);
-            } else if (cur.line &gt; cm.doc.first) {
-              var prev = getLine(cm.doc, cur.line - 1).text;
-              if (prev)
-                cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
-                                prev.charAt(prev.length - 1),
-                                Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), &quot;+transpose&quot;);
-            }
-          }
-          newSel.push(new Range(cur, cur));
-        }
-        cm.setSelections(newSel);
-      });
-    },
-    newlineAndIndent: function(cm) {
-      runInOp(cm, function() {
-        var len = cm.listSelections().length;
-        for (var i = 0; i &lt; len; i++) {
-          var range = cm.listSelections()[i];
-          cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, &quot;+input&quot;);
-          cm.indentLine(range.from().line + 1, null, true);
-          ensureCursorVisible(cm);
-        }
-      });
-    },
-    toggleOverwrite: function(cm) {cm.toggleOverwrite();}
-  };
</del><span class="cx"> 
</span><del>-
-  // STANDARD KEYMAPS
-
-  var keyMap = CodeMirror.keyMap = {};
-
-  keyMap.basic = {
-    &quot;Left&quot;: &quot;goCharLeft&quot;, &quot;Right&quot;: &quot;goCharRight&quot;, &quot;Up&quot;: &quot;goLineUp&quot;, &quot;Down&quot;: &quot;goLineDown&quot;,
-    &quot;End&quot;: &quot;goLineEnd&quot;, &quot;Home&quot;: &quot;goLineStartSmart&quot;, &quot;PageUp&quot;: &quot;goPageUp&quot;, &quot;PageDown&quot;: &quot;goPageDown&quot;,
-    &quot;Delete&quot;: &quot;delCharAfter&quot;, &quot;Backspace&quot;: &quot;delCharBefore&quot;, &quot;Shift-Backspace&quot;: &quot;delCharBefore&quot;,
-    &quot;Tab&quot;: &quot;defaultTab&quot;, &quot;Shift-Tab&quot;: &quot;indentAuto&quot;,
-    &quot;Enter&quot;: &quot;newlineAndIndent&quot;, &quot;Insert&quot;: &quot;toggleOverwrite&quot;,
-    &quot;Esc&quot;: &quot;singleSelection&quot;
-  };
-  // Note that the save and find-related commands aren't defined by
-  // default. User code or addons can define them. Unknown commands
-  // are simply ignored.
-  keyMap.pcDefault = {
-    &quot;Ctrl-A&quot;: &quot;selectAll&quot;, &quot;Ctrl-D&quot;: &quot;deleteLine&quot;, &quot;Ctrl-Z&quot;: &quot;undo&quot;, &quot;Shift-Ctrl-Z&quot;: &quot;redo&quot;, &quot;Ctrl-Y&quot;: &quot;redo&quot;,
-    &quot;Ctrl-Home&quot;: &quot;goDocStart&quot;, &quot;Ctrl-End&quot;: &quot;goDocEnd&quot;, &quot;Ctrl-Up&quot;: &quot;goLineUp&quot;, &quot;Ctrl-Down&quot;: &quot;goLineDown&quot;,
-    &quot;Ctrl-Left&quot;: &quot;goGroupLeft&quot;, &quot;Ctrl-Right&quot;: &quot;goGroupRight&quot;, &quot;Alt-Left&quot;: &quot;goLineStart&quot;, &quot;Alt-Right&quot;: &quot;goLineEnd&quot;,
-    &quot;Ctrl-Backspace&quot;: &quot;delGroupBefore&quot;, &quot;Ctrl-Delete&quot;: &quot;delGroupAfter&quot;, &quot;Ctrl-S&quot;: &quot;save&quot;, &quot;Ctrl-F&quot;: &quot;find&quot;,
-    &quot;Ctrl-G&quot;: &quot;findNext&quot;, &quot;Shift-Ctrl-G&quot;: &quot;findPrev&quot;, &quot;Shift-Ctrl-F&quot;: &quot;replace&quot;, &quot;Shift-Ctrl-R&quot;: &quot;replaceAll&quot;,
-    &quot;Ctrl-[&quot;: &quot;indentLess&quot;, &quot;Ctrl-]&quot;: &quot;indentMore&quot;,
-    &quot;Ctrl-U&quot;: &quot;undoSelection&quot;, &quot;Shift-Ctrl-U&quot;: &quot;redoSelection&quot;, &quot;Alt-U&quot;: &quot;redoSelection&quot;,
-    fallthrough: &quot;basic&quot;
-  };
-  // Very basic readline/emacs-style bindings, which are standard on Mac.
-  keyMap.emacsy = {
-    &quot;Ctrl-F&quot;: &quot;goCharRight&quot;, &quot;Ctrl-B&quot;: &quot;goCharLeft&quot;, &quot;Ctrl-P&quot;: &quot;goLineUp&quot;, &quot;Ctrl-N&quot;: &quot;goLineDown&quot;,
-    &quot;Alt-F&quot;: &quot;goWordRight&quot;, &quot;Alt-B&quot;: &quot;goWordLeft&quot;, &quot;Ctrl-A&quot;: &quot;goLineStart&quot;, &quot;Ctrl-E&quot;: &quot;goLineEnd&quot;,
-    &quot;Ctrl-V&quot;: &quot;goPageDown&quot;, &quot;Shift-Ctrl-V&quot;: &quot;goPageUp&quot;, &quot;Ctrl-D&quot;: &quot;delCharAfter&quot;, &quot;Ctrl-H&quot;: &quot;delCharBefore&quot;,
-    &quot;Alt-D&quot;: &quot;delWordAfter&quot;, &quot;Alt-Backspace&quot;: &quot;delWordBefore&quot;, &quot;Ctrl-K&quot;: &quot;killLine&quot;, &quot;Ctrl-T&quot;: &quot;transposeChars&quot;
-  };
-  keyMap.macDefault = {
-    &quot;Cmd-A&quot;: &quot;selectAll&quot;, &quot;Cmd-D&quot;: &quot;deleteLine&quot;, &quot;Cmd-Z&quot;: &quot;undo&quot;, &quot;Shift-Cmd-Z&quot;: &quot;redo&quot;, &quot;Cmd-Y&quot;: &quot;redo&quot;,
-    &quot;Cmd-Home&quot;: &quot;goDocStart&quot;, &quot;Cmd-Up&quot;: &quot;goDocStart&quot;, &quot;Cmd-End&quot;: &quot;goDocEnd&quot;, &quot;Cmd-Down&quot;: &quot;goDocEnd&quot;, &quot;Alt-Left&quot;: &quot;goGroupLeft&quot;,
-    &quot;Alt-Right&quot;: &quot;goGroupRight&quot;, &quot;Cmd-Left&quot;: &quot;goLineLeft&quot;, &quot;Cmd-Right&quot;: &quot;goLineRight&quot;, &quot;Alt-Backspace&quot;: &quot;delGroupBefore&quot;,
-    &quot;Ctrl-Alt-Backspace&quot;: &quot;delGroupAfter&quot;, &quot;Alt-Delete&quot;: &quot;delGroupAfter&quot;, &quot;Cmd-S&quot;: &quot;save&quot;, &quot;Cmd-F&quot;: &quot;find&quot;,
-    &quot;Cmd-G&quot;: &quot;findNext&quot;, &quot;Shift-Cmd-G&quot;: &quot;findPrev&quot;, &quot;Cmd-Alt-F&quot;: &quot;replace&quot;, &quot;Shift-Cmd-Alt-F&quot;: &quot;replaceAll&quot;,
-    &quot;Cmd-[&quot;: &quot;indentLess&quot;, &quot;Cmd-]&quot;: &quot;indentMore&quot;, &quot;Cmd-Backspace&quot;: &quot;delWrappedLineLeft&quot;, &quot;Cmd-Delete&quot;: &quot;delWrappedLineRight&quot;,
-    &quot;Cmd-U&quot;: &quot;undoSelection&quot;, &quot;Shift-Cmd-U&quot;: &quot;redoSelection&quot;, &quot;Ctrl-Up&quot;: &quot;goDocStart&quot;, &quot;Ctrl-Down&quot;: &quot;goDocEnd&quot;,
-    fallthrough: [&quot;basic&quot;, &quot;emacsy&quot;]
-  };
-  keyMap[&quot;default&quot;] = mac ? keyMap.macDefault : keyMap.pcDefault;
-
-  // KEYMAP DISPATCH
-
-  function normalizeKeyName(name) {
-    var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
-    var alt, ctrl, shift, cmd;
-    for (var i = 0; i &lt; parts.length - 1; i++) {
-      var mod = parts[i];
-      if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
-      else if (/^a(lt)?$/i.test(mod)) alt = true;
-      else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
-      else if (/^s(hift)$/i.test(mod)) shift = true;
-      else throw new Error(&quot;Unrecognized modifier name: &quot; + mod);
</del><ins>+      if (type) { sawType = type }
+      if (dir &gt; 0 &amp;&amp; !moveOnce(!first)) { break }
</ins><span class="cx">     }
</span><del>-    if (alt) name = &quot;Alt-&quot; + name;
-    if (ctrl) name = &quot;Ctrl-&quot; + name;
-    if (cmd) name = &quot;Cmd-&quot; + name;
-    if (shift) name = &quot;Shift-&quot; + name;
-    return name;
</del><span class="cx">   }
</span><ins>+  var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true)
+  if (!cmp(pos, result)) { result.hitSide = true }
+  return result
+}
</ins><span class="cx"> 
</span><del>-  // This is a kludge to keep keymaps mostly working as raw objects
-  // (backwards compatibility) while at the same time support features
-  // like normalization and multi-stroke key bindings. It compiles a
-  // new normalized keymap, and then updates the old object to reflect
-  // this.
-  CodeMirror.normalizeKeyMap = function(keymap) {
-    var copy = {};
-    for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
-      var value = keymap[keyname];
-      if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
-      if (value == &quot;...&quot;) { delete keymap[keyname]; continue; }
</del><ins>+// For relative vertical movement. Dir may be -1 or 1. Unit can be
+// &quot;page&quot; or &quot;line&quot;. The resulting position will have a hitSide=true
+// property if it reached the end of the document.
+function findPosV(cm, pos, dir, unit) {
+  var doc = cm.doc, x = pos.left, y
+  if (unit == &quot;page&quot;) {
+    var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight)
+    var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3)
+    y = (dir &gt; 0 ? pos.bottom : pos.top) + dir * moveAmount
</ins><span class="cx"> 
</span><del>-      var keys = map(keyname.split(&quot; &quot;), normalizeKeyName);
-      for (var i = 0; i &lt; keys.length; i++) {
-        var val, name;
-        if (i == keys.length - 1) {
-          name = keys.join(&quot; &quot;);
-          val = value;
-        } else {
-          name = keys.slice(0, i + 1).join(&quot; &quot;);
-          val = &quot;...&quot;;
-        }
-        var prev = copy[name];
-        if (!prev) copy[name] = val;
-        else if (prev != val) throw new Error(&quot;Inconsistent bindings for &quot; + name);
-      }
-      delete keymap[keyname];
-    }
-    for (var prop in copy) keymap[prop] = copy[prop];
-    return keymap;
-  };
-
-  var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
-    map = getKeyMap(map);
-    var found = map.call ? map.call(key, context) : map[key];
-    if (found === false) return &quot;nothing&quot;;
-    if (found === &quot;...&quot;) return &quot;multi&quot;;
-    if (found != null &amp;&amp; handle(found)) return &quot;handled&quot;;
-
-    if (map.fallthrough) {
-      if (Object.prototype.toString.call(map.fallthrough) != &quot;[object Array]&quot;)
-        return lookupKey(key, map.fallthrough, handle, context);
-      for (var i = 0; i &lt; map.fallthrough.length; i++) {
-        var result = lookupKey(key, map.fallthrough[i], handle, context);
-        if (result) return result;
-      }
-    }
-  };
-
-  // Modifier key presses don't count as 'real' key presses for the
-  // purpose of keymap fallthrough.
-  var isModifierKey = CodeMirror.isModifierKey = function(value) {
-    var name = typeof value == &quot;string&quot; ? value : keyNames[value.keyCode];
-    return name == &quot;Ctrl&quot; || name == &quot;Alt&quot; || name == &quot;Shift&quot; || name == &quot;Mod&quot;;
-  };
-
-  // Look up the name of a key as indicated by an event object.
-  var keyName = CodeMirror.keyName = function(event, noShift) {
-    if (presto &amp;&amp; event.keyCode == 34 &amp;&amp; event[&quot;char&quot;]) return false;
-    var base = keyNames[event.keyCode], name = base;
-    if (name == null || event.altGraphKey) return false;
-    if (event.altKey &amp;&amp; base != &quot;Alt&quot;) name = &quot;Alt-&quot; + name;
-    if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) &amp;&amp; base != &quot;Ctrl&quot;) name = &quot;Ctrl-&quot; + name;
-    if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) &amp;&amp; base != &quot;Cmd&quot;) name = &quot;Cmd-&quot; + name;
-    if (!noShift &amp;&amp; event.shiftKey &amp;&amp; base != &quot;Shift&quot;) name = &quot;Shift-&quot; + name;
-    return name;
-  };
-
-  function getKeyMap(val) {
-    return typeof val == &quot;string&quot; ? keyMap[val] : val;
</del><ins>+  } else if (unit == &quot;line&quot;) {
+    y = dir &gt; 0 ? pos.bottom + 3 : pos.top - 3
</ins><span class="cx">   }
</span><ins>+  var target
+  for (;;) {
+    target = coordsChar(cm, x, y)
+    if (!target.outside) { break }
+    if (dir &lt; 0 ? y &lt;= 0 : y &gt;= doc.height) { target.hitSide = true; break }
+    y += dir * 5
+  }
+  return target
+}
</ins><span class="cx"> 
</span><del>-  // FROMTEXTAREA
</del><ins>+// CONTENTEDITABLE INPUT STYLE
</ins><span class="cx"> 
</span><del>-  CodeMirror.fromTextArea = function(textarea, options) {
-    options = options ? copyObj(options) : {};
-    options.value = textarea.value;
-    if (!options.tabindex &amp;&amp; textarea.tabIndex)
-      options.tabindex = textarea.tabIndex;
-    if (!options.placeholder &amp;&amp; textarea.placeholder)
-      options.placeholder = textarea.placeholder;
-    // Set autofocus to true if this textarea is focused, or if it has
-    // autofocus and no other element is focused.
-    if (options.autofocus == null) {
-      var hasFocus = activeElt();
-      options.autofocus = hasFocus == textarea ||
-        textarea.getAttribute(&quot;autofocus&quot;) != null &amp;&amp; hasFocus == document.body;
-    }
</del><ins>+var ContentEditableInput = function(cm) {
+  this.cm = cm
+  this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null
+  this.polling = new Delayed()
+  this.composing = null
+  this.gracePeriod = false
+  this.readDOMTimeout = null
+};
</ins><span class="cx"> 
</span><del>-    function save() {textarea.value = cm.getValue();}
-    if (textarea.form) {
-      on(textarea.form, &quot;submit&quot;, save);
-      // Deplorable hack to make the submit method do the right thing.
-      if (!options.leaveSubmitMethodAlone) {
-        var form = textarea.form, realSubmit = form.submit;
-        try {
-          var wrappedSubmit = form.submit = function() {
-            save();
-            form.submit = realSubmit;
-            form.submit();
-            form.submit = wrappedSubmit;
-          };
-        } catch(e) {}
-      }
-    }
</del><ins>+ContentEditableInput.prototype.init = function (display) {
+    var this$1 = this;
</ins><span class="cx"> 
</span><del>-    options.finishInit = function(cm) {
-      cm.save = save;
-      cm.getTextArea = function() { return textarea; };
-      cm.toTextArea = function() {
-        cm.toTextArea = isNaN; // Prevent this from being ran twice
-        save();
-        textarea.parentNode.removeChild(cm.getWrapperElement());
-        textarea.style.display = &quot;&quot;;
-        if (textarea.form) {
-          off(textarea.form, &quot;submit&quot;, save);
-          if (typeof textarea.form.submit == &quot;function&quot;)
-            textarea.form.submit = realSubmit;
-        }
-      };
-    };
</del><ins>+  var input = this, cm = input.cm
+  var div = input.div = display.lineDiv
+  disableBrowserMagic(div, cm.options.spellcheck)
</ins><span class="cx"> 
</span><del>-    textarea.style.display = &quot;none&quot;;
-    var cm = CodeMirror(function(node) {
-      textarea.parentNode.insertBefore(node, textarea.nextSibling);
-    }, options);
-    return cm;
-  };
</del><ins>+  on(div, &quot;paste&quot;, function (e) {
+    if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
+    // IE doesn't fire input events, so we schedule a read for the pasted content in this way
+    if (ie_version &lt;= 11) { setTimeout(operation(cm, function () {
+      if (!input.pollContent()) { regChange(cm) }
+    }), 20) }
+  })
</ins><span class="cx"> 
</span><del>-  // STRING STREAM
-
-  // Fed to the mode parsers, provides helper functions to make
-  // parsers more succinct.
-
-  var StringStream = CodeMirror.StringStream = function(string, tabSize) {
-    this.pos = this.start = 0;
-    this.string = string;
-    this.tabSize = tabSize || 8;
-    this.lastColumnPos = this.lastColumnValue = 0;
-    this.lineStart = 0;
-  };
-
-  StringStream.prototype = {
-    eol: function() {return this.pos &gt;= this.string.length;},
-    sol: function() {return this.pos == this.lineStart;},
-    peek: function() {return this.string.charAt(this.pos) || undefined;},
-    next: function() {
-      if (this.pos &lt; this.string.length)
-        return this.string.charAt(this.pos++);
-    },
-    eat: function(match) {
-      var ch = this.string.charAt(this.pos);
-      if (typeof match == &quot;string&quot;) var ok = ch == match;
-      else var ok = ch &amp;&amp; (match.test ? match.test(ch) : match(ch));
-      if (ok) {++this.pos; return ch;}
-    },
-    eatWhile: function(match) {
-      var start = this.pos;
-      while (this.eat(match)){}
-      return this.pos &gt; start;
-    },
-    eatSpace: function() {
-      var start = this.pos;
-      while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
-      return this.pos &gt; start;
-    },
-    skipToEnd: function() {this.pos = this.string.length;},
-    skipTo: function(ch) {
-      var found = this.string.indexOf(ch, this.pos);
-      if (found &gt; -1) {this.pos = found; return true;}
-    },
-    backUp: function(n) {this.pos -= n;},
-    column: function() {
-      if (this.lastColumnPos &lt; 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);
-    },
-    indentation: function() {
-      return countColumn(this.string, null, this.tabSize) -
-        (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
-    },
-    match: function(pattern, consume, caseInsensitive) {
-      if (typeof pattern == &quot;string&quot;) {
-        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 &amp;&amp; match.index &gt; 0) return null;
-        if (match &amp;&amp; consume !== false) this.pos += match[0].length;
-        return match;
-      }
-    },
-    current: function(){return this.string.slice(this.start, this.pos);},
-    hideFirstChars: function(n, inner) {
-      this.lineStart += n;
-      try { return inner(); }
-      finally { this.lineStart -= n; }
</del><ins>+  on(div, &quot;compositionstart&quot;, function (e) {
+    this$1.composing = {data: e.data, done: false}
+  })
+  on(div, &quot;compositionupdate&quot;, function (e) {
+    if (!this$1.composing) { this$1.composing = {data: e.data, done: false} }
+  })
+  on(div, &quot;compositionend&quot;, function (e) {
+    if (this$1.composing) {
+      if (e.data != this$1.composing.data) { this$1.readFromDOMSoon() }
+      this$1.composing.done = true
</ins><span class="cx">     }
</span><del>-  };
</del><ins>+  })
</ins><span class="cx"> 
</span><del>-  // TEXTMARKERS
</del><ins>+  on(div, &quot;touchstart&quot;, function () { return input.forceCompositionEnd(); })
</ins><span class="cx"> 
</span><del>-  // Created with markText and setBookmark methods. A TextMarker is a
-  // handle that can be used to clear or find a marked position in the
-  // document. Line objects hold arrays (markedSpans) containing
-  // {from, to, marker} object pointing to such marker objects, and
-  // indicating that such a marker is present on that line. Multiple
-  // lines may point to the same marker when it spans across lines.
-  // The spans will have null for their from/to properties when the
-  // marker continues beyond the start/end of the line. Markers have
-  // links back to the lines they currently touch.
</del><ins>+  on(div, &quot;input&quot;, function () {
+    if (!this$1.composing) { this$1.readFromDOMSoon() }
+  })
</ins><span class="cx"> 
</span><del>-  var nextMarkerId = 0;
-
-  var TextMarker = CodeMirror.TextMarker = function(doc, type) {
-    this.lines = [];
-    this.type = type;
-    this.doc = doc;
-    this.id = ++nextMarkerId;
-  };
-  eventMixin(TextMarker);
-
-  // Clear the marker.
-  TextMarker.prototype.clear = function() {
-    if (this.explicitlyCleared) return;
-    var cm = this.doc.cm, withOp = cm &amp;&amp; !cm.curOp;
-    if (withOp) startOperation(cm);
-    if (hasHandler(this, &quot;clear&quot;)) {
-      var found = this.find();
-      if (found) signalLater(this, &quot;clear&quot;, found.from, found.to);
-    }
-    var min = null, max = null;
-    for (var i = 0; i &lt; this.lines.length; ++i) {
-      var line = this.lines[i];
-      var span = getMarkedSpanFor(line.markedSpans, this);
-      if (cm &amp;&amp; !this.collapsed) regLineChange(cm, lineNo(line), &quot;text&quot;);
-      else if (cm) {
-        if (span.to != null) max = lineNo(line);
-        if (span.from != null) min = lineNo(line);
</del><ins>+  function onCopyCut(e) {
+    if (signalDOMEvent(cm, e)) { return }
+    if (cm.somethingSelected()) {
+      setLastCopied({lineWise: false, text: cm.getSelections()})
+      if (e.type == &quot;cut&quot;) { cm.replaceSelection(&quot;&quot;, null, &quot;cut&quot;) }
+    } else if (!cm.options.lineWiseCopyCut) {
+      return
+    } else {
+      var ranges = copyableRanges(cm)
+      setLastCopied({lineWise: true, text: ranges.text})
+      if (e.type == &quot;cut&quot;) {
+        cm.operation(function () {
+          cm.setSelections(ranges.ranges, 0, sel_dontScroll)
+          cm.replaceSelection(&quot;&quot;, null, &quot;cut&quot;)
+        })
</ins><span class="cx">       }
</span><del>-      line.markedSpans = removeMarkedSpan(line.markedSpans, span);
-      if (span.from == null &amp;&amp; this.collapsed &amp;&amp; !lineIsHidden(this.doc, line) &amp;&amp; cm)
-        updateLineHeight(line, textHeight(cm.display));
</del><span class="cx">     }
</span><del>-    if (cm &amp;&amp; this.collapsed &amp;&amp; !cm.options.lineWrapping) for (var i = 0; i &lt; this.lines.length; ++i) {
-      var visual = visualLine(this.lines[i]), len = lineLength(visual);
-      if (len &gt; cm.display.maxLineLength) {
-        cm.display.maxLine = visual;
-        cm.display.maxLineLength = len;
-        cm.display.maxLineChanged = true;
</del><ins>+    if (e.clipboardData) {
+      e.clipboardData.clearData()
+      var content = lastCopied.text.join(&quot;\n&quot;)
+      // iOS exposes the clipboard API, but seems to discard content inserted into it
+      e.clipboardData.setData(&quot;Text&quot;, content)
+      if (e.clipboardData.getData(&quot;Text&quot;) == content) {
+        e.preventDefault()
+        return
</ins><span class="cx">       }
</span><span class="cx">     }
</span><del>-
-    if (min != null &amp;&amp; cm &amp;&amp; this.collapsed) regChange(cm, min, max + 1);
-    this.lines.length = 0;
-    this.explicitlyCleared = true;
-    if (this.atomic &amp;&amp; this.doc.cantEdit) {
-      this.doc.cantEdit = false;
-      if (cm) reCheckSelection(cm.doc);
-    }
-    if (cm) signalLater(cm, &quot;markerCleared&quot;, cm, this);
-    if (withOp) endOperation(cm);
-    if (this.parent) this.parent.clear();
-  };
-
-  // Find the position of the marker in the document. Returns a {from,
-  // to} object by default. Side can be passed to get a specific side
-  // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
-  // Pos objects returned contain a line object, rather than a line
-  // number (used to prevent looking up the same line twice).
-  TextMarker.prototype.find = function(side, lineObj) {
-    if (side == null &amp;&amp; this.type == &quot;bookmark&quot;) side = 1;
-    var from, to;
-    for (var i = 0; i &lt; this.lines.length; ++i) {
-      var line = this.lines[i];
-      var span = getMarkedSpanFor(line.markedSpans, this);
-      if (span.from != null) {
-        from = Pos(lineObj ? line : lineNo(line), span.from);
-        if (side == -1) return from;
-      }
-      if (span.to != null) {
-        to = Pos(lineObj ? line : lineNo(line), span.to);
-        if (side == 1) return to;
-      }
-    }
-    return from &amp;&amp; {from: from, to: to};
-  };
-
-  // Signals that the marker's widget changed, and surrounding layout
-  // should be recomputed.
-  TextMarker.prototype.changed = function() {
-    var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
-    if (!pos || !cm) return;
-    runInOp(cm, function() {
-      var line = pos.line, lineN = lineNo(pos.line);
-      var view = findViewForLine(cm, lineN);
-      if (view) {
-        clearLineMeasurementCacheFor(view);
-        cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
-      }
-      cm.curOp.updateMaxLine = true;
-      if (!lineIsHidden(widget.doc, line) &amp;&amp; widget.height != null) {
-        var oldHeight = widget.height;
-        widget.height = null;
-        var dHeight = widgetHeight(widget) - oldHeight;
-        if (dHeight)
-          updateLineHeight(line, line.height + dHeight);
-      }
-    });
-  };
-
-  TextMarker.prototype.attachLine = function(line) {
-    if (!this.lines.length &amp;&amp; this.doc.cm) {
-      var op = this.doc.cm.curOp;
-      if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
-        (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
-    }
-    this.lines.push(line);
-  };
-  TextMarker.prototype.detachLine = function(line) {
-    this.lines.splice(indexOf(this.lines, line), 1);
-    if (!this.lines.length &amp;&amp; this.doc.cm) {
-      var op = this.doc.cm.curOp;
-      (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
-    }
-  };
-
-  // Collapsed markers have unique ids, in order to be able to order
-  // them, which is needed for uniquely determining an outer marker
-  // when they overlap (they may nest, but not partially overlap).
-  var nextMarkerId = 0;
-
-  // Create a marker, wire it up to the right lines, and
-  function markText(doc, from, to, options, type) {
-    // Shared markers (across linked documents) are handled separately
-    // (markTextShared will call out to this again, once per
-    // document).
-    if (options &amp;&amp; options.shared) return markTextShared(doc, from, to, options, type);
-    // Ensure we are in an operation.
-    if (doc.cm &amp;&amp; !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
-
-    var marker = new TextMarker(doc, type), diff = cmp(from, to);
-    if (options) copyObj(options, marker, false);
-    // Don't connect empty markers unless clearWhenEmpty is false
-    if (diff &gt; 0 || diff == 0 &amp;&amp; marker.clearWhenEmpty !== false)
-      return marker;
-    if (marker.replacedWith) {
-      // Showing up as a widget implies collapsed (widget replaces text)
-      marker.collapsed = true;
-      marker.widgetNode = elt(&quot;span&quot;, [marker.replacedWith], &quot;CodeMirror-widget&quot;);
-      if (!options.handleMouseEvents) marker.widgetNode.setAttribute(&quot;cm-ignore-events&quot;, &quot;true&quot;);
-      if (options.insertLeft) marker.widgetNode.insertLeft = true;
-    }
-    if (marker.collapsed) {
-      if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
-          from.line != to.line &amp;&amp; conflictingCollapsedRange(doc, to.line, from, to, marker))
-        throw new Error(&quot;Inserting collapsed marker partially overlapping an existing one&quot;);
-      sawCollapsedSpans = true;
-    }
-
-    if (marker.addToHistory)
-      addChangeToHistory(doc, {from: from, to: to, origin: &quot;markText&quot;}, doc.sel, NaN);
-
-    var curLine = from.line, cm = doc.cm, updateMaxLine;
-    doc.iter(curLine, to.line + 1, function(line) {
-      if (cm &amp;&amp; marker.collapsed &amp;&amp; !cm.options.lineWrapping &amp;&amp; visualLine(line) == cm.display.maxLine)
-        updateMaxLine = true;
-      if (marker.collapsed &amp;&amp; curLine != from.line) updateLineHeight(line, 0);
-      addMarkedSpan(line, new MarkedSpan(marker,
-                                         curLine == from.line ? from.ch : null,
-                                         curLine == to.line ? to.ch : null));
-      ++curLine;
-    });
-    // lineIsHidden depends on the presence of the spans, so needs a second pass
-    if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
-      if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
-    });
-
-    if (marker.clearOnEnter) on(marker, &quot;beforeCursorEnter&quot;, function() { marker.clear(); });
-
-    if (marker.readOnly) {
-      sawReadOnlySpans = true;
-      if (doc.history.done.length || doc.history.undone.length)
-        doc.clearHistory();
-    }
-    if (marker.collapsed) {
-      marker.id = ++nextMarkerId;
-      marker.atomic = true;
-    }
-    if (cm) {
-      // Sync editor state
-      if (updateMaxLine) cm.curOp.updateMaxLine = true;
-      if (marker.collapsed)
-        regChange(cm, from.line, to.line + 1);
-      else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
-        for (var i = from.line; i &lt;= to.line; i++) regLineChange(cm, i, &quot;text&quot;);
-      if (marker.atomic) reCheckSelection(cm.doc);
-      signalLater(cm, &quot;markerAdded&quot;, cm, marker);
-    }
-    return marker;
</del><ins>+    // 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(&quot;\n&quot;)
+    var hadFocus = document.activeElement
+    selectInput(te)
+    setTimeout(function () {
+      cm.display.lineSpace.removeChild(kludge)
+      hadFocus.focus()
+      if (hadFocus == div) { input.showPrimarySelection() }
+    }, 50)
</ins><span class="cx">   }
</span><ins>+  on(div, &quot;copy&quot;, onCopyCut)
+  on(div, &quot;cut&quot;, onCopyCut)
+};
</ins><span class="cx"> 
</span><del>-  // SHARED TEXTMARKERS
</del><ins>+ContentEditableInput.prototype.prepareSelection = function () {
+  var result = prepareSelection(this.cm, false)
+  result.focus = this.cm.state.focused
+  return result
+};
</ins><span class="cx"> 
</span><del>-  // A shared marker spans multiple linked documents. It is
-  // implemented as a meta-marker-object controlling multiple normal
-  // markers.
-  var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
-    this.markers = markers;
-    this.primary = primary;
-    for (var i = 0; i &lt; markers.length; ++i)
-      markers[i].parent = this;
-  };
-  eventMixin(SharedTextMarker);
</del><ins>+ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
+  if (!info || !this.cm.display.view.length) { return }
+  if (info.focus || takeFocus) { this.showPrimarySelection() }
+  this.showMultipleSelections(info)
+};
</ins><span class="cx"> 
</span><del>-  SharedTextMarker.prototype.clear = function() {
-    if (this.explicitlyCleared) return;
-    this.explicitlyCleared = true;
-    for (var i = 0; i &lt; this.markers.length; ++i)
-      this.markers[i].clear();
-    signalLater(this, &quot;clear&quot;);
-  };
-  SharedTextMarker.prototype.find = function(side, lineObj) {
-    return this.primary.find(side, lineObj);
-  };
</del><ins>+ContentEditableInput.prototype.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 &amp;&amp; !curAnchor.bad &amp;&amp; curFocus &amp;&amp; !curFocus.bad &amp;&amp;
+      cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &amp;&amp;
+      cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
+    { return }
</ins><span class="cx"> 
</span><del>-  function markTextShared(doc, from, to, options, type) {
-    options = copyObj(options);
-    options.shared = false;
-    var markers = [markText(doc, from, to, options, type)], primary = markers[0];
-    var widget = options.widgetNode;
-    linkedDocs(doc, function(doc) {
-      if (widget) options.widgetNode = widget.cloneNode(true);
-      markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
-      for (var i = 0; i &lt; doc.linked.length; ++i)
-        if (doc.linked[i].isParent) return;
-      primary = lst(markers);
-    });
-    return new SharedTextMarker(markers, primary);
-  }
</del><ins>+  var start = posToDOM(this.cm, prim.from())
+  var end = posToDOM(this.cm, prim.to())
+  if (!start &amp;&amp; !end) { return }
</ins><span class="cx"> 
</span><del>-  function findSharedMarkers(doc) {
-    return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
-                         function(m) { return m.parent; });
</del><ins>+  var view = this.cm.display.view
+  var old = sel.rangeCount &amp;&amp; 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]}
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  function copySharedMarkers(doc, markers) {
-    for (var i = 0; i &lt; markers.length; i++) {
-      var marker = markers[i], pos = marker.find();
-      var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
-      if (cmp(mFrom, mTo)) {
-        var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
-        marker.markers.push(subMark);
-        subMark.parent = marker;
</del><ins>+  var rng
+  try { 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 &amp;&amp; this.cm.state.focused) {
+      sel.collapse(start.node, start.offset)
+      if (!rng.collapsed) {
+        sel.removeAllRanges()
+        sel.addRange(rng)
</ins><span class="cx">       }
</span><ins>+    } else {
+      sel.removeAllRanges()
+      sel.addRange(rng)
</ins><span class="cx">     }
</span><ins>+    if (old &amp;&amp; sel.anchorNode == null) { sel.addRange(old) }
+    else if (gecko) { this.startGracePeriod() }
</ins><span class="cx">   }
</span><ins>+  this.rememberSelection()
+};
</ins><span class="cx"> 
</span><del>-  function detachSharedMarkers(markers) {
-    for (var i = 0; i &lt; markers.length; i++) {
-      var marker = markers[i], linked = [marker.primary.doc];;
-      linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
-      for (var j = 0; j &lt; marker.markers.length; j++) {
-        var subMarker = marker.markers[j];
-        if (indexOf(linked, subMarker.doc) == -1) {
-          subMarker.parent = null;
-          marker.markers.splice(j--, 1);
-        }
-      }
-    }
-  }
</del><ins>+ContentEditableInput.prototype.startGracePeriod = function () {
+    var this$1 = this;
</ins><span class="cx"> 
</span><del>-  // TEXTMARKER SPANS
</del><ins>+  clearTimeout(this.gracePeriod)
+  this.gracePeriod = setTimeout(function () {
+    this$1.gracePeriod = false
+    if (this$1.selectionChanged())
+      { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }) }
+  }, 20)
+};
</ins><span class="cx"> 
</span><del>-  function MarkedSpan(marker, from, to) {
-    this.marker = marker;
-    this.from = from; this.to = to;
-  }
</del><ins>+ContentEditableInput.prototype.showMultipleSelections = function (info) {
+  removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors)
+  removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection)
+};
</ins><span class="cx"> 
</span><del>-  // Search an array of spans for a span matching the given marker.
-  function getMarkedSpanFor(spans, marker) {
-    if (spans) for (var i = 0; i &lt; 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) {
-    for (var r, i = 0; i &lt; 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);
-  }
</del><ins>+ContentEditableInput.prototype.rememberSelection = function () {
+  var sel = window.getSelection()
+  this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset
+  this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset
+};
</ins><span class="cx"> 
</span><del>-  // 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) {
-    if (old) for (var i = 0, nw; i &lt; old.length; ++i) {
-      var span = old[i], marker = span.marker;
-      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from &lt;= startCh : span.from &lt; startCh);
-      if (startsBefore || span.from == startCh &amp;&amp; marker.type == &quot;bookmark&quot; &amp;&amp; (!isInsert || !span.marker.insertLeft)) {
-        var endsAfter = span.to == null || (marker.inclusiveRight ? span.to &gt;= startCh : span.to &gt; startCh);
-        (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
-      }
-    }
-    return nw;
-  }
-  function markedSpansAfter(old, endCh, isInsert) {
-    if (old) for (var i = 0, nw; i &lt; old.length; ++i) {
-      var span = old[i], marker = span.marker;
-      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to &gt;= endCh : span.to &gt; endCh);
-      if (endsAfter || span.from == endCh &amp;&amp; marker.type == &quot;bookmark&quot; &amp;&amp; (!isInsert || span.marker.insertLeft)) {
-        var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from &lt;= endCh : span.from &lt; endCh);
-        (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
-                                              span.to == null ? null : span.to - endCh));
-      }
-    }
-    return nw;
-  }
</del><ins>+ContentEditableInput.prototype.selectionInEditor = function () {
+  var sel = window.getSelection()
+  if (!sel.rangeCount) { return false }
+  var node = sel.getRangeAt(0).commonAncestorContainer
+  return contains(this.div, node)
+};
</ins><span class="cx"> 
</span><del>-  // 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) &amp;&amp; getLine(doc, change.from.line).markedSpans;
-    var oldLast = isLine(doc, change.to.line) &amp;&amp; getLine(doc, change.to.line).markedSpans;
-    if (!oldFirst &amp;&amp; !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 &lt; 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 = 0; i &lt; last.length; ++i) {
-        var span = last[i];
-        if (span.to != null) span.to += offset;
-        if (span.from == null) {
-          var found = getMarkedSpanFor(first, span.marker);
-          if (!found) {
-            span.from = offset;
-            if (sameLine) (first || (first = [])).push(span);
-          }
-        } else {
-          span.from += offset;
-          if (sameLine) (first || (first = [])).push(span);
-        }
-      }
-    }
-    // Make sure we didn't create any zero-length spans
-    if (first) first = clearEmptySpans(first);
-    if (last &amp;&amp; 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 &gt; 0 &amp;&amp; first)
-        for (var i = 0; i &lt; first.length; ++i)
-          if (first[i].to == null)
-            (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
-      for (var i = 0; i &lt; gap; ++i)
-        newMarkers.push(gapMarkers);
-      newMarkers.push(last);
-    }
-    return newMarkers;
</del><ins>+ContentEditableInput.prototype.focus = function () {
+  if (this.cm.options.readOnly != &quot;nocursor&quot;) {
+    if (!this.selectionInEditor())
+      { this.showSelection(this.prepareSelection(), true) }
+    this.div.focus()
</ins><span class="cx">   }
</span><ins>+};
+ContentEditableInput.prototype.blur = function () { this.div.blur() };
+ContentEditableInput.prototype.getField = function () { return this.div };
</ins><span class="cx"> 
</span><del>-  // Remove spans that are empty and don't have a clearWhenEmpty
-  // option of false.
-  function clearEmptySpans(spans) {
-    for (var i = 0; i &lt; spans.length; ++i) {
-      var span = spans[i];
-      if (span.from != null &amp;&amp; span.from == span.to &amp;&amp; span.marker.clearWhenEmpty !== false)
-        spans.splice(i--, 1);
-    }
-    if (!spans.length) return null;
-    return spans;
-  }
</del><ins>+ContentEditableInput.prototype.supportsTouch = function () { return true };
</ins><span class="cx"> 
</span><del>-  // Used for un/re-doing changes from the history. Combines the
-  // result of computing the existing spans with the set of spans that
-  // existed in the history (so that deleting around a span and then
-  // undoing brings back the span).
-  function mergeOldSpans(doc, change) {
-    var old = getOldSpans(doc, change);
-    var stretched = stretchSpansOverChange(doc, change);
-    if (!old) return stretched;
-    if (!stretched) return old;
</del><ins>+ContentEditableInput.prototype.receivedFocus = function () {
+  var input = this
+  if (this.selectionInEditor())
+    { this.pollSelection() }
+  else
+    { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }) }
</ins><span class="cx"> 
</span><del>-    for (var i = 0; i &lt; old.length; ++i) {
-      var oldCur = old[i], stretchCur = stretched[i];
-      if (oldCur &amp;&amp; stretchCur) {
-        spans: for (var j = 0; j &lt; stretchCur.length; ++j) {
-          var span = stretchCur[j];
-          for (var k = 0; k &lt; oldCur.length; ++k)
-            if (oldCur[k].marker == span.marker) continue spans;
-          oldCur.push(span);
-        }
-      } else if (stretchCur) {
-        old[i] = stretchCur;
-      }
</del><ins>+  function poll() {
+    if (input.cm.state.focused) {
+      input.pollSelection()
+      input.polling.set(input.cm.options.pollInterval, poll)
</ins><span class="cx">     }
</span><del>-    return old;
</del><span class="cx">   }
</span><ins>+  this.polling.set(this.cm.options.pollInterval, poll)
+};
</ins><span class="cx"> 
</span><del>-  // 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 &lt; line.markedSpans.length; ++i) {
-        var mark = line.markedSpans[i].marker;
-        if (mark.readOnly &amp;&amp; (!markers || indexOf(markers, mark) == -1))
-          (markers || (markers = [])).push(mark);
-      }
-    });
-    if (!markers) return null;
-    var parts = [{from: from, to: to}];
-    for (var i = 0; i &lt; markers.length; ++i) {
-      var mk = markers[i], m = mk.find(0);
-      for (var j = 0; j &lt; parts.length; ++j) {
-        var p = parts[j];
-        if (cmp(p.to, m.from) &lt; 0 || cmp(p.from, m.to) &gt; 0) continue;
-        var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
-        if (dfrom &lt; 0 || !mk.inclusiveLeft &amp;&amp; !dfrom)
-          newParts.push({from: p.from, to: m.from});
-        if (dto &gt; 0 || !mk.inclusiveRight &amp;&amp; !dto)
-          newParts.push({from: m.to, to: p.to});
-        parts.splice.apply(parts, newParts);
-        j += newParts.length - 1;
-      }
-    }
-    return parts;
-  }
</del><ins>+ContentEditableInput.prototype.selectionChanged = function () {
+  var sel = window.getSelection()
+  return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
+    sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
+};
</ins><span class="cx"> 
</span><del>-  // Connect or disconnect spans from a line.
-  function detachMarkedSpans(line) {
-    var spans = line.markedSpans;
-    if (!spans) return;
-    for (var i = 0; i &lt; spans.length; ++i)
-      spans[i].marker.detachLine(line);
-    line.markedSpans = null;
</del><ins>+ContentEditableInput.prototype.pollSelection = function () {
+  if (!this.composing &amp;&amp; this.readDOMTimeout == null &amp;&amp; !this.gracePeriod &amp;&amp; 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 &amp;&amp; head) { runInOp(cm, function () {
+      setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll)
+      if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true }
+    }) }
</ins><span class="cx">   }
</span><del>-  function attachMarkedSpans(line, spans) {
-    if (!spans) return;
-    for (var i = 0; i &lt; spans.length; ++i)
-      spans[i].marker.attachLine(line);
-    line.markedSpans = spans;
-  }
</del><ins>+};
</ins><span class="cx"> 
</span><del>-  // 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;
</del><ins>+ContentEditableInput.prototype.pollContent = function () {
+  if (this.readDOMTimeout != null) {
+    clearTimeout(this.readDOMTimeout)
+    this.readDOMTimeout = null
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // 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 &amp;&amp; line.markedSpans, found;
-    if (sps) for (var sp, i = 0; i &lt; sps.length; ++i) {
-      sp = sps[i];
-      if (sp.marker.collapsed &amp;&amp; (start ? sp.from : sp.to) == null &amp;&amp;
-          (!found || compareCollapsedMarkers(found, sp.marker) &lt; 0))
-        found = sp.marker;
-    }
-    return found;
-  }
-  function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
-  function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
</del><ins>+  var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary()
+  var from = sel.from(), to = sel.to()
+  if (from.ch == 0 &amp;&amp; from.line &gt; cm.firstLine())
+    { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length) }
+  if (to.ch == getLine(cm.doc, to.line).text.length &amp;&amp; to.line &lt; cm.lastLine())
+    { to = Pos(to.line + 1, 0) }
+  if (from.line &lt; display.viewFrom || to.line &gt; display.viewTo - 1) { return false }
</ins><span class="cx"> 
</span><del>-  // 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 &amp;&amp; line.markedSpans;
-    if (sps) for (var i = 0; i &lt; 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 &gt;= 0 &amp;&amp; toCmp &lt;= 0 || fromCmp &lt;= 0 &amp;&amp; toCmp &gt;= 0) continue;
-      if (fromCmp &lt;= 0 &amp;&amp; (cmp(found.to, from) &gt; 0 || (sp.marker.inclusiveRight &amp;&amp; marker.inclusiveLeft)) ||
-          fromCmp &gt;= 0 &amp;&amp; (cmp(found.from, to) &lt; 0 || (sp.marker.inclusiveLeft &amp;&amp; marker.inclusiveRight)))
-        return true;
-    }
</del><ins>+  var fromIndex, fromLine, fromNode
+  if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
+    fromLine = lineNo(display.view[0].line)
+    fromNode = display.view[0].node
+  } else {
+    fromLine = lineNo(display.view[fromIndex].line)
+    fromNode = display.view[fromIndex - 1].node.nextSibling
</ins><span class="cx">   }
</span><del>-
-  // 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;
</del><ins>+  var toIndex = findViewIndex(cm, to.line)
+  var toLine, toNode
+  if (toIndex == display.view.length - 1) {
+    toLine = display.viewTo - 1
+    toNode = display.lineDiv.lastChild
+  } else {
+    toLine = lineNo(display.view[toIndex + 1].line) - 1
+    toNode = display.view[toIndex + 1].node.previousSibling
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // 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;
</del><ins>+  if (!fromNode) { return false }
+  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 &gt; 1 &amp;&amp; oldText.length &gt; 1) {
+    if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine-- }
+    else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++ }
+    else { break }
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // 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 &gt; 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;
-  }
</del><ins>+  var cutFront = 0, cutEnd = 0
+  var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length)
+  while (cutFront &lt; maxCutFront &amp;&amp; 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 &lt; maxCutEnd &amp;&amp;
+         newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
+    { ++cutEnd }
</ins><span class="cx"> 
</span><del>-  // 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 &amp;&amp; line.markedSpans;
-    if (sps) for (var sp, i = 0; i &lt; 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 &amp;&amp; sp.marker.inclusiveLeft &amp;&amp; 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 &amp;&amp; span.to == line.text.length)
-      return true;
-    for (var sp, i = 0; i &lt; line.markedSpans.length; ++i) {
-      sp = line.markedSpans[i];
-      if (sp.marker.collapsed &amp;&amp; !sp.marker.widgetNode &amp;&amp; sp.from == span.to &amp;&amp;
-          (sp.to == null || sp.to != span.from) &amp;&amp;
-          (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &amp;&amp;
-          lineIsHiddenInner(doc, line, sp)) return true;
-    }
-  }
</del><ins>+  newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, &quot;&quot;)
+  newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, &quot;&quot;)
</ins><span class="cx"> 
</span><del>-  // LINE WIDGETS
-
-  // Line widgets are block elements displayed above or below a line.
-
-  var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
-    if (options) for (var opt in options) if (options.hasOwnProperty(opt))
-      this[opt] = options[opt];
-    this.doc = doc;
-    this.node = node;
-  };
-  eventMixin(LineWidget);
-
-  function adjustScrollWhenAboveVisible(cm, line, diff) {
-    if (heightAtLine(line) &lt; ((cm.curOp &amp;&amp; cm.curOp.scrollTop) || cm.doc.scrollTop))
-      addToScrollPos(cm, null, diff);
</del><ins>+  var chFrom = Pos(fromLine, cutFront)
+  var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0)
+  if (newText.length &gt; 1 || newText[0] || cmp(chFrom, chTo)) {
+    replaceRange(cm.doc, newText, chFrom, chTo, &quot;+input&quot;)
+    return true
</ins><span class="cx">   }
</span><ins>+};
</ins><span class="cx"> 
</span><del>-  LineWidget.prototype.clear = function() {
-    var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
-    if (no == null || !ws) return;
-    for (var i = 0; i &lt; ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
-    if (!ws.length) line.widgets = null;
-    var height = widgetHeight(this);
-    updateLineHeight(line, Math.max(0, line.height - height));
-    if (cm) runInOp(cm, function() {
-      adjustScrollWhenAboveVisible(cm, line, -height);
-      regLineChange(cm, no, &quot;widget&quot;);
-    });
-  };
-  LineWidget.prototype.changed = function() {
-    var oldH = this.height, cm = this.doc.cm, line = this.line;
-    this.height = null;
-    var diff = widgetHeight(this) - oldH;
-    if (!diff) return;
-    updateLineHeight(line, line.height + diff);
-    if (cm) runInOp(cm, function() {
-      cm.curOp.forceUpdate = true;
-      adjustScrollWhenAboveVisible(cm, line, diff);
-    });
-  };
</del><ins>+ContentEditableInput.prototype.ensurePolled = function () {
+  this.forceCompositionEnd()
+};
+ContentEditableInput.prototype.reset = function () {
+  this.forceCompositionEnd()
+};
+ContentEditableInput.prototype.forceCompositionEnd = function () {
+  if (!this.composing) { return }
+  clearTimeout(this.readDOMTimeout)
+  this.composing = null
+  if (!this.pollContent()) { regChange(this.cm) }
+  this.div.blur()
+  this.div.focus()
+};
+ContentEditableInput.prototype.readFromDOMSoon = function () {
+    var this$1 = this;
</ins><span class="cx"> 
</span><del>-  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 = &quot;position: relative;&quot;;
-      if (widget.coverGutter)
-        parentStyle += &quot;margin-left: -&quot; + cm.display.gutters.offsetWidth + &quot;px;&quot;;
-      if (widget.noHScroll)
-        parentStyle += &quot;width: &quot; + cm.display.wrapper.clientWidth + &quot;px;&quot;;
-      removeChildrenAndAdd(cm.display.measure, elt(&quot;div&quot;, [widget.node], null, parentStyle));
</del><ins>+  if (this.readDOMTimeout != null) { return }
+  this.readDOMTimeout = setTimeout(function () {
+    this$1.readDOMTimeout = null
+    if (this$1.composing) {
+      if (this$1.composing.done) { this$1.composing = null }
+      else { return }
</ins><span class="cx">     }
</span><del>-    return widget.height = widget.node.offsetHeight;
-  }
</del><ins>+    if (this$1.cm.isReadOnly() || !this$1.pollContent())
+      { runInOp(this$1.cm, function () { return regChange(this$1.cm); }) }
+  }, 80)
+};
</ins><span class="cx"> 
</span><del>-  function addLineWidget(doc, handle, node, options) {
-    var widget = new LineWidget(doc, node, options);
-    var cm = doc.cm;
-    if (cm &amp;&amp; widget.noHScroll) cm.display.alignWidgets = true;
-    changeLine(doc, handle, &quot;widget&quot;, function(line) {
-      var widgets = line.widgets || (line.widgets = []);
-      if (widget.insertAt == null) widgets.push(widget);
-      else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
-      widget.line = line;
-      if (cm &amp;&amp; !lineIsHidden(doc, line)) {
-        var aboveVisible = heightAtLine(line) &lt; doc.scrollTop;
-        updateLineHeight(line, line.height + widgetHeight(widget));
-        if (aboveVisible) addToScrollPos(cm, null, widget.height);
-        cm.curOp.forceUpdate = true;
-      }
-      return true;
-    });
-    return widget;
-  }
</del><ins>+ContentEditableInput.prototype.setUneditable = function (node) {
+  node.contentEditable = &quot;false&quot;
+};
</ins><span class="cx"> 
</span><del>-  // LINE DATA STRUCTURE
</del><ins>+ContentEditableInput.prototype.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) }
+};
</ins><span class="cx"> 
</span><del>-  // Line objects. These hold state related to a line, including
-  // highlighting info (the styles array).
-  var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
-    this.text = text;
-    attachMarkedSpans(this, markedSpans);
-    this.height = estimateHeight ? estimateHeight(this) : 1;
-  };
-  eventMixin(Line);
-  Line.prototype.lineNo = function() { return lineNo(this); };
</del><ins>+ContentEditableInput.prototype.readOnlyChanged = function (val) {
+  this.div.contentEditable = String(val != &quot;nocursor&quot;)
+};
</ins><span class="cx"> 
</span><del>-  // 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);
-  }
</del><ins>+ContentEditableInput.prototype.onContextMenu = function () {};
+ContentEditableInput.prototype.resetPosition = function () {};
</ins><span class="cx"> 
</span><del>-  // Detach a line from the document tree and its markers.
-  function cleanUpLine(line) {
-    line.parent = null;
-    detachMarkedSpans(line);
-  }
</del><ins>+ContentEditableInput.prototype.needsContentAttribute = true
</ins><span class="cx"> 
</span><del>-  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] ? &quot;bgClass&quot; : &quot;textClass&quot;;
-      if (output[prop] == null)
-        output[prop] = lineClass[2];
-      else if (!(new RegExp(&quot;(?:^|\s)&quot; + lineClass[2] + &quot;(?:$|\s)&quot;)).test(output[prop]))
-        output[prop] += &quot; &quot; + lineClass[2];
-    }
-    return type;
-  }
</del><ins>+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)
</ins><span class="cx"> 
</span><del>-  function callBlankLine(mode, state) {
-    if (mode.blankLine) return mode.blankLine(state);
-    if (!mode.innerMode) return;
-    var inner = CodeMirror.innerMode(mode, state);
-    if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
</del><ins>+  var order = getOrder(line), side = &quot;left&quot;
+  if (order) {
+    var partPos = getBidiPartAt(order, pos.ch)
+    side = partPos % 2 ? &quot;right&quot; : &quot;left&quot;
</ins><span class="cx">   }
</span><ins>+  var result = nodeAndOffsetInLineMap(info.map, pos.ch, side)
+  result.offset = result.collapse == &quot;right&quot; ? result.end : result.start
+  return result
+}
</ins><span class="cx"> 
</span><del>-  function readToken(mode, stream, state, inner) {
-    for (var i = 0; i &lt; 10; i++) {
-      if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
-      var style = mode.token(stream, state);
-      if (stream.pos &gt; stream.start) return style;
-    }
-    throw new Error(&quot;Mode &quot; + mode.name + &quot; failed to advance stream.&quot;);
-  }
</del><ins>+function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
</ins><span class="cx"> 
</span><del>-  // Utility for getTokenAt and getLineTokens
-  function takeToken(cm, pos, precise, asArray) {
-    function getObj(copy) {
-      return {start: stream.start, end: stream.pos,
-              string: stream.current(),
-              type: style || null,
-              state: copy ? copyState(doc.mode, state) : state};
-    }
-
-    var doc = cm.doc, mode = doc.mode, style;
-    pos = clipPos(doc, pos);
-    var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
-    var stream = new StringStream(line.text, cm.options.tabSize), tokens;
-    if (asArray) tokens = [];
-    while ((asArray || stream.pos &lt; pos.ch) &amp;&amp; !stream.eol()) {
-      stream.start = stream.pos;
-      style = readToken(mode, stream, state);
-      if (asArray) tokens.push(getObj(true));
-    }
-    return asArray ? tokens : getObj();
-  }
-
-  // Run the given mode's parser over a line, calling f for each token.
-  function runMode(cm, text, mode, state, 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), style;
-    var inner = cm.options.addModeClass &amp;&amp; [null];
-    if (text == &quot;&quot;) extractLineClasses(callBlankLine(mode, state), lineClasses);
-    while (!stream.eol()) {
-      if (stream.pos &gt; cm.options.maxHighlightLength) {
-        flattenSpans = false;
-        if (forceToEnd) processLine(cm, text, state, stream.pos);
-        stream.pos = text.length;
-        style = null;
-      } else {
-        style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
</del><ins>+function domTextBetween(cm, from, to, fromLine, toLine) {
+  var text = &quot;&quot;, 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(&quot;cm-text&quot;)
+      if (cmText != null) {
+        if (cmText == &quot;&quot;) { text += node.textContent.replace(/\u200b/g, &quot;&quot;) }
+        else { text += cmText }
+        return
</ins><span class="cx">       }
</span><del>-      if (inner) {
-        var mName = inner[0].name;
-        if (mName) style = &quot;m-&quot; + (style ? mName + &quot; &quot; + style : mName);
</del><ins>+      var markerID = node.getAttribute(&quot;cm-marker&quot;), range
+      if (markerID) {
+        var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID))
+        if (found.length &amp;&amp; (range = found[0].find()))
+          { text += getBetween(cm.doc, range.from, range.to).join(lineSep) }
+        return
</ins><span class="cx">       }
</span><del>-      if (!flattenSpans || curStyle != style) {
-        while (curStart &lt; stream.start) {
-          curStart = Math.min(stream.start, curStart + 50000);
-          f(curStart, curStyle);
-        }
-        curStyle = style;
</del><ins>+      if (node.getAttribute(&quot;contenteditable&quot;) == &quot;false&quot;) { return }
+      for (var i = 0; i &lt; 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
</ins><span class="cx">       }
</span><del>-      stream.start = stream.pos;
</del><ins>+      text += val
</ins><span class="cx">     }
</span><del>-    while (curStart &lt; stream.pos) {
-      // Webkit seems to refuse to render text nodes longer than 57444 characters
-      var pos = Math.min(stream.pos, curStart + 50000);
-      f(pos, curStyle);
-      curStart = pos;
-    }
</del><span class="cx">   }
</span><del>-
-  // 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, state, 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, state, function(end, style) {
-      st.push(end, style);
-    }, lineClasses, forceToEnd);
-
-    // Run overlays, adjust style array.
-    for (var o = 0; o &lt; cm.state.overlays.length; ++o) {
-      var overlay = cm.state.overlays[o], i = 1, at = 0;
-      runMode(cm, line.text, overlay.mode, true, function(end, style) {
-        var start = i;
-        // Ensure there's a token end at the current position, and that i points at it
-        while (at &lt; end) {
-          var i_end = st[i];
-          if (i_end &gt; 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, &quot;cm-overlay &quot; + style);
-          i = start + 2;
-        } else {
-          for (; start &lt; i; start += 2) {
-            var cur = st[start+1];
-            st[start+1] = (cur ? cur + &quot; &quot; : &quot;&quot;) + &quot;cm-overlay &quot; + style;
-          }
-        }
-      }, lineClasses);
-    }
-
-    return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
</del><ins>+  for (;;) {
+    walk(from)
+    if (from == to) { break }
+    from = from.nextSibling
</ins><span class="cx">   }
</span><ins>+  return text
+}
</ins><span class="cx"> 
</span><del>-  function getLineStyles(cm, line, updateFrontier) {
-    if (!line.styles || line.styles[0] != cm.state.modeGen) {
-      var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
-      line.styles = result.styles;
-      if (result.classes) line.styleClasses = result.classes;
-      else if (line.styleClasses) line.styleClasses = null;
-      if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
</del><ins>+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
+  } else {
+    for (lineNode = node;; lineNode = lineNode.parentNode) {
+      if (!lineNode || lineNode == cm.display.lineDiv) { return null }
+      if (lineNode.parentNode &amp;&amp; lineNode.parentNode == cm.display.lineDiv) { break }
</ins><span class="cx">     }
</span><del>-    return line.styles;
</del><span class="cx">   }
</span><del>-
-  // 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, state, startAt) {
-    var mode = cm.doc.mode;
-    var stream = new StringStream(text, cm.options.tabSize);
-    stream.start = stream.pos = startAt || 0;
-    if (text == &quot;&quot;) callBlankLine(mode, state);
-    while (!stream.eol() &amp;&amp; stream.pos &lt;= cm.options.maxHighlightLength) {
-      readToken(mode, stream, state);
-      stream.start = stream.pos;
-    }
</del><ins>+  for (var i = 0; i &lt; cm.display.view.length; i++) {
+    var lineView = cm.display.view[i]
+    if (lineView.node == lineNode)
+      { return locateNodeInLineView(lineView, node, offset) }
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  // 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 = {}, 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, &quot;cm-$&amp;&quot;));
-  }
-
-  // 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 = elt(&quot;span&quot;, null, null, webkit ? &quot;padding-right: .1px&quot; : null);
-    var builder = {pre: elt(&quot;pre&quot;, [content], &quot;CodeMirror-line&quot;), content: content,
-                   col: 0, pos: 0, cm: cm,
-                   splitSpaces: (ie || webkit) &amp;&amp; cm.getOption(&quot;lineWrapping&quot;)};
-    lineView.measure = {};
-
-    // Iterate over the logical lines that make up this visual line.
-    for (var i = 0; i &lt;= (lineView.rest ? lineView.rest.length : 0); i++) {
-      var line = i ? lineView.rest[i - 1] : lineView.line, order;
-      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) &amp;&amp; (order = getOrder(line)))
-        builder.addToken = buildTokenBadBidi(builder.addToken, order);
-      builder.map = [];
-      var allowFrontierUpdate = lineView != cm.display.externalMeasured &amp;&amp; lineNo(line);
-      insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
-      if (line.styleClasses) {
-        if (line.styleClasses.bgClass)
-          builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || &quot;&quot;);
-        if (line.styleClasses.textClass)
-          builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || &quot;&quot;);
-      }
-
-      // 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({});
-      }
</del><ins>+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)
</ins><span class="cx">     }
</span><del>-
-    // See issue #2901
-    if (webkit &amp;&amp; /\bcm-tab\b/.test(builder.content.lastChild.className))
-      builder.content.className = &quot;cm-tab-wrap-hack&quot;;
-
-    signal(cm, &quot;renderLine&quot;, cm, lineView.line, builder.pre);
-    if (builder.pre.className)
-      builder.textClass = joinClasses(builder.pre.className, builder.textClass || &quot;&quot;);
-
-    return builder;
</del><span class="cx">   }
</span><span class="cx"> 
</span><del>-  function defaultSpecialCharPlaceholder(ch) {
-    var token = elt(&quot;span&quot;, &quot;\u2022&quot;, &quot;cm-invalidchar&quot;);
-    token.title = &quot;\\u&quot; + ch.charCodeAt(0).toString(16);
-    token.setAttribute(&quot;aria-label&quot;, token.title);
-    return token;
</del><ins>+  var textNode = node.nodeType == 3 ? node : null, topNode = node
+  if (!textNode &amp;&amp; node.childNodes.length == 1 &amp;&amp; node.firstChild.nodeType == 3) {
+    textNode = node.firstChild
+    if (offset) { offset = textNode.nodeValue.length }
</ins><span class="cx">   }
</span><ins>+  while (topNode.parentNode != wrapper) { topNode = topNode.parentNode }
+  var measure = lineView.measure, maps = measure.maps
</ins><span class="cx"> 
</span><del>-  // 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 ? text.replace(/ {3,}/g, splitSpaces) : text;
-    var special = builder.cm.state.specialChars, mustWrap = false;
-    if (!special.test(text)) {
-      builder.col += text.length;
-      var content = document.createTextNode(displayText);
-      builder.map.push(builder.pos, builder.pos + text.length, content);
-      if (ie &amp;&amp; ie_version &lt; 9) mustWrap = true;
-      builder.pos += text.length;
-    } else {
-      var content = document.createDocumentFragment(), 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 &amp;&amp; ie_version &lt; 9) content.appendChild(elt(&quot;span&quot;, [txt]));
-          else content.appendChild(txt);
-          builder.map.push(builder.pos, builder.pos + skipped, txt);
-          builder.col += skipped;
-          builder.pos += skipped;
</del><ins>+  function find(textNode, topNode, offset) {
+    for (var i = -1; i &lt; (maps ? maps.length : 0); i++) {
+      var map = i &lt; 0 ? measure.map : maps[i]
+      for (var j = 0; j &lt; map.length; j += 3) {
+        var curNode = map[j + 2]
+        if (curNode == textNode || curNode == topNode) {
+          var line = lineNo(i &lt; 0 ? lineView.line : lineView.rest[i])
+          var ch = map[j] + offset
+          if (offset &lt; 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)] }
+          return Pos(line, ch)
</ins><span class="cx">         }
</span><del>-        if (!m) break;
-        pos += skipped + 1;
-        if (m[0] == &quot;\t&quot;) {
-          var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
-          var txt = content.appendChild(elt(&quot;span&quot;, spaceStr(tabWidth), &quot;cm-tab&quot;));
-          txt.setAttribute(&quot;role&quot;, &quot;presentation&quot;);
-          txt.setAttribute(&quot;cm-text&quot;, &quot;\t&quot;);
-          builder.col += tabWidth;
-        } else if (m[0] == &quot;\r&quot; || m[0] == &quot;\n&quot;) {
-          var txt = content.appendChild(elt(&quot;span&quot;, m[0] == &quot;\r&quot; ? &quot;␍&quot; : &quot;␤&quot;, &quot;cm-invalidchar&quot;));
-          txt.setAttribute(&quot;cm-text&quot;, m[0]);
-          builder.col += 1;
-        } else {
-          var txt = builder.cm.options.specialCharPlaceholder(m[0]);
-          txt.setAttribute(&quot;cm-text&quot;, m[0]);
-          if (ie &amp;&amp; ie_version &lt; 9) content.appendChild(elt(&quot;span&quot;, [txt]));
-          else content.appendChild(txt);
-          builder.col += 1;
-        }
-        builder.map.push(builder.pos, builder.pos + 1, txt);
-        builder.pos++;
</del><span class="cx">       }
</span><span class="cx">     }
</span><del>-    if (style || startStyle || endStyle || mustWrap || css) {
-      var fullStyle = style || &quot;&quot;;
-      if (startStyle) fullStyle += startStyle;
-      if (endStyle) fullStyle += endStyle;
-      var token = elt(&quot;span&quot;, [content], fullStyle, css);
-      if (title) token.title = title;
-      return builder.content.appendChild(token);
-    }
-    builder.content.appendChild(content);
</del><span class="cx">   }
</span><ins>+  var found = find(textNode, topNode, offset)
+  if (found) { return badPos(found, bad) }
</ins><span class="cx"> 
</span><del>-  function splitSpaces(old) {
-    var out = &quot; &quot;;
-    for (var i = 0; i &lt; old.length - 2; ++i) out += i % 2 ? &quot; &quot; : &quot;\u00a0&quot;;
-    out += &quot; &quot;;
-    return out;
</del><ins>+  // 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 }
</ins><span class="cx">   }
</span><del>-
-  // 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 + &quot; cm-force-border&quot; : &quot;cm-force-border&quot;;
-      var start = builder.pos, end = start + text.length;
-      for (;;) {
-        // Find the part that overlaps with the start of this text
-        for (var i = 0; i &lt; order.length; i++) {
-          var part = order[i];
-          if (part.to &gt; start &amp;&amp; part.from &lt;= start) break;
-        }
-        if (part.to &gt;= 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;
-      }
-    };
</del><ins>+  for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
+    found = find(before, before.firstChild, -1)
+    if (found)
+      { return badPos(Pos(found.line, found.ch + dist$1), bad) }
+    else
+      { dist$1 += before.textContent.length }
</ins><span class="cx">   }
</span><ins>+}
</ins><span class="cx"> 
</span><del>-  function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
-    var widget = !ignoreWidget &amp;&amp; marker.widgetNode;
-    if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
-    if (!ignoreWidget &amp;&amp; builder.cm.display.input.needsContentAttribute) {
-      if (!widget)
-        widget = builder.content.appendChild(document.createElement(&quot;span&quot;));
-      widget.setAttribute(&quot;cm-marker&quot;, marker.id);
-    }
-    if (widget) {
-      builder.cm.display.input.setUneditable(widget);
-      builder.content.appendChild(widget);
-    }
-    builder.pos += size;
-  }
</del><ins>+// TEXTAREA INPUT STYLE
</ins><span class="cx"> 
</span><del>-  // 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; i &lt; styles.length; i+=2)
-        builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
-      return;
-    }
</del><ins>+var TextareaInput = function(cm) {
+  this.cm = cm
+  // See input.poll and input.reset
+  this.prevInput = &quot;&quot;
</ins><span class="cx"> 
</span><del>-    var len = allText.length, pos = 0, i = 1, text = &quot;&quot;, style, css;
-    var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
-    for (;;) {
-      if (nextChange == pos) { // Update current marker set
-        spanStyle = spanEndStyle = spanStartStyle = title = css = &quot;&quot;;
-        collapsed = null; nextChange = Infinity;
-        var foundBookmarks = [];
-        for (var j = 0; j &lt; spans.length; ++j) {
-          var sp = spans[j], m = sp.marker;
-          if (m.type == &quot;bookmark&quot; &amp;&amp; sp.from == pos &amp;&amp; m.widgetNode) {
-            foundBookmarks.push(m);
-          } else if (sp.from &lt;= pos &amp;&amp; (sp.to == null || sp.to &gt; pos || m.collapsed &amp;&amp; sp.to == pos &amp;&amp; sp.from == pos)) {
-            if (sp.to != null &amp;&amp; sp.to != pos &amp;&amp; nextChange &gt; sp.to) {
-              nextChange = sp.to;
-              spanEndStyle = &quot;&quot;;
-            }
-            if (m.className) spanStyle += &quot; &quot; + m.className;
-            if (m.css) css = m.css;
-            if (m.startStyle &amp;&amp; sp.from == pos) spanStartStyle += &quot; &quot; + m.startStyle;
-            if (m.endStyle &amp;&amp; sp.to == nextChange) spanEndStyle += &quot; &quot; + m.endStyle;
-            if (m.title &amp;&amp; !title) title = m.title;
-            if (m.collapsed &amp;&amp; (!collapsed || compareCollapsedMarkers(collapsed.marker, m) &lt; 0))
-              collapsed = sp;
-          } else if (sp.from &gt; pos &amp;&amp; nextChange &gt; sp.from) {
-            nextChange = sp.from;
-          }
-        }
-        if (collapsed &amp;&amp; (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 (!collapsed &amp;&amp; foundBookmarks.length) for (var j = 0; j &lt; foundBookmarks.length; ++j)
-          buildCollapsedSpan(builder, 0, foundBookmarks[j]);
-      }
-      if (pos &gt;= len) break;
</del><ins>+  // 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
+};
</ins><span class="cx"> 
</span><del>-      var upto = Math.min(len, nextChange);
-      while (true) {
-        if (text) {
-          var end = pos + text.length;
-          if (!collapsed) {
-            var tokenText = end &gt; upto ? text.slice(0, upto - pos) : text;
-            builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
-                             spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : &quot;&quot;, title, css);
-          }
-          if (end &gt;= upto) {text = text.slice(upto - pos); pos = upto; break;}
-          pos = end;
-          spanStartStyle = &quot;&quot;;
-        }
-        text = allText.slice(at, at = styles[i++]);
-        style = interpretTokenStyle(styles[i++], builder.cm.options);
-      }
-    }
-  }
</del><ins>+TextareaInput.prototype.init = function (display) {
+    var this$1 = this;
</ins><span class="cx"> 
</span><del>-  // DOCUMENT DATA STRUCTURE
</del><ins>+  var input = this, cm = this.cm
</ins><span class="cx"> 
</span><del>-  // By default, updates that start and end at the beginning of a line
-  // are treated specially, in order to make the association of line
-  // widgets and marker elements with the text behave more intuitive.
-  function isWholeLineUpdate(doc, change) {
-    return change.from.ch == 0 &amp;&amp; change.to.ch == 0 &amp;&amp; lst(change.text) == &quot;&quot; &amp;&amp;
-      (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
-  }
</del><ins>+  // 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)
</ins><span class="cx"> 
</span><del>-  // Perform a change on the document data structure.
-  function updateDoc(doc, change, markedSpans, estimateHeight) {
-    function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
-    function update(line, text, spans) {
-      updateLine(line, text, spans, estimateHeight);
-      signalLater(line, &quot;change&quot;, line, change);
-    }
-    function linesFor(start, end) {
-      for (var i = start, result = []; i &lt; end; ++i)
-        result.push(new Line(text[i], spansFor(i), estimateHeight));
-      return result;
-    }
</del><ins>+  // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
+  if (ios) { te.style.width = &quot;0px&quot; }
</ins><span class="cx"> 
</span><del>-    var from = change.from, to = change.to, text = change.text;
-    var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
-    var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
</del><ins>+  on(te, &quot;input&quot;, function () {
+    if (ie &amp;&amp; ie_version &gt;= 9 &amp;&amp; this$1.hasSelection) { this$1.hasSelection = null }
+    input.poll()
+  })
</ins><span class="cx"> 
</span><del>-    // Adjust the line structure
-    if (change.full) {
-      doc.insert(0, linesFor(0, text.length));
-      doc.remove(text.length, doc.size - text.length);
-    } else if (isWholeLineUpdate(doc, change)) {
-      // This is a whole-line replace. Treated specially to make
-      // sure line objects move the way they are supposed to.
-      var added = linesFor(0, text.length - 1);
-      update(lastLine, lastLine.text, lastSpans);
-      if (nlines) doc.remove(from.line, nlines);
-      if (added.length) doc.insert(from.line, added);
-    } else if (firstLine == lastLine) {
-      if (text.length == 1) {
-        update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
-      } else {
-        var added = linesFor(1, text.length - 1);
-        added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
-        update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
-        doc.insert(from.line + 1, added);
-      }
-    } else if (text.length == 1) {
-      update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
-      doc.remove(from.line + 1, nlines);
-    } else {
-      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
-      update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
-      var added = linesFor(1, text.length - 1);
-      if (nlines &gt; 1) doc.remove(from.line + 1, nlines - 1);
-      doc.insert(from.line + 1, added);
-    }
</del><ins>+  on(te, &quot;paste&quot;, function (e) {
+    if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
</ins><span class="cx"> 
</span><del>-    signalLater(doc, &quot;change&quot;, doc, change);
-  }
</del><ins>+    cm.state.pasteIncoming = true
+    input.fastPoll()
+  })
</ins><span class="cx"> 
</span><del>-  // The document is represented as a BTree consisting of leaves, with
-  // chunk of lines in them, and branches, with up to ten leaves or
-  // other branch nodes below them. The top node is always a branch
-  // node, and is the document object itself (meaning it has
-  // additional methods and properties).
-  //
-  // All nodes have parent links. The tree is used both to go from
-  // line numbers to line objects, and to go from objects to numbers.
-  // It also indexes by height, and is used to convert between height
-  // and line object, and to find the total height of the document.
-  //
-  // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
-
-  function LeafChunk(lines) {
-    this.lines = lines;
-    this.parent = null;
-    for (var i = 0, height = 0; i &lt; lines.length; ++i) {
-      lines[i].parent = this;
-      height += lines[i].height;
-    }
-    this.height = height;
-  }
-
-  LeafChunk.prototype = {
-    chunkSize: function() { return this.lines.length; },
-    // Remove the n lines at offset 'at'.
-    removeInner: function(at, n) {
-      for (var i = at, e = at + n; i &lt; e; ++i) {
-        var line = this.lines[i];
-        this.height -= line.height;
-        cleanUpLine(line);
-        signalLater(line, &quot;delete&quot;);
</del><ins>+  function prepareCopyCut(e) {
+    if (signalDOMEvent(cm, e)) { return }
+    if (cm.somethingSelected()) {
+      setLastCopied({lineWise: false, text: cm.getSelections()})
+      if (input.inaccurateSelection) {
+        input.prevInput = &quot;&quot;
+        input.inaccurateSelection = false
+        te.value = lastCopied.text.join(&quot;\n&quot;)
+        selectInput(te)
</ins><span class="cx">       }
</span><del>-      this.lines.splice(at, n);
-    },
-    // Helper used to collapse a small branch into a single leaf.
-    collapse: function(lines) {
-      lines.push.apply(lines, this.lines);
-    },
-    // Insert the given array of lines at offset 'at', count them as
-    // having the given height.
-    insertInner: function(at, lines, height) {
-      this.height += height;
-      this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
-      for (var i = 0; i &lt; lines.length; ++i) lines[i].parent = this;
-    },
-    // Used to iterate over a part of the tree.
-    iterN: function(at, n, op) {
-      for (var e = at + n; at &lt; e; ++at)
-        if (op(this.lines[at])) return true;
-    }
-  };
-
-  function BranchChunk(children) {
-    this.children = children;
-    var size = 0, height = 0;
-    for (var i = 0; i &lt; children.length; ++i) {
-      var ch = children[i];
-      size += ch.chunkSize(); height += ch.height;
-      ch.parent = this;
-    }
-    this.size = size;
-    this.height = height;
-    this.parent = null;
-  }
-
-  BranchChunk.prototype = {
-    chunkSize: function() { return this.size; },
-    removeInner: function(at, n) {
-      this.size -= n;
-      for (var i = 0; i &lt; this.children.length; ++i) {
-        var child = this.children[i], sz = child.chunkSize();
-        if (at &lt; sz) {
-          var rm = Math.min(n, sz - at), oldHeight = child.height;
-          child.removeInner(at, rm);
-          this.height -= oldHeight - child.height;
-          if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
-          if ((n -= rm) == 0) break;
-          at = 0;
-        } else at -= sz;
</del><ins>+    } else if (!cm.options.lineWiseCopyCut) {
+      return
+    } else {
+      var ranges = copyableRanges(cm)
+      setLastCopied({lineWise: true, text: ranges.text})
+      if (e.type == &quot;cut&quot;) {
+        cm.setSelections(ranges.ranges, null, sel_dontScroll)
+      } else {
+        input.prevInput = &quot;&quot;
+        te.value = ranges.text.join(&quot;\n&quot;)
+        selectInput(te)
</ins><span class="cx">       }
</span><del>-      // If the result is smaller than 25 lines, ensure that it is a
-      // single leaf node.
-      if (this.size - n &lt; 25 &amp;&amp;
-          (this.children.length &gt; 1 || !(this.children[0] instanceof LeafChunk))) {
-        var lines = [];
-        this.collapse(lines);
-        this.children = [new LeafChunk(lines)];
-        this.children[0].parent = this;
-      }
-    },
-    collapse: function(lines) {
-      for (var i = 0; i &lt; this.children.length; ++i) this.children[i].collapse(lines);
-    },
-    insertInner: function(at, lines, height) {
-      this.size += lines.length;
-      this.height += height;
-      for (var i = 0; i &lt; this.children.length; ++i) {
-        var child = this.children[i], sz = child.chunkSize();
-        if (at &lt;= sz) {
-          child.insertInner(at, lines, height);
-          if (child.lines &amp;&amp; child.lines.length &gt; 50) {
-            while (child.lines.length &gt; 50) {
-              var spilled = child.lines.splice(child.lines.length - 25, 25);
-              var newleaf = new LeafChunk(spilled);
-              child.height -= newleaf.height;
-              this.children.splice(i + 1, 0, newleaf);
-              newleaf.parent = this;
-            }
-            this.maybeSpill();
-          }
-          break;
-        }
-        at -= sz;
-      }
-    },
-    // When a node has grown, check whether it should be split.
-    maybeSpill: function() {
-      if (this.children.length &lt;= 10) return;
-      var me = this;
-      do {
-        var spilled = me.children.splice(me.children.length - 5, 5);
-        var sibling = new BranchChunk(spilled);
-        if (!me.parent) { // Become the parent node
-          var copy = new BranchChunk(me.children);
-          copy.parent = me;
-          me.children = [copy, sibling];
-          me = copy;
-        } else {
-          me.size -= sibling.size;
-          me.height -= sibling.height;
-          var myIndex = indexOf(me.parent.children, me);
-          me.parent.children.splice(myIndex + 1, 0, sibling);
-        }
-        sibling.parent = me.parent;
-      } while (me.children.length &gt; 10);
-      me.parent.maybeSpill();
-    },
-    iterN: function(at, n, op) {
-      for (var i = 0; i &lt; this.children.length; ++i) {
-        var child = this.children[i], sz = child.chunkSize();
-        if (at &lt; sz) {
-          var used = Math.min(n, sz - at);
-          if (child.iterN(at, used, op)) return true;
-          if ((n -= used) == 0) break;
-          at = 0;
-        } else at -= sz;
-      }
</del><span class="cx">     }
</span><del>-  };
-
-  var nextDocId = 0;
-  var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
-    if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
-    if (firstLine == null) firstLine = 0;
-
-    BranchChunk.call(this, [new LeafChunk([new Line(&quot;&quot;, null)])]);
-    this.first = firstLine;
-    this.scrollTop = this.scrollLeft = 0;
-    this.cantEdit = false;
-    this.cleanGeneration = 1;
-    this.frontier = firstLine;
-    var start = Pos(firstLine, 0);
-    this.sel = simpleSelection(start);
-    this.history = new History(null);
-    this.id = ++nextDocId;
-    this.modeOption = mode;
-    this.lineSep = lineSep;
-
-    if (typeof text == &quot;string&quot;) text = this.splitLines(text);
-    updateDoc(this, {from: start, to: start, text: text});
-    setSelection(this, simpleSelection(start), sel_dontScroll);
-  };
-
-  Doc.prototype = createObj(BranchChunk.prototype, {
-    constructor: Doc,
-    // Iterate over the document. Supports two forms -- with only one
-    // argument, it calls that for each line in the document. With
-    // three, it iterates over the range given by the first two (with
-    // the second being non-inclusive).
-    iter: function(from, to, op) {
-      if (op) this.iterN(from - this.first, to - from, op);
-      else this.iterN(this.first, this.first + this.size, from);
-    },
-
-    // Non-public interface for adding and removing lines.
-    insert: function(at, lines) {
-      var height = 0;
-      for (var i = 0; i &lt; lines.length; ++i) height += lines[i].height;
-      this.insertInner(at - this.first, lines, height);
-    },
-    remove: function(at, n) { this.removeInner(at - this.first, n); },
-
-    // From here, the methods are part of the public interface. Most
-    // are also available from CodeMirror (editor) instances.
-
-    getValue: function(lineSep) {
-      var lines = getLines(this, this.first, this.first + this.size);
-      if (lineSep === false) return lines;
-      return lines.join(lineSep || this.lineSeparator());
-    },
-    setValue: docMethodOp(function(code) {
-      var top = Pos(this.first, 0), last = this.first + this.size - 1;
-      makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
-                        text: this.splitLines(code), origin: &quot;setValue&quot;, full: true}, true);
-      setSelection(this, simpleSelection(top));
-    }),
-    replaceRange: function(code, from, to, origin) {
-      from = clipPos(this, from);
-      to = to ? clipPos(this, to) : from;
-      replaceRange(this, code, from, to, origin);
-    },
-    getRange: function(from, to, lineSep) {
-      var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
-      if (lineSep === false) return lines;
-      return lines.join(lineSep || this.lineSeparator());
-    },
-
-    getLine: function(line) {var l = this.getLineHandle(line); return l &amp;&amp; l.text;},
-
-    getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
-    getLineNumber: function(line) {return lineNo(line);},
-
-    getLineHandleVisualStart: function(line) {
-      if (typeof line == &quot;number&quot;) line = getLine(this, line);
-      return visualLine(line);
-    },
-
-    lineCount: function() {return this.size;},
-    firstLine: function() {return this.first;},
-    lastLine: function() {return this.first + this.size - 1;},
-
-    clipPos: function(pos) {return clipPos(this, pos);},
-
-    getCursor: function(start) {
-      var range = this.sel.primary(), pos;
-      if (start == null || start == &quot;head&quot;) pos = range.head;
-      else if (start == &quot;anchor&quot;) pos = range.anchor;
-      else if (start == &quot;end&quot; || start == &quot;to&quot; || start === false) pos = range.to();
-      else pos = range.from();
-      return pos;
-    },
-    listSelections: function() { return this.sel.ranges; },
-    somethingSelected: function() {return this.sel.somethingSelected();},
-
-    setCursor: docMethodOp(function(line, ch, options) {
-      setSimpleSelection(this, clipPos(this, typeof line == &quot;number&quot; ? Pos(line, ch || 0) : line), null, options);
-    }),
-    setSelection: docMethodOp(function(anchor, head, options) {
-      setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
-    }),
-    extendSelection: docMethodOp(function(head, other, options) {
-      extendSelection(this, clipPos(this, head), other &amp;&amp; clipPos(this, other), options);
-    }),
-    extendSelections: docMethodOp(function(heads, options) {
-      extendSelections(this, clipPosArray(this, heads, options));
-    }),
-    extendSelectionsBy: docMethodOp(function(f, options) {
-      extendSelections(this, map(this.sel.ranges, f), options);
-    }),
-    setSelections: docMethodOp(function(ranges, primary, options) {
-      if (!ranges.length) return;
-      for (var i = 0, out = []; i &lt; ranges.length; i++)
-        out[i] = new Range(clipPos(this, ranges[i].anchor),
-                           clipPos(this, ranges[i].head));
-      if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
-      setSelection(this, normalizeSelection(out, primary), options);
-    }),
-    addSelection: docMethodOp(function(anchor, head, options) {
-      var ranges = this.sel.ranges.slice(0);
-      ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
-      setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
-    }),
-
-    getSelection: function(lineSep) {
-      var ranges = this.sel.ranges, lines;
-      for (var i = 0; i &lt; ranges.length; i++) {
-        var sel = getBetween(this, ranges[i].from(), ranges[i].to());
-        lines = lines ? lines.concat(sel) : sel;
-      }
-      if (lineSep === false) return lines;
-      else return lines.join(lineSep || this.lineSeparator());
-    },
-    getSelections: function(lineSep) {
-      var parts = [], ranges = this.sel.ranges;
-      for (var i = 0; i &lt; ranges.length; i++) {
-        var sel = getBetween(this, ranges[i].from(), ranges[i].to());
-        if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
-        parts[i] = sel;
-      }
-      return parts;
-    },
-    replaceSelection: function(code, collapse, origin) {
-      var dup = [];
-      for (var i = 0; i &lt; this.sel.ranges.length; i++)
-        dup[i] = code;
-      this.replaceSelections(dup, collapse, origin || &quot;+input&quot;);
-    },
-    replaceSelections: docMethodOp(function(code, collapse, origin) {
-      var changes = [], sel = this.sel;
-      for (var i = 0; i &lt; sel.ranges.length; i++) {
-        var range = sel.ranges[i];
-        changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
-      }
-      var newSel = collapse &amp;&amp; collapse != &quot;end&quot; &amp;&amp; computeReplacedSel(this, changes, collapse);
-      for (var i = changes.length - 1; i &gt;= 0; i--)
-        makeChange(this, changes[i]);
-      if (newSel) setSelectionReplaceHistory(this, newSel);
-      else if (this.cm) ensureCursorVisible(this.cm);
-    }),
-    undo: docMethodOp(function() {makeChangeFromHistory(this, &quot;undo&quot;);}),
-    redo: docMethodOp(function() {makeChangeFromHistory(this, &quot;redo&quot;);}),
-    undoSelection: docMethodOp(function() {makeChangeFromHistory(this, &quot;undo&quot;, true);}),
-    redoSelection: docMethodOp(function() {makeChangeFromHistory(this, &quot;redo&quot;, true);}),
-
-    setExtending: function(val) {this.extend = val;},
-    getExtending: function() {return this.extend;},
-
-    historySize: function() {
-      var hist = this.history, done = 0, undone = 0;
-      for (var i = 0; i &lt; hist.done.length; i++) if (!hist.done[i].ranges) ++done;
-      for (var i = 0; i &lt; hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
-      return {undo: done, redo: undone};
-    },
-    clearHistory: function() {this.history = new History(this.history.maxGeneration);},
-
-    markClean: function() {
-      this.cleanGeneration = this.changeGeneration(true);
-    },
-    changeGeneration: function(forceSplit) {
-      if (forceSplit)
-        this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
-      return this.history.generation;
-    },
-    isClean: function (gen) {
-      return this.history.generation == (gen || this.cleanGeneration);
-    },
-
-    getHistory: function() {
-      return {done: copyHistoryArray(this.history.done),
-              undone: copyHistoryArray(this.history.undone)};
-    },
-    setHistory: function(histData) {
-      var hist = this.history = new History(this.history.maxGeneration);
-      hist.done = copyHistoryArray(histData.done.slice(0), null, true);
-      hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
-    },
-
-    addLineClass: docMethodOp(function(handle, where, cls) {
-      return changeLine(this, handle, where == &quot;gutter&quot; ? &quot;gutter&quot; : &quot;class&quot;, function(line) {
-        var prop = where == &quot;text&quot; ? &quot;textClass&quot;
-                 : where == &quot;background&quot; ? &quot;bgClass&quot;
-                 : where == &quot;gutter&quot; ? &quot;gutterClass&quot; : &quot;wrapClass&quot;;
-        if (!line[prop]) line[prop] = cls;
-        else if (classTest(cls).test(line[prop])) return false;
-        else line[prop] += &quot; &quot; + cls;
-        return true;
-      });
-    }),
-    removeLineClass: docMethodOp(function(handle, where, cls) {
-      return changeLine(this, handle, where == &quot;gutter&quot; ? &quot;gutter&quot; : &quot;class&quot;, function(line) {
-        var prop = where == &quot;text&quot; ? &quot;textClass&quot;
-                 : where == &quot;background&quot; ? &quot;bgClass&quot;
-                 : where == &quot;gutter&quot; ? &quot;gutterClass&quot; : &quot;wrapClass&quot;;
-        var cur = line[prop];
-        if (!cur) return false;
-        else if (cls == null) line[prop] = null;
-        else {
-          var found = cur.match(classTest(cls));
-          if (!found) return false;
-          var end = found.index + found[0].length;
-          line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? &quot;&quot; : &quot; &quot;) + cur.slice(end) || null;
-        }
-        return true;
-      });
-    }),
-
-    addLineWidget: docMethodOp(function(handle, node, options) {
-      return addLineWidget(this, handle, node, options);
-    }),
-    removeLineWidget: function(widget) { widget.clear(); },
-
-    markText: function(from, to, options) {
-      return markText(this, clipPos(this, from), clipPos(this, to), options, &quot;range&quot;);
-    },
-    setBookmark: function(pos, options) {
-      var realOpts = {replacedWith: options &amp;&amp; (options.nodeType == null ? options.widget : options),
-                      insertLeft: options &amp;&amp; options.insertLeft,
-                      clearWhenEmpty: false, shared: options &amp;&amp; options.shared,
-                      handleMouseEvents: options &amp;&amp; options.handleMouseEvents};
-      pos = clipPos(this, pos);
-      return markText(this, pos, pos, realOpts, &quot;bookmark&quot;);
-    },
-    findMarksAt: function(pos) {
-      pos = clipPos(this, pos);
-      var markers = [], spans = getLine(this, pos.line).markedSpans;
-      if (spans) for (var i = 0; i &lt; spans.length; ++i) {
-        var span = spans[i];
-        if ((span.from == null || span.from &lt;= pos.ch) &amp;&amp;
-            (span.to == null || span.to &gt;= pos.ch))
-          markers.push(span.marker.parent || span.marker);
-      }
-      return markers;
-    },
-    findMarks: function(from, to, filter) {
-      from = clipPos(this, from); to = clipPos(this, to);
-      var found = [], lineNo = from.line;
-      this.iter(from.line, to.line + 1, function(line) {
-        var spans = line.markedSpans;
-        if (spans) for (var i = 0; i &lt; spans.length; i++) {
-          var span = spans[i];
-          if (!(lineNo == from.line &amp;&amp; from.ch &gt; span.to ||
-                span.from == null &amp;&amp; lineNo != from.line||
-                lineNo == to.line &amp;&amp; span.from &gt; to.ch) &amp;&amp;
-              (!filter || filter(span.marker)))
-            found.push(span.marker.parent || span.marker);
-        }
-        ++lineNo;
-      });
-      return found;
-    },
-    getAllMarks: function() {
-      var markers = [];
-      this.iter(function(line) {
-        var sps = line.markedSpans;
-        if (sps) for (var i = 0; i &lt; sps.length; ++i)
-          if (sps[i].from != null) markers.push(sps[i].marker);
-      });
-      return markers;
-    },
-
-    posFromIndex: function(off) {
-      var ch, lineNo = this.first;
-      this.iter(function(line) {
-        var sz = line.text.length + 1;
-        if (sz &gt; off) { ch = off; return true; }
-        off -= sz;
-        ++lineNo;
-      });
-      return clipPos(this, Pos(lineNo, ch));
-    },
-    indexFromPos: function (coords) {
-      coords = clipPos(this, coords);
-      var index = coords.ch;
-      if (coords.line &lt; this.first || coords.ch &lt; 0) return 0;
-      this.iter(this.first, coords.line, function (line) {
-        index += line.text.length + 1;
-      });
-      return index;
-    },
-
-    copy: function(copyHistory) {
-      var doc = new Doc(getLines(this, this.first, this.first + this.size),
-                        this.modeOption, this.first, this.lineSep);
-      doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
-      doc.sel = this.sel;
-      doc.extend = false;
-      if (copyHistory) {
-        doc.history.undoDepth = this.history.undoDepth;
-        doc.setHistory(this.getHistory());
-      }
-      return doc;
-    },
-
-    linkedDoc: function(options) {
-      if (!options) options = {};
-      var from = this.first, to = this.first + this.size;
-      if (options.from != null &amp;&amp; options.from &gt; from) from = options.from;
-      if (options.to != null &amp;&amp; options.to &lt; to) to = options.to;
-      var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
-      if (options.sharedHist) copy.history = this.history;
-      (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
-      copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
-      copySharedMarkers(copy, findSharedMarkers(this));
-      return copy;
-    },
-    unlinkDoc: function(other) {
-      if (other instanceof CodeMirror) other = other.doc;
-      if (this.linked) for (var i = 0; i &lt; this.linked.length; ++i) {
-        var link = this.linked[i];
-        if (link.doc != other) continue;
-        this.linked.splice(i, 1);
-        other.unlinkDoc(this);
-        detachSharedMarkers(findSharedMarkers(this));
-        break;
-      }
-      // If the histories were shared, split them again
-      if (other.history == this.history) {
-        var splitIds = [other.id];
-        linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
-        other.history = new History(null);
-        other.history.done = copyHistoryArray(this.history.done, splitIds);
-        other.history.undone = copyHistoryArray(this.history.undone, splitIds);
-      }
-    },
-    iterLinkedDocs: function(f) {linkedDocs(this, f);},
-
-    getMode: function() {return this.mode;},
-    getEditor: function() {return this.cm;},
-
-    splitLines: function(str) {
-      if (this.lineSep) return str.split(this.lineSep);
-      return splitLinesAuto(str);
-    },
-    lineSeparator: function() { return this.lineSep || &quot;\n&quot;; }
-  });
-
-  // Public alias.
-  Doc.prototype.eachLine = Doc.prototype.iter;
-
-  // Set up methods on CodeMirror's prototype to redirect to the editor's document.
-  var dontDelegate = &quot;iter insert remove copy getEditor constructor&quot;.split(&quot; &quot;);
-  for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) &amp;&amp; indexOf(dontDelegate, prop) &lt; 0)
-    CodeMirror.prototype[prop] = (function(method) {
-      return function() {return method.apply(this.doc, arguments);};
-    })(Doc.prototype[prop]);
-
-  eventMixin(Doc);
-
-  // Call f for all linked documents.
-  function linkedDocs(doc, f, sharedHistOnly) {
-    function propagate(doc, skip, sharedHist) {
-      if (doc.linked) for (var i = 0; i &lt; doc.linked.length; ++i) {
-        var rel = doc.linked[i];
-        if (rel.doc == skip) continue;
-        var shared = sharedHist &amp;&amp; rel.sharedHist;
-        if (sharedHistOnly &amp;&amp; !shared) continue;
-        f(rel.doc, shared);
-        propagate(rel.doc, doc, shared);
-      }
-    }
-    propagate(doc, null, true);
</del><ins>+    if (e.type == &quot;cut&quot;) { cm.state.cutIncoming = true }
</ins><span class="cx">   }
</span><ins>+  on(te, &quot;cut&quot;, prepareCopyCut)
+  on(te, &quot;copy&quot;, prepareCopyCut)
</ins><span class="cx"> 
</span><del>-  // Attach a document to an editor.
-  function attachDoc(cm, doc) {
-    if (doc.cm) throw new Error(&quot;This document is already in use.&quot;);
-    cm.doc = doc;
-    doc.cm = cm;
-    estimateLineHeights(cm);
-    loadMode(cm);
-    if (!cm.options.lineWrapping) findMaxLine(cm);
-    cm.options.mode = doc.modeOption;
-    regChange(cm);
-  }
</del><ins>+  on(display.scroller, &quot;paste&quot;, function (e) {
+    if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
+    cm.state.pasteIncoming = true
+    input.focus()
+  })
</ins><span class="cx"> 
</span><del>-  // LINE UTILITIES
</del><ins>+  // Prevent normal selection in the editor (we handle our own)
+  on(display.lineSpace, &quot;selectstart&quot;, function (e) {
+    if (!eventInWidget(display, e)) { e_preventDefault(e) }
+  })
</ins><span class="cx"> 
</span><del>-  // Find the line object corresponding to the given line number.
-  function getLine(doc, n) {
-    n -= doc.first;
-    if (n &lt; 0 || n &gt;= doc.size) throw new Error(&quot;There is no line &quot; + (n + doc.first) + &quot; in the document.&quot;);
-    for (var chunk = doc; !chunk.lines;) {
-      for (var i = 0;; ++i) {
-        var child = chunk.children[i], sz = child.chunkSize();
-        if (n &lt; sz) { chunk = child; break; }
-        n -= sz;
-      }
</del><ins>+  on(te, &quot;compositionstart&quot;, function () {
+    var start = cm.getCursor(&quot;from&quot;)
+    if (input.composing) { input.composing.range.clear() }
+    input.composing = {
+      start: start,
+      range: cm.markText(start, cm.getCursor(&quot;to&quot;), {className: &quot;CodeMirror-composing&quot;})
</ins><span class="cx">     }
</span><del>-    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); });
-    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();
-      }
</del><ins>+  })
+  on(te, &quot;compositionend&quot;, function () {
+    if (input.composing) {
+      input.poll()
+      input.composing.range.clear()
+      input.composing = null
</ins><span class="cx">     }
</span><del>-    return no + cur.first;
-  }
</del><ins>+  })
+};
</ins><span class="cx"> 
</span><del>-  // 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 = 0; i &lt; chunk.children.length; ++i) {
-        var child = chunk.children[i], ch = child.height;
-        if (h &lt; ch) { chunk = child; continue outer; }
-        h -= ch;
-        n += child.chunkSize();
-      }
-      return n;
-    } while (!chunk.lines);
-    for (var i = 0; i &lt; chunk.lines.length; ++i) {
-      var line = chunk.lines[i], lh = line.height;
-      if (h &lt; lh) break;
-      h -= lh;
-    }
-    return n + i;
-  }
</del><ins>+TextareaInput.prototype.prepareSelection = function () {
+  // Redraw the selection and/or cursor
+  var cm = this.cm, display = cm.display, doc = cm.doc
+  var result = prepareSelection(cm)
</ins><span class="cx"> 
</span><del>-
-  // Find the height above the given line.
-  function heightAtLine(lineObj) {
-    lineObj = visualLine(lineObj);
-
-    var h = 0, chunk = lineObj.parent;
-    for (var i = 0; i &lt; 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 = 0; i &lt; p.children.length; ++i) {
-        var cur = p.children[i];
-        if (cur == chunk) break;
-        else h += cur.height;
-      }
-    }
-    return h;
</del><ins>+  // Move the hidden textarea near the cursor to prevent scrolling artifacts
+  if (cm.options.moveInputWithCursor) {
+    var headPos = cursorCoords(cm, doc.sel.primary().head, &quot;div&quot;)
+    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))
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // 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) {
-    var order = line.order;
-    if (order == null) order = line.order = bidiOrdering(line.text);
-    return order;
-  }
</del><ins>+  return result
+};
</ins><span class="cx"> 
</span><del>-  // HISTORY
-
-  function History(startGen) {
-    // Arrays of change events and selections. Doing something adds an
-    // event to done and clears undo. Undoing moves events from done
-    // to undone, redoing moves them in the other direction.
-    this.done = []; this.undone = [];
-    this.undoDepth = Infinity;
-    // Used to track when changes can be merged into a single undo
-    // event
-    this.lastModTime = this.lastSelTime = 0;
-    this.lastOp = this.lastSelOp = null;
-    this.lastOrigin = this.lastSelOrigin = null;
-    // Used by the isClean() method
-    this.generation = this.maxGeneration = startGen || 1;
</del><ins>+TextareaInput.prototype.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 + &quot;px&quot;
+    this.wrapper.style.left = drawn.teLeft + &quot;px&quot;
</ins><span class="cx">   }
</span><ins>+};
</ins><span class="cx"> 
</span><del>-  // Create a history change event from an updateDoc-style change
-  // object.
-  function historyChangeFromChange(doc, change) {
-    var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
-    attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
-    linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
-    return histChange;
</del><ins>+// Reset the input to correspond to the selection (or to be empty,
+// when not typing and nothing is selected)
+TextareaInput.prototype.reset = function (typing) {
+  if (this.contextMenuPending) { return }
+  var minimal, selected, cm = this.cm, doc = cm.doc
+  if (cm.somethingSelected()) {
+    this.prevInput = &quot;&quot;
+    var range = doc.sel.primary()
+    minimal = hasCopyEvent &amp;&amp;
+      (range.to().line - range.from().line &gt; 100 || (selected = cm.getSelection()).length &gt; 1000)
+    var content = minimal ? &quot;-&quot; : selected || cm.getSelection()
+    this.textarea.value = content
+    if (cm.state.focused) { selectInput(this.textarea) }
+    if (ie &amp;&amp; ie_version &gt;= 9) { this.hasSelection = content }
+  } else if (!typing) {
+    this.prevInput = this.textarea.value = &quot;&quot;
+    if (ie &amp;&amp; ie_version &gt;= 9) { this.hasSelection = null }
</ins><span class="cx">   }
</span><ins>+  this.inaccurateSelection = minimal
+};
</ins><span class="cx"> 
</span><del>-  // Pop all selection events off the end of a history array. Stop at
-  // a change event.
-  function clearSelectionEvents(array) {
-    while (array.length) {
-      var last = lst(array);
-      if (last.ranges) array.pop();
-      else break;
-    }
-  }
</del><ins>+TextareaInput.prototype.getField = function () { return this.textarea };
</ins><span class="cx"> 
</span><del>-  // Find the top change event in the history. Pop off selection
-  // events that are in the way.
-  function lastChangeEvent(hist, force) {
-    if (force) {
-      clearSelectionEvents(hist.done);
-      return lst(hist.done);
-    } else if (hist.done.length &amp;&amp; !lst(hist.done).ranges) {
-      return lst(hist.done);
-    } else if (hist.done.length &gt; 1 &amp;&amp; !hist.done[hist.done.length - 2].ranges) {
-      hist.done.pop();
-      return lst(hist.done);
-    }
-  }
</del><ins>+TextareaInput.prototype.supportsTouch = function () { return false };
</ins><span class="cx"> 
</span><del>-  // Register a change in the history. Merges changes that are within
-  // a single operation, ore are close together with an origin that
-  // allows merging (starting with &quot;+&quot;) into a single event.
-  function addChangeToHistory(doc, change, selAfter, opId) {
-    var hist = doc.history;
-    hist.undone.length = 0;
-    var time = +new Date, cur;
-
-    if ((hist.lastOp == opId ||
-         hist.lastOrigin == change.origin &amp;&amp; change.origin &amp;&amp;
-         ((change.origin.charAt(0) == &quot;+&quot; &amp;&amp; doc.cm &amp;&amp; hist.lastModTime &gt; time - doc.cm.options.historyEventDelay) ||
-          change.origin.charAt(0) == &quot;*&quot;)) &amp;&amp;
-        (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
-      // Merge this change into the last event
-      var last = lst(cur.changes);
-      if (cmp(change.from, change.to) == 0 &amp;&amp; cmp(change.from, last.to) == 0) {
-        // Optimized case for simple insertion -- don't want to add
-        // new changesets for every character typed
-        last.to = changeEnd(change);
-      } else {
-        // Add new sub-event
-        cur.changes.push(historyChangeFromChange(doc, change));
-      }
-    } else {
-      // Can not be merged, start a new event.
-      var before = lst(hist.done);
-      if (!before || !before.ranges)
-        pushSelectionToHistory(doc.sel, hist.done);
-      cur = {changes: [historyChangeFromChange(doc, change)],
-             generation: hist.generation};
-      hist.done.push(cur);
-      while (hist.done.length &gt; hist.undoDepth) {
-        hist.done.shift();
-        if (!hist.done[0].ranges) hist.done.shift();
-      }
-    }
-    hist.done.push(selAfter);
-    hist.generation = ++hist.maxGeneration;
-    hist.lastModTime = hist.lastSelTime = time;
-    hist.lastOp = hist.lastSelOp = opId;
-    hist.lastOrigin = hist.lastSelOrigin = change.origin;
-
-    if (!last) signal(doc, &quot;historyAdded&quot;);
</del><ins>+TextareaInput.prototype.focus = function () {
+  if (this.cm.options.readOnly != &quot;nocursor&quot; &amp;&amp; (!mobile || activeElt() != this.textarea)) {
+    try { this.textarea.focus() }
+    catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
</ins><span class="cx">   }
</span><ins>+};
</ins><span class="cx"> 
</span><del>-  function selectionEventCanBeMerged(doc, origin, prev, sel) {
-    var ch = origin.charAt(0);
-    return ch == &quot;*&quot; ||
-      ch == &quot;+&quot; &amp;&amp;
-      prev.ranges.length == sel.ranges.length &amp;&amp;
-      prev.somethingSelected() == sel.somethingSelected() &amp;&amp;
-      new Date - doc.history.lastSelTime &lt;= (doc.cm ? doc.cm.options.historyEventDelay : 500);
-  }
</del><ins>+TextareaInput.prototype.blur = function () { this.textarea.blur() };
</ins><span class="cx"> 
</span><del>-  // Called whenever the selection changes, sets the new selection as
-  // the pending selection in the history, and pushes the old pending
-  // selection into the 'done' array when it was significantly
-  // different (in number of selected ranges, emptiness, or time).
-  function addSelectionToHistory(doc, sel, opId, options) {
-    var hist = doc.history, origin = options &amp;&amp; options.origin;
</del><ins>+TextareaInput.prototype.resetPosition = function () {
+  this.wrapper.style.top = this.wrapper.style.left = 0
+};
</ins><span class="cx"> 
</span><del>-    // A new event is started when the previous origin does not match
-    // the current, or the origins don't allow matching. Origins
-    // starting with * are always merged, those starting with + are
-    // merged when similar and close together in time.
-    if (opId == hist.lastSelOp ||
-        (origin &amp;&amp; hist.lastSelOrigin == origin &amp;&amp;
-         (hist.lastModTime == hist.lastSelTime &amp;&amp; hist.lastOrigin == origin ||
-          selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
-      hist.done[hist.done.length - 1] = sel;
-    else
-      pushSelectionToHistory(sel, hist.done);
</del><ins>+TextareaInput.prototype.receivedFocus = function () { this.slowPoll() };
</ins><span class="cx"> 
</span><del>-    hist.lastSelTime = +new Date;
-    hist.lastSelOrigin = origin;
-    hist.lastSelOp = opId;
-    if (options &amp;&amp; options.clearRedo !== false)
-      clearSelectionEvents(hist.undone);
-  }
</del><ins>+// Poll for input changes, using the normal rate of polling. This
+// runs as long as the editor is focused.
+TextareaInput.prototype.slowPoll = function () {
+    var this$1 = this;
</ins><span class="cx"> 
</span><del>-  function pushSelectionToHistory(sel, dest) {
-    var top = lst(dest);
-    if (!(top &amp;&amp; top.ranges &amp;&amp; top.equals(sel)))
-      dest.push(sel);
-  }
</del><ins>+  if (this.pollingFast) { return }
+  this.polling.set(this.cm.options.pollInterval, function () {
+    this$1.poll()
+    if (this$1.cm.state.focused) { this$1.slowPoll() }
+  })
+};
</ins><span class="cx"> 
</span><del>-  // Used to store marked span information in the history.
-  function attachLocalSpans(doc, change, from, to) {
-    var existing = change[&quot;spans_&quot; + doc.id], n = 0;
-    doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
-      if (line.markedSpans)
-        (existing || (existing = change[&quot;spans_&quot; + doc.id] = {}))[n] = line.markedSpans;
-      ++n;
-    });
</del><ins>+// 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.
+TextareaInput.prototype.fastPoll = function () {
+  var missed = false, input = this
+  input.pollingFast = true
+  function p() {
+    var changed = input.poll()
+    if (!changed &amp;&amp; !missed) {missed = true; input.polling.set(60, p)}
+    else {input.pollingFast = false; input.slowPoll()}
</ins><span class="cx">   }
</span><ins>+  input.polling.set(20, p)
+};
</ins><span class="cx"> 
</span><del>-  // When un/re-doing restores text containing marked spans, those
-  // that have been explicitly cleared should not be restored.
-  function removeClearedSpans(spans) {
-    if (!spans) return null;
-    for (var i = 0, out; i &lt; spans.length; ++i) {
-      if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
-      else if (out) out.push(spans[i]);
-    }
-    return !out ? spans : out.length ? out : null;
-  }
</del><ins>+// 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).
+TextareaInput.prototype.poll = function () {
+    var this$1 = this;
</ins><span class="cx"> 
</span><del>-  // Retrieve and filter the old marked spans stored in a change event.
-  function getOldSpans(doc, change) {
-    var found = change[&quot;spans_&quot; + doc.id];
-    if (!found) return null;
-    for (var i = 0, nw = []; i &lt; change.text.length; ++i)
-      nw.push(removeClearedSpans(found[i]));
-    return nw;
-  }
</del><ins>+  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) &amp;&amp; !prevInput &amp;&amp; !this.composing) ||
+      cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
+    { return false }
</ins><span class="cx"> 
</span><del>-  // Used both to provide a JSON-safe object in .getHistory, and, when
-  // detaching a document, to split the history in two
-  function copyHistoryArray(events, newGroup, instantiateSel) {
-    for (var i = 0, copy = []; i &lt; events.length; ++i) {
-      var event = events[i];
-      if (event.ranges) {
-        copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
-        continue;
-      }
-      var changes = event.changes, newChanges = [];
-      copy.push({changes: newChanges});
-      for (var j = 0; j &lt; changes.length; ++j) {
-        var change = changes[j], m;
-        newChanges.push({from: change.from, to: change.to, text: change.text});
-        if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
-          if (indexOf(newGroup, Number(m[1])) &gt; -1) {
-            lst(newChanges)[prop] = change[prop];
-            delete change[prop];
-          }
-        }
-      }
-    }
-    return copy;
</del><ins>+  var text = input.value
+  // If nothing changed, bail.
+  if (text == prevInput &amp;&amp; !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 &amp;&amp; ie_version &gt;= 9 &amp;&amp; this.hasSelection === text ||
+      mac &amp;&amp; /[\uf700-\uf7ff]/.test(text)) {
+    cm.display.input.reset()
+    return false
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // Rebasing/resetting history to deal with externally-sourced changes
-
-  function rebaseHistSelSingle(pos, from, to, diff) {
-    if (to &lt; pos.line) {
-      pos.line += diff;
-    } else if (from &lt; pos.line) {
-      pos.line = from;
-      pos.ch = 0;
-    }
</del><ins>+  if (cm.doc.sel == cm.display.selForContextMenu) {
+    var first = text.charCodeAt(0)
+    if (first == 0x200b &amp;&amp; !prevInput) { prevInput = &quot;\u200b&quot; }
+    if (first == 0x21da) { this.reset(); return this.cm.execCommand(&quot;undo&quot;) }
</ins><span class="cx">   }
</span><ins>+  // Find the part of the input that is actually new
+  var same = 0, l = Math.min(prevInput.length, text.length)
+  while (same &lt; l &amp;&amp; prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same }
</ins><span class="cx"> 
</span><del>-  // Tries to rebase an array of history events given a change in the
-  // document. If the change touches the same lines as the event, the
-  // event, and everything 'behind' it, is discarded. If the change is
-  // before the event, the event's positions are updated. Uses a
-  // copy-on-write scheme for the positions, to avoid having to
-  // reallocate them all on every rebase, but also avoid problems with
-  // shared position objects being unsafely updated.
-  function rebaseHistArray(array, from, to, diff) {
-    for (var i = 0; i &lt; array.length; ++i) {
-      var sub = array[i], ok = true;
-      if (sub.ranges) {
-        if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
-        for (var j = 0; j &lt; sub.ranges.length; j++) {
-          rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
-          rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
-        }
-        continue;
-      }
-      for (var j = 0; j &lt; sub.changes.length; ++j) {
-        var cur = sub.changes[j];
-        if (to &lt; cur.from.line) {
-          cur.from = Pos(cur.from.line + diff, cur.from.ch);
-          cur.to = Pos(cur.to.line + diff, cur.to.ch);
-        } else if (from &lt;= cur.to.line) {
-          ok = false;
-          break;
-        }
-      }
-      if (!ok) {
-        array.splice(0, i + 1);
-        i = 0;
-      }
-    }
-  }
</del><ins>+  runInOp(cm, function () {
+    applyTextInput(cm, text.slice(same), prevInput.length - same,
+                   null, this$1.composing ? &quot;*compose&quot; : null)
</ins><span class="cx"> 
</span><del>-  function rebaseHist(hist, change) {
-    var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
-    rebaseHistArray(hist.done, from, to, diff);
-    rebaseHistArray(hist.undone, from, to, diff);
-  }
</del><ins>+    // Don't leave long text in the textarea, since it makes further polling slow
+    if (text.length &gt; 1000 || text.indexOf(&quot;\n&quot;) &gt; -1) { input.value = this$1.prevInput = &quot;&quot; }
+    else { this$1.prevInput = text }
</ins><span class="cx"> 
</span><del>-  // EVENT UTILITIES
-
-  // Due to the fact that we still support jurassic IE versions, some
-  // compatibility wrappers are needed.
-
-  var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
-    if (e.preventDefault) e.preventDefault();
-    else e.returnValue = false;
-  };
-  var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
-    if (e.stopPropagation) e.stopPropagation();
-    else e.cancelBubble = true;
-  };
-  function e_defaultPrevented(e) {
-    return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
-  }
-  var e_stop = CodeMirror.e_stop = function(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 &amp; 1) b = 1;
-      else if (e.button &amp; 2) b = 3;
-      else if (e.button &amp; 4) b = 2;
</del><ins>+    if (this$1.composing) {
+      this$1.composing.range.clear()
+      this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor(&quot;to&quot;),
+                                         {className: &quot;CodeMirror-composing&quot;})
</ins><span class="cx">     }
</span><del>-    if (mac &amp;&amp; e.ctrlKey &amp;&amp; b == 1) b = 3;
-    return b;
-  }
</del><ins>+  })
+  return true
+};
</ins><span class="cx"> 
</span><del>-  // EVENT HANDLING
</del><ins>+TextareaInput.prototype.ensurePolled = function () {
+  if (this.pollingFast &amp;&amp; this.poll()) { this.pollingFast = false }
+};
</ins><span class="cx"> 
</span><del>-  // Lightweight event framework. on/off also work on DOM nodes,
-  // registering native DOM handlers.
</del><ins>+TextareaInput.prototype.onKeyPress = function () {
+  if (ie &amp;&amp; ie_version &gt;= 9) { this.hasSelection = null }
+  this.fastPoll()
+};
</ins><span class="cx"> 
</span><del>-  var on = CodeMirror.on = function(emitter, type, f) {
-    if (emitter.addEventListener)
-      emitter.addEventListener(type, f, false);
-    else if (emitter.attachEvent)
-      emitter.attachEvent(&quot;on&quot; + type, f);
-    else {
-      var map = emitter._handlers || (emitter._handlers = {});
-      var arr = map[type] || (map[type] = []);
-      arr.push(f);
-    }
-  };
</del><ins>+TextareaInput.prototype.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.
</ins><span class="cx"> 
</span><del>-  var off = CodeMirror.off = function(emitter, type, f) {
-    if (emitter.removeEventListener)
-      emitter.removeEventListener(type, f, false);
-    else if (emitter.detachEvent)
-      emitter.detachEvent(&quot;on&quot; + type, f);
-    else {
-      var arr = emitter._handlers &amp;&amp; emitter._handlers[type];
-      if (!arr) return;
-      for (var i = 0; i &lt; arr.length; ++i)
-        if (arr[i] == f) { arr.splice(i, 1); break; }
-    }
-  };
</del><ins>+  // 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 &amp;&amp; cm.doc.sel.contains(pos) == -1)
+    { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll) }
</ins><span class="cx"> 
</span><del>-  var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
-    var arr = emitter._handlers &amp;&amp; emitter._handlers[type];
-    if (!arr) return;
-    var args = Array.prototype.slice.call(arguments, 2);
-    for (var i = 0; i &lt; arr.length; ++i) arr[i].apply(null, args);
-  };
</del><ins>+  var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText
+  input.wrapper.style.cssText = &quot;position: absolute&quot;
+  var wrapperBox = input.wrapper.getBoundingClientRect()
+  te.style.cssText = &quot;position: absolute; width: 30px; height: 30px;\n      top: &quot; + (e.clientY - wrapperBox.top - 5) + &quot;px; left: &quot; + (e.clientX - wrapperBox.left - 5) + &quot;px;\n      z-index: 1000; background: &quot; + (ie ? &quot;rgba(255, 255, 255, .05)&quot; : &quot;transparent&quot;) + &quot;;\n      outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);&quot;
+  var oldScrollY
+  if (webkit) { oldScrollY = window.scrollY } // Work around Chrome issue (#2712)
+  display.input.focus()
+  if (webkit) { window.scrollTo(null, oldScrollY) }
+  display.input.reset()
+  // Adds &quot;Select all&quot; to context menu in FF
+  if (!cm.somethingSelected()) { te.value = input.prevInput = &quot; &quot; }
+  input.contextMenuPending = true
+  display.selForContextMenu = cm.doc.sel
+  clearTimeout(display.detectingSelectAll)
</ins><span class="cx"> 
</span><del>-  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 = emitter._handlers &amp;&amp; emitter._handlers[type];
-    if (!arr) 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);
</del><ins>+  // 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 = &quot;\u200b&quot; + (selected ? te.value : &quot;&quot;)
+      te.value = &quot;\u21da&quot;; // Used to catch context-menu undo
+      te.value = extval
+      input.prevInput = selected ? &quot;&quot; : &quot;\u200b&quot;
+      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
</ins><span class="cx">     }
</span><del>-    function bnd(f) {return function(){f.apply(null, args);};};
-    for (var i = 0; i &lt; arr.length; ++i)
-      list.push(bnd(arr[i]));
</del><span class="cx">   }
</span><ins>+  function rehide() {
+    input.contextMenuPending = false
+    input.wrapper.style.cssText = oldWrapperCSS
+    te.style.cssText = oldCSS
+    if (ie &amp;&amp; ie_version &lt; 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos) }
</ins><span class="cx"> 
</span><del>-  function fireOrphanDelayed() {
-    var delayed = orphanDelayedCallbacks;
-    orphanDelayedCallbacks = null;
-    for (var i = 0; i &lt; delayed.length; ++i) delayed[i]();
-  }
-
-  // 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 == &quot;string&quot;)
-      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 &amp;&amp; cm._handlers.cursorActivity;
-    if (!arr) return;
-    var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
-    for (var i = 0; i &lt; arr.length; ++i) if (indexOf(set, arr[i]) == -1)
-      set.push(arr[i]);
-  }
-
-  function hasHandler(emitter, type) {
-    var arr = emitter._handlers &amp;&amp; emitter._handlers[type];
-    return arr &amp;&amp; arr.length &gt; 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);};
-  }
-
-  // MISC UTILITIES
-
-  // 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 = CodeMirror.Pass = {toString: function(){return &quot;CodeMirror.Pass&quot;;}};
-
-  // Reused option objects for setSelection &amp; friends
-  var sel_dontScroll = {scroll: false}, sel_mouse = {origin: &quot;*mouse&quot;}, sel_move = {origin: &quot;+move&quot;};
-
-  function Delayed() {this.id = null;}
-  Delayed.prototype.set = function(ms, f) {
-    clearTimeout(this.id);
-    this.id = setTimeout(f, ms);
-  };
-
-  // Counts the column offset in a string, taking tabs into account.
-  // Used mostly to find indentation.
-  var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
-    if (end == null) {
-      end = string.search(/[^\s\u00a0]/);
-      if (end == -1) end = string.length;
</del><ins>+    // Try to detect the user choosing select-all
+    if (te.selectionStart != null) {
+      if (!ie || (ie &amp;&amp; ie_version &lt; 9)) { prepareSelectAllHack() }
+      var i = 0, poll = function () {
+        if (display.selForContextMenu == cm.doc.sel &amp;&amp; te.selectionStart == 0 &amp;&amp;
+            te.selectionEnd &gt; 0 &amp;&amp; input.prevInput == &quot;\u200b&quot;)
+          { operation(cm, selectAll)(cm) }
+        else if (i++ &lt; 10) { display.detectingSelectAll = setTimeout(poll, 500) }
+        else { display.input.reset() }
+      }
+      display.detectingSelectAll = setTimeout(poll, 200)
</ins><span class="cx">     }
</span><del>-    for (var i = startIndex || 0, n = startValue || 0;;) {
-      var nextTab = string.indexOf(&quot;\t&quot;, i);
-      if (nextTab &lt; 0 || nextTab &gt;= end)
-        return n + (end - i);
-      n += nextTab - i;
-      n += tabSize - (n % tabSize);
-      i = nextTab + 1;
-    }
-  };
-
-  // 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(&quot;\t&quot;, pos);
-      if (nextTab == -1) nextTab = string.length;
-      var skipped = nextTab - pos;
-      if (nextTab == string.length || col + skipped &gt;= goal)
-        return pos + Math.min(skipped, goal - col);
-      col += nextTab - pos;
-      col += tabSize - (col % tabSize);
-      pos = nextTab + 1;
-      if (col &gt;= goal) return pos;
-    }
</del><span class="cx">   }
</span><span class="cx"> 
</span><del>-  var spaceStrs = [&quot;&quot;];
-  function spaceStr(n) {
-    while (spaceStrs.length &lt;= n)
-      spaceStrs.push(lst(spaceStrs) + &quot; &quot;);
-    return spaceStrs[n];
-  }
-
-  function lst(arr) { return arr[arr.length-1]; }
-
-  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 indexOf(array, elt) {
-    for (var i = 0; i &lt; array.length; ++i)
-      if (array[i] == elt) return i;
-    return -1;
-  }
-  function map(array, f) {
-    var out = [];
-    for (var i = 0; i &lt; array.length; i++) out[i] = f(array[i], i);
-    return out;
-  }
-
-  function nothing() {}
-
-  function createObj(base, props) {
-    var inst;
-    if (Object.create) {
-      inst = Object.create(base);
-    } else {
-      nothing.prototype = base;
-      inst = new nothing();
</del><ins>+  if (ie &amp;&amp; ie_version &gt;= 9) { prepareSelectAllHack() }
+  if (captureRightClick) {
+    e_stop(e)
+    var mouseup = function () {
+      off(window, &quot;mouseup&quot;, mouseup)
+      setTimeout(rehide, 20)
</ins><span class="cx">     }
</span><del>-    if (props) copyObj(props, inst);
-    return inst;
-  };
-
-  function copyObj(obj, target, overwrite) {
-    if (!target) target = {};
-    for (var prop in obj)
-      if (obj.hasOwnProperty(prop) &amp;&amp; (overwrite !== false || !target.hasOwnProperty(prop)))
-        target[prop] = obj[prop];
-    return target;
</del><ins>+    on(window, &quot;mouseup&quot;, mouseup)
+  } else {
+    setTimeout(rehide, 50)
</ins><span class="cx">   }
</span><ins>+};
</ins><span class="cx"> 
</span><del>-  function bind(f) {
-    var args = Array.prototype.slice.call(arguments, 1);
-    return function(){return f.apply(null, args);};
-  }
</del><ins>+TextareaInput.prototype.readOnlyChanged = function (val) {
+  if (!val) { this.reset() }
+};
</ins><span class="cx"> 
</span><del>-  var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
-  var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
-    return /\w/.test(ch) || ch &gt; &quot;\x80&quot; &amp;&amp;
-      (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
-  };
-  function isWordChar(ch, helper) {
-    if (!helper) return isWordCharBasic(ch);
-    if (helper.source.indexOf(&quot;\\w&quot;) &gt; -1 &amp;&amp; isWordCharBasic(ch)) return true;
-    return helper.test(ch);
-  }
</del><ins>+TextareaInput.prototype.setUneditable = function () {};
</ins><span class="cx"> 
</span><del>-  function isEmpty(obj) {
-    for (var n in obj) if (obj.hasOwnProperty(n) &amp;&amp; obj[n]) return false;
-    return true;
-  }
</del><ins>+TextareaInput.prototype.needsContentAttribute = false
</ins><span class="cx"> 
</span><del>-  // 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) &gt;= 768 &amp;&amp; extendingChars.test(ch); }
-
-  // DOM UTILITIES
-
-  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 == &quot;string&quot;) e.appendChild(document.createTextNode(content));
-    else if (content) for (var i = 0; i &lt; content.length; ++i) e.appendChild(content[i]);
-    return e;
</del><ins>+function fromTextArea(textarea, options) {
+  options = options ? copyObj(options) : {}
+  options.value = textarea.value
+  if (!options.tabindex &amp;&amp; textarea.tabIndex)
+    { options.tabindex = textarea.tabIndex }
+  if (!options.placeholder &amp;&amp; textarea.placeholder)
+    { options.placeholder = textarea.placeholder }
+  // Set autofocus to true if this textarea is focused, or if it has
+  // autofocus and no other element is focused.
+  if (options.autofocus == null) {
+    var hasFocus = activeElt()
+    options.autofocus = hasFocus == textarea ||
+      textarea.getAttribute(&quot;autofocus&quot;) != null &amp;&amp; hasFocus == document.body
</ins><span class="cx">   }
</span><span class="cx"> 
</span><del>-  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(&quot;character&quot;, end);
-    r.moveStart(&quot;character&quot;, start);
-    return r;
-  };
</del><ins>+  function save() {textarea.value = cm.getValue()}
</ins><span class="cx"> 
</span><del>-  function removeChildren(e) {
-    for (var count = e.childNodes.length; count &gt; 0; --count)
-      e.removeChild(e.firstChild);
-    return e;
-  }
-
-  function removeChildrenAndAdd(parent, e) {
-    return removeChildren(parent).appendChild(e);
-  }
-
-  var contains = CodeMirror.contains = function(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() {
-    var activeElement = document.activeElement;
-    while (activeElement &amp;&amp; activeElement.root &amp;&amp; activeElement.root.activeElement)
-      activeElement = activeElement.root.activeElement;
-    return activeElement;
-  }
-  // Older versions of IE throws unspecified error when touching
-  // document.activeElement in some cases (during loading, in iframe)
-  if (ie &amp;&amp; ie_version &lt; 11) activeElt = function() {
-    try { return document.activeElement; }
-    catch(e) { return document.body; }
-  };
-
-  function classTest(cls) { return new RegExp(&quot;(^|\\s)&quot; + cls + &quot;(?:$|\\s)\\s*&quot;); }
-  var rmClass = CodeMirror.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 : &quot;&quot;);
</del><ins>+  var realSubmit
+  if (textarea.form) {
+    on(textarea.form, &quot;submit&quot;, save)
+    // Deplorable hack to make the submit method do the right thing.
+    if (!options.leaveSubmitMethodAlone) {
+      var form = textarea.form
+      realSubmit = form.submit
+      try {
+        var wrappedSubmit = form.submit = function () {
+          save()
+          form.submit = realSubmit
+          form.submit()
+          form.submit = wrappedSubmit
+        }
+      } catch(e) {}
</ins><span class="cx">     }
</span><del>-  };
-  var addClass = CodeMirror.addClass = function(node, cls) {
-    var current = node.className;
-    if (!classTest(cls).test(current)) node.className += (current ? &quot; &quot; : &quot;&quot;) + cls;
-  };
-  function joinClasses(a, b) {
-    var as = a.split(&quot; &quot;);
-    for (var i = 0; i &lt; as.length; i++)
-      if (as[i] &amp;&amp; !classTest(as[i]).test(b)) b += &quot; &quot; + as[i];
-    return b;
</del><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // WINDOW-WIDE EVENTS
-
-  // These must be handled carefully, because naively registering a
-  // handler for each editor will cause the editors to never be
-  // garbage collected.
-
-  function forEachCodeMirror(f) {
-    if (!document.body.getElementsByClassName) return;
-    var byClass = document.body.getElementsByClassName(&quot;CodeMirror&quot;);
-    for (var i = 0; i &lt; byClass.length; i++) {
-      var cm = byClass[i].CodeMirror;
-      if (cm) f(cm);
-    }
-  }
-
-  var globalsRegistered = false;
-  function ensureGlobalHandlers() {
-    if (globalsRegistered) return;
-    registerGlobalHandlers();
-    globalsRegistered = true;
-  }
-  function registerGlobalHandlers() {
-    // When the window resizes, we need to refresh active editors.
-    var resizeTimer;
-    on(window, &quot;resize&quot;, function() {
-      if (resizeTimer == null) resizeTimer = setTimeout(function() {
-        resizeTimer = null;
-        forEachCodeMirror(onResize);
-      }, 100);
-    });
-    // When the window loses focus, we want to show the editor as blurred
-    on(window, &quot;blur&quot;, function() {
-      forEachCodeMirror(onBlur);
-    });
-  }
-
-  // FEATURE DETECTION
-
-  // 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 &amp;&amp; ie_version &lt; 9) return false;
-    var div = elt('div');
-    return &quot;draggable&quot; in div || &quot;dragDrop&quot; in div;
-  }();
-
-  var zwspSupported;
-  function zeroWidthElement(measure) {
-    if (zwspSupported == null) {
-      var test = elt(&quot;span&quot;, &quot;\u200b&quot;);
-      removeChildrenAndAdd(measure, elt(&quot;span&quot;, [test, document.createTextNode(&quot;x&quot;)]));
-      if (measure.firstChild.offsetHeight != 0)
-        zwspSupported = test.offsetWidth &lt;= 1 &amp;&amp; test.offsetHeight &gt; 2 &amp;&amp; !(ie &amp;&amp; ie_version &lt; 8);
-    }
-    var node = zwspSupported ? elt(&quot;span&quot;, &quot;\u200b&quot;) :
-      elt(&quot;span&quot;, &quot;\u00a0&quot;, null, &quot;display: inline-block; width: 1px; margin-right: -1px&quot;);
-    node.setAttribute(&quot;cm-text&quot;, &quot;&quot;);
-    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(&quot;A\u062eA&quot;));
-    var r0 = range(txt, 0, 1).getBoundingClientRect();
-    if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
-    var r1 = range(txt, 1, 2).getBoundingClientRect();
-    return badBidiRects = (r1.right - r0.right &lt; 3);
-  }
-
-  // See if &quot;&quot;.split is the broken IE version, if so, provide an
-  // alternative way to split lines.
-  var splitLinesAuto = CodeMirror.splitLines = &quot;\n\nb&quot;.split(/\n/).length != 3 ? function(string) {
-    var pos = 0, result = [], l = string.length;
-    while (pos &lt;= l) {
-      var nl = string.indexOf(&quot;\n&quot;, pos);
-      if (nl == -1) nl = string.length;
-      var line = string.slice(pos, string.charAt(nl - 1) == &quot;\r&quot; ? nl - 1 : nl);
-      var rt = line.indexOf(&quot;\r&quot;);
-      if (rt != -1) {
-        result.push(line.slice(0, rt));
-        pos += rt + 1;
-      } else {
-        result.push(line);
-        pos = nl + 1;
</del><ins>+  options.finishInit = function (cm) {
+    cm.save = save
+    cm.getTextArea = function () { return textarea; }
+    cm.toTextArea = function () {
+      cm.toTextArea = isNaN // Prevent this from being ran twice
+      save()
+      textarea.parentNode.removeChild(cm.getWrapperElement())
+      textarea.style.display = &quot;&quot;
+      if (textarea.form) {
+        off(textarea.form, &quot;submit&quot;, save)
+        if (typeof textarea.form.submit == &quot;function&quot;)
+          { textarea.form.submit = realSubmit }
</ins><span class="cx">       }
</span><span class="cx">     }
</span><del>-    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) {
-    try {var range = te.ownerDocument.selection.createRange();}
-    catch(e) {}
-    if (!range || range.parentElement() != te) return false;
-    return range.compareEndPoints(&quot;StartToEnd&quot;, range) != 0;
-  };
-
-  var hasCopyEvent = (function() {
-    var e = elt(&quot;div&quot;);
-    if (&quot;oncopy&quot; in e) return true;
-    e.setAttribute(&quot;oncopy&quot;, &quot;return;&quot;);
-    return typeof e.oncopy == &quot;function&quot;;
-  })();
-
-  var badZoomedRects = null;
-  function hasBadZoomedRects(measure) {
-    if (badZoomedRects != null) return badZoomedRects;
-    var node = removeChildrenAndAdd(measure, elt(&quot;span&quot;, &quot;x&quot;));
-    var normal = node.getBoundingClientRect();
-    var fromRange = range(node, 0, 1).getBoundingClientRect();
-    return badZoomedRects = Math.abs(normal.left - fromRange.left) &gt; 1;
</del><span class="cx">   }
</span><span class="cx"> 
</span><del>-  // KEY NAMES
</del><ins>+  textarea.style.display = &quot;none&quot;
+  var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
+    options)
+  return cm
+}
</ins><span class="cx"> 
</span><del>-  var keyNames = {3: &quot;Enter&quot;, 8: &quot;Backspace&quot;, 9: &quot;Tab&quot;, 13: &quot;Enter&quot;, 16: &quot;Shift&quot;, 17: &quot;Ctrl&quot;, 18: &quot;Alt&quot;,
-                  19: &quot;Pause&quot;, 20: &quot;CapsLock&quot;, 27: &quot;Esc&quot;, 32: &quot;Space&quot;, 33: &quot;PageUp&quot;, 34: &quot;PageDown&quot;, 35: &quot;End&quot;,
-                  36: &quot;Home&quot;, 37: &quot;Left&quot;, 38: &quot;Up&quot;, 39: &quot;Right&quot;, 40: &quot;Down&quot;, 44: &quot;PrintScrn&quot;, 45: &quot;Insert&quot;,
-                  46: &quot;Delete&quot;, 59: &quot;;&quot;, 61: &quot;=&quot;, 91: &quot;Mod&quot;, 92: &quot;Mod&quot;, 93: &quot;Mod&quot;, 107: &quot;=&quot;, 109: &quot;-&quot;, 127: &quot;Delete&quot;,
-                  173: &quot;-&quot;, 186: &quot;;&quot;, 187: &quot;=&quot;, 188: &quot;,&quot;, 189: &quot;-&quot;, 190: &quot;.&quot;, 191: &quot;/&quot;, 192: &quot;`&quot;, 219: &quot;[&quot;, 220: &quot;\\&quot;,
-                  221: &quot;]&quot;, 222: &quot;'&quot;, 63232: &quot;Up&quot;, 63233: &quot;Down&quot;, 63234: &quot;Left&quot;, 63235: &quot;Right&quot;, 63272: &quot;Delete&quot;,
-                  63273: &quot;Home&quot;, 63275: &quot;End&quot;, 63276: &quot;PageUp&quot;, 63277: &quot;PageDown&quot;, 63302: &quot;Insert&quot;};
-  CodeMirror.keyNames = keyNames;
-  (function() {
-    // Number keys
-    for (var i = 0; i &lt; 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
-    // Alphabetic keys
-    for (var i = 65; i &lt;= 90; i++) keyNames[i] = String.fromCharCode(i);
-    // Function keys
-    for (var i = 1; i &lt;= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = &quot;F&quot; + i;
-  })();
</del><ins>+function addLegacyProps(CodeMirror) {
+  CodeMirror.off = off
+  CodeMirror.on = on
+  CodeMirror.wheelEventPixels = wheelEventPixels
+  CodeMirror.Doc = Doc
+  CodeMirror.splitLines = splitLinesAuto
+  CodeMirror.countColumn = countColumn
+  CodeMirror.findColumn = findColumn
+  CodeMirror.isWordChar = isWordCharBasic
+  CodeMirror.Pass = Pass
+  CodeMirror.signal = signal
+  CodeMirror.Line = Line
+  CodeMirror.changeEnd = changeEnd
+  CodeMirror.scrollbarModel = scrollbarModel
+  CodeMirror.Pos = Pos
+  CodeMirror.cmpPos = cmp
+  CodeMirror.modes = modes
+  CodeMirror.mimeModes = mimeModes
+  CodeMirror.resolveMode = resolveMode
+  CodeMirror.getMode = getMode
+  CodeMirror.modeExtensions = modeExtensions
+  CodeMirror.extendMode = extendMode
+  CodeMirror.copyState = copyState
+  CodeMirror.startState = startState
+  CodeMirror.innerMode = innerMode
+  CodeMirror.commands = commands
+  CodeMirror.keyMap = keyMap
+  CodeMirror.keyName = keyName
+  CodeMirror.isModifierKey = isModifierKey
+  CodeMirror.lookupKey = lookupKey
+  CodeMirror.normalizeKeyMap = normalizeKeyMap
+  CodeMirror.StringStream = StringStream
+  CodeMirror.SharedTextMarker = SharedTextMarker
+  CodeMirror.TextMarker = TextMarker
+  CodeMirror.LineWidget = LineWidget
+  CodeMirror.e_preventDefault = e_preventDefault
+  CodeMirror.e_stopPropagation = e_stopPropagation
+  CodeMirror.e_stop = e_stop
+  CodeMirror.addClass = addClass
+  CodeMirror.contains = contains
+  CodeMirror.rmClass = rmClass
+  CodeMirror.keyNames = keyNames
+}
</ins><span class="cx"> 
</span><del>-  // BIDI HELPERS
</del><ins>+// EDITOR CONSTRUCTOR
</ins><span class="cx"> 
</span><del>-  function iterateBidiSections(order, from, to, f) {
-    if (!order) return f(from, to, &quot;ltr&quot;);
-    var found = false;
-    for (var i = 0; i &lt; order.length; ++i) {
-      var part = order[i];
-      if (part.from &lt; to &amp;&amp; part.to &gt; from || from == to &amp;&amp; part.to == from) {
-        f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? &quot;rtl&quot; : &quot;ltr&quot;);
-        found = true;
-      }
-    }
-    if (!found) f(from, to, &quot;ltr&quot;);
-  }
</del><ins>+defineOptions(CodeMirror)
</ins><span class="cx"> 
</span><del>-  function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
-  function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
</del><ins>+addEditorMethods(CodeMirror)
</ins><span class="cx"> 
</span><del>-  function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
-  function lineRight(line) {
-    var order = getOrder(line);
-    if (!order) return line.text.length;
-    return bidiRight(lst(order));
-  }
</del><ins>+// Set up methods on CodeMirror's prototype to redirect to the editor's document.
+var dontDelegate = &quot;iter insert remove copy getEditor constructor&quot;.split(&quot; &quot;)
+for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) &amp;&amp; indexOf(dontDelegate, prop) &lt; 0)
+  { CodeMirror.prototype[prop] = (function(method) {
+    return function() {return method.apply(this.doc, arguments)}
+  })(Doc.prototype[prop]) } }
</ins><span class="cx"> 
</span><del>-  function lineStart(cm, lineN) {
-    var line = getLine(cm.doc, lineN);
-    var visual = visualLine(line);
-    if (visual != line) lineN = lineNo(visual);
-    var order = getOrder(visual);
-    var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
-    return Pos(lineN, ch);
-  }
-  function lineEnd(cm, lineN) {
-    var merged, line = getLine(cm.doc, lineN);
-    while (merged = collapsedSpanAtEnd(line)) {
-      line = merged.find(1, true).line;
-      lineN = null;
-    }
-    var order = getOrder(line);
-    var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
-    return Pos(lineN == null ? lineNo(line) : lineN, ch);
-  }
-  function lineStartSmart(cm, pos) {
-    var start = lineStart(cm, pos.line);
-    var line = getLine(cm.doc, start.line);
-    var order = getOrder(line);
-    if (!order || order[0].level == 0) {
-      var firstNonWS = Math.max(0, line.text.search(/\S/));
-      var inWS = pos.line == start.line &amp;&amp; pos.ch &lt;= firstNonWS &amp;&amp; pos.ch;
-      return Pos(start.line, inWS ? 0 : firstNonWS);
-    }
-    return start;
-  }
</del><ins>+eventMixin(Doc)
</ins><span class="cx"> 
</span><del>-  function compareBidiLevel(order, a, b) {
-    var linedir = order[0].level;
-    if (a == linedir) return true;
-    if (b == linedir) return false;
-    return a &lt; b;
-  }
-  var bidiOther;
-  function getBidiPartAt(order, pos) {
-    bidiOther = null;
-    for (var i = 0, found; i &lt; order.length; ++i) {
-      var cur = order[i];
-      if (cur.from &lt; pos &amp;&amp; cur.to &gt; pos) return i;
-      if ((cur.from == pos || cur.to == pos)) {
-        if (found == null) {
-          found = i;
-        } else if (compareBidiLevel(order, cur.level, order[found].level)) {
-          if (cur.from != cur.to) bidiOther = found;
-          return i;
-        } else {
-          if (cur.from != cur.to) bidiOther = i;
-          return found;
-        }
-      }
-    }
-    return found;
-  }
</del><ins>+// INPUT HANDLING
</ins><span class="cx"> 
</span><del>-  function moveInLine(line, pos, dir, byUnit) {
-    if (!byUnit) return pos + dir;
-    do pos += dir;
-    while (pos &gt; 0 &amp;&amp; isExtendingChar(line.text.charAt(pos)));
-    return pos;
-  }
</del><ins>+CodeMirror.inputStyles = {&quot;textarea&quot;: TextareaInput, &quot;contenteditable&quot;: ContentEditableInput}
</ins><span class="cx"> 
</span><del>-  // This is needed in order to move 'visually' through bi-directional
-  // text -- i.e., pressing left should make the cursor go left, even
-  // when in RTL text. The tricky part is the 'jumps', where RTL and
-  // LTR text touch each other. This often requires the cursor offset
-  // to move more than one unit, in order to visually move one unit.
-  function moveVisually(line, start, dir, byUnit) {
-    var bidi = getOrder(line);
-    if (!bidi) return moveLogically(line, start, dir, byUnit);
-    var pos = getBidiPartAt(bidi, start), part = bidi[pos];
-    var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
</del><ins>+// MODE DEFINITION AND QUERYING
</ins><span class="cx"> 
</span><del>-    for (;;) {
-      if (target &gt; part.from &amp;&amp; target &lt; part.to) return target;
-      if (target == part.from || target == part.to) {
-        if (getBidiPartAt(bidi, target) == pos) return target;
-        part = bidi[pos += dir];
-        return (dir &gt; 0) == part.level % 2 ? part.to : part.from;
-      } else {
-        part = bidi[pos += dir];
-        if (!part) return null;
-        if ((dir &gt; 0) == part.level % 2)
-          target = moveInLine(line, part.to, -1, byUnit);
-        else
-          target = moveInLine(line, part.from, 1, byUnit);
-      }
-    }
-  }
</del><ins>+// 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.)
+CodeMirror.defineMode = function(name/*, mode, …*/) {
+  if (!CodeMirror.defaults.mode &amp;&amp; name != &quot;null&quot;) { CodeMirror.defaults.mode = name }
+  defineMode.apply(this, arguments)
+}
</ins><span class="cx"> 
</span><del>-  function moveLogically(line, start, dir, byUnit) {
-    var target = start + dir;
-    if (byUnit) while (target &gt; 0 &amp;&amp; isExtendingChar(line.text.charAt(target))) target += dir;
-    return target &lt; 0 || target &gt; line.text.length ? null : target;
-  }
</del><ins>+CodeMirror.defineMIME = defineMIME
</ins><span class="cx"> 
</span><del>-  // Bidirectional ordering algorithm
-  // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
-  // that this (partially) implements.
</del><ins>+// Minimal default mode.
+CodeMirror.defineMode(&quot;null&quot;, function () { return ({token: function (stream) { return stream.skipToEnd(); }}); })
+CodeMirror.defineMIME(&quot;text/plain&quot;, &quot;null&quot;)
</ins><span class="cx"> 
</span><del>-  // 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
</del><ins>+// EXTENSIONS
</ins><span class="cx"> 
</span><del>-  // 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 = &quot;bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN&quot;;
-    // Character types for codepoints 0x600 to 0x6ff
-    var arabicTypes = &quot;rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm&quot;;
-    function charType(code) {
-      if (code &lt;= 0xf7) return lowTypes.charAt(code);
-      else if (0x590 &lt;= code &amp;&amp; code &lt;= 0x5f4) return &quot;R&quot;;
-      else if (0x600 &lt;= code &amp;&amp; code &lt;= 0x6ed) return arabicTypes.charAt(code - 0x600);
-      else if (0x6ee &lt;= code &amp;&amp; code &lt;= 0x8ac) return &quot;r&quot;;
-      else if (0x2000 &lt;= code &amp;&amp; code &lt;= 0x200b) return &quot;w&quot;;
-      else if (code == 0x200c) return &quot;b&quot;;
-      else return &quot;L&quot;;
-    }
</del><ins>+CodeMirror.defineExtension = function (name, func) {
+  CodeMirror.prototype[name] = func
+}
+CodeMirror.defineDocExtension = function (name, func) {
+  Doc.prototype[name] = func
+}
</ins><span class="cx"> 
</span><del>-    var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
-    var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
-    // Browsers seem to always treat the boundaries of block elements as being L.
-    var outerType = &quot;L&quot;;
</del><ins>+CodeMirror.fromTextArea = fromTextArea
</ins><span class="cx"> 
</span><del>-    function BidiSpan(level, from, to) {
-      this.level = level;
-      this.from = from; this.to = to;
-    }
</del><ins>+addLegacyProps(CodeMirror)
</ins><span class="cx"> 
</span><del>-    return function(str) {
-      if (!bidiRE.test(str)) return false;
-      var len = str.length, types = [];
-      for (var i = 0, type; i &lt; len; ++i)
-        types.push(type = charType(str.charCodeAt(i)));
</del><ins>+CodeMirror.version = &quot;5.21.1&quot;
</ins><span class="cx"> 
</span><del>-      // 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 = 0, prev = outerType; i &lt; len; ++i) {
-        var type = types[i];
-        if (type == &quot;m&quot;) types[i] = prev;
-        else prev = type;
-      }
</del><ins>+return CodeMirror;
</ins><span class="cx"> 
</span><del>-      // 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 = 0, cur = outerType; i &lt; len; ++i) {
-        var type = types[i];
-        if (type == &quot;1&quot; &amp;&amp; cur == &quot;r&quot;) types[i] = &quot;n&quot;;
-        else if (isStrong.test(type)) { cur = type; if (type == &quot;r&quot;) types[i] = &quot;R&quot;; }
-      }
-
-      // 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 = 1, prev = types[0]; i &lt; len - 1; ++i) {
-        var type = types[i];
-        if (type == &quot;+&quot; &amp;&amp; prev == &quot;1&quot; &amp;&amp; types[i+1] == &quot;1&quot;) types[i] = &quot;1&quot;;
-        else if (type == &quot;,&quot; &amp;&amp; prev == types[i+1] &amp;&amp;
-                 (prev == &quot;1&quot; || prev == &quot;n&quot;)) types[i] = prev;
-        prev = type;
-      }
-
-      // 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 = 0; i &lt; len; ++i) {
-        var type = types[i];
-        if (type == &quot;,&quot;) types[i] = &quot;N&quot;;
-        else if (type == &quot;%&quot;) {
-          for (var end = i + 1; end &lt; len &amp;&amp; types[end] == &quot;%&quot;; ++end) {}
-          var replace = (i &amp;&amp; types[i-1] == &quot;!&quot;) || (end &lt; len &amp;&amp; types[end] == &quot;1&quot;) ? &quot;1&quot; : &quot;N&quot;;
-          for (var j = i; j &lt; end; ++j) types[j] = replace;
-          i = 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 = 0, cur = outerType; i &lt; len; ++i) {
-        var type = types[i];
-        if (cur == &quot;L&quot; &amp;&amp; type == &quot;1&quot;) types[i] = &quot;L&quot;;
-        else if (isStrong.test(type)) cur = type;
-      }
-
-      // 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 = 0; i &lt; len; ++i) {
-        if (isNeutral.test(types[i])) {
-          for (var end = i + 1; end &lt; len &amp;&amp; isNeutral.test(types[end]); ++end) {}
-          var before = (i ? types[i-1] : outerType) == &quot;L&quot;;
-          var after = (end &lt; len ? types[end] : outerType) == &quot;L&quot;;
-          var replace = before || after ? &quot;L&quot; : &quot;R&quot;;
-          for (var j = i; j &lt; end; ++j) types[j] = replace;
-          i = end - 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 = 0; i &lt; len;) {
-        if (countsAsLeft.test(types[i])) {
-          var start = i;
-          for (++i; i &lt; len &amp;&amp; countsAsLeft.test(types[i]); ++i) {}
-          order.push(new BidiSpan(0, start, i));
-        } else {
-          var pos = i, at = order.length;
-          for (++i; i &lt; len &amp;&amp; types[i] != &quot;L&quot;; ++i) {}
-          for (var j = pos; j &lt; i;) {
-            if (countsAsNum.test(types[j])) {
-              if (pos &lt; j) order.splice(at, 0, new BidiSpan(1, pos, j));
-              var nstart = j;
-              for (++j; j &lt; i &amp;&amp; countsAsNum.test(types[j]); ++j) {}
-              order.splice(at, 0, new BidiSpan(2, nstart, j));
-              pos = j;
-            } else ++j;
-          }
-          if (pos &lt; i) order.splice(at, 0, new BidiSpan(1, pos, i));
-        }
-      }
-      if (order[0].level == 1 &amp;&amp; (m = str.match(/^\s+/))) {
-        order[0].from = m[0].length;
-        order.unshift(new BidiSpan(0, 0, m[0].length));
-      }
-      if (lst(order).level == 1 &amp;&amp; (m = str.match(/\s+$/))) {
-        lst(order).to -= m[0].length;
-        order.push(new BidiSpan(0, len - m[0].length, len));
-      }
-      if (order[0].level == 2)
-        order.unshift(new BidiSpan(1, order[0].to, order[0].to));
-      if (order[0].level != lst(order).level)
-        order.push(new BidiSpan(order[0].level, len, len));
-
-      return order;
-    };
-  })();
-
-  // THE END
-
-  CodeMirror.version = &quot;5.5.1&quot;;
-
-  return CodeMirror;
-});
</del><ins>+})));
</ins><span class="cx">\ No newline at end of file
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorcoffeescriptjs"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/coffeescript.js (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/coffeescript.js        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/coffeescript.js        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -25,7 +25,7 @@
</span><span class="cx">   var operators = /^(?:-&gt;|=&gt;|\+[+=]?|-[\-=]?|\*[\*=]?|\/[\/=]?|[=!]=|&lt;[&gt;&lt;]?=?|&gt;&gt;?=?|%=?|&amp;=?|\|=?|\^=?|\~|!|\?|(or|and|\|\||&amp;&amp;|\?)=)/;
</span><span class="cx">   var delimiters = /^(?:[()\[\]{},:`=;]|\.\.?\.?)/;
</span><span class="cx">   var identifiers = /^[_A-Za-z$][_A-Za-z$0-9]*/;
</span><del>-  var properties = /^(@|this\.)[_A-Za-z$][_A-Za-z$0-9]*/;
</del><ins>+  var atProp = /^@[_A-Za-z$][_A-Za-z$0-9]*/;
</ins><span class="cx"> 
</span><span class="cx">   var wordOperators = wordRegexp([&quot;and&quot;, &quot;or&quot;, &quot;not&quot;,
</span><span class="cx">                                   &quot;is&quot;, &quot;isnt&quot;, &quot;in&quot;,
</span><span class="lines">@@ -145,6 +145,8 @@
</span><span class="cx">       }
</span><span class="cx">     }
</span><span class="cx"> 
</span><ins>+
+
</ins><span class="cx">     // Handle operators and delimiters
</span><span class="cx">     if (stream.match(operators) || stream.match(wordOperators)) {
</span><span class="cx">       return &quot;operator&quot;;
</span><span class="lines">@@ -157,6 +159,10 @@
</span><span class="cx">       return &quot;atom&quot;;
</span><span class="cx">     }
</span><span class="cx"> 
</span><ins>+    if (stream.match(atProp) || state.prop &amp;&amp; stream.match(identifiers)) {
+      return &quot;property&quot;;
+    }
+
</ins><span class="cx">     if (stream.match(keywords)) {
</span><span class="cx">       return &quot;keyword&quot;;
</span><span class="cx">     }
</span><span class="lines">@@ -165,10 +171,6 @@
</span><span class="cx">       return &quot;variable&quot;;
</span><span class="cx">     }
</span><span class="cx"> 
</span><del>-    if (stream.match(properties)) {
-      return &quot;property&quot;;
-    }
-
</del><span class="cx">     // Handle non-detected items
</span><span class="cx">     stream.next();
</span><span class="cx">     return ERRORCLASS;
</span><span class="lines">@@ -265,24 +267,11 @@
</span><span class="cx">     var style = state.tokenize(stream, state);
</span><span class="cx">     var current = stream.current();
</span><span class="cx"> 
</span><del>-    // Handle &quot;.&quot; connected identifiers
-    if (current === &quot;.&quot;) {
-      style = state.tokenize(stream, state);
-      current = stream.current();
-      if (/^\.[\w$]+$/.test(current)) {
-        return &quot;variable&quot;;
-      } else {
-        return ERRORCLASS;
-      }
-    }
-
</del><span class="cx">     // Handle scope changes.
</span><span class="cx">     if (current === &quot;return&quot;) {
</span><span class="cx">       state.dedent = true;
</span><span class="cx">     }
</span><del>-    if (((current === &quot;-&gt;&quot; || current === &quot;=&gt;&quot;) &amp;&amp;
-         !state.lambda &amp;&amp;
-         !stream.peek())
</del><ins>+    if (((current === &quot;-&gt;&quot; || current === &quot;=&gt;&quot;) &amp;&amp; stream.eol())
</ins><span class="cx">         || style === &quot;indent&quot;) {
</span><span class="cx">       indent(stream, state);
</span><span class="cx">     }
</span><span class="lines">@@ -324,8 +313,7 @@
</span><span class="cx">       return {
</span><span class="cx">         tokenize: tokenBase,
</span><span class="cx">         scope: {offset:basecolumn || 0, type:&quot;coffee&quot;, prev: null, align: false},
</span><del>-        lastToken: null,
-        lambda: false,
</del><ins>+        prop: false,
</ins><span class="cx">         dedent: 0
</span><span class="cx">       };
</span><span class="cx">     },
</span><span class="lines">@@ -335,12 +323,9 @@
</span><span class="cx">       if (fillAlign &amp;&amp; stream.sol()) fillAlign.align = false;
</span><span class="cx"> 
</span><span class="cx">       var style = tokenLexer(stream, state);
</span><del>-      if (fillAlign &amp;&amp; style &amp;&amp; style != &quot;comment&quot;) fillAlign.align = true;
-
-      state.lastToken = {style:style, content: stream.current()};
-
-      if (stream.eol() &amp;&amp; stream.lambda) {
-        state.lambda = false;
</del><ins>+      if (style &amp;&amp; style != &quot;comment&quot;) {
+        if (fillAlign) fillAlign.align = true;
+        state.prop = style == &quot;punctuation&quot; &amp;&amp; stream.current() == &quot;.&quot;
</ins><span class="cx">       }
</span><span class="cx"> 
</span><span class="cx">       return style;
</span><span class="lines">@@ -365,5 +350,6 @@
</span><span class="cx"> });
</span><span class="cx"> 
</span><span class="cx"> CodeMirror.defineMIME(&quot;text/x-coffeescript&quot;, &quot;coffeescript&quot;);
</span><ins>+CodeMirror.defineMIME(&quot;text/coffeescript&quot;, &quot;coffeescript&quot;);
</ins><span class="cx"> 
</span><span class="cx"> });
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorcommentjs"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/comment.js (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/comment.js        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/comment.js        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -21,7 +21,13 @@
</span><span class="cx">   }
</span><span class="cx"> 
</span><span class="cx">   CodeMirror.commands.toggleComment = function(cm) {
</span><del>-    var minLine = Infinity, ranges = cm.listSelections(), mode = null;
</del><ins>+    cm.toggleComment();
+  };
+
+  CodeMirror.defineExtension(&quot;toggleComment&quot;, function(options) {
+    if (!options) options = noOptions;
+    var cm = this;
+    var minLine = Infinity, ranges = this.listSelections(), mode = null;
</ins><span class="cx">     for (var i = ranges.length - 1; i &gt;= 0; i--) {
</span><span class="cx">       var from = ranges[i].from(), to = ranges[i].to();
</span><span class="cx">       if (from.line &gt;= minLine) continue;
</span><span class="lines">@@ -28,19 +34,27 @@
</span><span class="cx">       if (to.line &gt;= minLine) to = Pos(minLine, 0);
</span><span class="cx">       minLine = from.line;
</span><span class="cx">       if (mode == null) {
</span><del>-        if (cm.uncomment(from, to)) mode = &quot;un&quot;;
-        else { cm.lineComment(from, to); mode = &quot;line&quot;; }
</del><ins>+        if (cm.uncomment(from, to, options)) mode = &quot;un&quot;;
+        else { cm.lineComment(from, to, options); mode = &quot;line&quot;; }
</ins><span class="cx">       } else if (mode == &quot;un&quot;) {
</span><del>-        cm.uncomment(from, to);
</del><ins>+        cm.uncomment(from, to, options);
</ins><span class="cx">       } else {
</span><del>-        cm.lineComment(from, to);
</del><ins>+        cm.lineComment(from, to, options);
</ins><span class="cx">       }
</span><span class="cx">     }
</span><del>-  };
</del><ins>+  });
</ins><span class="cx"> 
</span><ins>+  // 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))) &amp;&amp; !/^[\'\&quot;`]/.test(line)
+  }
+
</ins><span class="cx">   CodeMirror.defineExtension(&quot;lineComment&quot;, function(from, to, options) {
</span><span class="cx">     if (!options) options = noOptions;
</span><span class="cx">     var self = this, mode = self.getModeAt(from);
</span><ins>+    var firstLine = self.getLine(from.line);
+    if (firstLine == null || probablyInsideString(self, from, firstLine)) return;
+
</ins><span class="cx">     var commentString = options.lineComment || mode.lineComment;
</span><span class="cx">     if (!commentString) {
</span><span class="cx">       if (options.blockCommentStart || mode.blockCommentStart) {
</span><span class="lines">@@ -49,8 +63,7 @@
</span><span class="cx">       }
</span><span class="cx">       return;
</span><span class="cx">     }
</span><del>-    var firstLine = self.getLine(from.line);
-    if (firstLine == null) return;
</del><ins>+
</ins><span class="cx">     var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1);
</span><span class="cx">     var pad = options.padding == null ? &quot; &quot; : options.padding;
</span><span class="cx">     var blankLines = options.commentBlankLines || from.line == to.line;
</span><span class="lines">@@ -57,8 +70,15 @@
</span><span class="cx"> 
</span><span class="cx">     self.operation(function() {
</span><span class="cx">       if (options.indent) {
</span><del>-        var baseString = firstLine.slice(0, firstNonWS(firstLine));
</del><ins>+        var baseString = null;
</ins><span class="cx">         for (var i = from.line; i &lt; end; ++i) {
</span><ins>+          var line = self.getLine(i);
+          var whitespace = line.slice(0, firstNonWS(line));
+          if (baseString == null || baseString.length &gt; whitespace.length) {
+            baseString = whitespace;
+          }
+        }
+        for (var i = from.line; i &lt; end; ++i) {
</ins><span class="cx">           var line = self.getLine(i), cut = baseString.length;
</span><span class="cx">           if (!blankLines &amp;&amp; !nonWS.test(line)) continue;
</span><span class="cx">           if (line.slice(0, cut) != baseString) cut = firstNonWS(line);
</span><span class="lines">@@ -83,6 +103,7 @@
</span><span class="cx">         self.lineComment(from, to, options);
</span><span class="cx">       return;
</span><span class="cx">     }
</span><ins>+    if (/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line, 0)))) return
</ins><span class="cx"> 
</span><span class="cx">     var end = Math.min(to.line, self.lastLine());
</span><span class="cx">     if (end != from.line &amp;&amp; to.ch == 0 &amp;&amp; nonWS.test(self.getLine(end))) --end;
</span><span class="lines">@@ -120,7 +141,7 @@
</span><span class="cx">         var line = self.getLine(i);
</span><span class="cx">         var found = line.indexOf(lineString);
</span><span class="cx">         if (found &gt; -1 &amp;&amp; !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1;
</span><del>-        if (found == -1 &amp;&amp; (i != end || i == start) &amp;&amp; nonWS.test(line)) break lineComment;
</del><ins>+        if (found == -1 &amp;&amp; nonWS.test(line)) break lineComment;
</ins><span class="cx">         if (found &gt; -1 &amp;&amp; nonWS.test(line.slice(0, found))) break lineComment;
</span><span class="cx">         lines.push(line);
</span><span class="cx">       }
</span><span class="lines">@@ -142,13 +163,15 @@
</span><span class="cx">     var endString = options.blockCommentEnd || mode.blockCommentEnd;
</span><span class="cx">     if (!startString || !endString) return false;
</span><span class="cx">     var lead = options.blockCommentLead || mode.blockCommentLead;
</span><del>-    var startLine = self.getLine(start), endLine = end == start ? startLine : self.getLine(end);
-    var open = startLine.indexOf(startString), close = endLine.lastIndexOf(endString);
</del><ins>+    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);
</ins><span class="cx">     if (close == -1 &amp;&amp; start != end) {
</span><span class="cx">       endLine = self.getLine(--end);
</span><del>-      close = endLine.lastIndexOf(endString);
</del><ins>+      close = endLine.indexOf(endString);
</ins><span class="cx">     }
</span><del>-    if (open == -1 || close == -1 ||
</del><ins>+    if (close == -1 ||
</ins><span class="cx">         !/comment/.test(self.getTokenTypeAt(Pos(start, open + 1))) ||
</span><span class="cx">         !/comment/.test(self.getTokenTypeAt(Pos(end, close + 1))))
</span><span class="cx">       return false;
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorcssjs"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/css.js (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/css.js        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/css.js        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -12,9 +12,8 @@
</span><span class="cx"> &quot;use strict&quot;;
</span><span class="cx"> 
</span><span class="cx"> CodeMirror.defineMode(&quot;css&quot;, function(config, parserConfig) {
</span><del>-  var provided = parserConfig;
</del><ins>+  var inline = parserConfig.inline
</ins><span class="cx">   if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode(&quot;text/css&quot;);
</span><del>-  parserConfig.inline = provided.inline;
</del><span class="cx"> 
</span><span class="cx">   var indentUnit = config.indentUnit,
</span><span class="cx">       tokenHooks = parserConfig.tokenHooks,
</span><span class="lines">@@ -28,7 +27,8 @@
</span><span class="cx">       counterDescriptors = parserConfig.counterDescriptors || {},
</span><span class="cx">       colorKeywords = parserConfig.colorKeywords || {},
</span><span class="cx">       valueKeywords = parserConfig.valueKeywords || {},
</span><del>-      allowNested = parserConfig.allowNested;
</del><ins>+      allowNested = parserConfig.allowNested,
+      supportsAtComponent = parserConfig.supportsAtComponent === true;
</ins><span class="cx"> 
</span><span class="cx">   var type, override;
</span><span class="cx">   function ret(style, tp) { type = tp; return style; }
</span><span class="lines">@@ -122,13 +122,14 @@
</span><span class="cx">     this.prev = prev;
</span><span class="cx">   }
</span><span class="cx"> 
</span><del>-  function pushContext(state, stream, type) {
-    state.context = new Context(type, stream.indentation() + indentUnit, state.context);
</del><ins>+  function pushContext(state, stream, type, indent) {
+    state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context);
</ins><span class="cx">     return type;
</span><span class="cx">   }
</span><span class="cx"> 
</span><span class="cx">   function popContext(state) {
</span><del>-    state.context = state.context.prev;
</del><ins>+    if (state.context.prev)
+      state.context = state.context.prev;
</ins><span class="cx">     return state.context.type;
</span><span class="cx">   }
</span><span class="cx"> 
</span><span class="lines">@@ -160,9 +161,13 @@
</span><span class="cx">       return pushContext(state, stream, &quot;block&quot;);
</span><span class="cx">     } else if (type == &quot;}&quot; &amp;&amp; state.context.prev) {
</span><span class="cx">       return popContext(state);
</span><del>-    } else if (/@(media|supports|(-moz-)?document)/.test(type)) {
</del><ins>+    } else if (supportsAtComponent &amp;&amp; /@component/.test(type)) {
+      return pushContext(state, stream, &quot;atComponentBlock&quot;);
+    } else if (/^@(-moz-)?document$/.test(type)) {
+      return pushContext(state, stream, &quot;documentTypes&quot;);
+    } else if (/^@(media|supports|(-moz-)?document|import)$/.test(type)) {
</ins><span class="cx">       return pushContext(state, stream, &quot;atBlock&quot;);
</span><del>-    } else if (/@(font-face|counter-style)/.test(type)) {
</del><ins>+    } else if (/^@(font-face|counter-style)/.test(type)) {
</ins><span class="cx">       state.stateArg = type;
</span><span class="cx">       return &quot;restricted_atBlock_before&quot;;
</span><span class="cx">     } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) {
</span><span class="lines">@@ -222,7 +227,7 @@
</span><span class="cx">     if (type == &quot;}&quot; || type == &quot;{&quot;) return popAndPass(type, stream, state);
</span><span class="cx">     if (type == &quot;(&quot;) return pushContext(state, stream, &quot;parens&quot;);
</span><span class="cx"> 
</span><del>-    if (type == &quot;hash&quot; &amp;&amp; !/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(stream.current())) {
</del><ins>+    if (type == &quot;hash&quot; &amp;&amp; !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) {
</ins><span class="cx">       override += &quot; error&quot;;
</span><span class="cx">     } else if (type == &quot;word&quot;) {
</span><span class="cx">       wordAsValue(stream);
</span><span class="lines">@@ -255,17 +260,26 @@
</span><span class="cx">     return pass(type, stream, state);
</span><span class="cx">   };
</span><span class="cx"> 
</span><ins>+  states.documentTypes = function(type, stream, state) {
+    if (type == &quot;word&quot; &amp;&amp; documentTypes.hasOwnProperty(stream.current())) {
+      override = &quot;tag&quot;;
+      return state.context.type;
+    } else {
+      return states.atBlock(type, stream, state);
+    }
+  };
+
</ins><span class="cx">   states.atBlock = function(type, stream, state) {
</span><span class="cx">     if (type == &quot;(&quot;) return pushContext(state, stream, &quot;atBlock_parens&quot;);
</span><del>-    if (type == &quot;}&quot;) return popAndPass(type, stream, state);
</del><ins>+    if (type == &quot;}&quot; || type == &quot;;&quot;) return popAndPass(type, stream, state);
</ins><span class="cx">     if (type == &quot;{&quot;) return popContext(state) &amp;&amp; pushContext(state, stream, allowNested ? &quot;block&quot; : &quot;top&quot;);
</span><span class="cx"> 
</span><ins>+    if (type == &quot;interpolation&quot;) return pushContext(state, stream, &quot;interpolation&quot;);
+
</ins><span class="cx">     if (type == &quot;word&quot;) {
</span><span class="cx">       var word = stream.current().toLowerCase();
</span><span class="cx">       if (word == &quot;only&quot; || word == &quot;not&quot; || word == &quot;and&quot; || word == &quot;or&quot;)
</span><span class="cx">         override = &quot;keyword&quot;;
</span><del>-      else if (documentTypes.hasOwnProperty(word))
-        override = &quot;tag&quot;;
</del><span class="cx">       else if (mediaTypes.hasOwnProperty(word))
</span><span class="cx">         override = &quot;attribute&quot;;
</span><span class="cx">       else if (mediaFeatures.hasOwnProperty(word))
</span><span class="lines">@@ -286,6 +300,16 @@
</span><span class="cx">     return state.context.type;
</span><span class="cx">   };
</span><span class="cx"> 
</span><ins>+  states.atComponentBlock = function(type, stream, state) {
+    if (type == &quot;}&quot;)
+      return popAndPass(type, stream, state);
+    if (type == &quot;{&quot;)
+      return popContext(state) &amp;&amp; pushContext(state, stream, allowNested ? &quot;block&quot; : &quot;top&quot;, false);
+    if (type == &quot;word&quot;)
+      override = &quot;error&quot;;
+    return state.context.type;
+  };
+
</ins><span class="cx">   states.atBlock_parens = function(type, stream, state) {
</span><span class="cx">     if (type == &quot;)&quot;) return popContext(state);
</span><span class="cx">     if (type == &quot;{&quot; || type == &quot;}&quot;) return popAndPass(type, stream, state, 2);
</span><span class="lines">@@ -343,9 +367,9 @@
</span><span class="cx">   return {
</span><span class="cx">     startState: function(base) {
</span><span class="cx">       return {tokenize: null,
</span><del>-              state: parserConfig.inline ? &quot;block&quot; : &quot;top&quot;,
</del><ins>+              state: inline ? &quot;block&quot; : &quot;top&quot;,
</ins><span class="cx">               stateArg: null,
</span><del>-              context: new Context(parserConfig.inline ? &quot;block&quot; : &quot;top&quot;, base || 0, null)};
</del><ins>+              context: new Context(inline ? &quot;block&quot; : &quot;top&quot;, base || 0, null)};
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     token: function(stream, state) {
</span><span class="lines">@@ -364,12 +388,18 @@
</span><span class="cx">       var cx = state.context, ch = textAfter &amp;&amp; textAfter.charAt(0);
</span><span class="cx">       var indent = cx.indent;
</span><span class="cx">       if (cx.type == &quot;prop&quot; &amp;&amp; (ch == &quot;}&quot; || ch == &quot;)&quot;)) cx = cx.prev;
</span><del>-      if (cx.prev &amp;&amp;
-          (ch == &quot;}&quot; &amp;&amp; (cx.type == &quot;block&quot; || cx.type == &quot;top&quot; || cx.type == &quot;interpolation&quot; || cx.type == &quot;restricted_atBlock&quot;) ||
-           ch == &quot;)&quot; &amp;&amp; (cx.type == &quot;parens&quot; || cx.type == &quot;atBlock_parens&quot;) ||
-           ch == &quot;{&quot; &amp;&amp; (cx.type == &quot;at&quot; || cx.type == &quot;atBlock&quot;))) {
-        indent = cx.indent - indentUnit;
-        cx = cx.prev;
</del><ins>+      if (cx.prev) {
+        if (ch == &quot;}&quot; &amp;&amp; (cx.type == &quot;block&quot; || cx.type == &quot;top&quot; ||
+                          cx.type == &quot;interpolation&quot; || cx.type == &quot;restricted_atBlock&quot;)) {
+          // Resume indentation from parent context.
+          cx = cx.prev;
+          indent = cx.indent;
+        } else if (ch == &quot;)&quot; &amp;&amp; (cx.type == &quot;parens&quot; || cx.type == &quot;atBlock_parens&quot;) ||
+            ch == &quot;{&quot; &amp;&amp; (cx.type == &quot;at&quot; || cx.type == &quot;atBlock&quot;)) {
+          // Dedent relative to current context.
+          indent = Math.max(0, cx.indent - indentUnit);
+          cx = cx.prev;
+        }
</ins><span class="cx">       }
</span><span class="cx">       return indent;
</span><span class="cx">     },
</span><span class="lines">@@ -384,7 +414,7 @@
</span><span class="cx">   function keySet(array) {
</span><span class="cx">     var keys = {};
</span><span class="cx">     for (var i = 0; i &lt; array.length; ++i) {
</span><del>-      keys[array[i]] = true;
</del><ins>+      keys[array[i].toLowerCase()] = true;
</ins><span class="cx">     }
</span><span class="cx">     return keys;
</span><span class="cx">   }
</span><span class="lines">@@ -422,8 +452,8 @@
</span><span class="cx">     &quot;animation-direction&quot;, &quot;animation-duration&quot;, &quot;animation-fill-mode&quot;,
</span><span class="cx">     &quot;animation-iteration-count&quot;, &quot;animation-name&quot;, &quot;animation-play-state&quot;,
</span><span class="cx">     &quot;animation-timing-function&quot;, &quot;appearance&quot;, &quot;azimuth&quot;, &quot;backface-visibility&quot;,
</span><del>-    &quot;background&quot;, &quot;background-attachment&quot;, &quot;background-clip&quot;, &quot;background-color&quot;,
-    &quot;background-image&quot;, &quot;background-origin&quot;, &quot;background-position&quot;,
</del><ins>+    &quot;background&quot;, &quot;background-attachment&quot;, &quot;background-blend-mode&quot;, &quot;background-clip&quot;,
+    &quot;background-color&quot;, &quot;background-image&quot;, &quot;background-origin&quot;, &quot;background-position&quot;,
</ins><span class="cx">     &quot;background-repeat&quot;, &quot;background-size&quot;, &quot;baseline-shift&quot;, &quot;binding&quot;,
</span><span class="cx">     &quot;bleed&quot;, &quot;bookmark-label&quot;, &quot;bookmark-level&quot;, &quot;bookmark-state&quot;,
</span><span class="cx">     &quot;bookmark-target&quot;, &quot;border&quot;, &quot;border-bottom&quot;, &quot;border-bottom-color&quot;,
</span><span class="lines">@@ -454,9 +484,9 @@
</span><span class="cx">     &quot;font-variant-alternates&quot;, &quot;font-variant-caps&quot;, &quot;font-variant-east-asian&quot;,
</span><span class="cx">     &quot;font-variant-ligatures&quot;, &quot;font-variant-numeric&quot;, &quot;font-variant-position&quot;,
</span><span class="cx">     &quot;font-weight&quot;, &quot;grid&quot;, &quot;grid-area&quot;, &quot;grid-auto-columns&quot;, &quot;grid-auto-flow&quot;,
</span><del>-    &quot;grid-auto-position&quot;, &quot;grid-auto-rows&quot;, &quot;grid-column&quot;, &quot;grid-column-end&quot;,
-    &quot;grid-column-start&quot;, &quot;grid-row&quot;, &quot;grid-row-end&quot;, &quot;grid-row-start&quot;,
-    &quot;grid-template&quot;, &quot;grid-template-areas&quot;, &quot;grid-template-columns&quot;,
</del><ins>+    &quot;grid-auto-rows&quot;, &quot;grid-column&quot;, &quot;grid-column-end&quot;, &quot;grid-column-gap&quot;,
+    &quot;grid-column-start&quot;, &quot;grid-gap&quot;, &quot;grid-row&quot;, &quot;grid-row-end&quot;, &quot;grid-row-gap&quot;,
+    &quot;grid-row-start&quot;, &quot;grid-template&quot;, &quot;grid-template-areas&quot;, &quot;grid-template-columns&quot;,
</ins><span class="cx">     &quot;grid-template-rows&quot;, &quot;hanging-punctuation&quot;, &quot;height&quot;, &quot;hyphens&quot;,
</span><span class="cx">     &quot;icon&quot;, &quot;image-orientation&quot;, &quot;image-rendering&quot;, &quot;image-resolution&quot;,
</span><span class="cx">     &quot;inline-box-align&quot;, &quot;justify-content&quot;, &quot;left&quot;, &quot;letter-spacing&quot;,
</span><span class="lines">@@ -464,7 +494,7 @@
</span><span class="cx">     &quot;line-stacking-shift&quot;, &quot;line-stacking-strategy&quot;, &quot;list-style&quot;,
</span><span class="cx">     &quot;list-style-image&quot;, &quot;list-style-position&quot;, &quot;list-style-type&quot;, &quot;margin&quot;,
</span><span class="cx">     &quot;margin-bottom&quot;, &quot;margin-left&quot;, &quot;margin-right&quot;, &quot;margin-top&quot;,
</span><del>-    &quot;marker-offset&quot;, &quot;marks&quot;, &quot;marquee-direction&quot;, &quot;marquee-loop&quot;,
</del><ins>+    &quot;marks&quot;, &quot;marquee-direction&quot;, &quot;marquee-loop&quot;,
</ins><span class="cx">     &quot;marquee-play-count&quot;, &quot;marquee-speed&quot;, &quot;marquee-style&quot;, &quot;max-height&quot;,
</span><span class="cx">     &quot;max-width&quot;, &quot;min-height&quot;, &quot;min-width&quot;, &quot;move-to&quot;, &quot;nav-down&quot;, &quot;nav-index&quot;,
</span><span class="cx">     &quot;nav-left&quot;, &quot;nav-right&quot;, &quot;nav-up&quot;, &quot;object-fit&quot;, &quot;object-position&quot;,
</span><span class="lines">@@ -492,9 +522,9 @@
</span><span class="cx">     &quot;text-wrap&quot;, &quot;top&quot;, &quot;transform&quot;, &quot;transform-origin&quot;, &quot;transform-style&quot;,
</span><span class="cx">     &quot;transition&quot;, &quot;transition-delay&quot;, &quot;transition-duration&quot;,
</span><span class="cx">     &quot;transition-property&quot;, &quot;transition-timing-function&quot;, &quot;unicode-bidi&quot;,
</span><del>-    &quot;vertical-align&quot;, &quot;visibility&quot;, &quot;voice-balance&quot;, &quot;voice-duration&quot;,
</del><ins>+    &quot;user-select&quot;, &quot;vertical-align&quot;, &quot;visibility&quot;, &quot;voice-balance&quot;, &quot;voice-duration&quot;,
</ins><span class="cx">     &quot;voice-family&quot;, &quot;voice-pitch&quot;, &quot;voice-range&quot;, &quot;voice-rate&quot;, &quot;voice-stress&quot;,
</span><del>-    &quot;voice-volume&quot;, &quot;volume&quot;, &quot;white-space&quot;, &quot;widows&quot;, &quot;width&quot;, &quot;word-break&quot;,
</del><ins>+    &quot;voice-volume&quot;, &quot;volume&quot;, &quot;white-space&quot;, &quot;widows&quot;, &quot;width&quot;, &quot;will-change&quot;, &quot;word-break&quot;,
</ins><span class="cx">     &quot;word-spacing&quot;, &quot;word-wrap&quot;, &quot;z-index&quot;,
</span><span class="cx">     // SVG-specific
</span><span class="cx">     &quot;clip-path&quot;, &quot;clip-rule&quot;, &quot;mask&quot;, &quot;enable-background&quot;, &quot;filter&quot;, &quot;flood-color&quot;,
</span><span class="lines">@@ -567,11 +597,12 @@
</span><span class="cx">     &quot;capitalize&quot;, &quot;caps-lock-indicator&quot;, &quot;caption&quot;, &quot;captiontext&quot;, &quot;caret&quot;,
</span><span class="cx">     &quot;cell&quot;, &quot;center&quot;, &quot;checkbox&quot;, &quot;circle&quot;, &quot;cjk-decimal&quot;, &quot;cjk-earthly-branch&quot;,
</span><span class="cx">     &quot;cjk-heavenly-stem&quot;, &quot;cjk-ideographic&quot;, &quot;clear&quot;, &quot;clip&quot;, &quot;close-quote&quot;,
</span><del>-    &quot;col-resize&quot;, &quot;collapse&quot;, &quot;column&quot;, &quot;column-reverse&quot;, &quot;compact&quot;, &quot;condensed&quot;, &quot;contain&quot;, &quot;content&quot;,
</del><ins>+    &quot;col-resize&quot;, &quot;collapse&quot;, &quot;color&quot;, &quot;color-burn&quot;, &quot;color-dodge&quot;, &quot;column&quot;, &quot;column-reverse&quot;,
+    &quot;compact&quot;, &quot;condensed&quot;, &quot;contain&quot;, &quot;content&quot;, &quot;contents&quot;,
</ins><span class="cx">     &quot;content-box&quot;, &quot;context-menu&quot;, &quot;continuous&quot;, &quot;copy&quot;, &quot;counter&quot;, &quot;counters&quot;, &quot;cover&quot;, &quot;crop&quot;,
</span><del>-    &quot;cross&quot;, &quot;crosshair&quot;, &quot;currentcolor&quot;, &quot;cursive&quot;, &quot;cyclic&quot;, &quot;dashed&quot;, &quot;decimal&quot;,
-    &quot;decimal-leading-zero&quot;, &quot;default&quot;, &quot;default-button&quot;, &quot;destination-atop&quot;,
-    &quot;destination-in&quot;, &quot;destination-out&quot;, &quot;destination-over&quot;, &quot;devanagari&quot;,
</del><ins>+    &quot;cross&quot;, &quot;crosshair&quot;, &quot;currentcolor&quot;, &quot;cursive&quot;, &quot;cyclic&quot;, &quot;darken&quot;, &quot;dashed&quot;, &quot;decimal&quot;,
+    &quot;decimal-leading-zero&quot;, &quot;default&quot;, &quot;default-button&quot;, &quot;dense&quot;, &quot;destination-atop&quot;,
+    &quot;destination-in&quot;, &quot;destination-out&quot;, &quot;destination-over&quot;, &quot;devanagari&quot;, &quot;difference&quot;,
</ins><span class="cx">     &quot;disc&quot;, &quot;discard&quot;, &quot;disclosure-closed&quot;, &quot;disclosure-open&quot;, &quot;document&quot;,
</span><span class="cx">     &quot;dot-dash&quot;, &quot;dot-dot-dash&quot;,
</span><span class="cx">     &quot;dotted&quot;, &quot;double&quot;, &quot;down&quot;, &quot;e-resize&quot;, &quot;ease&quot;, &quot;ease-in&quot;, &quot;ease-in-out&quot;, &quot;ease-out&quot;,
</span><span class="lines">@@ -582,23 +613,23 @@
</span><span class="cx">     &quot;ethiopic-halehame-gez&quot;, &quot;ethiopic-halehame-om-et&quot;,
</span><span class="cx">     &quot;ethiopic-halehame-sid-et&quot;, &quot;ethiopic-halehame-so-et&quot;,
</span><span class="cx">     &quot;ethiopic-halehame-ti-er&quot;, &quot;ethiopic-halehame-ti-et&quot;, &quot;ethiopic-halehame-tig&quot;,
</span><del>-    &quot;ethiopic-numeric&quot;, &quot;ew-resize&quot;, &quot;expanded&quot;, &quot;extends&quot;, &quot;extra-condensed&quot;,
-    &quot;extra-expanded&quot;, &quot;fantasy&quot;, &quot;fast&quot;, &quot;fill&quot;, &quot;fixed&quot;, &quot;flat&quot;, &quot;flex&quot;, &quot;footnotes&quot;,
-    &quot;forwards&quot;, &quot;from&quot;, &quot;geometricPrecision&quot;, &quot;georgian&quot;, &quot;graytext&quot;, &quot;groove&quot;,
-    &quot;gujarati&quot;, &quot;gurmukhi&quot;, &quot;hand&quot;, &quot;hangul&quot;, &quot;hangul-consonant&quot;, &quot;hebrew&quot;,
</del><ins>+    &quot;ethiopic-numeric&quot;, &quot;ew-resize&quot;, &quot;exclusion&quot;, &quot;expanded&quot;, &quot;extends&quot;, &quot;extra-condensed&quot;,
+    &quot;extra-expanded&quot;, &quot;fantasy&quot;, &quot;fast&quot;, &quot;fill&quot;, &quot;fixed&quot;, &quot;flat&quot;, &quot;flex&quot;, &quot;flex-end&quot;, &quot;flex-start&quot;, &quot;footnotes&quot;,
+    &quot;forwards&quot;, &quot;from&quot;, &quot;geometricPrecision&quot;, &quot;georgian&quot;, &quot;graytext&quot;, &quot;grid&quot;, &quot;groove&quot;,
+    &quot;gujarati&quot;, &quot;gurmukhi&quot;, &quot;hand&quot;, &quot;hangul&quot;, &quot;hangul-consonant&quot;, &quot;hard-light&quot;, &quot;hebrew&quot;,
</ins><span class="cx">     &quot;help&quot;, &quot;hidden&quot;, &quot;hide&quot;, &quot;higher&quot;, &quot;highlight&quot;, &quot;highlighttext&quot;,
</span><del>-    &quot;hiragana&quot;, &quot;hiragana-iroha&quot;, &quot;horizontal&quot;, &quot;hsl&quot;, &quot;hsla&quot;, &quot;icon&quot;, &quot;ignore&quot;,
</del><ins>+    &quot;hiragana&quot;, &quot;hiragana-iroha&quot;, &quot;horizontal&quot;, &quot;hsl&quot;, &quot;hsla&quot;, &quot;hue&quot;, &quot;icon&quot;, &quot;ignore&quot;,
</ins><span class="cx">     &quot;inactiveborder&quot;, &quot;inactivecaption&quot;, &quot;inactivecaptiontext&quot;, &quot;infinite&quot;,
</span><span class="cx">     &quot;infobackground&quot;, &quot;infotext&quot;, &quot;inherit&quot;, &quot;initial&quot;, &quot;inline&quot;, &quot;inline-axis&quot;,
</span><del>-    &quot;inline-block&quot;, &quot;inline-flex&quot;, &quot;inline-table&quot;, &quot;inset&quot;, &quot;inside&quot;, &quot;intrinsic&quot;, &quot;invert&quot;,
</del><ins>+    &quot;inline-block&quot;, &quot;inline-flex&quot;, &quot;inline-grid&quot;, &quot;inline-table&quot;, &quot;inset&quot;, &quot;inside&quot;, &quot;intrinsic&quot;, &quot;invert&quot;,
</ins><span class="cx">     &quot;italic&quot;, &quot;japanese-formal&quot;, &quot;japanese-informal&quot;, &quot;justify&quot;, &quot;kannada&quot;,
</span><span class="cx">     &quot;katakana&quot;, &quot;katakana-iroha&quot;, &quot;keep-all&quot;, &quot;khmer&quot;,
</span><span class="cx">     &quot;korean-hangul-formal&quot;, &quot;korean-hanja-formal&quot;, &quot;korean-hanja-informal&quot;,
</span><del>-    &quot;landscape&quot;, &quot;lao&quot;, &quot;large&quot;, &quot;larger&quot;, &quot;left&quot;, &quot;level&quot;, &quot;lighter&quot;,
</del><ins>+    &quot;landscape&quot;, &quot;lao&quot;, &quot;large&quot;, &quot;larger&quot;, &quot;left&quot;, &quot;level&quot;, &quot;lighter&quot;, &quot;lighten&quot;,
</ins><span class="cx">     &quot;line-through&quot;, &quot;linear&quot;, &quot;linear-gradient&quot;, &quot;lines&quot;, &quot;list-item&quot;, &quot;listbox&quot;, &quot;listitem&quot;,
</span><span class="cx">     &quot;local&quot;, &quot;logical&quot;, &quot;loud&quot;, &quot;lower&quot;, &quot;lower-alpha&quot;, &quot;lower-armenian&quot;,
</span><span class="cx">     &quot;lower-greek&quot;, &quot;lower-hexadecimal&quot;, &quot;lower-latin&quot;, &quot;lower-norwegian&quot;,
</span><del>-    &quot;lower-roman&quot;, &quot;lowercase&quot;, &quot;ltr&quot;, &quot;malayalam&quot;, &quot;match&quot;, &quot;matrix&quot;, &quot;matrix3d&quot;,
</del><ins>+    &quot;lower-roman&quot;, &quot;lowercase&quot;, &quot;ltr&quot;, &quot;luminosity&quot;, &quot;malayalam&quot;, &quot;match&quot;, &quot;matrix&quot;, &quot;matrix3d&quot;,
</ins><span class="cx">     &quot;media-controls-background&quot;, &quot;media-current-time-display&quot;,
</span><span class="cx">     &quot;media-fullscreen-button&quot;, &quot;media-mute-button&quot;, &quot;media-play-button&quot;,
</span><span class="cx">     &quot;media-return-to-realtime-button&quot;, &quot;media-rewind-button&quot;,
</span><span class="lines">@@ -607,10 +638,10 @@
</span><span class="cx">     &quot;media-volume-slider-container&quot;, &quot;media-volume-sliderthumb&quot;, &quot;medium&quot;,
</span><span class="cx">     &quot;menu&quot;, &quot;menulist&quot;, &quot;menulist-button&quot;, &quot;menulist-text&quot;,
</span><span class="cx">     &quot;menulist-textfield&quot;, &quot;menutext&quot;, &quot;message-box&quot;, &quot;middle&quot;, &quot;min-intrinsic&quot;,
</span><del>-    &quot;mix&quot;, &quot;mongolian&quot;, &quot;monospace&quot;, &quot;move&quot;, &quot;multiple&quot;, &quot;myanmar&quot;, &quot;n-resize&quot;,
</del><ins>+    &quot;mix&quot;, &quot;mongolian&quot;, &quot;monospace&quot;, &quot;move&quot;, &quot;multiple&quot;, &quot;multiply&quot;, &quot;myanmar&quot;, &quot;n-resize&quot;,
</ins><span class="cx">     &quot;narrower&quot;, &quot;ne-resize&quot;, &quot;nesw-resize&quot;, &quot;no-close-quote&quot;, &quot;no-drop&quot;,
</span><span class="cx">     &quot;no-open-quote&quot;, &quot;no-repeat&quot;, &quot;none&quot;, &quot;normal&quot;, &quot;not-allowed&quot;, &quot;nowrap&quot;,
</span><del>-    &quot;ns-resize&quot;, &quot;numbers&quot;, &quot;numeric&quot;, &quot;nw-resize&quot;, &quot;nwse-resize&quot;, &quot;oblique&quot;, &quot;octal&quot;, &quot;open-quote&quot;,
</del><ins>+    &quot;ns-resize&quot;, &quot;numbers&quot;, &quot;numeric&quot;, &quot;nw-resize&quot;, &quot;nwse-resize&quot;, &quot;oblique&quot;, &quot;octal&quot;, &quot;opacity&quot;, &quot;open-quote&quot;,
</ins><span class="cx">     &quot;optimizeLegibility&quot;, &quot;optimizeSpeed&quot;, &quot;oriya&quot;, &quot;oromo&quot;, &quot;outset&quot;,
</span><span class="cx">     &quot;outside&quot;, &quot;outside-shape&quot;, &quot;overlay&quot;, &quot;overline&quot;, &quot;padding&quot;, &quot;padding-box&quot;,
</span><span class="cx">     &quot;painted&quot;, &quot;page&quot;, &quot;paused&quot;, &quot;persian&quot;, &quot;perspective&quot;, &quot;plus-darker&quot;, &quot;plus-lighter&quot;,
</span><span class="lines">@@ -621,8 +652,8 @@
</span><span class="cx">     &quot;repeating-radial-gradient&quot;, &quot;repeat-x&quot;, &quot;repeat-y&quot;, &quot;reset&quot;, &quot;reverse&quot;,
</span><span class="cx">     &quot;rgb&quot;, &quot;rgba&quot;, &quot;ridge&quot;, &quot;right&quot;, &quot;rotate&quot;, &quot;rotate3d&quot;, &quot;rotateX&quot;, &quot;rotateY&quot;,
</span><span class="cx">     &quot;rotateZ&quot;, &quot;round&quot;, &quot;row&quot;, &quot;row-resize&quot;, &quot;row-reverse&quot;, &quot;rtl&quot;, &quot;run-in&quot;, &quot;running&quot;,
</span><del>-    &quot;s-resize&quot;, &quot;sans-serif&quot;, &quot;scale&quot;, &quot;scale3d&quot;, &quot;scaleX&quot;, &quot;scaleY&quot;, &quot;scaleZ&quot;,
-    &quot;scroll&quot;, &quot;scrollbar&quot;, &quot;se-resize&quot;, &quot;searchfield&quot;,
</del><ins>+    &quot;s-resize&quot;, &quot;sans-serif&quot;, &quot;saturation&quot;, &quot;scale&quot;, &quot;scale3d&quot;, &quot;scaleX&quot;, &quot;scaleY&quot;, &quot;scaleZ&quot;, &quot;screen&quot;,
+    &quot;scroll&quot;, &quot;scrollbar&quot;, &quot;scroll-position&quot;, &quot;se-resize&quot;, &quot;searchfield&quot;,
</ins><span class="cx">     &quot;searchfield-cancel-button&quot;, &quot;searchfield-decoration&quot;,
</span><span class="cx">     &quot;searchfield-results-button&quot;, &quot;searchfield-results-decoration&quot;,
</span><span class="cx">     &quot;semi-condensed&quot;, &quot;semi-expanded&quot;, &quot;separate&quot;, &quot;serif&quot;, &quot;show&quot;, &quot;sidama&quot;,
</span><span class="lines">@@ -629,8 +660,8 @@
</span><span class="cx">     &quot;simp-chinese-formal&quot;, &quot;simp-chinese-informal&quot;, &quot;single&quot;,
</span><span class="cx">     &quot;skew&quot;, &quot;skewX&quot;, &quot;skewY&quot;, &quot;skip-white-space&quot;, &quot;slide&quot;, &quot;slider-horizontal&quot;,
</span><span class="cx">     &quot;slider-vertical&quot;, &quot;sliderthumb-horizontal&quot;, &quot;sliderthumb-vertical&quot;, &quot;slow&quot;,
</span><del>-    &quot;small&quot;, &quot;small-caps&quot;, &quot;small-caption&quot;, &quot;smaller&quot;, &quot;solid&quot;, &quot;somali&quot;,
-    &quot;source-atop&quot;, &quot;source-in&quot;, &quot;source-out&quot;, &quot;source-over&quot;, &quot;space&quot;, &quot;spell-out&quot;, &quot;square&quot;,
</del><ins>+    &quot;small&quot;, &quot;small-caps&quot;, &quot;small-caption&quot;, &quot;smaller&quot;, &quot;soft-light&quot;, &quot;solid&quot;, &quot;somali&quot;,
+    &quot;source-atop&quot;, &quot;source-in&quot;, &quot;source-out&quot;, &quot;source-over&quot;, &quot;space&quot;, &quot;space-around&quot;, &quot;space-between&quot;, &quot;spell-out&quot;, &quot;square&quot;,
</ins><span class="cx">     &quot;square-button&quot;, &quot;start&quot;, &quot;static&quot;, &quot;status-bar&quot;, &quot;stretch&quot;, &quot;stroke&quot;, &quot;sub&quot;,
</span><span class="cx">     &quot;subpixel-antialiased&quot;, &quot;super&quot;, &quot;sw-resize&quot;, &quot;symbolic&quot;, &quot;symbols&quot;, &quot;table&quot;,
</span><span class="cx">     &quot;table-caption&quot;, &quot;table-cell&quot;, &quot;table-column&quot;, &quot;table-column-group&quot;,
</span><span class="lines">@@ -640,14 +671,14 @@
</span><span class="cx">     &quot;thick&quot;, &quot;thin&quot;, &quot;threeddarkshadow&quot;, &quot;threedface&quot;, &quot;threedhighlight&quot;,
</span><span class="cx">     &quot;threedlightshadow&quot;, &quot;threedshadow&quot;, &quot;tibetan&quot;, &quot;tigre&quot;, &quot;tigrinya-er&quot;,
</span><span class="cx">     &quot;tigrinya-er-abegede&quot;, &quot;tigrinya-et&quot;, &quot;tigrinya-et-abegede&quot;, &quot;to&quot;, &quot;top&quot;,
</span><del>-    &quot;trad-chinese-formal&quot;, &quot;trad-chinese-informal&quot;,
</del><ins>+    &quot;trad-chinese-formal&quot;, &quot;trad-chinese-informal&quot;, &quot;transform&quot;,
</ins><span class="cx">     &quot;translate&quot;, &quot;translate3d&quot;, &quot;translateX&quot;, &quot;translateY&quot;, &quot;translateZ&quot;,
</span><del>-    &quot;transparent&quot;, &quot;ultra-condensed&quot;, &quot;ultra-expanded&quot;, &quot;underline&quot;, &quot;up&quot;,
</del><ins>+    &quot;transparent&quot;, &quot;ultra-condensed&quot;, &quot;ultra-expanded&quot;, &quot;underline&quot;, &quot;unset&quot;, &quot;up&quot;,
</ins><span class="cx">     &quot;upper-alpha&quot;, &quot;upper-armenian&quot;, &quot;upper-greek&quot;, &quot;upper-hexadecimal&quot;,
</span><span class="cx">     &quot;upper-latin&quot;, &quot;upper-norwegian&quot;, &quot;upper-roman&quot;, &quot;uppercase&quot;, &quot;urdu&quot;, &quot;url&quot;,
</span><span class="cx">     &quot;var&quot;, &quot;vertical&quot;, &quot;vertical-text&quot;, &quot;visible&quot;, &quot;visibleFill&quot;, &quot;visiblePainted&quot;,
</span><span class="cx">     &quot;visibleStroke&quot;, &quot;visual&quot;, &quot;w-resize&quot;, &quot;wait&quot;, &quot;wave&quot;, &quot;wider&quot;,
</span><del>-    &quot;window&quot;, &quot;windowframe&quot;, &quot;windowtext&quot;, &quot;words&quot;, &quot;x-large&quot;, &quot;x-small&quot;, &quot;xor&quot;,
</del><ins>+    &quot;window&quot;, &quot;windowframe&quot;, &quot;windowtext&quot;, &quot;words&quot;, &quot;wrap&quot;, &quot;wrap-reverse&quot;, &quot;x-large&quot;, &quot;x-small&quot;, &quot;xor&quot;,
</ins><span class="cx">     &quot;xx-large&quot;, &quot;xx-small&quot;
</span><span class="cx">   ], valueKeywords = keySet(valueKeywords_);
</span><span class="cx"> 
</span><span class="lines">@@ -769,4 +800,26 @@
</span><span class="cx">     helperType: &quot;less&quot;
</span><span class="cx">   });
</span><span class="cx"> 
</span><ins>+  CodeMirror.defineMIME(&quot;text/x-gss&quot;, {
+    documentTypes: documentTypes,
+    mediaTypes: mediaTypes,
+    mediaFeatures: mediaFeatures,
+    propertyKeywords: propertyKeywords,
+    nonStandardPropertyKeywords: nonStandardPropertyKeywords,
+    fontProperties: fontProperties,
+    counterDescriptors: counterDescriptors,
+    colorKeywords: colorKeywords,
+    valueKeywords: valueKeywords,
+    supportsAtComponent: true,
+    tokenHooks: {
+      &quot;/&quot;: function(stream, state) {
+        if (!stream.eat(&quot;*&quot;)) return false;
+        state.tokenize = tokenCComment;
+        return tokenCComment(stream, state);
+      }
+    },
+    name: &quot;css&quot;,
+    helperType: &quot;gss&quot;
+  });
+
</ins><span class="cx"> });
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorhtmlmixedjs"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/htmlmixed.js (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/htmlmixed.js        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/htmlmixed.js        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -9,113 +9,144 @@
</span><span class="cx">   else // Plain browser env
</span><span class="cx">     mod(CodeMirror);
</span><span class="cx"> })(function(CodeMirror) {
</span><del>-&quot;use strict&quot;;
</del><ins>+  &quot;use strict&quot;;
</ins><span class="cx"> 
</span><del>-CodeMirror.defineMode(&quot;htmlmixed&quot;, function(config, parserConfig) {
-  var htmlMode = CodeMirror.getMode(config, {name: &quot;xml&quot;,
-                                             htmlMode: true,
-                                             multilineTagIndentFactor: parserConfig.multilineTagIndentFactor,
-                                             multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag});
-  var cssMode = CodeMirror.getMode(config, &quot;css&quot;);
</del><ins>+  var defaultTags = {
+    script: [
+      [&quot;lang&quot;, /(javascript|babel)/i, &quot;javascript&quot;],
+      [&quot;type&quot;, /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i, &quot;javascript&quot;],
+      [&quot;type&quot;, /./, &quot;text/plain&quot;],
+      [null, null, &quot;javascript&quot;]
+    ],
+    style:  [
+      [&quot;lang&quot;, /^css$/i, &quot;css&quot;],
+      [&quot;type&quot;, /^(text\/)?(x-)?(stylesheet|css)$/i, &quot;css&quot;],
+      [&quot;type&quot;, /./, &quot;text/plain&quot;],
+      [null, null, &quot;css&quot;]
+    ]
+  };
</ins><span class="cx"> 
</span><del>-  var scriptTypes = [], scriptTypesConf = parserConfig &amp;&amp; parserConfig.scriptTypes;
-  scriptTypes.push({matches: /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i,
-                    mode: CodeMirror.getMode(config, &quot;javascript&quot;)});
-  if (scriptTypesConf) for (var i = 0; i &lt; scriptTypesConf.length; ++i) {
-    var conf = scriptTypesConf[i];
-    scriptTypes.push({matches: conf.matches, mode: conf.mode &amp;&amp; CodeMirror.getMode(config, conf.mode)});
-  }
-  scriptTypes.push({matches: /./,
-                    mode: CodeMirror.getMode(config, &quot;text/plain&quot;)});
-
-  function html(stream, state) {
-    var tagName = state.htmlState.tagName;
-    if (tagName) tagName = tagName.toLowerCase();
-    var style = htmlMode.token(stream, state.htmlState);
-    if (tagName == &quot;script&quot; &amp;&amp; /\btag\b/.test(style) &amp;&amp; stream.current() == &quot;&gt;&quot;) {
-      // Script block: mode to change to depends on type attribute
-      var scriptType = stream.string.slice(Math.max(0, stream.pos - 100), stream.pos).match(/\btype\s*=\s*(&quot;[^&quot;]+&quot;|'[^']+'|\S+)[^&lt;]*$/i);
-      scriptType = scriptType ? scriptType[1] : &quot;&quot;;
-      if (scriptType &amp;&amp; /[\&quot;\']/.test(scriptType.charAt(0))) scriptType = scriptType.slice(1, scriptType.length - 1);
-      for (var i = 0; i &lt; scriptTypes.length; ++i) {
-        var tp = scriptTypes[i];
-        if (typeof tp.matches == &quot;string&quot; ? scriptType == tp.matches : tp.matches.test(scriptType)) {
-          if (tp.mode) {
-            state.token = script;
-            state.localMode = tp.mode;
-            state.localState = tp.mode.startState &amp;&amp; tp.mode.startState(htmlMode.indent(state.htmlState, &quot;&quot;));
-          }
-          break;
-        }
-      }
-    } else if (tagName == &quot;style&quot; &amp;&amp; /\btag\b/.test(style) &amp;&amp; stream.current() == &quot;&gt;&quot;) {
-      state.token = css;
-      state.localMode = cssMode;
-      state.localState = cssMode.startState(htmlMode.indent(state.htmlState, &quot;&quot;));
-    }
-    return style;
-  }
</del><span class="cx">   function maybeBackup(stream, pat, style) {
</span><del>-    var cur = stream.current();
-    var close = cur.search(pat);
-    if (close &gt; -1) stream.backUp(cur.length - close);
-    else if (cur.match(/&lt;\/?$/)) {
</del><ins>+    var cur = stream.current(), close = cur.search(pat);
+    if (close &gt; -1) {
+      stream.backUp(cur.length - close);
+    } else if (cur.match(/&lt;\/?$/)) {
</ins><span class="cx">       stream.backUp(cur.length);
</span><span class="cx">       if (!stream.match(pat, false)) stream.match(cur);
</span><span class="cx">     }
</span><span class="cx">     return style;
</span><span class="cx">   }
</span><del>-  function script(stream, state) {
-    if (stream.match(/^&lt;\/\s*script\s*&gt;/i, false)) {
-      state.token = html;
-      state.localState = state.localMode = null;
-      return null;
</del><ins>+
+  var attrRegexpCache = {};
+  function getAttrRegexp(attr) {
+    var regexp = attrRegexpCache[attr];
+    if (regexp) return regexp;
+    return attrRegexpCache[attr] = new RegExp(&quot;\\s+&quot; + attr + &quot;\\s*=\\s*('|\&quot;)?([^'\&quot;]+)('|\&quot;)?\\s*&quot;);
+  }
+
+  function getAttrValue(text, attr) {
+    var match = text.match(getAttrRegexp(attr))
+    return match ? /^\s*(.*?)\s*$/.exec(match[2])[1] : &quot;&quot;
+  }
+
+  function getTagRegexp(tagName, anchored) {
+    return new RegExp((anchored ? &quot;^&quot; : &quot;&quot;) + &quot;&lt;\/\s*&quot; + tagName + &quot;\s*&gt;&quot;, &quot;i&quot;);
+  }
+
+  function addTags(from, to) {
+    for (var tag in from) {
+      var dest = to[tag] || (to[tag] = []);
+      var source = from[tag];
+      for (var i = source.length - 1; i &gt;= 0; i--)
+        dest.unshift(source[i])
</ins><span class="cx">     }
</span><del>-    return maybeBackup(stream, /&lt;\/\s*script\s*&gt;/,
-                       state.localMode.token(stream, state.localState));
</del><span class="cx">   }
</span><del>-  function css(stream, state) {
-    if (stream.match(/^&lt;\/\s*style\s*&gt;/i, false)) {
-      state.token = html;
-      state.localState = state.localMode = null;
-      return null;
</del><ins>+
+  function findMatchingMode(tagInfo, tagText) {
+    for (var i = 0; i &lt; tagInfo.length; i++) {
+      var spec = tagInfo[i];
+      if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2];
</ins><span class="cx">     }
</span><del>-    return maybeBackup(stream, /&lt;\/\s*style\s*&gt;/,
-                       cssMode.token(stream, state.localState));
</del><span class="cx">   }
</span><span class="cx"> 
</span><del>-  return {
-    startState: function() {
-      var state = htmlMode.startState();
-      return {token: html, localMode: null, localState: null, htmlState: state};
-    },
</del><ins>+  CodeMirror.defineMode(&quot;htmlmixed&quot;, function (config, parserConfig) {
+    var htmlMode = CodeMirror.getMode(config, {
+      name: &quot;xml&quot;,
+      htmlMode: true,
+      multilineTagIndentFactor: parserConfig.multilineTagIndentFactor,
+      multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag
+    });
</ins><span class="cx"> 
</span><del>-    copyState: function(state) {
-      if (state.localState)
-        var local = CodeMirror.copyState(state.localMode, state.localState);
-      return {token: state.token, localMode: state.localMode, localState: local,
-              htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
-    },
</del><ins>+    var tags = {};
+    var configTags = parserConfig &amp;&amp; parserConfig.tags, configScript = parserConfig &amp;&amp; parserConfig.scriptTypes;
+    addTags(defaultTags, tags);
+    if (configTags) addTags(configTags, tags);
+    if (configScript) for (var i = configScript.length - 1; i &gt;= 0; i--)
+      tags.script.unshift([&quot;type&quot;, configScript[i].matches, configScript[i].mode])
</ins><span class="cx"> 
</span><del>-    token: function(stream, state) {
-      return state.token(stream, state);
-    },
</del><ins>+    function html(stream, state) {
+      var style = htmlMode.token(stream, state.htmlState), tag = /\btag\b/.test(style), tagName
+      if (tag &amp;&amp; !/[&lt;&gt;\s\/]/.test(stream.current()) &amp;&amp;
+          (tagName = state.htmlState.tagName &amp;&amp; state.htmlState.tagName.toLowerCase()) &amp;&amp;
+          tags.hasOwnProperty(tagName)) {
+        state.inTag = tagName + &quot; &quot;
+      } else if (state.inTag &amp;&amp; tag &amp;&amp; /&gt;$/.test(stream.current())) {
+        var inTag = /^([\S]+) (.*)/.exec(state.inTag)
+        state.inTag = null
+        var modeSpec = stream.current() == &quot;&gt;&quot; &amp;&amp; findMatchingMode(tags[inTag[1]], inTag[2])
+        var mode = CodeMirror.getMode(config, modeSpec)
+        var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false);
+        state.token = function (stream, state) {
+          if (stream.match(endTagA, false)) {
+            state.token = html;
+            state.localState = state.localMode = null;
+            return null;
+          }
+          return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState));
+        };
+        state.localMode = mode;
+        state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, &quot;&quot;));
+      } else if (state.inTag) {
+        state.inTag += stream.current()
+        if (stream.eol()) state.inTag += &quot; &quot;
+      }
+      return style;
+    };
</ins><span class="cx"> 
</span><del>-    indent: function(state, textAfter) {
-      if (!state.localMode || /^\s*&lt;\//.test(textAfter))
-        return htmlMode.indent(state.htmlState, textAfter);
-      else if (state.localMode.indent)
-        return state.localMode.indent(state.localState, textAfter);
-      else
-        return CodeMirror.Pass;
-    },
</del><ins>+    return {
+      startState: function () {
+        var state = CodeMirror.startState(htmlMode);
+        return {token: html, inTag: null, localMode: null, localState: null, htmlState: state};
+      },
</ins><span class="cx"> 
</span><del>-    innerMode: function(state) {
-      return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};
-    }
-  };
-}, &quot;xml&quot;, &quot;javascript&quot;, &quot;css&quot;);
</del><ins>+      copyState: function (state) {
+        var local;
+        if (state.localState) {
+          local = CodeMirror.copyState(state.localMode, state.localState);
+        }
+        return {token: state.token, inTag: state.inTag,
+                localMode: state.localMode, localState: local,
+                htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
+      },
</ins><span class="cx"> 
</span><del>-CodeMirror.defineMIME(&quot;text/html&quot;, &quot;htmlmixed&quot;);
</del><ins>+      token: function (stream, state) {
+        return state.token(stream, state);
+      },
</ins><span class="cx"> 
</span><ins>+      indent: function (state, textAfter) {
+        if (!state.localMode || /^\s*&lt;\//.test(textAfter))
+          return htmlMode.indent(state.htmlState, textAfter);
+        else if (state.localMode.indent)
+          return state.localMode.indent(state.localState, textAfter);
+        else
+          return CodeMirror.Pass;
+      },
+
+      innerMode: function (state) {
+        return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};
+      }
+    };
+  }, &quot;xml&quot;, &quot;javascript&quot;, &quot;css&quot;);
+
+  CodeMirror.defineMIME(&quot;text/html&quot;, &quot;htmlmixed&quot;);
</ins><span class="cx"> });
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorjavascriptjs"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/javascript.js (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/javascript.js        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/javascript.js        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -1,8 +1,6 @@
</span><span class="cx"> // CodeMirror, copyright (c) by Marijn Haverbeke and others
</span><span class="cx"> // Distributed under an MIT license: http://codemirror.net/LICENSE
</span><span class="cx"> 
</span><del>-// TODO actually recognize syntax of TypeScript constructs
-
</del><span class="cx"> (function(mod) {
</span><span class="cx">   if (typeof exports == &quot;object&quot; &amp;&amp; typeof module == &quot;object&quot;) // CommonJS
</span><span class="cx">     mod(require(&quot;../../lib/codemirror&quot;));
</span><span class="lines">@@ -13,6 +11,11 @@
</span><span class="cx"> })(function(CodeMirror) {
</span><span class="cx"> &quot;use strict&quot;;
</span><span class="cx"> 
</span><ins>+function expressionAllowed(stream, state, backUp) {
+  return /^(?:operator|sof|keyword c|case|new|[\[{}\(,;:]|=&gt;)$/.test(state.lastType) ||
+    (state.lastType == &quot;quasi&quot; &amp;&amp; /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
+}
+
</ins><span class="cx"> CodeMirror.defineMode(&quot;javascript&quot;, function(config, parserConfig) {
</span><span class="cx">   var indentUnit = config.indentUnit;
</span><span class="cx">   var statementIndent = parserConfig.statementIndent;
</span><span class="lines">@@ -30,14 +33,15 @@
</span><span class="cx"> 
</span><span class="cx">     var jsKeywords = {
</span><span class="cx">       &quot;if&quot;: kw(&quot;if&quot;), &quot;while&quot;: A, &quot;with&quot;: A, &quot;else&quot;: B, &quot;do&quot;: B, &quot;try&quot;: B, &quot;finally&quot;: B,
</span><del>-      &quot;return&quot;: C, &quot;break&quot;: C, &quot;continue&quot;: C, &quot;new&quot;: C, &quot;delete&quot;: C, &quot;throw&quot;: C, &quot;debugger&quot;: C,
</del><ins>+      &quot;return&quot;: C, &quot;break&quot;: C, &quot;continue&quot;: C, &quot;new&quot;: kw(&quot;new&quot;), &quot;delete&quot;: C, &quot;throw&quot;: C, &quot;debugger&quot;: C,
</ins><span class="cx">       &quot;var&quot;: kw(&quot;var&quot;), &quot;const&quot;: kw(&quot;var&quot;), &quot;let&quot;: kw(&quot;var&quot;),
</span><span class="cx">       &quot;function&quot;: kw(&quot;function&quot;), &quot;catch&quot;: kw(&quot;catch&quot;),
</span><span class="cx">       &quot;for&quot;: kw(&quot;for&quot;), &quot;switch&quot;: kw(&quot;switch&quot;), &quot;case&quot;: kw(&quot;case&quot;), &quot;default&quot;: kw(&quot;default&quot;),
</span><span class="cx">       &quot;in&quot;: operator, &quot;typeof&quot;: operator, &quot;instanceof&quot;: operator,
</span><span class="cx">       &quot;true&quot;: atom, &quot;false&quot;: atom, &quot;null&quot;: atom, &quot;undefined&quot;: atom, &quot;NaN&quot;: atom, &quot;Infinity&quot;: atom,
</span><del>-      &quot;this&quot;: kw(&quot;this&quot;), &quot;module&quot;: kw(&quot;module&quot;), &quot;class&quot;: kw(&quot;class&quot;), &quot;super&quot;: kw(&quot;atom&quot;),
-      &quot;yield&quot;: C, &quot;export&quot;: kw(&quot;export&quot;), &quot;import&quot;: kw(&quot;import&quot;), &quot;extends&quot;: C
</del><ins>+      &quot;this&quot;: kw(&quot;this&quot;), &quot;class&quot;: kw(&quot;class&quot;), &quot;super&quot;: kw(&quot;atom&quot;),
+      &quot;yield&quot;: C, &quot;export&quot;: kw(&quot;export&quot;), &quot;import&quot;: kw(&quot;import&quot;), &quot;extends&quot;: C,
+      &quot;await&quot;: C, &quot;async&quot;: kw(&quot;async&quot;)
</ins><span class="cx">     };
</span><span class="cx"> 
</span><span class="cx">     // Extend the 'normal' keywords with the TypeScript language extensions
</span><span class="lines">@@ -45,18 +49,24 @@
</span><span class="cx">       var type = {type: &quot;variable&quot;, style: &quot;variable-3&quot;};
</span><span class="cx">       var tsKeywords = {
</span><span class="cx">         // object-like things
</span><del>-        &quot;interface&quot;: kw(&quot;interface&quot;),
-        &quot;extends&quot;: kw(&quot;extends&quot;),
-        &quot;constructor&quot;: kw(&quot;constructor&quot;),
</del><ins>+        &quot;interface&quot;: kw(&quot;class&quot;),
+        &quot;implements&quot;: C,
+        &quot;namespace&quot;: C,
+        &quot;module&quot;: kw(&quot;module&quot;),
+        &quot;enum&quot;: kw(&quot;module&quot;),
+        &quot;type&quot;: kw(&quot;type&quot;),
</ins><span class="cx"> 
</span><span class="cx">         // scope modifiers
</span><del>-        &quot;public&quot;: kw(&quot;public&quot;),
-        &quot;private&quot;: kw(&quot;private&quot;),
-        &quot;protected&quot;: kw(&quot;protected&quot;),
-        &quot;static&quot;: kw(&quot;static&quot;),
</del><ins>+        &quot;public&quot;: kw(&quot;modifier&quot;),
+        &quot;private&quot;: kw(&quot;modifier&quot;),
+        &quot;protected&quot;: kw(&quot;modifier&quot;),
+        &quot;abstract&quot;: kw(&quot;modifier&quot;),
</ins><span class="cx"> 
</span><ins>+        // operators
+        &quot;as&quot;: operator,
+
</ins><span class="cx">         // types
</span><del>-        &quot;string&quot;: type, &quot;number&quot;: type, &quot;bool&quot;: type, &quot;any&quot;: type
</del><ins>+        &quot;string&quot;: type, &quot;number&quot;: type, &quot;boolean&quot;: type, &quot;any&quot;: type
</ins><span class="cx">       };
</span><span class="cx"> 
</span><span class="cx">       for (var attr in tsKeywords) {
</span><span class="lines">@@ -105,6 +115,12 @@
</span><span class="cx">     } else if (ch == &quot;0&quot; &amp;&amp; stream.eat(/x/i)) {
</span><span class="cx">       stream.eatWhile(/[\da-f]/i);
</span><span class="cx">       return ret(&quot;number&quot;, &quot;number&quot;);
</span><ins>+    } else if (ch == &quot;0&quot; &amp;&amp; stream.eat(/o/i)) {
+      stream.eatWhile(/[0-7]/i);
+      return ret(&quot;number&quot;, &quot;number&quot;);
+    } else if (ch == &quot;0&quot; &amp;&amp; stream.eat(/b/i)) {
+      stream.eatWhile(/[01]/i);
+      return ret(&quot;number&quot;, &quot;number&quot;);
</ins><span class="cx">     } else if (/\d/.test(ch)) {
</span><span class="cx">       stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
</span><span class="cx">       return ret(&quot;number&quot;, &quot;number&quot;);
</span><span class="lines">@@ -115,8 +131,7 @@
</span><span class="cx">       } else if (stream.eat(&quot;/&quot;)) {
</span><span class="cx">         stream.skipToEnd();
</span><span class="cx">         return ret(&quot;comment&quot;, &quot;comment&quot;);
</span><del>-      } else if (state.lastType == &quot;operator&quot; || state.lastType == &quot;keyword c&quot; ||
-               state.lastType == &quot;sof&quot; || /^[\[{}\(,;:]$/.test(state.lastType)) {
</del><ins>+      } else if (expressionAllowed(stream, state, 1)) {
</ins><span class="cx">         readRegexp(stream);
</span><span class="cx">         stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/);
</span><span class="cx">         return ret(&quot;regexp&quot;, &quot;string-2&quot;);
</span><span class="lines">@@ -131,7 +146,8 @@
</span><span class="cx">       stream.skipToEnd();
</span><span class="cx">       return ret(&quot;error&quot;, &quot;error&quot;);
</span><span class="cx">     } else if (isOperatorChar.test(ch)) {
</span><del>-      stream.eatWhile(isOperatorChar);
</del><ins>+      if (ch != &quot;&gt;&quot; || !state.lexical || state.lexical.type != &quot;&gt;&quot;)
+        stream.eatWhile(isOperatorChar);
</ins><span class="cx">       return ret(&quot;operator&quot;, &quot;operator&quot;, stream.current());
</span><span class="cx">     } else if (wordRE.test(ch)) {
</span><span class="cx">       stream.eatWhile(wordRE);
</span><span class="lines">@@ -194,6 +210,11 @@
</span><span class="cx">     var arrow = stream.string.indexOf(&quot;=&gt;&quot;, stream.start);
</span><span class="cx">     if (arrow &lt; 0) return;
</span><span class="cx"> 
</span><ins>+    if (isTS) { // Try to skip TypeScript return type declarations after the arguments
+      var m = /:\s*(?:\w+(?:&lt;[^&gt;]*&gt;|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow))
+      if (m) arrow = m.index
+    }
+
</ins><span class="cx">     var depth = 0, sawSomething = false;
</span><span class="cx">     for (var pos = arrow - 1; pos &gt;= 0; --pos) {
</span><span class="cx">       var ch = stream.string.charAt(pos);
</span><span class="lines">@@ -200,7 +221,7 @@
</span><span class="cx">       var bracket = brackets.indexOf(ch);
</span><span class="cx">       if (bracket &gt;= 0 &amp;&amp; bracket &lt; 3) {
</span><span class="cx">         if (!depth) { ++pos; break; }
</span><del>-        if (--depth == 0) break;
</del><ins>+        if (--depth == 0) { if (ch == &quot;(&quot;) sawSomething = true; break; }
</ins><span class="cx">       } else if (bracket &gt;= 3 &amp;&amp; bracket &lt; 6) {
</span><span class="cx">         ++depth;
</span><span class="cx">       } else if (wordRE.test(ch)) {
</span><span class="lines">@@ -275,8 +296,8 @@
</span><span class="cx">       return false;
</span><span class="cx">     }
</span><span class="cx">     var state = cx.state;
</span><ins>+    cx.marked = &quot;def&quot;;
</ins><span class="cx">     if (state.context) {
</span><del>-      cx.marked = &quot;def&quot;;
</del><span class="cx">       if (inList(state.localVars)) return;
</span><span class="cx">       state.localVars = {name: varname, next: state.localVars};
</span><span class="cx">     } else {
</span><span class="lines">@@ -329,7 +350,7 @@
</span><span class="cx"> 
</span><span class="cx">   function statement(type, value) {
</span><span class="cx">     if (type == &quot;var&quot;) return cont(pushlex(&quot;vardef&quot;, value.length), vardef, expect(&quot;;&quot;), poplex);
</span><del>-    if (type == &quot;keyword a&quot;) return cont(pushlex(&quot;form&quot;), expression, statement, poplex);
</del><ins>+    if (type == &quot;keyword a&quot;) return cont(pushlex(&quot;form&quot;), parenExpr, statement, poplex);
</ins><span class="cx">     if (type == &quot;keyword b&quot;) return cont(pushlex(&quot;form&quot;), statement, poplex);
</span><span class="cx">     if (type == &quot;{&quot;) return cont(pushlex(&quot;}&quot;), block, poplex);
</span><span class="cx">     if (type == &quot;;&quot;) return cont();
</span><span class="lines">@@ -336,21 +357,23 @@
</span><span class="cx">     if (type == &quot;if&quot;) {
</span><span class="cx">       if (cx.state.lexical.info == &quot;else&quot; &amp;&amp; cx.state.cc[cx.state.cc.length - 1] == poplex)
</span><span class="cx">         cx.state.cc.pop()();
</span><del>-      return cont(pushlex(&quot;form&quot;), expression, statement, poplex, maybeelse);
</del><ins>+      return cont(pushlex(&quot;form&quot;), parenExpr, statement, poplex, maybeelse);
</ins><span class="cx">     }
</span><span class="cx">     if (type == &quot;function&quot;) return cont(functiondef);
</span><span class="cx">     if (type == &quot;for&quot;) return cont(pushlex(&quot;form&quot;), forspec, statement, poplex);
</span><span class="cx">     if (type == &quot;variable&quot;) return cont(pushlex(&quot;stat&quot;), maybelabel);
</span><del>-    if (type == &quot;switch&quot;) return cont(pushlex(&quot;form&quot;), expression, pushlex(&quot;}&quot;, &quot;switch&quot;), expect(&quot;{&quot;),
</del><ins>+    if (type == &quot;switch&quot;) return cont(pushlex(&quot;form&quot;), parenExpr, pushlex(&quot;}&quot;, &quot;switch&quot;), expect(&quot;{&quot;),
</ins><span class="cx">                                       block, poplex, poplex);
</span><span class="cx">     if (type == &quot;case&quot;) return cont(expression, expect(&quot;:&quot;));
</span><span class="cx">     if (type == &quot;default&quot;) return cont(expect(&quot;:&quot;));
</span><span class="cx">     if (type == &quot;catch&quot;) return cont(pushlex(&quot;form&quot;), pushcontext, expect(&quot;(&quot;), funarg, expect(&quot;)&quot;),
</span><span class="cx">                                      statement, poplex, popcontext);
</span><del>-    if (type == &quot;module&quot;) return cont(pushlex(&quot;form&quot;), pushcontext, afterModule, popcontext, poplex);
</del><span class="cx">     if (type == &quot;class&quot;) return cont(pushlex(&quot;form&quot;), className, poplex);
</span><del>-    if (type == &quot;export&quot;) return cont(pushlex(&quot;form&quot;), afterExport, poplex);
-    if (type == &quot;import&quot;) return cont(pushlex(&quot;form&quot;), afterImport, poplex);
</del><ins>+    if (type == &quot;export&quot;) return cont(pushlex(&quot;stat&quot;), afterExport, poplex);
+    if (type == &quot;import&quot;) return cont(pushlex(&quot;stat&quot;), afterImport, poplex);
+    if (type == &quot;module&quot;) return cont(pushlex(&quot;form&quot;), pattern, pushlex(&quot;}&quot;), expect(&quot;{&quot;), block, poplex, poplex)
+    if (type == &quot;type&quot;) return cont(typeexpr, expect(&quot;operator&quot;), typeexpr, expect(&quot;;&quot;));
+    if (type == &quot;async&quot;) return cont(statement)
</ins><span class="cx">     return pass(pushlex(&quot;stat&quot;), expression, expect(&quot;;&quot;), poplex);
</span><span class="cx">   }
</span><span class="cx">   function expression(type) {
</span><span class="lines">@@ -359,6 +382,10 @@
</span><span class="cx">   function expressionNoComma(type) {
</span><span class="cx">     return expressionInner(type, true);
</span><span class="cx">   }
</span><ins>+  function parenExpr(type) {
+    if (type != &quot;(&quot;) return pass()
+    return cont(pushlex(&quot;)&quot;), expression, expect(&quot;)&quot;), poplex)
+  }
</ins><span class="cx">   function expressionInner(type, noComma) {
</span><span class="cx">     if (cx.state.fatArrowAt == cx.stream.start) {
</span><span class="cx">       var body = noComma ? arrowBodyNoComma : arrowBody;
</span><span class="lines">@@ -369,12 +396,14 @@
</span><span class="cx">     var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
</span><span class="cx">     if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
</span><span class="cx">     if (type == &quot;function&quot;) return cont(functiondef, maybeop);
</span><del>-    if (type == &quot;keyword c&quot;) return cont(noComma ? maybeexpressionNoComma : maybeexpression);
-    if (type == &quot;(&quot;) return cont(pushlex(&quot;)&quot;), maybeexpression, comprehension, expect(&quot;)&quot;), poplex, maybeop);
</del><ins>+    if (type == &quot;class&quot;) return cont(pushlex(&quot;form&quot;), classExpression, poplex);
+    if (type == &quot;keyword c&quot; || type == &quot;async&quot;) return cont(noComma ? maybeexpressionNoComma : maybeexpression);
+    if (type == &quot;(&quot;) return cont(pushlex(&quot;)&quot;), maybeexpression, expect(&quot;)&quot;), poplex, maybeop);
</ins><span class="cx">     if (type == &quot;operator&quot; || type == &quot;spread&quot;) return cont(noComma ? expressionNoComma : expression);
</span><span class="cx">     if (type == &quot;[&quot;) return cont(pushlex(&quot;]&quot;), arrayLiteral, poplex, maybeop);
</span><span class="cx">     if (type == &quot;{&quot;) return contCommasep(objprop, &quot;}&quot;, null, maybeop);
</span><del>-    if (type == &quot;quasi&quot;) { return pass(quasi, maybeop); }
</del><ins>+    if (type == &quot;quasi&quot;) return pass(quasi, maybeop);
+    if (type == &quot;new&quot;) return cont(maybeTarget(noComma));
</ins><span class="cx">     return cont();
</span><span class="cx">   }
</span><span class="cx">   function maybeexpression(type) {
</span><span class="lines">@@ -425,6 +454,18 @@
</span><span class="cx">     findFatArrow(cx.stream, cx.state);
</span><span class="cx">     return pass(type == &quot;{&quot; ? statement : expressionNoComma);
</span><span class="cx">   }
</span><ins>+  function maybeTarget(noComma) {
+    return function(type) {
+      if (type == &quot;.&quot;) return cont(noComma ? targetNoComma : target);
+      else return pass(noComma ? expressionNoComma : expression);
+    };
+  }
+  function target(_, value) {
+    if (value == &quot;target&quot;) { cx.marked = &quot;keyword&quot;; return cont(maybeoperatorComma); }
+  }
+  function targetNoComma(_, value) {
+    if (value == &quot;target&quot;) { cx.marked = &quot;keyword&quot;; return cont(maybeoperatorNoComma); }
+  }
</ins><span class="cx">   function maybelabel(type) {
</span><span class="cx">     if (type == &quot;:&quot;) return cont(poplex, statement);
</span><span class="cx">     return pass(maybeoperatorComma, expect(&quot;;&quot;), poplex);
</span><span class="lines">@@ -433,8 +474,11 @@
</span><span class="cx">     if (type == &quot;variable&quot;) {cx.marked = &quot;property&quot;; return cont();}
</span><span class="cx">   }
</span><span class="cx">   function objprop(type, value) {
</span><del>-    if (type == &quot;variable&quot; || cx.style == &quot;keyword&quot;) {
</del><ins>+    if (type == &quot;async&quot;) {
</ins><span class="cx">       cx.marked = &quot;property&quot;;
</span><ins>+      return cont(objprop);
+    } else if (type == &quot;variable&quot; || cx.style == &quot;keyword&quot;) {
+      cx.marked = &quot;property&quot;;
</ins><span class="cx">       if (value == &quot;get&quot; || value == &quot;set&quot;) return cont(getterSetter);
</span><span class="cx">       return cont(afterprop);
</span><span class="cx">     } else if (type == &quot;number&quot; || type == &quot;string&quot;) {
</span><span class="lines">@@ -442,8 +486,14 @@
</span><span class="cx">       return cont(afterprop);
</span><span class="cx">     } else if (type == &quot;jsonld-keyword&quot;) {
</span><span class="cx">       return cont(afterprop);
</span><ins>+    } else if (type == &quot;modifier&quot;) {
+      return cont(objprop)
</ins><span class="cx">     } else if (type == &quot;[&quot;) {
</span><span class="cx">       return cont(expression, expect(&quot;]&quot;), afterprop);
</span><ins>+    } else if (type == &quot;spread&quot;) {
+      return cont(expression);
+    } else if (type == &quot;:&quot;) {
+      return pass(afterprop)
</ins><span class="cx">     }
</span><span class="cx">   }
</span><span class="cx">   function getterSetter(type) {
</span><span class="lines">@@ -456,17 +506,20 @@
</span><span class="cx">     if (type == &quot;(&quot;) return pass(functiondef);
</span><span class="cx">   }
</span><span class="cx">   function commasep(what, end) {
</span><del>-    function proceed(type) {
</del><ins>+    function proceed(type, value) {
</ins><span class="cx">       if (type == &quot;,&quot;) {
</span><span class="cx">         var lex = cx.state.lexical;
</span><span class="cx">         if (lex.info == &quot;call&quot;) lex.pos = (lex.pos || 0) + 1;
</span><del>-        return cont(what, proceed);
</del><ins>+        return cont(function(type, value) {
+          if (type == end || value == end) return pass()
+          return pass(what)
+        }, proceed);
</ins><span class="cx">       }
</span><del>-      if (type == end) return cont();
</del><ins>+      if (type == end || value == end) return cont();
</ins><span class="cx">       return cont(expect(end));
</span><span class="cx">     }
</span><del>-    return function(type) {
-      if (type == end) return cont();
</del><ins>+    return function(type, value) {
+      if (type == end || value == end) return cont();
</ins><span class="cx">       return pass(what, proceed);
</span><span class="cx">     };
</span><span class="cx">   }
</span><span class="lines">@@ -479,20 +532,45 @@
</span><span class="cx">     if (type == &quot;}&quot;) return cont();
</span><span class="cx">     return pass(statement, block);
</span><span class="cx">   }
</span><del>-  function maybetype(type) {
-    if (isTS &amp;&amp; type == &quot;:&quot;) return cont(typedef);
</del><ins>+  function maybetype(type, value) {
+    if (isTS) {
+      if (type == &quot;:&quot;) return cont(typeexpr);
+      if (value == &quot;?&quot;) return cont(maybetype);
+    }
</ins><span class="cx">   }
</span><del>-  function maybedefault(_, value) {
-    if (value == &quot;=&quot;) return cont(expressionNoComma);
</del><ins>+  function typeexpr(type) {
+    if (type == &quot;variable&quot;) {cx.marked = &quot;variable-3&quot;; return cont(afterType);}
+    if (type == &quot;string&quot; || type == &quot;number&quot; || type == &quot;atom&quot;) return cont(afterType);
+    if (type == &quot;{&quot;) return cont(commasep(typeprop, &quot;}&quot;))
+    if (type == &quot;(&quot;) return cont(commasep(typearg, &quot;)&quot;), maybeReturnType)
</ins><span class="cx">   }
</span><del>-  function typedef(type) {
-    if (type == &quot;variable&quot;) {cx.marked = &quot;variable-3&quot;; return cont();}
</del><ins>+  function maybeReturnType(type) {
+    if (type == &quot;=&gt;&quot;) return cont(typeexpr)
</ins><span class="cx">   }
</span><ins>+  function typeprop(type) {
+    if (type == &quot;variable&quot; || cx.style == &quot;keyword&quot;) {
+      cx.marked = &quot;property&quot;
+      return cont(typeprop)
+    } else if (type == &quot;:&quot;) {
+      return cont(typeexpr)
+    }
+  }
+  function typearg(type) {
+    if (type == &quot;variable&quot;) return cont(typearg)
+    else if (type == &quot;:&quot;) return cont(typeexpr)
+  }
+  function afterType(type, value) {
+    if (value == &quot;&lt;&quot;) return cont(pushlex(&quot;&gt;&quot;), commasep(typeexpr, &quot;&gt;&quot;), poplex, afterType)
+    if (value == &quot;|&quot; || type == &quot;.&quot;) return cont(typeexpr)
+    if (type == &quot;[&quot;) return cont(expect(&quot;]&quot;), afterType)
+  }
</ins><span class="cx">   function vardef() {
</span><span class="cx">     return pass(pattern, maybetype, maybeAssign, vardefCont);
</span><span class="cx">   }
</span><span class="cx">   function pattern(type, value) {
</span><ins>+    if (type == &quot;modifier&quot;) return cont(pattern)
</ins><span class="cx">     if (type == &quot;variable&quot;) { register(value); return cont(); }
</span><ins>+    if (type == &quot;spread&quot;) return cont(pattern);
</ins><span class="cx">     if (type == &quot;[&quot;) return contCommasep(pattern, &quot;]&quot;);
</span><span class="cx">     if (type == &quot;{&quot;) return contCommasep(proppattern, &quot;}&quot;);
</span><span class="cx">   }
</span><span class="lines">@@ -502,6 +580,8 @@
</span><span class="cx">       return cont(maybeAssign);
</span><span class="cx">     }
</span><span class="cx">     if (type == &quot;variable&quot;) cx.marked = &quot;property&quot;;
</span><ins>+    if (type == &quot;spread&quot;) return cont(pattern);
+    if (type == &quot;}&quot;) return pass();
</ins><span class="cx">     return cont(expect(&quot;:&quot;), pattern, maybeAssign);
</span><span class="cx">   }
</span><span class="cx">   function maybeAssign(_type, value) {
</span><span class="lines">@@ -537,28 +617,34 @@
</span><span class="cx">   function functiondef(type, value) {
</span><span class="cx">     if (value == &quot;*&quot;) {cx.marked = &quot;keyword&quot;; return cont(functiondef);}
</span><span class="cx">     if (type == &quot;variable&quot;) {register(value); return cont(functiondef);}
</span><del>-    if (type == &quot;(&quot;) return cont(pushcontext, pushlex(&quot;)&quot;), commasep(funarg, &quot;)&quot;), poplex, statement, popcontext);
</del><ins>+    if (type == &quot;(&quot;) return cont(pushcontext, pushlex(&quot;)&quot;), commasep(funarg, &quot;)&quot;), poplex, maybetype, statement, popcontext);
</ins><span class="cx">   }
</span><span class="cx">   function funarg(type) {
</span><span class="cx">     if (type == &quot;spread&quot;) return cont(funarg);
</span><del>-    return pass(pattern, maybetype, maybedefault);
</del><ins>+    return pass(pattern, maybetype, maybeAssign);
</ins><span class="cx">   }
</span><ins>+  function classExpression(type, value) {
+    // Class expressions may have an optional name.
+    if (type == &quot;variable&quot;) return className(type, value);
+    return classNameAfter(type, value);
+  }
</ins><span class="cx">   function className(type, value) {
</span><span class="cx">     if (type == &quot;variable&quot;) {register(value); return cont(classNameAfter);}
</span><span class="cx">   }
</span><span class="cx">   function classNameAfter(type, value) {
</span><del>-    if (value == &quot;extends&quot;) return cont(expression, classNameAfter);
</del><ins>+    if (value == &quot;extends&quot; || value == &quot;implements&quot;) return cont(isTS ? typeexpr : expression, classNameAfter);
</ins><span class="cx">     if (type == &quot;{&quot;) return cont(pushlex(&quot;}&quot;), classBody, poplex);
</span><span class="cx">   }
</span><span class="cx">   function classBody(type, value) {
</span><span class="cx">     if (type == &quot;variable&quot; || cx.style == &quot;keyword&quot;) {
</span><del>-      if (value == &quot;static&quot;) {
</del><ins>+      if ((value == &quot;static&quot; || value == &quot;get&quot; || value == &quot;set&quot; ||
+           (isTS &amp;&amp; (value == &quot;public&quot; || value == &quot;private&quot; || value == &quot;protected&quot; || value == &quot;readonly&quot; || value == &quot;abstract&quot;))) &amp;&amp;
+          cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false)) {
</ins><span class="cx">         cx.marked = &quot;keyword&quot;;
</span><span class="cx">         return cont(classBody);
</span><span class="cx">       }
</span><span class="cx">       cx.marked = &quot;property&quot;;
</span><del>-      if (value == &quot;get&quot; || value == &quot;set&quot;) return cont(classGetterSetter, functiondef, classBody);
-      return cont(functiondef, classBody);
</del><ins>+      return cont(isTS ? classfield : functiondef, classBody);
</ins><span class="cx">     }
</span><span class="cx">     if (value == &quot;*&quot;) {
</span><span class="cx">       cx.marked = &quot;keyword&quot;;
</span><span class="lines">@@ -567,15 +653,11 @@
</span><span class="cx">     if (type == &quot;;&quot;) return cont(classBody);
</span><span class="cx">     if (type == &quot;}&quot;) return cont();
</span><span class="cx">   }
</span><del>-  function classGetterSetter(type) {
-    if (type != &quot;variable&quot;) return pass();
-    cx.marked = &quot;property&quot;;
-    return cont();
</del><ins>+  function classfield(type, value) {
+    if (value == &quot;?&quot;) return cont(classfield)
+    if (type == &quot;:&quot;) return cont(typeexpr, maybeAssign)
+    return pass(functiondef)
</ins><span class="cx">   }
</span><del>-  function afterModule(type, value) {
-    if (type == &quot;string&quot;) return cont(statement);
-    if (type == &quot;variable&quot;) { register(value); return cont(maybeFrom); }
-  }
</del><span class="cx">   function afterExport(_type, value) {
</span><span class="cx">     if (value == &quot;*&quot;) { cx.marked = &quot;keyword&quot;; return cont(maybeFrom, expect(&quot;;&quot;)); }
</span><span class="cx">     if (value == &quot;default&quot;) { cx.marked = &quot;keyword&quot;; return cont(expression, expect(&quot;;&quot;)); }
</span><span class="lines">@@ -599,17 +681,8 @@
</span><span class="cx">   }
</span><span class="cx">   function arrayLiteral(type) {
</span><span class="cx">     if (type == &quot;]&quot;) return cont();
</span><del>-    return pass(expressionNoComma, maybeArrayComprehension);
-  }
-  function maybeArrayComprehension(type) {
-    if (type == &quot;for&quot;) return pass(comprehension, expect(&quot;]&quot;));
-    if (type == &quot;,&quot;) return cont(commasep(maybeexpressionNoComma, &quot;]&quot;));
</del><span class="cx">     return pass(commasep(expressionNoComma, &quot;]&quot;));
</span><span class="cx">   }
</span><del>-  function comprehension(type) {
-    if (type == &quot;for&quot;) return cont(forspec, comprehension);
-    if (type == &quot;if&quot;) return cont(expression, comprehension);
-  }
</del><span class="cx"> 
</span><span class="cx">   function isContinuedStatement(state, textAfter) {
</span><span class="cx">     return state.lastType == &quot;operator&quot; || state.lastType == &quot;,&quot; ||
</span><span class="lines">@@ -628,7 +701,7 @@
</span><span class="cx">         lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, &quot;block&quot;, false),
</span><span class="cx">         localVars: parserConfig.localVars,
</span><span class="cx">         context: parserConfig.localVars &amp;&amp; {vars: parserConfig.localVars},
</span><del>-        indented: 0
</del><ins>+        indented: basecolumn || 0
</ins><span class="cx">       };
</span><span class="cx">       if (parserConfig.globalVars &amp;&amp; typeof parserConfig.globalVars == &quot;object&quot;)
</span><span class="cx">         state.globalVars = parserConfig.globalVars;
</span><span class="lines">@@ -652,7 +725,7 @@
</span><span class="cx">     indent: function(state, textAfter) {
</span><span class="cx">       if (state.tokenize == tokenComment) return CodeMirror.Pass;
</span><span class="cx">       if (state.tokenize != tokenBase) return 0;
</span><del>-      var firstChar = textAfter &amp;&amp; textAfter.charAt(0), lexical = state.lexical;
</del><ins>+      var firstChar = textAfter &amp;&amp; textAfter.charAt(0), lexical = state.lexical, top
</ins><span class="cx">       // Kludge to prevent 'maybelse' from blocking lexical scope pops
</span><span class="cx">       if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i &gt;= 0; --i) {
</span><span class="cx">         var c = state.cc[i];
</span><span class="lines">@@ -659,7 +732,11 @@
</span><span class="cx">         if (c == poplex) lexical = lexical.prev;
</span><span class="cx">         else if (c != maybeelse) break;
</span><span class="cx">       }
</span><del>-      if (lexical.type == &quot;stat&quot; &amp;&amp; firstChar == &quot;}&quot;) lexical = lexical.prev;
</del><ins>+      while ((lexical.type == &quot;stat&quot; || lexical.type == &quot;form&quot;) &amp;&amp;
+             (firstChar == &quot;}&quot; || ((top = state.cc[state.cc.length - 1]) &amp;&amp;
+                                   (top == maybeoperatorComma || top == maybeoperatorNoComma) &amp;&amp;
+                                   !/^[,\.=+\-*:?[\(]/.test(textAfter))))
+        lexical = lexical.prev;
</ins><span class="cx">       if (statementIndent &amp;&amp; lexical.type == &quot;)&quot; &amp;&amp; lexical.prev.type == &quot;stat&quot;)
</span><span class="cx">         lexical = lexical.prev;
</span><span class="cx">       var type = lexical.type, closing = firstChar == type;
</span><span class="lines">@@ -684,7 +761,13 @@
</span><span class="cx"> 
</span><span class="cx">     helperType: jsonMode ? &quot;json&quot; : &quot;javascript&quot;,
</span><span class="cx">     jsonldMode: jsonldMode,
</span><del>-    jsonMode: jsonMode
</del><ins>+    jsonMode: jsonMode,
+
+    expressionAllowed: expressionAllowed,
+    skipExpression: function(state) {
+      var top = state.cc[state.cc.length - 1]
+      if (top == expression || top == expressionNoComma) state.cc.pop()
+    }
</ins><span class="cx">   };
</span><span class="cx"> });
</span><span class="cx"> 
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorlivescriptjs"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/livescript.js (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/livescript.js        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/livescript.js        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -50,7 +50,7 @@
</span><span class="cx">       startState: function(){
</span><span class="cx">         return {
</span><span class="cx">           next: 'start',
</span><del>-          lastToken: null
</del><ins>+          lastToken: {style: null, indent: 0, content: &quot;&quot;}
</ins><span class="cx">         };
</span><span class="cx">       },
</span><span class="cx">       token: function(stream, state){
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrormatchbracketsjs"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/matchbrackets.js (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/matchbrackets.js        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/matchbrackets.js        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -102,8 +102,10 @@
</span><span class="cx">   }
</span><span class="cx"> 
</span><span class="cx">   CodeMirror.defineOption(&quot;matchBrackets&quot;, false, function(cm, val, old) {
</span><del>-    if (old &amp;&amp; old != CodeMirror.Init)
</del><ins>+    if (old &amp;&amp; old != CodeMirror.Init) {
</ins><span class="cx">       cm.off(&quot;cursorActivity&quot;, doMatchBrackets);
</span><ins>+      if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
+    }
</ins><span class="cx">     if (val) {
</span><span class="cx">       cm.state.matchBrackets = typeof val == &quot;object&quot; ? val : {};
</span><span class="cx">       cm.on(&quot;cursorActivity&quot;, doMatchBrackets);
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirroroverlayjs"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/overlay.js (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/overlay.js        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/overlay.js        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -76,8 +76,13 @@
</span><span class="cx">     innerMode: function(state) { return {state: state.base, mode: base}; },
</span><span class="cx"> 
</span><span class="cx">     blankLine: function(state) {
</span><del>-      if (base.blankLine) base.blankLine(state.base);
-      if (overlay.blankLine) overlay.blankLine(state.overlay);
</del><ins>+      var baseToken, overlayToken;
+      if (base.blankLine) baseToken = base.blankLine(state.base);
+      if (overlay.blankLine) overlayToken = overlay.blankLine(state.overlay);
+
+      return overlayToken == null ?
+        baseToken :
+        (combine &amp;&amp; baseToken != null ? baseToken + &quot; &quot; + overlayToken : overlayToken);
</ins><span class="cx">     }
</span><span class="cx">   };
</span><span class="cx"> };
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorplaceholderjs"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/placeholder.js (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/placeholder.js        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/placeholder.js        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -14,10 +14,12 @@
</span><span class="cx">     if (val &amp;&amp; !prev) {
</span><span class="cx">       cm.on(&quot;blur&quot;, onBlur);
</span><span class="cx">       cm.on(&quot;change&quot;, onChange);
</span><ins>+      cm.on(&quot;swapDoc&quot;, onChange);
</ins><span class="cx">       onChange(cm);
</span><span class="cx">     } else if (!val &amp;&amp; prev) {
</span><span class="cx">       cm.off(&quot;blur&quot;, onBlur);
</span><span class="cx">       cm.off(&quot;change&quot;, onChange);
</span><ins>+      cm.off(&quot;swapDoc&quot;, onChange);
</ins><span class="cx">       clearPlaceholder(cm);
</span><span class="cx">       var wrapper = cm.getWrapperElement();
</span><span class="cx">       wrapper.className = wrapper.className.replace(&quot; CodeMirror-empty&quot;, &quot;&quot;);
</span><span class="lines">@@ -37,7 +39,9 @@
</span><span class="cx">     var elt = cm.state.placeholder = document.createElement(&quot;pre&quot;);
</span><span class="cx">     elt.style.cssText = &quot;height: 0; overflow: visible&quot;;
</span><span class="cx">     elt.className = &quot;CodeMirror-placeholder&quot;;
</span><del>-    elt.appendChild(document.createTextNode(cm.getOption(&quot;placeholder&quot;)));
</del><ins>+    var placeHolder = cm.getOption(&quot;placeholder&quot;)
+    if (typeof placeHolder == &quot;string&quot;) placeHolder = document.createTextNode(placeHolder)
+    elt.appendChild(placeHolder)
</ins><span class="cx">     cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
</span><span class="cx">   }
</span><span class="cx"> 
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorrunmodejs"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/runmode.js (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/runmode.js        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/runmode.js        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -16,7 +16,7 @@
</span><span class="cx">   var ie = /MSIE \d/.test(navigator.userAgent);
</span><span class="cx">   var ie_lt9 = ie &amp;&amp; (document.documentMode == null || document.documentMode &lt; 9);
</span><span class="cx"> 
</span><del>-  if (callback.nodeType == 1) {
</del><ins>+  if (callback.appendChild) {
</ins><span class="cx">     var tabSize = (options &amp;&amp; options.tabSize) || CodeMirror.defaults.tabSize;
</span><span class="cx">     var node = callback, col = 0;
</span><span class="cx">     node.innerHTML = &quot;&quot;;
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorsqljs"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/sql.js (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/sql.js        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/sql.js        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -32,13 +32,13 @@
</span><span class="cx">       if (result !== false) return result;
</span><span class="cx">     }
</span><span class="cx"> 
</span><del>-    if (support.hexNumber == true &amp;&amp;
</del><ins>+    if (support.hexNumber &amp;&amp;
</ins><span class="cx">       ((ch == &quot;0&quot; &amp;&amp; stream.match(/^[xX][0-9a-fA-F]+/))
</span><span class="cx">       || (ch == &quot;x&quot; || ch == &quot;X&quot;) &amp;&amp; stream.match(/^'[0-9a-fA-F]+'/))) {
</span><span class="cx">       // hex
</span><span class="cx">       // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html
</span><span class="cx">       return &quot;number&quot;;
</span><del>-    } else if (support.binaryNumber == true &amp;&amp;
</del><ins>+    } else if (support.binaryNumber &amp;&amp;
</ins><span class="cx">       (((ch == &quot;b&quot; || ch == &quot;B&quot;) &amp;&amp; stream.match(/^'[01]+'/))
</span><span class="cx">       || (ch == &quot;0&quot; &amp;&amp; stream.match(/^b[01]+/)))) {
</span><span class="cx">       // bitstring
</span><span class="lines">@@ -48,7 +48,7 @@
</span><span class="cx">       // numbers
</span><span class="cx">       // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html
</span><span class="cx">           stream.match(/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/);
</span><del>-      support.decimallessFloat == true &amp;&amp; stream.eat('.');
</del><ins>+      support.decimallessFloat &amp;&amp; stream.eat('.');
</ins><span class="cx">       return &quot;number&quot;;
</span><span class="cx">     } else if (ch == &quot;?&quot; &amp;&amp; (stream.eatSpace() || stream.eol() || stream.eat(&quot;;&quot;))) {
</span><span class="cx">       // placeholders
</span><span class="lines">@@ -58,14 +58,14 @@
</span><span class="cx">       // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
</span><span class="cx">       state.tokenize = tokenLiteral(ch);
</span><span class="cx">       return state.tokenize(stream, state);
</span><del>-    } else if ((((support.nCharCast == true &amp;&amp; (ch == &quot;n&quot; || ch == &quot;N&quot;))
-        || (support.charsetCast == true &amp;&amp; ch == &quot;_&quot; &amp;&amp; stream.match(/[a-z][a-z0-9]*/i)))
</del><ins>+    } else if ((((support.nCharCast &amp;&amp; (ch == &quot;n&quot; || ch == &quot;N&quot;))
+        || (support.charsetCast &amp;&amp; ch == &quot;_&quot; &amp;&amp; stream.match(/[a-z][a-z0-9]*/i)))
</ins><span class="cx">         &amp;&amp; (stream.peek() == &quot;'&quot; || stream.peek() == '&quot;'))) {
</span><span class="cx">       // charset casting: _utf8'str', N'str', n'str'
</span><span class="cx">       // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
</span><span class="cx">       return &quot;keyword&quot;;
</span><span class="cx">     } else if (/^[\(\),\;\[\]]/.test(ch)) {
</span><del>-      // no highlightning
</del><ins>+      // no highlighting
</ins><span class="cx">       return null;
</span><span class="cx">     } else if (support.commentSlashSlash &amp;&amp; ch == &quot;/&quot; &amp;&amp; stream.eat(&quot;/&quot;)) {
</span><span class="cx">       // 1-line comment
</span><span class="lines">@@ -84,12 +84,12 @@
</span><span class="cx">       return state.tokenize(stream, state);
</span><span class="cx">     } else if (ch == &quot;.&quot;) {
</span><span class="cx">       // .1 for 0.1
</span><del>-      if (support.zerolessFloat == true &amp;&amp; stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) {
</del><ins>+      if (support.zerolessFloat &amp;&amp; stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) {
</ins><span class="cx">         return &quot;number&quot;;
</span><span class="cx">       }
</span><span class="cx">       // .table_name (ODBC)
</span><span class="cx">       // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
</span><del>-      if (support.ODBCdotTable == true &amp;&amp; stream.match(/^[a-zA-Z_]+/)) {
</del><ins>+      if (support.ODBCdotTable &amp;&amp; stream.match(/^[a-zA-Z_]+/)) {
</ins><span class="cx">         return &quot;variable-2&quot;;
</span><span class="cx">       }
</span><span class="cx">     } else if (operatorChars.test(ch)) {
</span><span class="lines">@@ -257,7 +257,7 @@
</span><span class="cx">   }
</span><span class="cx"> 
</span><span class="cx">   // these keywords are used by all SQL dialects (however, a mode can still overwrite it)
</span><del>-  var sqlKeywords = &quot;alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where &quot;;
</del><ins>+  var sqlKeywords = &quot;alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit &quot;;
</ins><span class="cx"> 
</span><span class="cx">   // turn a space-separated list into an array
</span><span class="cx">   function set(str) {
</span><span class="lines">@@ -280,7 +280,7 @@
</span><span class="cx">   CodeMirror.defineMIME(&quot;text/x-mssql&quot;, {
</span><span class="cx">     name: &quot;sql&quot;,
</span><span class="cx">     client: set(&quot;charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee&quot;),
</span><del>-    keywords: set(sqlKeywords + &quot;begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare&quot;),
</del><ins>+    keywords: set(sqlKeywords + &quot;begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare exec&quot;),
</ins><span class="cx">     builtin: set(&quot;bigint numeric bit smallint decimal smallmoney int tinyint money float real char varchar text nchar nvarchar ntext binary varbinary image cursor timestamp hierarchyid uniqueidentifier sql_variant xml table &quot;),
</span><span class="cx">     atoms: set(&quot;false true null unknown&quot;),
</span><span class="cx">     operatorChars: /^[*+\-%&lt;&gt;!=]/,
</span><span class="lines">@@ -341,7 +341,7 @@
</span><span class="cx">     name:       &quot;sql&quot;,
</span><span class="cx">     client:     set(&quot;appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap&quot;),
</span><span class="cx">     keywords:   set(&quot;abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elseif elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaud
 it nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning returns reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work&quot;),
</span><del>-    builtin:    set(&quot;abs acos add_months ascii asin atan atan2 average bfile bfilename bigserial bit blob ceil character chartorowid chr clob concat convert cos cosh count dec decode deref dual dump dup_val_on_index empty error exp false float floor found glb greatest hextoraw initcap instr instrb int integer isopen last_day least lenght lenghtb ln lower lpad ltrim lub make_ref max min mlslabel mod months_between natural naturaln nchar nclob new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null number numeric nvarchar2 nvl others power rawtohex real reftohex round rowcount rowidtochar rowtype rpad rtrim serial sign signtype sin sinh smallint soundex sqlcode sqlerrm sqrt stddev string substr substrb sum sysdate tan tanh to_char text to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid unlogged upper user userenv varchar varchar2 va
 riance varying vsize xml&quot;),
</del><ins>+    builtin:    set(&quot;abs acos add_months ascii asin atan atan2 average bfile bfilename bigserial bit blob ceil character chartorowid chr clob concat convert cos cosh count dec decode deref dual dump dup_val_on_index empty error exp false float floor found glb greatest hextoraw initcap instr instrb int integer isopen last_day least length lengthb ln lower lpad ltrim lub make_ref max min mlslabel mod months_between natural naturaln nchar nclob new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null number numeric nvarchar2 nvl others power rawtohex real reftohex round rowcount rowidtochar rowtype rpad rtrim serial sign signtype sin sinh smallint soundex sqlcode sqlerrm sqrt stddev string substr substrb sum sysdate tan tanh to_char text to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid unlogged upper user userenv varchar varchar2 var
 iance varying vsize xml&quot;),
</ins><span class="cx">     operatorChars: /^[*+\-%&lt;&gt;!=~]/,
</span><span class="cx">     dateSQL:    set(&quot;date time timestamp&quot;),
</span><span class="cx">     support:    set(&quot;doubleQuote nCharCast zerolessFloat binaryNumber hexNumber&quot;)
</span><span class="lines">@@ -357,6 +357,28 @@
</span><span class="cx">     dateSQL: set(&quot;date timestamp&quot;),
</span><span class="cx">     support: set(&quot;ODBCdotTable doubleQuote binaryNumber hexNumber&quot;)
</span><span class="cx">   });
</span><ins>+
+  CodeMirror.defineMIME(&quot;text/x-pgsql&quot;, {
+    name: &quot;sql&quot;,
+    client: set(&quot;source&quot;),
+    // http://www.postgresql.org/docs/9.5/static/sql-keywords-appendix.html
+    keywords: set(sqlKeywords + &quot;a abort abs absent absolute access according action ada add admin after aggregate all allocate also always analyse analyze any are array array_agg array_max_cardinality asensitive assertion assignment asymmetric at atomic attribute attributes authorization avg backward base64 before begin begin_frame begin_partition bernoulli binary bit_length blob blocked bom both breadth c cache call called cardinality cascade cascaded case cast catalog catalog_name ceil ceiling chain characteristics characters character_length character_set_catalog character_set_name character_set_schema char_length check checkpoint class class_origin clob close cluster coalesce cobol collate collation collation_catalog collation_name collation_schema collect column columns column_name command_function command_function_code comment comments commit committed concurrently condition condition_number configuration conflict connect connection connection_name constraint con
 straints constraint_catalog constraint_name constraint_schema constructor contains content continue control conversion convert copy corr corresponding cost covar_pop covar_samp cross csv cube cume_dist current current_catalog current_date current_default_transform_group current_path current_role current_row current_schema current_time current_timestamp current_transform_group_for_type current_user cursor cursor_name cycle data database datalink datetime_interval_code datetime_interval_precision day db deallocate dec declare default defaults deferrable deferred defined definer degree delimiter delimiters dense_rank depth deref derived describe descriptor deterministic diagnostics dictionary disable discard disconnect dispatch dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue do document domain dynamic dynamic_function dynamic_function_code each element else empty enable encoding e
 ncrypted end end-exec end_frame end_partition enforced enum equals escape event every except exception exclude excluding exclusive exec execute exists exp explain expression extension external extract false family fetch file filter final first first_value flag float floor following for force foreign fortran forward found frame_row free freeze fs full function functions fusion g general generated get global go goto grant granted greatest grouping groups handler header hex hierarchy hold hour id identity if ignore ilike immediate immediately immutable implementation implicit import including increment indent index indexes indicator inherit inherits initially inline inner inout input insensitive instance instantiable instead integrity intersect intersection invoker isnull isolation k key key_member key_type label lag language large last last_value lateral lead leading leakproof least left length level library like_regex link listen ln load local localtime localtimestamp locatio
 n locator lock locked logged lower m map mapping match matched materialized max maxvalue max_cardinality member merge message_length message_octet_length message_text method min minute minvalue mod mode modifies module month more move multiset mumps name names namespace national natural nchar nclob nesting new next nfc nfd nfkc nfkd nil no none normalize normalized nothing notify notnull nowait nth_value ntile null nullable nullif nulls number object occurrences_regex octets octet_length of off offset oids old only open operator option options ordering ordinality others out outer output over overlaps overlay overriding owned owner p pad parameter parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partial partition pascal passing passthrough password percent percentile_cont percentile_disc percent_rank period permission placing plans pli policy portion position position_regex power prece
 des preceding prepare prepared preserve primary prior privileges procedural procedure program public quote range rank read reads reassign recheck recovery recursive ref references referencing refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex relative release rename repeatable replace replica requiring reset respect restart restore restrict result return returned_cardinality returned_length returned_octet_length returned_sqlstate returning returns revoke right role rollback rollup routine routine_catalog routine_name routine_schema row rows row_count row_number rule savepoint scale schema schema_name scope scope_catalog scope_name scope_schema scroll search second section security selective self sensitive sequence sequences serializable server server_name session session_user setof sets share show similar simple size skip snapshot some source space specific specifictype specific_name sql sqlcode sqlerror sqlexception s
 qlstate sqlwarning sqrt stable standalone start state statement static statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset substring substring_regex succeeds sum symmetric sysid system system_time system_user t tables tablesample tablespace table_name temp template temporary then ties timezone_hour timezone_minute to token top_level_count trailing transaction transactions_committed transactions_rolled_back transaction_active transform transforms translate translate_regex translation treat trigger trigger_catalog trigger_name trigger_schema trim trim_array true truncate trusted type types uescape unbounded uncommitted under unencrypted unique unknown unlink unlisten unlogged unnamed unnest until untyped upper uri usage user user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema using vacuum valid validate validator value value_of varbinary variadic var_pop var_samp verbose ve
 rsion versioning view views volatile when whenever whitespace width_bucket window within work wrapper write xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate year yes loop repeat&quot;),
+    // http://www.postgresql.org/docs/9.5/static/datatype.html
+    builtin: set(&quot;bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float8 inet integer int int4 interval json jsonb line lseg macaddr money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml&quot;),
+    atoms: set(&quot;false true null unknown&quot;),
+    operatorChars: /^[*+\-%&lt;&gt;!=&amp;|^\/#@?~]/,
+    dateSQL: set(&quot;date time timestamp&quot;),
+    support: set(&quot;ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast&quot;)
+  });
+
+  // Google's SQL-like query language, GQL
+  CodeMirror.defineMIME(&quot;text/x-gql&quot;, {
+    name: &quot;sql&quot;,
+    keywords: set(&quot;ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where&quot;),
+    atoms: set(&quot;false true&quot;),
+    builtin: set(&quot;blob datetime first key __key__ string integer double boolean null&quot;),
+    operatorChars: /^[*+\-%&lt;&gt;!=]/
+  });
</ins><span class="cx"> }());
</span><span class="cx"> 
</span><span class="cx"> });
</span></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorsublimejs"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/sublime.js (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/sublime.js        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/sublime.js        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -166,17 +166,23 @@
</span><span class="cx"> 
</span><span class="cx">   var mirror = &quot;(){}[]&quot;;
</span><span class="cx">   function selectBetweenBrackets(cm) {
</span><del>-    var pos = cm.getCursor(), opening = cm.scanForBracket(pos, -1);
-    if (!opening) return;
-    for (;;) {
-      var closing = cm.scanForBracket(pos, 1);
-      if (!closing) return;
-      if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) {
-        cm.setSelection(Pos(opening.pos.line, opening.pos.ch + 1), closing.pos, false);
-        return true;
</del><ins>+    var ranges = cm.listSelections(), newRanges = []
+    for (var i = 0; i &lt; ranges.length; i++) {
+      var range = ranges[i], pos = range.head, opening = cm.scanForBracket(pos, -1);
+      if (!opening) return false;
+      for (;;) {
+        var closing = cm.scanForBracket(pos, 1);
+        if (!closing) return false;
+        if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) {
+          newRanges.push({anchor: Pos(opening.pos.line, opening.pos.ch + 1),
+                          head: closing.pos});
+          break;
+        }
+        pos = Pos(closing.pos.line, closing.pos.ch + 1);
</ins><span class="cx">       }
</span><del>-      pos = Pos(closing.pos.line, closing.pos.ch + 1);
</del><span class="cx">     }
</span><ins>+    cm.setSelections(newRanges);
+    return true;
</ins><span class="cx">   }
</span><span class="cx"> 
</span><span class="cx">   cmds[map[&quot;Shift-&quot; + ctrl + &quot;Space&quot;] = &quot;selectScope&quot;] = function(cm) {
</span><span class="lines">@@ -294,7 +300,7 @@
</span><span class="cx">     });
</span><span class="cx">   };
</span><span class="cx"> 
</span><del>-  map[ctrl + &quot;T&quot;] = &quot;transposeChars&quot;;
</del><ins>+  if (!mac) map[ctrl + &quot;T&quot;] = &quot;transposeChars&quot;;
</ins><span class="cx"> 
</span><span class="cx">   function sortLines(cm, caseSensitive) {
</span><span class="cx">     if (cm.isReadOnly()) return CodeMirror.Pass
</span><span class="lines">@@ -570,7 +576,7 @@
</span><span class="cx"> 
</span><span class="cx">   map[&quot;Shift-&quot; + ctrl + &quot;[&quot;] = &quot;fold&quot;;
</span><span class="cx">   map[&quot;Shift-&quot; + ctrl + &quot;]&quot;] = &quot;unfold&quot;;
</span><del>-  map[cK + ctrl + &quot;0&quot;] = map[cK + ctrl + &quot;j&quot;] = &quot;unfoldAll&quot;;
</del><ins>+  map[cK + ctrl + &quot;0&quot;] = map[cK + ctrl + &quot;J&quot;] = &quot;unfoldAll&quot;;
</ins><span class="cx"> 
</span><span class="cx">   map[ctrl + &quot;I&quot;] = &quot;findIncremental&quot;;
</span><span class="cx">   map[&quot;Shift-&quot; + ctrl + &quot;I&quot;] = &quot;findIncrementalReverse&quot;;
</span><span class="lines">@@ -579,4 +585,4 @@
</span><span class="cx">   map[&quot;Shift-F3&quot;] = &quot;findPrev&quot;;
</span><span class="cx"> 
</span><span class="cx">   CodeMirror.normalizeKeyMap(map);
</span><del>-});
</del><span class="cx">\ No newline at end of file
</span><ins>+});
</ins></span></pre></div>
<a id="branchessafari603branchSourceWebInspectorUIUserInterfaceExternalCodeMirrorxmljs"></a>
<div class="modfile"><h4>Modified: branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/xml.js (210336 => 210337)</h4>
<pre class="diff"><span>
<span class="info">--- branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/xml.js        2017-01-05 17:08:40 UTC (rev 210336)
+++ branches/safari-603-branch/Source/WebInspectorUI/UserInterface/External/CodeMirror/xml.js        2017-01-05 17:08:47 UTC (rev 210337)
</span><span class="lines">@@ -11,55 +11,57 @@
</span><span class="cx"> })(function(CodeMirror) {
</span><span class="cx"> &quot;use strict&quot;;
</span><span class="cx"> 
</span><del>-CodeMirror.defineMode(&quot;xml&quot;, function(config, parserConfig) {
-  var indentUnit = config.indentUnit;
-  var multilineTagIndentFactor = parserConfig.multilineTagIndentFactor || 1;
-  var multilineTagIndentPastTag = parserConfig.multilineTagIndentPastTag;
-  if (multilineTagIndentPastTag == null) multilineTagIndentPastTag = true;
</del><ins>+var htmlConfig = {
+  autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
+                    'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
+                    'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
+                    'track': true, 'wbr': true, 'menuitem': true},
+  implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
+                     'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
+                     'th': true, 'tr': true},
+  contextGrabbers: {
+    'dd': {'dd': true, 'dt': true},
+    'dt': {'dd': true, 'dt': true},
+    'li': {'li': true},
+    'option': {'option': true, 'optgroup': true},
+    'optgroup': {'optgroup': true},
+    'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
+          'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
+          'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
+          'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
+          'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
+    'rp': {'rp': true, 'rt': true},
+    'rt': {'rp': true, 'rt': true},
+    'tbody': {'tbody': true, 'tfoot': true},
+    'td': {'td': true, 'th': true},
+    'tfoot': {'tbody': true},
+    'th': {'td': true, 'th': true},
+    'thead': {'tbody': true, 'tfoot': true},
+    'tr': {'tr': true}
+  },
+  doNotIndent: {&quot;pre&quot;: true},
+  allowUnquoted: true,
+  allowMissing: true,
+  caseFold: true
+}
</ins><span class="cx"> 
</span><del>-  var Kludges = parserConfig.htmlMode ? {
-    autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
-                      'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
-                      'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
-                      'track': true, 'wbr': true, 'menuitem': true},
-    implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
-                       'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
-                       'th': true, 'tr': true},
-    contextGrabbers: {
-      'dd': {'dd': true, 'dt': true},
-      'dt': {'dd': true, 'dt': true},
-      'li': {'li': true},
-      'option': {'option': true, 'optgroup': true},
-      'optgroup': {'optgroup': true},
-      'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
-            'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
-            'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
-            'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
-            'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
-      'rp': {'rp': true, 'rt': true},
-      'rt': {'rp': true, 'rt': true},
-      'tbody': {'tbody': true, 'tfoot': true},
-      'td': {'td': true, 'th': true},
-      'tfoot': {'tbody': true},
-      'th': {'td': true, 'th': true},
-      'thead': {'tbody': true, 'tfoot': true},
-      'tr': {'tr': true}
-    },
-    doNotIndent: {&quot;pre&quot;: true},
-    allowUnquoted: true,
-    allowMissing: true,
-    caseFold: true
-  } : {
-    autoSelfClosers: {},
-    implicitlyClosed: {},
-    contextGrabbers: {},
-    doNotIndent: {},
-    allowUnquoted: false,
-    allowMissing: false,
-    caseFold: false
-  };
-  var alignCDATA = parserConfig.alignCDATA;
</del><ins>+var xmlConfig = {
+  autoSelfClosers: {},
+  implicitlyClosed: {},
+  contextGrabbers: {},
+  doNotIndent: {},
+  allowUnquoted: false,
+  allowMissing: false,
+  caseFold: false
+}
</ins><span class="cx"> 
</span><ins>+CodeMirror.defineMode(&quot;xml&quot;, function(editorConf, config_) {
+  var indentUnit = editorConf.indentUnit
+  var config = {}
+  var defaults = config_.htmlMode ? htmlConfig : xmlConfig
+  for (var prop in defaults) config[prop] = defaults[prop]
+  for (var prop in config_) config[prop] = config_[prop]
+
</ins><span class="cx">   // Return variables for tokenizers
</span><span class="cx">   var type, setStyle;
</span><span class="cx"> 
</span><span class="lines">@@ -188,7 +190,7 @@
</span><span class="cx">     this.tagName = tagName;
</span><span class="cx">     this.indent = state.indented;
</span><span class="cx">     this.startOfLine = startOfLine;
</span><del>-    if (Kludges.doNotIndent.hasOwnProperty(tagName) || (state.context &amp;&amp; state.context.noIndent))
</del><ins>+    if (config.doNotIndent.hasOwnProperty(tagName) || (state.context &amp;&amp; state.context.noIndent))
</ins><span class="cx">       this.noIndent = true;
</span><span class="cx">   }
</span><span class="cx">   function popContext(state) {
</span><span class="lines">@@ -201,8 +203,8 @@
</span><span class="cx">         return;
</span><span class="cx">       }
</span><span class="cx">       parentTagName = state.context.tagName;
</span><del>-      if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) ||
-          !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
</del><ins>+      if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
+          !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
</ins><span class="cx">         return;
</span><span class="cx">       }
</span><span class="cx">       popContext(state);
</span><span class="lines">@@ -233,9 +235,9 @@
</span><span class="cx">     if (type == &quot;word&quot;) {
</span><span class="cx">       var tagName = stream.current();
</span><span class="cx">       if (state.context &amp;&amp; state.context.tagName != tagName &amp;&amp;
</span><del>-          Kludges.implicitlyClosed.hasOwnProperty(state.context.tagName))
</del><ins>+          config.implicitlyClosed.hasOwnProperty(state.context.tagName))
</ins><span class="cx">         popContext(state);
</span><del>-      if (state.context &amp;&amp; state.context.tagName == tagName) {
</del><ins>+      if ((state.context &amp;&amp; state.context.tagName == tagName) || config.matchClosing === false) {
</ins><span class="cx">         setStyle = &quot;tag&quot;;
</span><span class="cx">         return closeState;
</span><span class="cx">       } else {
</span><span class="lines">@@ -269,7 +271,7 @@
</span><span class="cx">       var tagName = state.tagName, tagStart = state.tagStart;
</span><span class="cx">       state.tagName = state.tagStart = null;
</span><span class="cx">       if (type == &quot;selfcloseTag&quot; ||
</span><del>-          Kludges.autoSelfClosers.hasOwnProperty(tagName)) {
</del><ins>+          config.autoSelfClosers.hasOwnProperty(tagName)) {
</ins><span class="cx">         maybePopContext(state, tagName);
</span><span class="cx">       } else {
</span><span class="cx">         maybePopContext(state, tagName);
</span><span class="lines">@@ -282,12 +284,12 @@
</span><span class="cx">   }
</span><span class="cx">   function attrEqState(type, stream, state) {
</span><span class="cx">     if (type == &quot;equals&quot;) return attrValueState;
</span><del>-    if (!Kludges.allowMissing) setStyle = &quot;error&quot;;
</del><ins>+    if (!config.allowMissing) setStyle = &quot;error&quot;;
</ins><span class="cx">     return attrState(type, stream, state);
</span><span class="cx">   }
</span><span class="cx">   function attrValueState(type, stream, state) {
</span><span class="cx">     if (type == &quot;string&quot;) return attrContinuedState;
</span><del>-    if (type == &quot;word&quot; &amp;&amp; Kludges.allowUnquoted) {setStyle = &quot;string&quot;; return attrState;}
</del><ins>+    if (type == &quot;word&quot; &amp;&amp; config.allowUnquoted) {setStyle = &quot;string&quot;; return attrState;}
</ins><span class="cx">     setStyle = &quot;error&quot;;
</span><span class="cx">     return attrState(type, stream, state);
</span><span class="cx">   }
</span><span class="lines">@@ -297,12 +299,14 @@
</span><span class="cx">   }
</span><span class="cx"> 
</span><span class="cx">   return {
</span><del>-    startState: function() {
-      return {tokenize: inText,
-              state: baseState,
-              indented: 0,
-              tagName: null, tagStart: null,
-              context: null};
</del><ins>+    startState: function(baseIndent) {
+      var state = {tokenize: inText,
+                   state: baseState,
+                   indented: baseIndent || 0,
+                   tagName: null, tagStart: null,
+                   context: null}
+      if (baseIndent != null) state.baseIndent = baseIndent
+      return state
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     token: function(stream, state) {
</span><span class="lines">@@ -335,12 +339,12 @@
</span><span class="cx">         return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
</span><span class="cx">       // Indent the starts of attribute names.
</span><span class="cx">       if (state.tagName) {
</span><del>-        if (multilineTagIndentPastTag)
</del><ins>+        if (config.multilineTagIndentPastTag !== false)
</ins><span class="cx">           return state.tagStart + state.tagName.length + 2;
</span><span class="cx">         else
</span><del>-          return state.tagStart + indentUnit * multilineTagIndentFactor;
</del><ins>+          return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
</ins><span class="cx">       }
</span><del>-      if (alignCDATA &amp;&amp; /&lt;!\[CDATA\[/.test(textAfter)) return 0;
</del><ins>+      if (config.alignCDATA &amp;&amp; /&lt;!\[CDATA\[/.test(textAfter)) return 0;
</ins><span class="cx">       var tagAfter = textAfter &amp;&amp; /^&lt;(\/)?([\w_:\.-]*)/.exec(textAfter);
</span><span class="cx">       if (tagAfter &amp;&amp; tagAfter[1]) { // Closing tag spotted
</span><span class="cx">         while (context) {
</span><span class="lines">@@ -347,7 +351,7 @@
</span><span class="cx">           if (context.tagName == tagAfter[2]) {
</span><span class="cx">             context = context.prev;
</span><span class="cx">             break;
</span><del>-          } else if (Kludges.implicitlyClosed.hasOwnProperty(context.tagName)) {
</del><ins>+          } else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {
</ins><span class="cx">             context = context.prev;
</span><span class="cx">           } else {
</span><span class="cx">             break;
</span><span class="lines">@@ -355,7 +359,7 @@
</span><span class="cx">         }
</span><span class="cx">       } else if (tagAfter) { // Opening tag spotted
</span><span class="cx">         while (context) {
</span><del>-          var grabbers = Kludges.contextGrabbers[context.tagName];
</del><ins>+          var grabbers = config.contextGrabbers[context.tagName];
</ins><span class="cx">           if (grabbers &amp;&amp; grabbers.hasOwnProperty(tagAfter[2]))
</span><span class="cx">             context = context.prev;
</span><span class="cx">           else
</span><span class="lines">@@ -362,10 +366,10 @@
</span><span class="cx">             break;
</span><span class="cx">         }
</span><span class="cx">       }
</span><del>-      while (context &amp;&amp; !context.startOfLine)
</del><ins>+      while (context &amp;&amp; context.prev &amp;&amp; !context.startOfLine)
</ins><span class="cx">         context = context.prev;
</span><span class="cx">       if (context) return context.indent + indentUnit;
</span><del>-      else return 0;
</del><ins>+      else return state.baseIndent || 0;
</ins><span class="cx">     },
</span><span class="cx"> 
</span><span class="cx">     electricInput: /&lt;\/[\s\w:]+&gt;$/,
</span><span class="lines">@@ -372,8 +376,13 @@
</span><span class="cx">     blockCommentStart: &quot;&lt;!--&quot;,
</span><span class="cx">     blockCommentEnd: &quot;--&gt;&quot;,
</span><span class="cx"> 
</span><del>-    configuration: parserConfig.htmlMode ? &quot;html&quot; : &quot;xml&quot;,
-    helperType: parserConfig.htmlMode ? &quot;html&quot; : &quot;xml&quot;
</del><ins>+    configuration: config.htmlMode ? &quot;html&quot; : &quot;xml&quot;,
+    helperType: config.htmlMode ? &quot;html&quot; : &quot;xml&quot;,
+
+    skipAttribute: function(state) {
+      if (state.state == attrValueState)
+        state.state = attrState
+    }
</ins><span class="cx">   };
</span><span class="cx"> });
</span><span class="cx"> 
</span></span></pre>
</div>
</div>

</body>
</html>