vendor: 8,795 bytes, lines 1-253
1// CodeMirror, copyright (c) by Marijn Haverbeke and others 2// Distributed under an MIT license: http://codemirror.net/LICENSE 3 4// This is CodeMirror (http://codemirror.net), a code editor 5// implemented in JavaScript on top of the browser's DOM. 6// 7// You can find some technical background for some of the code below 8// at http://marijnhaverbeke.nl/blog/#cm-internals . 9 10(function (global, factory) { 11 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : 12 typeof define === 'function' && define.amd ? define(factory) : 13 (global.CodeMirror = factory()); 14}(this, (function () { 'use strict'; 15 16// Kludges for bugs and behavior differences that can't be feature 17// detected are enabled based on userAgent etc sniffing. 18var userAgent = navigator.userAgent; 19var platform = navigator.platform; 20 21var gecko = /gecko\/\d/i.test(userAgent); 22var ie_upto10 = /MSIE \d/.test(userAgent); 23var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); 24var edge = /Edge\/(\d+)/.exec(userAgent); 25var ie = ie_upto10 || ie_11up || edge; 26var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]); 27var webkit = !edge && /WebKit\//.test(userAgent); 28var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); 29var chrome = !edge && /Chrome\//.test(userAgent); 30var presto = /Opera\//.test(userAgent); 31var safari = /Apple Computer/.test(navigator.vendor); 32var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); 33var phantom = /PhantomJS/.test(userAgent); 34 35var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent); 36var android = /Android/.test(userAgent); 37// This is woefully incomplete. Suggestions for alternative methods welcome. 38var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); 39var mac = ios || /Mac/.test(platform); 40var chromeOS = /\bCrOS\b/.test(userAgent); 41var windows = /win/i.test(platform); 42 43var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); 44if (presto_version) { presto_version = Number(presto_version[1]); } 45if (presto_version && presto_version >= 15) { presto = false; webkit = true; } 46// Some browsers use the wrong event properties to signal cmd/ctrl on OS X 47var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); 48var captureRightClick = gecko || (ie && ie_version >= 9); 49 50function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } 51 52var rmClass = function(node, cls) { 53 var current = node.className; 54 var match = classTest(cls).exec(current); 55 if (match) { 56 var after = current.slice(match.index + match[0].length); 57 node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); 58 } 59}; 60 61function removeChildren(e) { 62 for (var count = e.childNodes.length; count > 0; --count) 63 { e.removeChild(e.firstChild); } 64 return e 65} 66 67function removeChildrenAndAdd(parent, e) { 68 return removeChildren(parent).appendChild(e) 69} 70 71function elt(tag, content, className, style) { 72 var e = document.createElement(tag); 73 if (className) { e.className = className; } 74 if (style) { e.style.cssText = style; } 75 if (typeof content == "string") { e.appendChild(document.createTextNode(content)); } 76 else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } } 77 return e 78} 79// wrapper for elt, which removes the elt from the accessibility tree 80function eltP(tag, content, className, style) { 81 var e = elt(tag, content, className, style); 82 e.setAttribute("role", "presentation"); 83 return e 84} 85 86var range; 87if (document.createRange) { range = function(node, start, end, endNode) { 88 var r = document.createRange(); 89 r.setEnd(endNode || node, end); 90 r.setStart(node, start); 91 return r 92}; } 93else { range = function(node, start, end) { 94 var r = document.body.createTextRange(); 95 try { r.moveToElementText(node.parentNode); } 96 catch(e) { return r } 97 r.collapse(true); 98 r.moveEnd("character", end); 99 r.moveStart("character", start); 100 return r 101}; } 102 103function contains(parent, child) { 104 if (child.nodeType == 3) // Android browser always returns false when child is a textnode 105 { child = child.parentNode; } 106 if (parent.contains) 107 { return parent.contains(child) } 108 do { 109 if (child.nodeType == 11) { child = child.host; } 110 if (child == parent) { return true } 111 } while (child = child.parentNode) 112} 113 114function activeElt() { 115 // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. 116 // IE < 10 will throw when accessed while the page is loading or in an iframe. 117 // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. 118 var activeElement; 119 try { 120 activeElement = document.activeElement; 121 } catch(e) { 122 activeElement = document.body || null; 123 } 124 while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) 125 { activeElement = activeElement.shadowRoot.activeElement; } 126 return activeElement 127} 128 129function addClass(node, cls) { 130 var current = node.className; 131 if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; } 132} 133function joinClasses(a, b) { 134 var as = a.split(" "); 135 for (var i = 0; i < as.length; i++) 136 { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } } 137 return b 138} 139 140var selectInput = function(node) { node.select(); }; 141if (ios) // Mobile Safari apparently has a bug where select() is broken. 142 { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; } 143else if (ie) // Suppress mysterious IE10 errors 144 { selectInput = function(node) { try { node.select(); } catch(_e) {} }; } 145 146function bind(f) { 147 var args = Array.prototype.slice.call(arguments, 1); 148 return function(){return f.apply(null, args)} 149} 150 151function copyObj(obj, target, overwrite) { 152 if (!target) { target = {}; } 153 for (var prop in obj) 154 { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) 155 { target[prop] = obj[prop]; } } 156 return target 157} 158 159// Counts the column offset in a string, taking tabs into account. 160// Used mostly to find indentation. 161function countColumn(string, end, tabSize, startIndex, startValue) { 162 if (end == null) { 163 end = string.search(/[^\s\u00a0]/); 164 if (end == -1) { end = string.length; } 165 } 166 for (var i = startIndex || 0, n = startValue || 0;;) { 167 var nextTab = string.indexOf("\t", i); 168 if (nextTab < 0 || nextTab >= end) 169 { return n + (end - i) } 170 n += nextTab - i; 171 n += tabSize - (n % tabSize); 172 i = nextTab + 1; 173 } 174} 175 176var Delayed = function() {this.id = null;}; 177Delayed.prototype.set = function (ms, f) { 178 clearTimeout(this.id); 179 this.id = setTimeout(f, ms); 180}; 181 182function indexOf(array, elt) { 183 for (var i = 0; i < array.length; ++i) 184 { if (array[i] == elt) { return i } } 185 return -1 186} 187 188// Number of pixels added to scroller and sizer to hide scrollbar 189var scrollerGap = 30; 190 191// Returned or thrown by various protocols to signal 'I'm not 192// handling this'. 193var Pass = {toString: function(){return "CodeMirror.Pass"}}; 194 195// Reused option objects for setSelection & friends 196var sel_dontScroll = {scroll: false}; 197var sel_mouse = {origin: "*mouse"}; 198var sel_move = {origin: "+move"}; 199 200// The inverse of countColumn -- find the offset that corresponds to 201// a particular column. 202function findColumn(string, goal, tabSize) { 203 for (var pos = 0, col = 0;;) { 204 var nextTab = string.indexOf("\t", pos); 205 if (nextTab == -1) { nextTab = string.length; } 206 var skipped = nextTab - pos; 207 if (nextTab == string.length || col + skipped >= goal) 208 { return pos + Math.min(skipped, goal - col) } 209 col += nextTab - pos; 210 col += tabSize - (col % tabSize); 211 pos = nextTab + 1; 212 if (col >= goal) { return pos } 213 } 214} 215 216var spaceStrs = [""]; 217function spaceStr(n) { 218 while (spaceStrs.length <= n) 219 { spaceStrs.push(lst(spaceStrs) + " "); } 220 return spaceStrs[n] 221} 222 223function lst(arr) { return arr[arr.length-1] } 224 225function map(array, f) { 226 var out = []; 227 for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); } 228 return out 229} 230 231function insertSorted(array, value, score) { 232 var pos = 0, priority = score(value); 233 while (pos < array.length && score(array[pos]) <= priority) { pos++; } 234 array.splice(pos, 0, value); 235} 236 237function nothing() {} 238 239function createObj(base, props) { 240 var inst; 241 if (Object.create) { 242 inst = Object.create(base); 243 } else { 244 nothing.prototype = base; 245 inst = new nothing(); 246 } 247 if (props) { copyObj(props, inst); } 248 return inst 249} 250 251var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; 252function isWordCharBasic(ch) { 253 return /\w/.test(ch) || ch > "\x80" &&
254 (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)) 255} 256function isWordChar(ch, helper) { 257 if (!helper) { return isWordCharBasic(ch) } 258 if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true } 259 return helper.test(ch) 260} 261 262function isEmpty(obj) { 263 for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } } 264 return true 265} 266 267// Extending unicode characters. A series of a non-extending char + 268// any number of extending chars is treated as a single unit as far 269// as editing and measuring is concerned. This is not fully correct, 270// since some scripts/fonts/browsers also treat other configurations 271// of code points as a group. 272var 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]/; 273function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) } 274 275// Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range. 276function skipExtendingChars(str, pos, dir) { 277 while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; } 278 return pos 279} 280 281// Returns the value from the range [`from`; `to`] that satisfies 282// `pred` and is closest to `from`. Assumes that at least `to` satisfies `pred`. 283function findFirst(pred, from, to) { 284 for (;;) { 285 if (Math.abs(from - to) <= 1) { return pred(from) ? from : to } 286 var mid = Math.floor((from + to) / 2); 287 if (pred(mid)) { to = mid; } 288 else { from = mid; } 289 } 290} 291 292// The display handles the DOM integration, both for input reading 293// and content drawing. It holds references to DOM nodes and 294// display-related state. 295 296function Display(place, doc, input) { 297 var d = this; 298 this.input = input; 299 300 // Covers bottom-right square when both scrollbars are present. 301 d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); 302 d.scrollbarFiller.setAttribute("cm-not-content", "true"); 303 // Covers bottom of gutter when coverGutterNextToScrollbar is on 304 // and h scrollbar is present. 305 d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); 306 d.gutterFiller.setAttribute("cm-not-content", "true"); 307 // Will contain the actual code, positioned to cover the viewport. 308 d.lineDiv = eltP("div", null, "CodeMirror-code"); 309 // Elements are added to these to represent selection and curs
vendor: 98,437 bytes, lines 309-2844
309ors. 310 d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); 311 d.cursorDiv = elt("div", null, "CodeMirror-cursors"); 312 // A visibility: hidden element used to find the size of things. 313 d.measure = elt("div", null, "CodeMirror-measure"); 314 // When lines outside of the viewport are measured, they are drawn in this. 315 d.lineMeasure = elt("div", null, "CodeMirror-measure"); 316 // Wraps everything that needs to exist inside the vertically-padded coordinate system 317 d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], 318 null, "position: relative; outline: none"); 319 var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); 320 // Moved around its parent to cover visible view. 321 d.mover = elt("div", [lines], null, "position: relative"); 322 // Set to the height of the document, allowing scrolling. 323 d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); 324 d.sizerWidth = null; 325 // Behavior of elts with overflow: auto and padding is 326 // inconsistent across browsers. This is used to ensure the 327 // scrollable area is big enough. 328 d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); 329 // Will contain the gutters, if any. 330 d.gutters = elt("div", null, "CodeMirror-gutters"); 331 d.lineGutter = null; 332 // Actual scrollable element. 333 d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); 334 d.scroller.setAttribute("tabIndex", "-1"); 335 // The element in which the editor lives. 336 d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); 337 338 // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) 339 if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } 340 if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; } 341 342 if (place) { 343 if (place.appendChild) { place.appendChild(d.wrapper); } 344 else { place(d.wrapper); } 345 } 346 347 // Current rendered range (may be bigger than the view window). 348 d.viewFrom = d.viewTo = doc.first; 349 d.reportedViewFrom = d.reportedViewTo = doc.first; 350 // Information about the rendered lines. 351 d.view = []; 352 d.renderedView = null; 353 // Holds info about a single rendered line when it was rendered 354 // for measurement, while not in view. 355 d.externalMeasured = null; 356 // Empty space (in pixels) above the view 357 d.viewOffset = 0; 358 d.lastWrapHeight = d.lastWrapWidth = 0; 359 d.updateLineNumbers = null; 360 361 d.nativeBarWidth = d.barHeight = d.barWidth = 0; 362 d.scrollbarsClipped = false; 363 364 // Used to only resize the line number gutter when necessary (when 365 // the amount of lines crosses a boundary that makes its width change) 366 d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; 367 // Set to true when a non-horizontal-scrolling line widget is 368 // added. As an optimization, line widget aligning is skipped when 369 // this is false. 370 d.alignWidgets = false; 371 372 d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; 373 374 // Tracks the maximum line length so that the horizontal scrollbar 375 // can be kept static when scrolling. 376 d.maxLine = null; 377 d.maxLineLength = 0; 378 d.maxLineChanged = false; 379 380 // Used for measuring wheel scrolling granularity 381 d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; 382 383 // True when shift is held down. 384 d.shift = false; 385 386 // Used to track whether anything happened since the context menu 387 // was opened. 388 d.selForContextMenu = null; 389 390 d.activeTouch = null; 391 392 input.init(d); 393} 394 395// Find the line object corresponding to the given line number. 396function getLine(doc, n) { 397 n -= doc.first; 398 if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") } 399 var chunk = doc; 400 while (!chunk.lines) { 401 for (var i = 0;; ++i) { 402 var child = chunk.children[i], sz = child.chunkSize(); 403 if (n < sz) { chunk = child; break } 404 n -= sz; 405 } 406 } 407 return chunk.lines[n] 408} 409 410// Get the part of a document between two positions, as an array of 411// strings. 412function getBetween(doc, start, end) { 413 var out = [], n = start.line; 414 doc.iter(start.line, end.line + 1, function (line) { 415 var text = line.text; 416 if (n == end.line) { text = text.slice(0, end.ch); } 417 if (n == start.line) { text = text.slice(start.ch); } 418 out.push(text); 419 ++n; 420 }); 421 return out 422} 423// Get the lines between from and to, as array of strings. 424function getLines(doc, from, to) { 425 var out = []; 426 doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value 427 return out 428} 429 430// Update the height of a line, propagating the height change 431// upwards to parent nodes. 432function updateLineHeight(line, height) { 433 var diff = height - line.height; 434 if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } } 435} 436 437// Given a line object, find its line number by walking up through 438// its parent links. 439function lineNo(line) { 440 if (line.parent == null) { return null } 441 var cur = line.parent, no = indexOf(cur.lines, line); 442 for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { 443 for (var i = 0;; ++i) { 444 if (chunk.children[i] == cur) { break } 445 no += chunk.children[i].chunkSize(); 446 } 447 } 448 return no + cur.first 449} 450 451// Find the line at the given vertical position, using the height 452// information in the document tree. 453function lineAtHeight(chunk, h) { 454 var n = chunk.first; 455 outer: do { 456 for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) { 457 var child = chunk.children[i$1], ch = child.height; 458 if (h < ch) { chunk = child; continue outer } 459 h -= ch; 460 n += child.chunkSize(); 461 } 462 return n 463 } while (!chunk.lines) 464 var i = 0; 465 for (; i < chunk.lines.length; ++i) { 466 var line = chunk.lines[i], lh = line.height; 467 if (h < lh) { break } 468 h -= lh; 469 } 470 return n + i 471} 472 473function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size} 474 475function lineNumberFor(options, i) { 476 return String(options.lineNumberFormatter(i + options.firstLineNumber)) 477} 478 479// A Pos instance represents a position within the text. 480function Pos(line, ch, sticky) { 481 if ( sticky === void 0 ) sticky = null; 482 483 if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) } 484 this.line = line; 485 this.ch = ch; 486 this.sticky = sticky; 487} 488 489// Compare two positions, return 0 if they are the same, a negative 490// number when a is less, and a positive number otherwise. 491function cmp(a, b) { return a.line - b.line || a.ch - b.ch } 492 493function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 } 494 495function copyPos(x) {return Pos(x.line, x.ch)} 496function maxPos(a, b) { return cmp(a, b) < 0 ? b : a } 497function minPos(a, b) { return cmp(a, b) < 0 ? a : b } 498 499// Most of the external API clips given positions to make sure they 500// actually exist within the document. 501function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))} 502function clipPos(doc, pos) { 503 if (pos.line < doc.first) { return Pos(doc.first, 0) } 504 var last = doc.first + doc.size - 1; 505 if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) } 506 return clipToLen(pos, getLine(doc, pos.line).text.length) 507} 508function clipToLen(pos, linelen) { 509 var ch = pos.ch; 510 if (ch == null || ch > linelen) { return Pos(pos.line, linelen) } 511 else if (ch < 0) { return Pos(pos.line, 0) } 512 else { return pos } 513} 514function clipPosArray(doc, array) { 515 var out = []; 516 for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); } 517 return out 518} 519 520// Optimize some code when these features are not used. 521var sawReadOnlySpans = false; 522var sawCollapsedSpans = false; 523 524function seeReadOnlySpans() { 525 sawReadOnlySpans = true; 526} 527 528function seeCollapsedSpans() { 529 sawCollapsedSpans = true; 530} 531 532// TEXTMARKER SPANS 533 534function MarkedSpan(marker, from, to) { 535 this.marker = marker; 536 this.from = from; this.to = to; 537} 538 539// Search an array of spans for a span matching the given marker. 540function getMarkedSpanFor(spans, marker) { 541 if (spans) { for (var i = 0; i < spans.length; ++i) { 542 var span = spans[i]; 543 if (span.marker == marker) { return span } 544 } } 545} 546// Remove a span from an array, returning undefined if no spans are 547// left (we don't store arrays for lines without spans). 548function removeMarkedSpan(spans, span) { 549 var r; 550 for (var i = 0; i < spans.length; ++i) 551 { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } } 552 return r 553} 554// Add a span to a line. 555function addMarkedSpan(line, span) { 556 line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; 557 span.marker.attachLine(line); 558} 559 560// Used for the algorithm that adjusts markers for a change in the 561// document. These functions cut an array of spans at a given 562// character position, returning an array of remaining chunks (or 563// undefined if nothing remains). 564function markedSpansBefore(old, startCh, isInsert) { 565 var nw; 566 if (old) { for (var i = 0; i < old.length; ++i) { 567 var span = old[i], marker = span.marker; 568 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); 569 if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { 570 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); 571 } 572 } } 573 return nw 574} 575function markedSpansAfter(old, endCh, isInsert) { 576 var nw; 577 if (old) { for (var i = 0; i < old.length; ++i) { 578 var span = old[i], marker = span.marker; 579 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); 580 if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { 581 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, 582 span.to == null ? null : span.to - endCh)); 583 } 584 } } 585 return nw 586} 587 588// Given a change object, compute the new set of marker spans that 589// cover the line in which the change took place. Removes spans 590// entirely within the change, reconnects spans belonging to the 591// same marker that appear on both sides of the change, and cuts off 592// spans partially within the change. Returns an array of span 593// arrays with one element for each line in (after) the change. 594function stretchSpansOverChange(doc, change) { 595 if (change.full) { return null } 596 var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; 597 var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; 598 if (!oldFirst && !oldLast) { return null } 599 600 var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; 601 // Get the spans that 'stick out' on both sides 602 var first = markedSpansBefore(oldFirst, startCh, isInsert); 603 var last = markedSpansAfter(oldLast, endCh, isInsert); 604 605 // Next, merge those two ends 606 var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); 607 if (first) { 608 // Fix up .to properties of first 609 for (var i = 0; i < first.length; ++i) { 610 var span = first[i]; 611 if (span.to == null) { 612 var found = getMarkedSpanFor(last, span.marker); 613 if (!found) { span.to = startCh; } 614 else if (sameLine) { span.to = found.to == null ? null : found.to + offset; } 615 } 616 } 617 } 618 if (last) { 619 // Fix up .from in last (or move them into first in case of sameLine) 620 for (var i$1 = 0; i$1 < last.length; ++i$1) { 621 var span$1 = last[i$1]; 622 if (span$1.to != null) { span$1.to += offset; } 623 if (span$1.from == null) { 624 var found$1 = getMarkedSpanFor(first, span$1.marker); 625 if (!found$1) { 626 span$1.from = offset; 627 if (sameLine) { (first || (first = [])).push(span$1); } 628 } 629 } else { 630 span$1.from += offset; 631 if (sameLine) { (first || (first = [])).push(span$1); } 632 } 633 } 634 } 635 // Make sure we didn't create any zero-length spans 636 if (first) { first = clearEmptySpans(first); } 637 if (last && last != first) { last = clearEmptySpans(last); } 638 639 var newMarkers = [first]; 640 if (!sameLine) { 641 // Fill gap with whole-line-spans 642 var gap = change.text.length - 2, gapMarkers; 643 if (gap > 0 && first) 644 { for (var i$2 = 0; i$2 < first.length; ++i$2) 645 { if (first[i$2].to == null) 646 { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } } 647 for (var i$3 = 0; i$3 < gap; ++i$3) 648 { newMarkers.push(gapMarkers); } 649 newMarkers.push(last); 650 } 651 return newMarkers 652} 653 654// Remove spans that are empty and don't have a clearWhenEmpty 655// option of false. 656function clearEmptySpans(spans) { 657 for (var i = 0; i < spans.length; ++i) { 658 var span = spans[i]; 659 if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) 660 { spans.splice(i--, 1); } 661 } 662 if (!spans.length) { return null } 663 return spans 664} 665 666// Used to 'clip' out readOnly ranges when making a change. 667function removeReadOnlyRanges(doc, from, to) { 668 var markers = null; 669 doc.iter(from.line, to.line + 1, function (line) { 670 if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { 671 var mark = line.markedSpans[i].marker; 672 if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) 673 { (markers || (markers = [])).push(mark); } 674 } } 675 }); 676 if (!markers) { return null } 677 var parts = [{from: from, to: to}]; 678 for (var i = 0; i < markers.length; ++i) { 679 var mk = markers[i], m = mk.find(0); 680 for (var j = 0; j < parts.length; ++j) { 681 var p = parts[j]; 682 if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue } 683 var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); 684 if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) 685 { newParts.push({from: p.from, to: m.from}); } 686 if (dto > 0 || !mk.inclusiveRight && !dto) 687 { newParts.push({from: m.to, to: p.to}); } 688 parts.splice.apply(parts, newParts); 689 j += newParts.length - 3; 690 } 691 } 692 return parts 693} 694 695// Connect or disconnect spans from a line. 696function detachMarkedSpans(line) { 697 var spans = line.markedSpans; 698 if (!spans) { return } 699 for (var i = 0; i < spans.length; ++i) 700 { spans[i].marker.detachLine(line); } 701 line.markedSpans = null; 702} 703function attachMarkedSpans(line, spans) { 704 if (!spans) { return } 705 for (var i = 0; i < spans.length; ++i) 706 { spans[i].marker.attachLine(line); } 707 line.markedSpans = spans; 708} 709 710// Helpers used when computing which overlapping collapsed span 711// counts as the larger one. 712function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 } 713function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 } 714 715// Returns a number indicating which of two overlapping collapsed 716// spans is larger (and thus includes the other). Falls back to 717// comparing ids when the spans cover exactly the same range. 718function compareCollapsedMarkers(a, b) { 719 var lenDiff = a.lines.length - b.lines.length; 720 if (lenDiff != 0) { return lenDiff } 721 var aPos = a.find(), bPos = b.find(); 722 var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); 723 if (fromCmp) { return -fromCmp } 724 var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); 725 if (toCmp) { return toCmp } 726 return b.id - a.id 727} 728 729// Find out whether a line ends or starts in a collapsed span. If 730// so, return the marker for that span. 731function collapsedSpanAtSide(line, start) { 732 var sps = sawCollapsedSpans && line.markedSpans, found; 733 if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { 734 sp = sps[i]; 735 if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && 736 (!found || compareCollapsedMarkers(found, sp.marker) < 0)) 737 { found = sp.marker; } 738 } } 739 return found 740} 741function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) } 742function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) } 743 744// Test whether there exists a collapsed span that partially 745// overlaps (covers the start or end, but not both) of a new span. 746// Such overlap is not allowed. 747function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) { 748 var line = getLine(doc, lineNo$$1); 749 var sps = sawCollapsedSpans && line.markedSpans; 750 if (sps) { for (var i = 0; i < sps.length; ++i) { 751 var sp = sps[i]; 752 if (!sp.marker.collapsed) { continue } 753 var found = sp.marker.find(0); 754 var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); 755 var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); 756 if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue } 757 if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || 758 fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) 759 { return true } 760 } } 761} 762 763// A visual line is a line as drawn on the screen. Folding, for 764// example, can cause multiple logical lines to appear on the same 765// visual line. This finds the start of the visual line that the 766// given line is part of (usually that is the line itself). 767function visualLine(line) { 768 var merged; 769 while (merged = collapsedSpanAtStart(line)) 770 { line = merged.find(-1, true).line; } 771 return line 772} 773 774function visualLineEnd(line) { 775 var merged; 776 while (merged = collapsedSpanAtEnd(line)) 777 { line = merged.find(1, true).line; } 778 return line 779} 780 781// Returns an array of logical lines that continue the visual line 782// started by the argument, or undefined if there are no such lines. 783function visualLineContinued(line) { 784 var merged, lines; 785 while (merged = collapsedSpanAtEnd(line)) { 786 line = merged.find(1, true).line 787 ;(lines || (lines = [])).push(line); 788 } 789 return lines 790} 791 792// Get the line number of the start of the visual line that the 793// given line number is part of. 794function visualLineNo(doc, lineN) { 795 var line = getLine(doc, lineN), vis = visualLine(line); 796 if (line == vis) { return lineN } 797 return lineNo(vis) 798} 799 800// Get the line number of the start of the next visual line after 801// the given line. 802function visualLineEndNo(doc, lineN) { 803 if (lineN > doc.lastLine()) { return lineN } 804 var line = getLine(doc, lineN), merged; 805 if (!lineIsHidden(doc, line)) { return lineN } 806 while (merged = collapsedSpanAtEnd(line)) 807 { line = merged.find(1, true).line; } 808 return lineNo(line) + 1 809} 810 811// Compute whether a line is hidden. Lines count as hidden when they 812// are part of a visual line that starts with another line, or when 813// they are entirely covered by collapsed, non-widget span. 814function lineIsHidden(doc, line) { 815 var sps = sawCollapsedSpans && line.markedSpans; 816 if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { 817 sp = sps[i]; 818 if (!sp.marker.collapsed) { continue } 819 if (sp.from == null) { return true } 820 if (sp.marker.widgetNode) { continue } 821 if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) 822 { return true } 823 } } 824} 825function lineIsHiddenInner(doc, line, span) { 826 if (span.to == null) { 827 var end = span.marker.find(1, true); 828 return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)) 829 } 830 if (span.marker.inclusiveRight && span.to == line.text.length) 831 { return true } 832 for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) { 833 sp = line.markedSpans[i]; 834 if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && 835 (sp.to == null || sp.to != span.from) && 836 (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && 837 lineIsHiddenInner(doc, line, sp)) { return true } 838 } 839} 840 841// Find the height above the given line. 842function heightAtLine(lineObj) { 843 lineObj = visualLine(lineObj); 844 845 var h = 0, chunk = lineObj.parent; 846 for (var i = 0; i < chunk.lines.length; ++i) { 847 var line = chunk.lines[i]; 848 if (line == lineObj) { break } 849 else { h += line.height; } 850 } 851 for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { 852 for (var i$1 = 0; i$1 < p.children.length; ++i$1) { 853 var cur = p.children[i$1]; 854 if (cur == chunk) { break } 855 else { h += cur.height; } 856 } 857 } 858 return h 859} 860 861// Compute the character length of a line, taking into account 862// collapsed ranges (see markText) that might hide parts, and join 863// other lines onto it. 864function lineLength(line) { 865 if (line.height == 0) { return 0 } 866 var len = line.text.length, merged, cur = line; 867 while (merged = collapsedSpanAtStart(cur)) { 868 var found = merged.find(0, true); 869 cur = found.from.line; 870 len += found.from.ch - found.to.ch; 871 } 872 cur = line; 873 while (merged = collapsedSpanAtEnd(cur)) { 874 var found$1 = merged.find(0, true); 875 len -= cur.text.length - found$1.from.ch; 876 cur = found$1.to.line; 877 len += cur.text.length - found$1.to.ch; 878 } 879 return len 880} 881 882// Find the longest line in the document. 883function findMaxLine(cm) { 884 var d = cm.display, doc = cm.doc; 885 d.maxLine = getLine(doc, doc.first); 886 d.maxLineLength = lineLength(d.maxLine); 887 d.maxLineChanged = true; 888 doc.iter(function (line) { 889 var len = lineLength(line); 890 if (len > d.maxLineLength) { 891 d.maxLineLength = len; 892 d.maxLine = line; 893 } 894 }); 895} 896 897// BIDI HELPERS 898 899function iterateBidiSections(order, from, to, f) { 900 if (!order) { return f(from, to, "ltr") } 901 var found = false; 902 for (var i = 0; i < order.length; ++i) { 903 var part = order[i]; 904 if (part.from < to && part.to > from || from == to && part.to == from) { 905 f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); 906 found = true; 907 } 908 } 909 if (!found) { f(from, to, "ltr"); } 910} 911 912var bidiOther = null; 913function getBidiPartAt(order, ch, sticky) { 914 var found; 915 bidiOther = null; 916 for (var i = 0; i < order.length; ++i) { 917 var cur = order[i]; 918 if (cur.from < ch && cur.to > ch) { return i } 919 if (cur.to == ch) { 920 if (cur.from != cur.to && sticky == "before") { found = i; } 921 else { bidiOther = i; } 922 } 923 if (cur.from == ch) { 924 if (cur.from != cur.to && sticky != "before") { found = i; } 925 else { bidiOther = i; } 926 } 927 } 928 return found != null ? found : bidiOther 929} 930 931// Bidirectional ordering algorithm 932// See http://unicode.org/reports/tr9/tr9-13.html for the algorithm 933// that this (partially) implements. 934 935// One-char codes used for character types: 936// L (L): Left-to-Right 937// R (R): Right-to-Left 938// r (AL): Right-to-Left Arabic 939// 1 (EN): European Number 940// + (ES): European Number Separator 941// % (ET): European Number Terminator 942// n (AN): Arabic Number 943// , (CS): Common Number Separator 944// m (NSM): Non-Spacing Mark 945// b (BN): Boundary Neutral 946// s (B): Paragraph Separator 947// t (S): Segment Separator 948// w (WS): Whitespace 949// N (ON): Other Neutrals 950 951// Returns null if characters are ordered as they appear 952// (left-to-right), or an array of sections ({from, to, level} 953// objects) in the order in which they occur visually. 954var bidiOrdering = (function() { 955 // Character types for codepoints 0 to 0xff 956 var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; 957 // Character types for codepoints 0x600 to 0x6f9 958 var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; 959 function charType(code) { 960 if (code <= 0xf7) { return lowTypes.charAt(code) } 961 else if (0x590 <= code && code <= 0x5f4) { return "R" } 962 else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) } 963 else if (0x6ee <= code && code <= 0x8ac) { return "r" } 964 else if (0x2000 <= code && code <= 0x200b) { return "w" } 965 else if (code == 0x200c) { return "b" } 966 else { return "L" } 967 } 968 969 var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; 970 var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; 971 972 function BidiSpan(level, from, to) { 973 this.level = level; 974 this.from = from; this.to = to; 975 } 976 977 return function(str, direction) { 978 var outerType = direction == "ltr" ? "L" : "R"; 979 980 if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false } 981 var len = str.length, types = []; 982 for (var i = 0; i < len; ++i) 983 { types.push(charType(str.charCodeAt(i))); } 984 985 // W1. Examine each non-spacing mark (NSM) in the level run, and 986 // change the type of the NSM to the type of the previous 987 // character. If the NSM is at the start of the level run, it will 988 // get the type of sor. 989 for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) { 990 var type = types[i$1]; 991 if (type == "m") { types[i$1] = prev; } 992 else { prev = type; } 993 } 994 995 // W2. Search backwards from each instance of a European number 996 // until the first strong type (R, L, AL, or sor) is found. If an 997 // AL is found, change the type of the European number to Arabic 998 // number. 999 // W3. Change all ALs to R. 1000 for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) { 1001 var type$1 = types[i$2]; 1002 if (type$1 == "1" && cur == "r") { types[i$2] = "n"; } 1003 else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } } 1004 } 1005 1006 // W4. A single European separator between two European numbers 1007 // changes to a European number. A single common separator between 1008 // two numbers of the same type changes to that type. 1009 for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { 1010 var type$2 = types[i$3]; 1011 if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; } 1012 else if (type$2 == "," && prev$1 == types[i$3+1] && 1013 (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; } 1014 prev$1 = type$2; 1015 } 1016 1017 // W5. A sequence of European terminators adjacent to European 1018 // numbers changes to all European numbers. 1019 // W6. Otherwise, separators and terminators change to Other 1020 // Neutral. 1021 for (var i$4 = 0; i$4 < len; ++i$4) { 1022 var type$3 = types[i$4]; 1023 if (type$3 == ",") { types[i$4] = "N"; } 1024 else if (type$3 == "%") { 1025 var end = (void 0); 1026 for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} 1027 var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; 1028 for (var j = i$4; j < end; ++j) { types[j] = replace; } 1029 i$4 = end - 1; 1030 } 1031 } 1032 1033 // W7. Search backwards from each instance of a European number 1034 // until the first strong type (R, L, or sor) is found. If an L is 1035 // found, then change the type of the European number to L. 1036 for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { 1037 var type$4 = types[i$5]; 1038 if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; } 1039 else if (isStrong.test(type$4)) { cur$1 = type$4; } 1040 } 1041 1042 // N1. A sequence of neutrals takes the direction of the 1043 // surrounding strong text if the text on both sides has the same 1044 // direction. European and Arabic numbers act as if they were R in 1045 // terms of their influence on neutrals. Start-of-level-run (sor) 1046 // and end-of-level-run (eor) are used at level run boundaries. 1047 // N2. Any remaining neutrals take the embedding direction. 1048 for (var i$6 = 0; i$6 < len; ++i$6) { 1049 if (isNeutral.test(types[i$6])) { 1050 var end$1 = (void 0); 1051 for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} 1052 var before = (i$6 ? types[i$6-1] : outerType) == "L"; 1053 var after = (end$1 < len ? types[end$1] : outerType) == "L"; 1054 var replace$1 = before == after ? (before ? "L" : "R") : outerType; 1055 for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; } 1056 i$6 = end$1 - 1; 1057 } 1058 } 1059 1060 // Here we depart from the documented algorithm, in order to avoid 1061 // building up an actual levels array. Since there are only three 1062 // levels (0, 1, 2) in an implementation that doesn't take 1063 // explicit embedding into account, we can build up the order on 1064 // the fly, without following the level-based algorithm. 1065 var order = [], m; 1066 for (var i$7 = 0; i$7 < len;) { 1067 if (countsAsLeft.test(types[i$7])) { 1068 var start = i$7; 1069 for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} 1070 order.push(new BidiSpan(0, start, i$7)); 1071 } else { 1072 var pos = i$7, at = order.length; 1073 for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} 1074 for (var j$2 = pos; j$2 < i$7;) { 1075 if (countsAsNum.test(types[j$2])) { 1076 if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); } 1077 var nstart = j$2; 1078 for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} 1079 order.splice(at, 0, new BidiSpan(2, nstart, j$2)); 1080 pos = j$2; 1081 } else { ++j$2; } 1082 } 1083 if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); } 1084 } 1085 } 1086 if (order[0].level == 1 && (m = str.match(/^\s+/))) { 1087 order[0].from = m[0].length; 1088 order.unshift(new BidiSpan(0, 0, m[0].length)); 1089 } 1090 if (lst(order).level == 1 && (m = str.match(/\s+$/))) { 1091 lst(order).to -= m[0].length; 1092 order.push(new BidiSpan(0, len - m[0].length, len)); 1093 } 1094 1095 return direction == "rtl" ? order.reverse() : order 1096 } 1097})(); 1098 1099// Get the bidi ordering for the given line (and cache it). Returns 1100// false for lines that are fully left-to-right, and an array of 1101// BidiSpan objects otherwise. 1102function getOrder(line, direction) { 1103 var order = line.order; 1104 if (order == null) { order = line.order = bidiOrdering(line.text, direction); } 1105 return order 1106} 1107 1108function moveCharLogically(line, ch, dir) { 1109 var target = skipExtendingChars(line.text, ch + dir, dir); 1110 return target < 0 || target > line.text.length ? null : target 1111} 1112 1113function moveLogically(line, start, dir) { 1114 var ch = moveCharLogically(line, start.ch, dir); 1115 return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before") 1116} 1117 1118function endOfLine(visually, cm, lineObj, lineNo, dir) { 1119 if (visually) { 1120 var order = getOrder(lineObj, cm.doc.direction); 1121 if (order) { 1122 var part = dir < 0 ? lst(order) : order[0]; 1123 var moveInStorageOrder = (dir < 0) == (part.level == 1); 1124 var sticky = moveInStorageOrder ? "after" : "before"; 1125 var ch; 1126 // With a wrapped rtl chunk (possibly spanning multiple bidi parts), 1127 // it could be that the last bidi part is not on the last visual line, 1128 // since visual lines contain content order-consecutive chunks. 1129 // Thus, in rtl, we are looking for the first (content-order) character 1130 // in the rtl chunk that is on the last line (that is, the same line 1131 // as the last (content-order) character). 1132 if (part.level > 0) { 1133 var prep = prepareMeasureForLine(cm, lineObj); 1134 ch = dir < 0 ? lineObj.text.length - 1 : 0; 1135 var targetTop = measureCharPrepared(cm, prep, ch).top; 1136 ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch); 1137 if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); } 1138 } else { ch = dir < 0 ? part.to : part.from; } 1139 return new Pos(lineNo, ch, sticky) 1140 } 1141 } 1142 return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after") 1143} 1144 1145function moveVisually(cm, line, start, dir) { 1146 var bidi = getOrder(line, cm.doc.direction); 1147 if (!bidi) { return moveLogically(line, start, dir) } 1148 if (start.ch >= line.text.length) { 1149 start.ch = line.text.length; 1150 start.sticky = "before"; 1151 } else if (start.ch <= 0) { 1152 start.ch = 0; 1153 start.sticky = "after"; 1154 } 1155 var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]; 1156 if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { 1157 // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines, 1158 // nothing interesting happens. 1159 return moveLogically(line, start, dir) 1160 } 1161 1162 var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }; 1163 var prep; 1164 var getWrappedLineExtent = function (ch) { 1165 if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} } 1166 prep = prep || prepareMeasureForLine(cm, line); 1167 return wrappedLineExtentChar(cm, line, prep, ch) 1168 }; 1169 var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); 1170 1171 if (cm.doc.direction == "rtl" || part.level == 1) { 1172 var moveInStorageOrder = (part.level == 1) == (dir < 0); 1173 var ch = mv(start, moveInStorageOrder ? 1 : -1); 1174 if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) { 1175 // Case 2: We move within an rtl part or in an rtl editor on the same visual line 1176 var sticky = moveInStorageOrder ? "before" : "after"; 1177 return new Pos(start.line, ch, sticky) 1178 } 1179 } 1180 1181 // Case 3: Could not move within this bidi part in this visual line, so leave 1182 // the current bidi part 1183 1184 var searchInVisualLine = function (partPos, dir, wrappedLineExtent) { 1185 var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder 1186 ? new Pos(start.line, mv(ch, 1), "before") 1187 : new Pos(start.line, ch, "after"); }; 1188 1189 for (; partPos >= 0 && partPos < bidi.length; partPos += dir) { 1190 var part = bidi[partPos]; 1191 var moveInStorageOrder = (dir > 0) == (part.level != 1); 1192 var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1); 1193 if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) } 1194 ch = moveInStorageOrder ? part.from : mv(part.to, -1); 1195 if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) } 1196 } 1197 }; 1198 1199 // Case 3a: Look for other bidi parts on the same visual line 1200 var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent); 1201 if (res) { return res } 1202 1203 // Case 3b: Look for other bidi parts on the next visual line 1204 var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1); 1205 if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { 1206 res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); 1207 if (res) { return res } 1208 } 1209 1210 // Case 4: Nowhere to move 1211 return null 1212} 1213 1214// EVENT HANDLING 1215 1216// Lightweight event framework. on/off also work on DOM nodes, 1217// registering native DOM handlers. 1218 1219var noHandlers = []; 1220 1221var on = function(emitter, type, f) { 1222 if (emitter.addEventListener) { 1223 emitter.addEventListener(type, f, false); 1224 } else if (emitter.attachEvent) { 1225 emitter.attachEvent("on" + type, f); 1226 } else { 1227 var map$$1 = emitter._handlers || (emitter._handlers = {}); 1228 map$$1[type] = (map$$1[type] || noHandlers).concat(f); 1229 } 1230}; 1231 1232function getHandlers(emitter, type) { 1233 return emitter._handlers && emitter._handlers[type] || noHandlers 1234} 1235 1236function off(emitter, type, f) { 1237 if (emitter.removeEventListener) { 1238 emitter.removeEventListener(type, f, false); 1239 } else if (emitter.detachEvent) { 1240 emitter.detachEvent("on" + type, f); 1241 } else { 1242 var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type]; 1243 if (arr) { 1244 var index = indexOf(arr, f); 1245 if (index > -1) 1246 { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); } 1247 } 1248 } 1249} 1250 1251function signal(emitter, type /*, values...*/) { 1252 var handlers = getHandlers(emitter, type); 1253 if (!handlers.length) { return } 1254 var args = Array.prototype.slice.call(arguments, 2); 1255 for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); } 1256} 1257 1258// The DOM events that CodeMirror handles can be overridden by 1259// registering a (non-DOM) handler on the editor for the event name, 1260// and preventDefault-ing the event in that handler. 1261function signalDOMEvent(cm, e, override) { 1262 if (typeof e == "string") 1263 { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; } 1264 signal(cm, override || e.type, cm, e); 1265 return e_defaultPrevented(e) || e.codemirrorIgnore 1266} 1267 1268function signalCursorActivity(cm) { 1269 var arr = cm._handlers && cm._handlers.cursorActivity; 1270 if (!arr) { return } 1271 var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); 1272 for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1) 1273 { set.push(arr[i]); } } 1274} 1275 1276function hasHandler(emitter, type) { 1277 return getHandlers(emitter, type).length > 0 1278} 1279 1280// Add on and off methods to a constructor's prototype, to make 1281// registering events on such objects more convenient. 1282function eventMixin(ctor) { 1283 ctor.prototype.on = function(type, f) {on(this, type, f);}; 1284 ctor.prototype.off = function(type, f) {off(this, type, f);}; 1285} 1286 1287// Due to the fact that we still support jurassic IE versions, some 1288// compatibility wrappers are needed. 1289 1290function e_preventDefault(e) { 1291 if (e.preventDefault) { e.preventDefault(); } 1292 else { e.returnValue = false; } 1293} 1294function e_stopPropagation(e) { 1295 if (e.stopPropagation) { e.stopPropagation(); } 1296 else { e.cancelBubble = true; } 1297} 1298function e_defaultPrevented(e) { 1299 return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false 1300} 1301function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} 1302 1303function e_target(e) {return e.target || e.srcElement} 1304function e_button(e) { 1305 var b = e.which; 1306 if (b == null) { 1307 if (e.button & 1) { b = 1; } 1308 else if (e.button & 2) { b = 3; } 1309 else if (e.button & 4) { b = 2; } 1310 } 1311 if (mac && e.ctrlKey && b == 1) { b = 3; } 1312 return b 1313} 1314 1315// Detect drag-and-drop 1316var dragAndDrop = function() { 1317 // There is *some* kind of drag-and-drop support in IE6-8, but I 1318 // couldn't get it to work yet. 1319 if (ie && ie_version < 9) { return false } 1320 var div = elt('div'); 1321 return "draggable" in div || "dragDrop" in div 1322}(); 1323 1324var zwspSupported; 1325function zeroWidthElement(measure) { 1326 if (zwspSupported == null) { 1327 var test = elt("span", "\u200b"); 1328 removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); 1329 if (measure.firstChild.offsetHeight != 0) 1330 { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); } 1331 } 1332 var node = zwspSupported ? elt("span", "\u200b") : 1333 elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); 1334 node.setAttribute("cm-text", ""); 1335 return node 1336} 1337 1338// Feature-detect IE's crummy client rect reporting for bidi text 1339var badBidiRects; 1340function hasBadBidiRects(measure) { 1341 if (badBidiRects != null) { return badBidiRects } 1342 var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); 1343 var r0 = range(txt, 0, 1).getBoundingClientRect(); 1344 var r1 = range(txt, 1, 2).getBoundingClientRect(); 1345 removeChildren(measure); 1346 if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780) 1347 return badBidiRects = (r1.right - r0.right < 3) 1348} 1349 1350// See if "".split is the broken IE version, if so, provide an 1351// alternative way to split lines. 1352var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { 1353 var pos = 0, result = [], l = string.length; 1354 while (pos <= l) { 1355 var nl = string.indexOf("\n", pos); 1356 if (nl == -1) { nl = string.length; } 1357 var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); 1358 var rt = line.indexOf("\r"); 1359 if (rt != -1) { 1360 result.push(line.slice(0, rt)); 1361 pos += rt + 1; 1362 } else { 1363 result.push(line); 1364 pos = nl + 1; 1365 } 1366 } 1367 return result 1368} : function (string) { return string.split(/\r\n?|\n/); }; 1369 1370var hasSelection = window.getSelection ? function (te) { 1371 try { return te.selectionStart != te.selectionEnd } 1372 catch(e) { return false } 1373} : function (te) { 1374 var range$$1; 1375 try {range$$1 = te.ownerDocument.selection.createRange();} 1376 catch(e) {} 1377 if (!range$$1 || range$$1.parentElement() != te) { return false } 1378 return range$$1.compareEndPoints("StartToEnd", range$$1) != 0 1379}; 1380 1381var hasCopyEvent = (function () { 1382 var e = elt("div"); 1383 if ("oncopy" in e) { return true } 1384 e.setAttribute("oncopy", "return;"); 1385 return typeof e.oncopy == "function" 1386})(); 1387 1388var badZoomedRects = null; 1389function hasBadZoomedRects(measure) { 1390 if (badZoomedRects != null) { return badZoomedRects } 1391 var node = removeChildrenAndAdd(measure, elt("span", "x")); 1392 var normal = node.getBoundingClientRect(); 1393 var fromRange = range(node, 0, 1).getBoundingClientRect(); 1394 return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 1395} 1396 1397// Known modes, by name and by MIME 1398var modes = {}; 1399var mimeModes = {}; 1400 1401// Extra arguments are stored as the mode's dependencies, which is 1402// used by (legacy) mechanisms like loadmode.js to automatically 1403// load a mode. (Preferred mechanism is the require/define calls.) 1404function defineMode(name, mode) { 1405 if (arguments.length > 2) 1406 { mode.dependencies = Array.prototype.slice.call(arguments, 2); } 1407 modes[name] = mode; 1408} 1409 1410function defineMIME(mime, spec) { 1411 mimeModes[mime] = spec; 1412} 1413 1414// Given a MIME type, a {name, ...options} config object, or a name 1415// string, return a mode config object. 1416function resolveMode(spec) { 1417 if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { 1418 spec = mimeModes[spec]; 1419 } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { 1420 var found = mimeModes[spec.name]; 1421 if (typeof found == "string") { found = {name: found}; } 1422 spec = createObj(found, spec); 1423 spec.name = found.name; 1424 } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { 1425 return resolveMode("application/xml") 1426 } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { 1427 return resolveMode("application/json") 1428 } 1429 if (typeof spec == "string") { return {name: spec} } 1430 else { return spec || {name: "null"} } 1431} 1432 1433// Given a mode spec (anything that resolveMode accepts), find and 1434// initialize an actual mode object. 1435function getMode(options, spec) { 1436 spec = resolveMode(spec); 1437 var mfactory = modes[spec.name]; 1438 if (!mfactory) { return getMode(options, "text/plain") } 1439 var modeObj = mfactory(options, spec); 1440 if (modeExtensions.hasOwnProperty(spec.name)) { 1441 var exts = modeExtensions[spec.name]; 1442 for (var prop in exts) { 1443 if (!exts.hasOwnProperty(prop)) { continue } 1444 if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; } 1445 modeObj[prop] = exts[prop]; 1446 } 1447 } 1448 modeObj.name = spec.name; 1449 if (spec.helperType) { modeObj.helperType = spec.helperType; } 1450 if (spec.modeProps) { for (var prop$1 in spec.modeProps) 1451 { modeObj[prop$1] = spec.modeProps[prop$1]; } } 1452 1453 return modeObj 1454} 1455 1456// This can be used to attach properties to mode objects from 1457// outside the actual mode definition. 1458var modeExtensions = {}; 1459function extendMode(mode, properties) { 1460 var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); 1461 copyObj(properties, exts); 1462} 1463 1464function copyState(mode, state) { 1465 if (state === true) { return state } 1466 if (mode.copyState) { return mode.copyState(state) } 1467 var nstate = {}; 1468 for (var n in state) { 1469 var val = state[n]; 1470 if (val instanceof Array) { val = val.concat([]); } 1471 nstate[n] = val; 1472 } 1473 return nstate 1474} 1475 1476// Given a mode and a state (for that mode), find the inner mode and 1477// state at the position that the state refers to. 1478function innerMode(mode, state) { 1479 var info; 1480 while (mode.innerMode) { 1481 info = mode.innerMode(state); 1482 if (!info || info.mode == mode) { break } 1483 state = info.state; 1484 mode = info.mode; 1485 } 1486 return info || {mode: mode, state: state} 1487} 1488 1489function startState(mode, a1, a2) { 1490 return mode.startState ? mode.startState(a1, a2) : true 1491} 1492 1493// STRING STREAM 1494 1495// Fed to the mode parsers, provides helper functions to make 1496// parsers more succinct. 1497 1498var StringStream = function(string, tabSize, lineOracle) { 1499 this.pos = this.start = 0; 1500 this.string = string; 1501 this.tabSize = tabSize || 8; 1502 this.lastColumnPos = this.lastColumnValue = 0; 1503 this.lineStart = 0; 1504 this.lineOracle = lineOracle; 1505}; 1506 1507StringStream.prototype.eol = function () {return this.pos >= this.string.length}; 1508StringStream.prototype.sol = function () {return this.pos == this.lineStart}; 1509StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined}; 1510StringStream.prototype.next = function () { 1511 if (this.pos < this.string.length) 1512 { return this.string.charAt(this.pos++) } 1513}; 1514StringStream.prototype.eat = function (match) { 1515 var ch = this.string.charAt(this.pos); 1516 var ok; 1517 if (typeof match == "string") { ok = ch == match; } 1518 else { ok = ch && (match.test ? match.test(ch) : match(ch)); } 1519 if (ok) {++this.pos; return ch} 1520}; 1521StringStream.prototype.eatWhile = function (match) { 1522 var start = this.pos; 1523 while (this.eat(match)){} 1524 return this.pos > start 1525}; 1526StringStream.prototype.eatSpace = function () { 1527 var this$1 = this; 1528 1529 var start = this.pos; 1530 while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; } 1531 return this.pos > start 1532}; 1533StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;}; 1534StringStream.prototype.skipTo = function (ch) { 1535 var found = this.string.indexOf(ch, this.pos); 1536 if (found > -1) {this.pos = found; return true} 1537}; 1538StringStream.prototype.backUp = function (n) {this.pos -= n;}; 1539StringStream.prototype.column = function () { 1540 if (this.lastColumnPos < this.start) { 1541 this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); 1542 this.lastColumnPos = this.start; 1543 } 1544 return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) 1545}; 1546StringStream.prototype.indentation = function () { 1547 return countColumn(this.string, null, this.tabSize) - 1548 (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) 1549}; 1550StringStream.prototype.match = function (pattern, consume, caseInsensitive) { 1551 if (typeof pattern == "string") { 1552 var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }; 1553 var substr = this.string.substr(this.pos, pattern.length); 1554 if (cased(substr) == cased(pattern)) { 1555 if (consume !== false) { this.pos += pattern.length; } 1556 return true 1557 } 1558 } else { 1559 var match = this.string.slice(this.pos).match(pattern); 1560 if (match && match.index > 0) { return null } 1561 if (match && consume !== false) { this.pos += match[0].length; } 1562 return match 1563 } 1564}; 1565StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)}; 1566StringStream.prototype.hideFirstChars = function (n, inner) { 1567 this.lineStart += n; 1568 try { return inner() } 1569 finally { this.lineStart -= n; } 1570}; 1571StringStream.prototype.lookAhead = function (n) { 1572 var oracle = this.lineOracle; 1573 return oracle && oracle.lookAhead(n) 1574}; 1575 1576var SavedContext = function(state, lookAhead) { 1577 this.state = state; 1578 this.lookAhead = lookAhead; 1579}; 1580 1581var Context = function(doc, state, line, lookAhead) { 1582 this.state = state; 1583 this.doc = doc; 1584 this.line = line; 1585 this.maxLookAhead = lookAhead || 0; 1586}; 1587 1588Context.prototype.lookAhead = function (n) { 1589 var line = this.doc.getLine(this.line + n); 1590 if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; } 1591 return line 1592}; 1593 1594Context.prototype.nextLine = function () { 1595 this.line++; 1596 if (this.maxLookAhead > 0) { this.maxLookAhead--; } 1597}; 1598 1599Context.fromSaved = function (doc, saved, line) { 1600 if (saved instanceof SavedContext) 1601 { return new Context(doc, copyState(doc.mode, saved.saved), line, saved.lookAhead) } 1602 else 1603 { return new Context(doc, copyState(doc.mode, saved), line) } 1604}; 1605 1606Context.prototype.save = function (copy) { 1607 var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; 1608 return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state 1609}; 1610 1611 1612// Compute a style array (an array starting with a mode generation 1613// -- for invalidation -- followed by pairs of end positions and 1614// style strings), which is used to highlight the tokens on the 1615// line. 1616function highlightLine(cm, line, context, forceToEnd) { 1617 // A styles array always starts with a number identifying the 1618 // mode/overlays that it is based on (for easy invalidation). 1619 var st = [cm.state.modeGen], lineClasses = {}; 1620 // Compute the base array of styles 1621 runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); }, 1622 lineClasses, forceToEnd); 1623 var state = context.state; 1624 1625 // Run overlays, adjust style array. 1626 var loop = function ( o ) { 1627 var overlay = cm.state.overlays[o], i = 1, at = 0; 1628 context.state = true; 1629 runMode(cm, line.text, overlay.mode, context, function (end, style) { 1630 var start = i; 1631 // Ensure there's a token end at the current position, and that i points at it 1632 while (at < end) { 1633 var i_end = st[i]; 1634 if (i_end > end) 1635 { st.splice(i, 1, end, st[i+1], i_end); } 1636 i += 2; 1637 at = Math.min(end, i_end); 1638 } 1639 if (!style) { return } 1640 if (overlay.opaque) { 1641 st.splice(start, i - start, end, "overlay " + style); 1642 i = start + 2; 1643 } else { 1644 for (; start < i; start += 2) { 1645 var cur = st[start+1]; 1646 st[start+1] = (cur ? cur + " " : "") + "overlay " + style; 1647 } 1648 } 1649 }, lineClasses); 1650 }; 1651 1652 for (var o = 0; o < cm.state.overlays.length; ++o) loop( o ); 1653 context.state = state; 1654 1655 return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} 1656} 1657 1658function getLineStyles(cm, line, updateFrontier) { 1659 if (!line.styles || line.styles[0] != cm.state.modeGen) { 1660 var context = getContextBefore(cm, lineNo(line)); 1661 var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); 1662 var result = highlightLine(cm, line, context); 1663 if (resetState) { context.state = resetState; } 1664 line.stateAfter = context.save(!resetState); 1665 line.styles = result.styles; 1666 if (result.classes) { line.styleClasses = result.classes; } 1667 else if (line.styleClasses) { line.styleClasses = null; } 1668 if (updateFrontier === cm.doc.highlightFrontier) 1669 { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); } 1670 } 1671 return line.styles 1672} 1673 1674function getContextBefore(cm, n, precise) { 1675 var doc = cm.doc, display = cm.display; 1676 if (!doc.mode.startState) { return new Context(doc, true, n) } 1677 var start = findStartLine(cm, n, precise); 1678 var saved = start > doc.first && getLine(doc, start - 1).stateAfter; 1679 var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start); 1680 1681 doc.iter(start, n, function (line) { 1682 processLine(cm, line.text, context); 1683 var pos = context.line; 1684 line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; 1685 context.nextLine(); 1686 }); 1687 if (precise) { doc.modeFrontier = context.line; } 1688 return context 1689} 1690 1691// Lightweight form of highlight -- proceed over this line and 1692// update state, but don't save a style array. Used for lines that 1693// aren't currently visible. 1694function processLine(cm, text, context, startAt) { 1695 var mode = cm.doc.mode; 1696 var stream = new StringStream(text, cm.options.tabSize, context); 1697 stream.start = stream.pos = startAt || 0; 1698 if (text == "") { callBlankLine(mode, context.state); } 1699 while (!stream.eol()) { 1700 readToken(mode, stream, context.state); 1701 stream.start = stream.pos; 1702 } 1703} 1704 1705function callBlankLine(mode, state) { 1706 if (mode.blankLine) { return mode.blankLine(state) } 1707 if (!mode.innerMode) { return } 1708 var inner = innerMode(mode, state); 1709 if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) } 1710} 1711 1712function readToken(mode, stream, state, inner) { 1713 for (var i = 0; i < 10; i++) { 1714 if (inner) { inner[0] = innerMode(mode, state).mode; } 1715 var style = mode.token(stream, state); 1716 if (stream.pos > stream.start) { return style } 1717 } 1718 throw new Error("Mode " + mode.name + " failed to advance stream.") 1719} 1720 1721var Token = function(stream, type, state) { 1722 this.start = stream.start; this.end = stream.pos; 1723 this.string = stream.current(); 1724 this.type = type || null; 1725 this.state = state; 1726}; 1727 1728// Utility for getTokenAt and getLineTokens 1729function takeToken(cm, pos, precise, asArray) { 1730 var doc = cm.doc, mode = doc.mode, style; 1731 pos = clipPos(doc, pos); 1732 var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise); 1733 var stream = new StringStream(line.text, cm.options.tabSize, context), tokens; 1734 if (asArray) { tokens = []; } 1735 while ((asArray || stream.pos < pos.ch) && !stream.eol()) { 1736 stream.start = stream.pos; 1737 style = readToken(mode, stream, context.state); 1738 if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); } 1739 } 1740 return asArray ? tokens : new Token(stream, style, context.state) 1741} 1742 1743function extractLineClasses(type, output) { 1744 if (type) { for (;;) { 1745 var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); 1746 if (!lineClass) { break } 1747 type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); 1748 var prop = lineClass[1] ? "bgClass" : "textClass"; 1749 if (output[prop] == null) 1750 { output[prop] = lineClass[2]; } 1751 else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) 1752 { output[prop] += " " + lineClass[2]; } 1753 } } 1754 return type 1755} 1756 1757// Run the given mode's parser over a line, calling f for each token. 1758function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { 1759 var flattenSpans = mode.flattenSpans; 1760 if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; } 1761 var curStart = 0, curStyle = null; 1762 var stream = new StringStream(text, cm.options.tabSize, context), style; 1763 var inner = cm.options.addModeClass && [null]; 1764 if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); } 1765 while (!stream.eol()) { 1766 if (stream.pos > cm.options.maxHighlightLength) { 1767 flattenSpans = false; 1768 if (forceToEnd) { processLine(cm, text, context, stream.pos); } 1769 stream.pos = text.length; 1770 style = null; 1771 } else { 1772 style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); 1773 } 1774 if (inner) { 1775 var mName = inner[0].name; 1776 if (mName) { style = "m-" + (style ? mName + " " + style : mName); } 1777 } 1778 if (!flattenSpans || curStyle != style) { 1779 while (curStart < stream.start) { 1780 curStart = Math.min(stream.start, curStart + 5000); 1781 f(curStart, curStyle); 1782 } 1783 curStyle = style; 1784 } 1785 stream.start = stream.pos; 1786 } 1787 while (curStart < stream.pos) { 1788 // Webkit seems to refuse to render text nodes longer than 57444 1789 // characters, and returns inaccurate measurements in nodes 1790 // starting around 5000 chars. 1791 var pos = Math.min(stream.pos, curStart + 5000); 1792 f(pos, curStyle); 1793 curStart = pos; 1794 } 1795} 1796 1797// Finds the line to start with when starting a parse. Tries to 1798// find a line with a stateAfter, so that it can start with a 1799// valid state. If that fails, it returns the line with the 1800// smallest indentation, which tends to need the least context to 1801// parse correctly. 1802function findStartLine(cm, n, precise) { 1803 var minindent, minline, doc = cm.doc; 1804 var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); 1805 for (var search = n; search > lim; --search) { 1806 if (search <= doc.first) { return doc.first } 1807 var line = getLine(doc, search - 1), after = line.stateAfter; 1808 if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) 1809 { return search } 1810 var indented = countColumn(line.text, null, cm.options.tabSize); 1811 if (minline == null || minindent > indented) { 1812 minline = search - 1; 1813 minindent = indented; 1814 } 1815 } 1816 return minline 1817} 1818 1819function retreatFrontier(doc, n) { 1820 doc.modeFrontier = Math.min(doc.modeFrontier, n); 1821 if (doc.highlightFrontier < n - 10) { return } 1822 var start = doc.first; 1823 for (var line = n - 1; line > start; line--) { 1824 var saved = getLine(doc, line).stateAfter; 1825 // change is on 3 1826 // state on line 1 looked ahead 2 -- so saw 3 1827 // test 1 + 2 < 3 should cover this 1828 if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { 1829 start = line + 1; 1830 break 1831 } 1832 } 1833 doc.highlightFrontier = Math.min(doc.highlightFrontier, start); 1834} 1835 1836// LINE DATA STRUCTURE 1837 1838// Line objects. These hold state related to a line, including 1839// highlighting info (the styles array). 1840var Line = function(text, markedSpans, estimateHeight) { 1841 this.text = text; 1842 attachMarkedSpans(this, markedSpans); 1843 this.height = estimateHeight ? estimateHeight(this) : 1; 1844}; 1845 1846Line.prototype.lineNo = function () { return lineNo(this) }; 1847eventMixin(Line); 1848 1849// Change the content (text, markers) of a line. Automatically 1850// invalidates cached information and tries to re-estimate the 1851// line's height. 1852function updateLine(line, text, markedSpans, estimateHeight) { 1853 line.text = text; 1854 if (line.stateAfter) { line.stateAfter = null; } 1855 if (line.styles) { line.styles = null; } 1856 if (line.order != null) { line.order = null; } 1857 detachMarkedSpans(line); 1858 attachMarkedSpans(line, markedSpans); 1859 var estHeight = estimateHeight ? estimateHeight(line) : 1; 1860 if (estHeight != line.height) { updateLineHeight(line, estHeight); } 1861} 1862 1863// Detach a line from the document tree and its markers. 1864function cleanUpLine(line) { 1865 line.parent = null; 1866 detachMarkedSpans(line); 1867} 1868 1869// Convert a style as returned by a mode (either null, or a string 1870// containing one or more styles) to a CSS style. This is cached, 1871// and also looks for line-wide styles. 1872var styleToClassCache = {}; 1873var styleToClassCacheWithMode = {}; 1874function interpretTokenStyle(style, options) { 1875 if (!style || /^\s*$/.test(style)) { return null } 1876 var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; 1877 return cache[style] || 1878 (cache[style] = style.replace(/\S+/g, "cm-$&")) 1879} 1880 1881// Render the DOM representation of the text of a line. Also builds 1882// up a 'line map', which points at the DOM nodes that represent 1883// specific stretches of text, and is used by the measuring code. 1884// The returned object contains the DOM node, this map, and 1885// information about line-wide styles that were set by the mode. 1886function buildLineContent(cm, lineView) { 1887 // The padding-right forces the element to have a 'border', which 1888 // is needed on Webkit to be able to get line-level bounding 1889 // rectangles for it (in measureChar). 1890 var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); 1891 var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content, 1892 col: 0, pos: 0, cm: cm, 1893 trailingSpace: false, 1894 splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}; 1895 lineView.measure = {}; 1896 1897 // Iterate over the logical lines that make up this visual line. 1898 for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { 1899 var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0); 1900 builder.pos = 0; 1901 builder.addToken = buildToken; 1902 // Optionally wire in some hacks into the token-rendering 1903 // algorithm, to deal with browser quirks. 1904 if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) 1905 { builder.addToken = buildTokenBadBidi(builder.addToken, order); } 1906 builder.map = []; 1907 var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); 1908 insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); 1909 if (line.styleClasses) { 1910 if (line.styleClasses.bgClass) 1911 { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); } 1912 if (line.styleClasses.textClass) 1913 { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); } 1914 } 1915 1916 // Ensure at least a single node is present, for measuring. 1917 if (builder.map.length == 0) 1918 { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); } 1919 1920 // Store the map and a cache object for the current logical line 1921 if (i == 0) { 1922 lineView.measure.map = builder.map; 1923 lineView.measure.cache = {}; 1924 } else { 1925 (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) 1926 ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}); 1927 } 1928 } 1929 1930 // See issue #2901 1931 if (webkit) { 1932 var last = builder.content.lastChild; 1933 if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) 1934 { builder.content.className = "cm-tab-wrap-hack"; } 1935 } 1936 1937 signal(cm, "renderLine", cm, lineView.line, builder.pre); 1938 if (builder.pre.className) 1939 { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); } 1940 1941 return builder 1942} 1943 1944function defaultSpecialCharPlaceholder(ch) { 1945 var token = elt("span", "\u2022", "cm-invalidchar"); 1946 token.title = "\\u" + ch.charCodeAt(0).toString(16); 1947 token.setAttribute("aria-label", token.title); 1948 return token 1949} 1950 1951// Build up the DOM representation for a single token, and add it to 1952// the line map. Takes care to render special characters separately. 1953function buildToken(builder, text, style, startStyle, endStyle, title, css) { 1954 if (!text) { return } 1955 var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; 1956 var special = builder.cm.state.specialChars, mustWrap = false; 1957 var content; 1958 if (!special.test(text)) { 1959 builder.col += text.length; 1960 content = document.createTextNode(displayText); 1961 builder.map.push(builder.pos, builder.pos + text.length, content); 1962 if (ie && ie_version < 9) { mustWrap = true; } 1963 builder.pos += text.length; 1964 } else { 1965 content = document.createDocumentFragment(); 1966 var pos = 0; 1967 while (true) { 1968 special.lastIndex = pos; 1969 var m = special.exec(text); 1970 var skipped = m ? m.index - pos : text.length - pos; 1971 if (skipped) { 1972 var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); 1973 if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); } 1974 else { content.appendChild(txt); } 1975 builder.map.push(builder.pos, builder.pos + skipped, txt); 1976 builder.col += skipped; 1977 builder.pos += skipped; 1978 } 1979 if (!m) { break } 1980 pos += skipped + 1; 1981 var txt$1 = (void 0); 1982 if (m[0] == "\t") { 1983 var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; 1984 txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); 1985 txt$1.setAttribute("role", "presentation"); 1986 txt$1.setAttribute("cm-text", "\t"); 1987 builder.col += tabWidth; 1988 } else if (m[0] == "\r" || m[0] == "\n") { 1989 txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); 1990 txt$1.setAttribute("cm-text", m[0]); 1991 builder.col += 1; 1992 } else { 1993 txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); 1994 txt$1.setAttribute("cm-text", m[0]); 1995 if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); } 1996 else { content.appendChild(txt$1); } 1997 builder.col += 1; 1998 } 1999 builder.map.push(builder.pos, builder.pos + 1, txt$1); 2000 builder.pos++; 2001 } 2002 } 2003 builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; 2004 if (style || startStyle || endStyle || mustWrap || css) { 2005 var fullStyle = style || ""; 2006 if (startStyle) { fullStyle += startStyle; } 2007 if (endStyle) { fullStyle += endStyle; } 2008 var token = elt("span", [content], fullStyle, css); 2009 if (title) { token.title = title; } 2010 return builder.content.appendChild(token) 2011 } 2012 builder.content.appendChild(content); 2013} 2014 2015function splitSpaces(text, trailingBefore) { 2016 if (text.length > 1 && !/ /.test(text)) { return text } 2017 var spaceBefore = trailingBefore, result = ""; 2018 for (var i = 0; i < text.length; i++) { 2019 var ch = text.charAt(i); 2020 if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) 2021 { ch = "\u00a0"; } 2022 result += ch; 2023 spaceBefore = ch == " "; 2024 } 2025 return result 2026} 2027 2028// Work around nonsense dimensions being reported for stretches of 2029// right-to-left text. 2030function buildTokenBadBidi(inner, order) { 2031 return function (builder, text, style, startStyle, endStyle, title, css) { 2032 style = style ? style + " cm-force-border" : "cm-force-border"; 2033 var start = builder.pos, end = start + text.length; 2034 for (;;) { 2035 // Find the part that overlaps with the start of this text 2036 var part = (void 0); 2037 for (var i = 0; i < order.length; i++) { 2038 part = order[i]; 2039 if (part.to > start && part.from <= start) { break } 2040 } 2041 if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) } 2042 inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css); 2043 startStyle = null; 2044 text = text.slice(part.to - start); 2045 start = part.to; 2046 } 2047 } 2048} 2049 2050function buildCollapsedSpan(builder, size, marker, ignoreWidget) { 2051 var widget = !ignoreWidget && marker.widgetNode; 2052 if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); } 2053 if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { 2054 if (!widget) 2055 { widget = builder.content.appendChild(document.createElement("span")); } 2056 widget.setAttribute("cm-marker", marker.id); 2057 } 2058 if (widget) { 2059 builder.cm.display.input.setUneditable(widget); 2060 builder.content.appendChild(widget); 2061 } 2062 builder.pos += size; 2063 builder.trailingSpace = false; 2064} 2065 2066// Outputs a number of spans to make up a line, taking highlighting 2067// and marked text into account. 2068function insertLineContent(line, builder, styles) { 2069 var spans = line.markedSpans, allText = line.text, at = 0; 2070 if (!spans) { 2071 for (var i$1 = 1; i$1 < styles.length; i$1+=2) 2072 { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); } 2073 return 2074 } 2075 2076 var len = allText.length, pos = 0, i = 1, text = "", style, css; 2077 var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; 2078 for (;;) { 2079 if (nextChange == pos) { // Update current marker set 2080 spanStyle = spanEndStyle = spanStartStyle = title = css = ""; 2081 collapsed = null; nextChange = Infinity; 2082 var foundBookmarks = [], endStyles = (void 0); 2083 for (var j = 0; j < spans.length; ++j) { 2084 var sp = spans[j], m = sp.marker; 2085 if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { 2086 foundBookmarks.push(m); 2087 } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { 2088 if (sp.to != null && sp.to != pos && nextChange > sp.to) { 2089 nextChange = sp.to; 2090 spanEndStyle = ""; 2091 } 2092 if (m.className) { spanStyle += " " + m.className; } 2093 if (m.css) { css = (css ? css + ";" : "") + m.css; } 2094 if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; } 2095 if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); } 2096 if (m.title && !title) { title = m.title; } 2097 if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) 2098 { collapsed = sp; } 2099 } else if (sp.from > pos && nextChange > sp.from) { 2100 nextChange = sp.from; 2101 } 2102 } 2103 if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) 2104 { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } } 2105 2106 if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) 2107 { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } } 2108 if (collapsed && (collapsed.from || 0) == pos) { 2109 buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, 2110 collapsed.marker, collapsed.from == null); 2111 if (collapsed.to == null) { return } 2112 if (collapsed.to == pos) { collapsed = false; } 2113 } 2114 } 2115 if (pos >= len) { break } 2116 2117 var upto = Math.min(len, nextChange); 2118 while (true) { 2119 if (text) { 2120 var end = pos + text.length; 2121 if (!collapsed) { 2122 var tokenText = end > upto ? text.slice(0, upto - pos) : text; 2123 builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, 2124 spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css); 2125 } 2126 if (end >= upto) {text = text.slice(upto - pos); pos = upto; break} 2127 pos = end; 2128 spanStartStyle = ""; 2129 } 2130 text = allText.slice(at, at = styles[i++]); 2131 style = interpretTokenStyle(styles[i++], builder.cm.options); 2132 } 2133 } 2134} 2135 2136 2137// These objects are used to represent the visible (currently drawn) 2138// part of the document. A LineView may correspond to multiple 2139// logical lines, if those are connected by collapsed ranges. 2140function LineView(doc, line, lineN) { 2141 // The starting line 2142 this.line = line; 2143 // Continuing lines, if any 2144 this.rest = visualLineContinued(line); 2145 // Number of logical lines in this visual line 2146 this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; 2147 this.node = this.text = null; 2148 this.hidden = lineIsHidden(doc, line); 2149} 2150 2151// Create a range of LineView objects for the given lines. 2152function buildViewArray(cm, from, to) { 2153 var array = [], nextPos; 2154 for (var pos = from; pos < to; pos = nextPos) { 2155 var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); 2156 nextPos = pos + view.size; 2157 array.push(view); 2158 } 2159 return array 2160} 2161 2162var operationGroup = null; 2163 2164function pushOperation(op) { 2165 if (operationGroup) { 2166 operationGroup.ops.push(op); 2167 } else { 2168 op.ownsGroup = operationGroup = { 2169 ops: [op], 2170 delayedCallbacks: [] 2171 }; 2172 } 2173} 2174 2175function fireCallbacksForOps(group) { 2176 // Calls delayed callbacks and cursorActivity handlers until no 2177 // new ones appear 2178 var callbacks = group.delayedCallbacks, i = 0; 2179 do { 2180 for (; i < callbacks.length; i++) 2181 { callbacks[i].call(null); } 2182 for (var j = 0; j < group.ops.length; j++) { 2183 var op = group.ops[j]; 2184 if (op.cursorActivityHandlers) 2185 { while (op.cursorActivityCalled < op.cursorActivityHandlers.length) 2186 { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } } 2187 } 2188 } while (i < callbacks.length) 2189} 2190 2191function finishOperation(op, endCb) { 2192 var group = op.ownsGroup; 2193 if (!group) { return } 2194 2195 try { fireCallbacksForOps(group); } 2196 finally { 2197 operationGroup = null; 2198 endCb(group); 2199 } 2200} 2201 2202var orphanDelayedCallbacks = null; 2203 2204// Often, we want to signal events at a point where we are in the 2205// middle of some work, but don't want the handler to start calling 2206// other methods on the editor, which might be in an inconsistent 2207// state or simply not expect any other events to happen. 2208// signalLater looks whether there are any handlers, and schedules 2209// them to be executed when the last operation ends, or, if no 2210// operation is active, when a timeout fires. 2211function signalLater(emitter, type /*, values...*/) { 2212 var arr = getHandlers(emitter, type); 2213 if (!arr.length) { return } 2214 var args = Array.prototype.slice.call(arguments, 2), list; 2215 if (operationGroup) { 2216 list = operationGroup.delayedCallbacks; 2217 } else if (orphanDelayedCallbacks) { 2218 list = orphanDelayedCallbacks; 2219 } else { 2220 list = orphanDelayedCallbacks = []; 2221 setTimeout(fireOrphanDelayed, 0); 2222 } 2223 var loop = function ( i ) { 2224 list.push(function () { return arr[i].apply(null, args); }); 2225 }; 2226 2227 for (var i = 0; i < arr.length; ++i) 2228 loop( i ); 2229} 2230 2231function fireOrphanDelayed() { 2232 var delayed = orphanDelayedCallbacks; 2233 orphanDelayedCallbacks = null; 2234 for (var i = 0; i < delayed.length; ++i) { delayed[i](); } 2235} 2236 2237// When an aspect of a line changes, a string is added to 2238// lineView.changes. This updates the relevant part of the line's 2239// DOM structure. 2240function updateLineForChanges(cm, lineView, lineN, dims) { 2241 for (var j = 0; j < lineView.changes.length; j++) { 2242 var type = lineView.changes[j]; 2243 if (type == "text") { updateLineText(cm, lineView); } 2244 else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); } 2245 else if (type == "class") { updateLineClasses(cm, lineView); } 2246 else if (type == "widget") { updateLineWidgets(cm, lineView, dims); } 2247 } 2248 lineView.changes = null; 2249} 2250 2251// Lines with gutter elements, widgets or a background class need to 2252// be wrapped, and have the extra elements added to the wrapper div 2253function ensureLineWrapped(lineView) { 2254 if (lineView.node == lineView.text) { 2255 lineView.node = elt("div", null, null, "position: relative"); 2256 if (lineView.text.parentNode) 2257 { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); } 2258 lineView.node.appendChild(lineView.text); 2259 if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; } 2260 } 2261 return lineView.node 2262} 2263 2264function updateLineBackground(cm, lineView) { 2265 var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; 2266 if (cls) { cls += " CodeMirror-linebackground"; } 2267 if (lineView.background) { 2268 if (cls) { lineView.background.className = cls; } 2269 else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } 2270 } else if (cls) { 2271 var wrap = ensureLineWrapped(lineView); 2272 lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); 2273 cm.display.input.setUneditable(lineView.background); 2274 } 2275} 2276 2277// Wrapper around buildLineContent which will reuse the structure 2278// in display.externalMeasured when possible. 2279function getLineContent(cm, lineView) { 2280 var ext = cm.display.externalMeasured; 2281 if (ext && ext.line == lineView.line) { 2282 cm.display.externalMeasured = null; 2283 lineView.measure = ext.measure; 2284 return ext.built 2285 } 2286 return buildLineContent(cm, lineView) 2287} 2288 2289// Redraw the line's text. Interacts with the background and text 2290// classes because the mode may output tokens that influence these 2291// classes. 2292function updateLineText(cm, lineView) { 2293 var cls = lineView.text.className; 2294 var built = getLineContent(cm, lineView); 2295 if (lineView.text == lineView.node) { lineView.node = built.pre; } 2296 lineView.text.parentNode.replaceChild(built.pre, lineView.text); 2297 lineView.text = built.pre; 2298 if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { 2299 lineView.bgClass = built.bgClass; 2300 lineView.textClass = built.textClass; 2301 updateLineClasses(cm, lineView); 2302 } else if (cls) { 2303 lineView.text.className = cls; 2304 } 2305} 2306 2307function updateLineClasses(cm, lineView) { 2308 updateLineBackground(cm, lineView); 2309 if (lineView.line.wrapClass) 2310 { ensureLineWrapped(lineView).className = lineView.line.wrapClass; } 2311 else if (lineView.node != lineView.text) 2312 { lineView.node.className = ""; } 2313 var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; 2314 lineView.text.className = textClass || ""; 2315} 2316 2317function updateLineGutter(cm, lineView, lineN, dims) { 2318 if (lineView.gutter) { 2319 lineView.node.removeChild(lineView.gutter); 2320 lineView.gutter = null; 2321 } 2322 if (lineView.gutterBackground) { 2323 lineView.node.removeChild(lineView.gutterBackground); 2324 lineView.gutterBackground = null; 2325 } 2326 if (lineView.line.gutterClass) { 2327 var wrap = ensureLineWrapped(lineView); 2328 lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, 2329 ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px")); 2330 cm.display.input.setUneditable(lineView.gutterBackground); 2331 wrap.insertBefore(lineView.gutterBackground, lineView.text); 2332 } 2333 var markers = lineView.line.gutterMarkers; 2334 if (cm.options.lineNumbers || markers) { 2335 var wrap$1 = ensureLineWrapped(lineView); 2336 var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px")); 2337 cm.display.input.setUneditable(gutterWrap); 2338 wrap$1.insertBefore(gutterWrap, lineView.text); 2339 if (lineView.line.gutterClass) 2340 { gutterWrap.className += " " + lineView.line.gutterClass; } 2341 if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) 2342 { lineView.lineNumber = gutterWrap.appendChild( 2343 elt("div", lineNumberFor(cm.options, lineN), 2344 "CodeMirror-linenumber CodeMirror-gutter-elt", 2345 ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); } 2346 if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) { 2347 var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; 2348 if (found) 2349 { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", 2350 ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); } 2351 } } 2352 } 2353} 2354 2355function updateLineWidgets(cm, lineView, dims) { 2356 if (lineView.alignable) { lineView.alignable = null; } 2357 for (var node = lineView.node.firstChild, next = (void 0); node; node = next) { 2358 next = node.nextSibling; 2359 if (node.className == "CodeMirror-linewidget") 2360 { lineView.node.removeChild(node); } 2361 } 2362 insertLineWidgets(cm, lineView, dims); 2363} 2364 2365// Build a line's DOM representation from scratch 2366function buildLineElement(cm, lineView, lineN, dims) { 2367 var built = getLineContent(cm, lineView); 2368 lineView.text = lineView.node = built.pre; 2369 if (built.bgClass) { lineView.bgClass = built.bgClass; } 2370 if (built.textClass) { lineView.textClass = built.textClass; } 2371 2372 updateLineClasses(cm, lineView); 2373 updateLineGutter(cm, lineView, lineN, dims); 2374 insertLineWidgets(cm, lineView, dims); 2375 return lineView.node 2376} 2377 2378// A lineView may contain multiple logical lines (when merged by 2379// collapsed spans). The widgets for all of them need to be drawn. 2380function insertLineWidgets(cm, lineView, dims) { 2381 insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); 2382 if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) 2383 { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } } 2384} 2385 2386function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { 2387 if (!line.widgets) { return } 2388 var wrap = ensureLineWrapped(lineView); 2389 for (var i = 0, ws = line.widgets; i < ws.length; ++i) { 2390 var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); 2391 if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); } 2392 positionLineWidget(widget, node, lineView, dims); 2393 cm.display.input.setUneditable(node); 2394 if (allowAbove && widget.above) 2395 { wrap.insertBefore(node, lineView.gutter || lineView.text); } 2396 else 2397 { wrap.appendChild(node); } 2398 signalLater(widget, "redraw"); 2399 } 2400} 2401 2402function positionLineWidget(widget, node, lineView, dims) { 2403 if (widget.noHScroll) { 2404 (lineView.alignable || (lineView.alignable = [])).push(node); 2405 var width = dims.wrapperWidth; 2406 node.style.left = dims.fixedPos + "px"; 2407 if (!widget.coverGutter) { 2408 width -= dims.gutterTotalWidth; 2409 node.style.paddingLeft = dims.gutterTotalWidth + "px"; 2410 } 2411 node.style.width = width + "px"; 2412 } 2413 if (widget.coverGutter) { 2414 node.style.zIndex = 5; 2415 node.style.position = "relative"; 2416 if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; } 2417 } 2418} 2419 2420function widgetHeight(widget) { 2421 if (widget.height != null) { return widget.height } 2422 var cm = widget.doc.cm; 2423 if (!cm) { return 0 } 2424 if (!contains(document.body, widget.node)) { 2425 var parentStyle = "position: relative;"; 2426 if (widget.coverGutter) 2427 { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; } 2428 if (widget.noHScroll) 2429 { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; } 2430 removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); 2431 } 2432 return widget.height = widget.node.parentNode.offsetHeight 2433} 2434 2435// Return true when the given mouse event happened in a widget 2436function eventInWidget(display, e) { 2437 for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { 2438 if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || 2439 (n.parentNode == display.sizer && n != display.mover)) 2440 { return true } 2441 } 2442} 2443 2444// POSITION MEASUREMENT 2445 2446function paddingTop(display) {return display.lineSpace.offsetTop} 2447function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight} 2448function paddingH(display) { 2449 if (display.cachedPaddingH) { return display.cachedPaddingH } 2450 var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); 2451 var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; 2452 var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; 2453 if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; } 2454 return data 2455} 2456 2457function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth } 2458function displayWidth(cm) { 2459 return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth 2460} 2461function displayHeight(cm) { 2462 return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight 2463} 2464 2465// Ensure the lineView.wrapping.heights array is populated. This is 2466// an array of bottom offsets for the lines that make up a drawn 2467// line. When lineWrapping is on, there might be more than one 2468// height. 2469function ensureLineHeights(cm, lineView, rect) { 2470 var wrapping = cm.options.lineWrapping; 2471 var curWidth = wrapping && displayWidth(cm); 2472 if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { 2473 var heights = lineView.measure.heights = []; 2474 if (wrapping) { 2475 lineView.measure.width = curWidth; 2476 var rects = lineView.text.firstChild.getClientRects(); 2477 for (var i = 0; i < rects.length - 1; i++) { 2478 var cur = rects[i], next = rects[i + 1]; 2479 if (Math.abs(cur.bottom - next.bottom) > 2) 2480 { heights.push((cur.bottom + next.top) / 2 - rect.top); } 2481 } 2482 } 2483 heights.push(rect.bottom - rect.top); 2484 } 2485} 2486 2487// Find a line map (mapping character offsets to text nodes) and a 2488// measurement cache for the given line number. (A line view might 2489// contain multiple lines when collapsed ranges are present.) 2490function mapFromLineView(lineView, line, lineN) { 2491 if (lineView.line == line) 2492 { return {map: lineView.measure.map, cache: lineView.measure.cache} } 2493 for (var i = 0; i < lineView.rest.length; i++) 2494 { if (lineView.rest[i] == line) 2495 { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } } 2496 for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) 2497 { if (lineNo(lineView.rest[i$1]) > lineN) 2498 { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } } 2499} 2500 2501// Render a line into the hidden node display.externalMeasured. Used 2502// when measurement is needed for a line that's not in the viewport. 2503function updateExternalMeasurement(cm, line) { 2504 line = visualLine(line); 2505 var lineN = lineNo(line); 2506 var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); 2507 view.lineN = lineN; 2508 var built = view.built = buildLineContent(cm, view); 2509 view.text = built.pre; 2510 removeChildrenAndAdd(cm.display.lineMeasure, built.pre); 2511 return view 2512} 2513 2514// Get a {top, bottom, left, right} box (in line-local coordinates) 2515// for a given character. 2516function measureChar(cm, line, ch, bias) { 2517 return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias) 2518} 2519 2520// Find a line view that corresponds to the given line number. 2521function findViewForLine(cm, lineN) { 2522 if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) 2523 { return cm.display.view[findViewIndex(cm, lineN)] } 2524 var ext = cm.display.externalMeasured; 2525 if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) 2526 { return ext } 2527} 2528 2529// Measurement can be split in two steps, the set-up work that 2530// applies to the whole line, and the measurement of the actual 2531// character. Functions like coordsChar, that need to do a lot of 2532// measurements in a row, can thus ensure that the set-up work is 2533// only done once. 2534function prepareMeasureForLine(cm, line) { 2535 var lineN = lineNo(line); 2536 var view = findViewForLine(cm, lineN); 2537 if (view && !view.text) { 2538 view = null; 2539 } else if (view && view.changes) { 2540 updateLineForChanges(cm, view, lineN, getDimensions(cm)); 2541 cm.curOp.forceUpdate = true; 2542 } 2543 if (!view) 2544 { view = updateExternalMeasurement(cm, line); } 2545 2546 var info = mapFromLineView(view, line, lineN); 2547 return { 2548 line: line, view: view, rect: null, 2549 map: info.map, cache: info.cache, before: info.before, 2550 hasHeights: false 2551 } 2552} 2553 2554// Given a prepared measurement object, measures the position of an 2555// actual character (or fetches it from the cache). 2556function measureCharPrepared(cm, prepared, ch, bias, varHeight) { 2557 if (prepared.before) { ch = -1; } 2558 var key = ch + (bias || ""), found; 2559 if (prepared.cache.hasOwnProperty(key)) { 2560 found = prepared.cache[key]; 2561 } else { 2562 if (!prepared.rect) 2563 { prepared.rect = prepared.view.text.getBoundingClientRect(); } 2564 if (!prepared.hasHeights) { 2565 ensureLineHeights(cm, prepared.view, prepared.rect); 2566 prepared.hasHeights = true; 2567 } 2568 found = measureCharInner(cm, prepared, ch, bias); 2569 if (!found.bogus) { prepared.cache[key] = found; } 2570 } 2571 return {left: found.left, right: found.right, 2572 top: varHeight ? found.rtop : found.top, 2573 bottom: varHeight ? found.rbottom : found.bottom} 2574} 2575 2576var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; 2577 2578function nodeAndOffsetInLineMap(map$$1, ch, bias) { 2579 var node, start, end, collapse, mStart, mEnd; 2580 // First, search the line map for the text node corresponding to, 2581 // or closest to, the target character. 2582 for (var i = 0; i < map$$1.length; i += 3) { 2583 mStart = map$$1[i]; 2584 mEnd = map$$1[i + 1]; 2585 if (ch < mStart) { 2586 start = 0; end = 1; 2587 collapse = "left"; 2588 } else if (ch < mEnd) { 2589 start = ch - mStart; 2590 end = start + 1; 2591 } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) { 2592 end = mEnd - mStart; 2593 start = end - 1; 2594 if (ch >= mEnd) { collapse = "right"; } 2595 } 2596 if (start != null) { 2597 node = map$$1[i + 2]; 2598 if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) 2599 { collapse = bias; } 2600 if (bias == "left" && start == 0) 2601 { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) { 2602 node = map$$1[(i -= 3) + 2]; 2603 collapse = "left"; 2604 } } 2605 if (bias == "right" && start == mEnd - mStart) 2606 { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) { 2607 node = map$$1[(i += 3) + 2]; 2608 collapse = "right"; 2609 } } 2610 break 2611 } 2612 } 2613 return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd} 2614} 2615 2616function getUsefulRect(rects, bias) { 2617 var rect = nullRect; 2618 if (bias == "left") { for (var i = 0; i < rects.length; i++) { 2619 if ((rect = rects[i]).left != rect.right) { break } 2620 } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) { 2621 if ((rect = rects[i$1]).left != rect.right) { break } 2622 } } 2623 return rect 2624} 2625 2626function measureCharInner(cm, prepared, ch, bias) { 2627 var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); 2628 var node = place.node, start = place.start, end = place.end, collapse = place.collapse; 2629 2630 var rect; 2631 if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. 2632 for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned 2633 while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; } 2634 while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; } 2635 if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) 2636 { rect = node.parentNode.getBoundingClientRect(); } 2637 else 2638 { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); } 2639 if (rect.left || rect.right || start == 0) { break } 2640 end = start; 2641 start = start - 1; 2642 collapse = "right"; 2643 } 2644 if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); } 2645 } else { // If it is a widget, simply get the box for the whole widget. 2646 if (start > 0) { collapse = bias = "right"; } 2647 var rects; 2648 if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) 2649 { rect = rects[bias == "right" ? rects.length - 1 : 0]; } 2650 else 2651 { rect = node.getBoundingClientRect(); } 2652 } 2653 if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { 2654 var rSpan = node.parentNode.getClientRects()[0]; 2655 if (rSpan) 2656 { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; } 2657 else 2658 { rect = nullRect; } 2659 } 2660 2661 var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; 2662 var mid = (rtop + rbot) / 2; 2663 var heights = prepared.view.measure.heights; 2664 var i = 0; 2665 for (; i < heights.length - 1; i++) 2666 { if (mid < heights[i]) { break } } 2667 var top = i ? heights[i - 1] : 0, bot = heights[i]; 2668 var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, 2669 right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, 2670 top: top, bottom: bot}; 2671 if (!rect.left && !rect.right) { result.bogus = true; } 2672 if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } 2673 2674 return result 2675} 2676 2677// Work around problem with bounding client rects on ranges being 2678// returned incorrectly when zoomed on IE10 and below. 2679function maybeUpdateRectForZooming(measure, rect) { 2680 if (!window.screen || screen.logicalXDPI == null || 2681 screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) 2682 { return rect } 2683 var scaleX = screen.logicalXDPI / screen.deviceXDPI; 2684 var scaleY = screen.logicalYDPI / screen.deviceYDPI; 2685 return {left: rect.left * scaleX, right: rect.right * scaleX, 2686 top: rect.top * scaleY, bottom: rect.bottom * scaleY} 2687} 2688 2689function clearLineMeasurementCacheFor(lineView) { 2690 if (lineView.measure) { 2691 lineView.measure.cache = {}; 2692 lineView.measure.heights = null; 2693 if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) 2694 { lineView.measure.caches[i] = {}; } } 2695 } 2696} 2697 2698function clearLineMeasurementCache(cm) { 2699 cm.display.externalMeasure = null; 2700 removeChildren(cm.display.lineMeasure); 2701 for (var i = 0; i < cm.display.view.length; i++) 2702 { clearLineMeasurementCacheFor(cm.display.view[i]); } 2703} 2704 2705function clearCaches(cm) { 2706 clearLineMeasurementCache(cm); 2707 cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; 2708 if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; } 2709 cm.display.lineNumChars = null; 2710} 2711 2712function pageScrollX() { 2713 // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206 2714 // which causes page_Offset and bounding client rects to use 2715 // different reference viewports and invalidate our calculations. 2716 if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) } 2717 return window.pageXOffset || (document.documentElement || document.body).scrollLeft 2718} 2719function pageScrollY() { 2720 if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) } 2721 return window.pageYOffset || (document.documentElement || document.body).scrollTop 2722} 2723 2724// Converts a {top, bottom, left, right} box from line-local 2725// coordinates into another coordinate system. Context may be one of 2726// "line", "div" (display.lineDiv), "local"./null (editor), "window", 2727// or "page". 2728function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { 2729 if (!includeWidgets && lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) { 2730 var size = widgetHeight(lineObj.widgets[i]); 2731 rect.top += size; rect.bottom += size; 2732 } } } 2733 if (context == "line") { return rect } 2734 if (!context) { context = "local"; } 2735 var yOff = heightAtLine(lineObj); 2736 if (context == "local") { yOff += paddingTop(cm.display); } 2737 else { yOff -= cm.display.viewOffset; } 2738 if (context == "page" || context == "window") { 2739 var lOff = cm.display.lineSpace.getBoundingClientRect(); 2740 yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); 2741 var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); 2742 rect.left += xOff; rect.right += xOff; 2743 } 2744 rect.top += yOff; rect.bottom += yOff; 2745 return rect 2746} 2747 2748// Coverts a box from "div" coords to another coordinate system. 2749// Context may be "window", "page", "div", or "local"./null. 2750function fromCoordSystem(cm, coords, context) { 2751 if (context == "div") { return coords } 2752 var left = coords.left, top = coords.top; 2753 // First move into "page" coordinate system 2754 if (context == "page") { 2755 left -= pageScrollX(); 2756 top -= pageScrollY(); 2757 } else if (context == "local" || !context) { 2758 var localBox = cm.display.sizer.getBoundingClientRect(); 2759 left += localBox.left; 2760 top += localBox.top; 2761 } 2762 2763 var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); 2764 return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} 2765} 2766 2767function charCoords(cm, pos, context, lineObj, bias) { 2768 if (!lineObj) { lineObj = getLine(cm.doc, pos.line); } 2769 return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context) 2770} 2771 2772// Returns a box for a given cursor position, which may have an 2773// 'other' property containing the position of the secondary cursor 2774// on a bidi boundary. 2775// A cursor Pos(line, char, "before") is on the same visual line as `char - 1` 2776// and after `char - 1` in writing order of `char - 1` 2777// A cursor Pos(line, char, "after") is on the same visual line as `char` 2778// and before `char` in writing order of `char` 2779// Examples (upper-case letters are RTL, lower-case are LTR): 2780// Pos(0, 1, ...) 2781// before after 2782// ab a|b a|b 2783// aB a|B aB| 2784// Ab |Ab A|b 2785// AB B|A B|A 2786// Every position after the last character on a line is considered to stick 2787// to the last character on the line. 2788function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { 2789 lineObj = lineObj || getLine(cm.doc, pos.line); 2790 if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } 2791 function get(ch, right) { 2792 var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); 2793 if (right) { m.left = m.right; } else { m.right = m.left; } 2794 return intoCoordSystem(cm, lineObj, m, context) 2795 } 2796 var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky; 2797 if (ch >= lineObj.text.length) { 2798 ch = lineObj.text.length; 2799 sticky = "before"; 2800 } else if (ch <= 0) { 2801 ch = 0; 2802 sticky = "after"; 2803 } 2804 if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") } 2805 2806 function getBidi(ch, partPos, invert) { 2807 var part = order[partPos], right = (part.level % 2) != 0; 2808 return get(invert ? ch - 1 : ch, right != invert) 2809 } 2810 var partPos = getBidiPartAt(order, ch, sticky); 2811 var other = bidiOther; 2812 var val = getBidi(ch, partPos, sticky == "before"); 2813 if (other != null) { val.other = getBidi(ch, other, sticky != "before"); } 2814 return val 2815} 2816 2817// Used to cheaply estimate the coordinates for a position. Used for 2818// intermediate scroll updates. 2819function estimateCoords(cm, pos) { 2820 var left = 0; 2821 pos = clipPos(cm.doc, pos); 2822 if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; } 2823 var lineObj = getLine(cm.doc, pos.line); 2824 var top = heightAtLine(lineObj) + paddingTop(cm.display); 2825 return {left: left, right: left, top: top, bottom: top + lineObj.height} 2826} 2827 2828// Positions returned by coordsChar contain some extra information. 2829// xRel is the relative x position of the input coordinates compared 2830// to the found position (so xRel > 0 means the coordinates are to 2831// the right of the character position, for example). When outside 2832// is true, that means the coordinates lie outside the line's 2833// vertical range. 2834function PosWithInfo(line, ch, sticky, outside, xRel) { 2835 var pos = Pos(line, ch, sticky); 2836 pos.xRel = xRel; 2837 if (outside) { pos.outside = true; } 2838 return pos 2839} 2840 2841// Compute the character position closest to the given coordinates. 2842// Input must be lineSpace-local ("div" coordinate system). 2843function coordsChar(cm, x, y) { 2844 var doc = cm.doc;
2845 y += cm.display.viewOffset; 2846 if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) } 2847 var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; 2848 if (lineN > last) 2849 { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) } 2850 if (x < 0) { x = 0; } 2851 2852 var lineObj = getLine(doc, lineN); 2853 for (;;) { 2854 var found = coordsCharInner(cm, lineObj, lineN, x, y); 2855 var merged = collapsedSpanAtEnd(lineObj); 2856 var mergedPos = merged && merged.find(0, true); 2857 if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) 2858 { lineN = lineNo(lineObj = mergedPos.to.line); } 2859 else 2860 { return found } 2861 } 2862} 2863 2864function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { 2865 var measure = function (ch) { return intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line"); }; 2866 var end = lineObj.text.length; 2867 var begin = findFirst(function (ch) { return measure(ch - 1).bottom <= y; }, end, 0); 2868 end = findFirst(function (ch) { return measure(ch).top > y; }, begin, end); 2869 return {begin: begin, end: end} 2870} 2871 2872function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { 2873 var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; 2874 return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop) 2875} 2876 2877function coordsCharInner(cm, lineObj, lineNo$$1, x, y) { 2878 y -= heightAtLine(lineObj); 2879 var begin = 0, end = lineObj.text.length; 2880 var preparedMeasure = prepareMeasureForLine(cm, lineObj); 2881 var pos; 2882 var order = getOrder(lineObj, cm.doc.direction); 2883 if (order) { 2884 if (cm.options.lineWrapping) { 2885 var assign; 2886 ((assign = wrappedLineExtent(cm, lineObj, preparedMeasure, y), begin = assign.begin, end = assign.end)); 2887 } 2888 pos = new Pos(lineNo$$1, Math.floor(begin + (end - begin) / 2)); 2889 var beginLeft = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left; 2890 var dir = beginLeft < x ? 1 : -1; 2891 var prevDiff, diff = beginLeft - x, prevPos; 2892 var steps = Math.ceil((end - begin) / 4); 2893 outer: do { 2894 prevDiff = diff; 2895 prevPos = pos; 2896 var i = 0; 2897 for (; i < steps; ++i) { 2898 var prevPos$1 = pos; 2899 pos = moveVisually(cm, lineObj, pos, dir); 2900 if (pos == null || pos.ch < begin || end <= (pos.sticky == "before" ? pos.ch - 1 : pos.ch)) { 2901 pos = prevPos$1; 2902 break outer 2903 } 2904 } 2905 diff = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left - x; 2906 if (steps > 1) { 2907 var diff_change_per_step = Math.abs(diff - prevDiff) / steps; 2908 steps = Math.min(steps, Math.ceil(Math.abs(diff) / diff_change_per_step)); 2909 dir = diff < 0 ? 1 : -1; 2910 } 2911 } while (diff != 0 && (steps > 1 || ((dir < 0) != (diff < 0) && (Math.abs(diff) <= Math.abs(prevDiff))))) 2912 if (Math.abs(diff) > Math.abs(prevDiff)) { 2913 if ((diff < 0) == (prevDiff < 0)) { throw new Error("Broke out of infinite loop in coordsCharInner") } 2914 pos = prevPos; 2915 } 2916 } else { 2917 var ch = findFirst(function (ch) { 2918 var box = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line"); 2919 if (box.top > y) { 2920 // For the cursor stickiness 2921 end = Math.min(ch, end); 2922 return true 2923 } 2924 else if (box.bottom <= y) { return false } 2925 else if (box.left > x) { return true } 2926 else if (box.right < x) { return false } 2927 else { return (x - box.left < box.right - x) } 2928 }, begin, end); 2929 ch = skipExtendingChars(lineObj.text, ch, 1); 2930 pos = new Pos(lineNo$$1, ch, ch == end ? "before" : "after"); 2931 } 2932 var coords = cursorCoords(cm, pos, "line", lineObj, preparedMeasure); 2933 if (y < coords.top || coords.bottom < y) { pos.outside = true; } 2934 pos.xRel = x < coords.left ? -1 : (x > coords.right ? 1 : 0); 2935 return pos 2936} 2937 2938var measureText; 2939// Compute the default text height. 2940function textHeight(display) { 2941 if (display.cachedTextHeight != null) { return display.cachedTextHeight } 2942 if (measureText == null) { 2943 measureText = elt("pre"); 2944 // Measure a bunch of lines, for browsers that compute 2945 // fractional heights. 2946 for (var i = 0; i < 49; ++i) { 2947 measureText.appendChild(document.createTextNode("x")); 2948 measureText.appendChild(elt("br")); 2949 } 2950 measureText.appendChild(document.createTextNode("x")); 2951 } 2952 removeChildrenAndAdd(display.measure, measureText); 2953 var height = measureText.offsetHeight / 50; 2954 if (height > 3) { display.cachedTextHeight = height; } 2955 removeChildren(display.measure); 2956 return height || 1 2957} 2958 2959// Compute the default character width. 2960function charWidth(display) {
2961 if (display.cachedCharWidth != null) { return display.cachedCharWidth } 2962 var anchor = elt("span", "xxxxxxxxxx"); 2963 var pre = elt("pre", [anchor]); 2964 removeChildrenAndAdd(display.measure, pre); 2965 var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; 2966 if (width > 2) { display.cachedCharWidth = width; } 2967 return width || 10 2968} 2969 2970// Do a bulk-read of the DOM positions and sizes needed to draw the 2971// view, so that we don't interleave reading and writing to the DOM. 2972function getDimensions(cm) { 2973 var d = cm.display, left = {}, width = {}; 2974 var gutterLeft = d.gutters.clientLeft; 2975 for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { 2976 left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; 2977 width[cm.options.gutters[i]] = n.clientWidth; 2978 } 2979 return {fixedPos: compensateForHScroll(d), 2980 gutterTotalWidth: d.gutters.offsetWidth, 2981 gutterLeft: left, 2982 gutterWidth: width, 2983 wrapperWidth: d.wrapper.clientWidth} 2984} 2985 2986// Computes display.scroller.scrollLeft + display.gutters.offsetWidth, 2987// but using getBoundingClientRect to get a sub-pixel-accurate 2988// result. 2989function compensateForHScroll(display) {
vendor: 2,327 bytes, lines 2990-3046
2990 return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left 2991} 2992 2993// Returns a function that estimates the height of a line, to use as 2994// first approximation until the line becomes visible (and is thus 2995// properly measurable). 2996function estimateHeight(cm) { 2997 var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; 2998 var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); 2999 return function (line) { 3000 if (lineIsHidden(cm.doc, line)) { return 0 } 3001 3002 var widgetsHeight = 0; 3003 if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { 3004 if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; } 3005 } } 3006 3007 if (wrapping) 3008 { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th } 3009 else 3010 { return widgetsHeight + th } 3011 } 3012} 3013 3014function estimateLineHeights(cm) { 3015 var doc = cm.doc, est = estimateHeight(cm); 3016 doc.iter(function (line) { 3017 var estHeight = est(line); 3018 if (estHeight != line.height) { updateLineHeight(line, estHeight); } 3019 }); 3020} 3021 3022// Given a mouse event, find the corresponding position. If liberal 3023// is false, it checks whether a gutter or scrollbar was clicked, 3024// and returns null if it was. forRect is used by rectangular 3025// selections, and tries to estimate a character position even for 3026// coordinates beyond the right of the text. 3027function posFromMouse(cm, e, liberal, forRect) { 3028 var display = cm.display; 3029 if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null } 3030 3031 var x, y, space = display.lineSpace.getBoundingClientRect(); 3032 // Fails unpredictably on IE[67] when mouse is dragged around quickly. 3033 try { x = e.clientX - space.left; y = e.clientY - space.top; } 3034 catch (e) { return null } 3035 var coords = coordsChar(cm, x, y), line; 3036 if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { 3037 var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; 3038 coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); 3039 } 3040 return coords 3041} 3042 3043// Find the view element corresponding to a given line. Return null 3044// when the line isn't visible. 3045function findViewIndex(cm, n) { 3046 if (n >
3046= cm.display.viewTo) { return null } 3047 n -= cm.display.viewFrom; 3048 if (n < 0) { return null } 3049 var view = cm.display.view; 3050 for (var i = 0; i < view.length; i++) { 3051 n -= view[i].size; 3052 if (n < 0) { return i } 3053 } 3054} 3055 3056function updateSelection(cm) { 3057 cm.display.input.showSelection(cm.display.input.prepareSelection()); 3058} 3059 3060function prepareSelection(cm, primary) { 3061 var doc = cm.doc, result = {}; 3062 var curFragment = result.cursors = document.createDocumentFragment(); 3063 var selFragment = result.selection = document.createDocumentFragment(); 3064 3065 for (var i = 0; i < doc.sel.ranges.length; i++) { 3066 if (primary === false && i == doc.sel.primIndex) { continue } 3067 var range$$1 = doc.sel.ranges[i]; 3068 if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue } 3069 var collapsed = range$$1.empty(); 3070 if (collapsed || cm.options.showCursorWhenSelecting) 3071 { drawSelectionCursor(cm, range$$1.head, curFragment); } 3072 if (!collapsed) 3073 { drawSelectionRange(cm, range$$1, selFragment); } 3074 } 3075 return result 3076} 3077 3078// Draws a cursor for the given range 3079function drawSelectionCursor(cm, head, output) { 3080 var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); 3081 3082 var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); 3083 cursor.style.left = pos.left + "px"; 3084 cursor.style.top = pos.top + "px"; 3085 cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; 3086 3087 if (pos.other) { 3088 // Secondary cursor, shown when on a 'jump' in bi-directional text 3089 var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); 3090 otherCursor.style.display = ""; 3091 otherCursor.style.left = pos.other.left + "px"; 3092 otherCursor.style.top = pos.other.top + "px"; 3093 otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; 3094 } 3095} 3096 3097// Draws the given range as a highlighted selection 3098function drawSelectionRange(cm, range$$1, output) { 3099 var display = cm.display, doc = cm.doc; 3100 var fragment = document.createDocumentFragment(); 3101 var padding = paddingH(cm.display), leftSide = padding.left; 3102 var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; 3103 3104 function add(left, top, width, bottom) { 3105 if (top < 0) { top = 0; } 3106 top = Math.round(top); 3107 bottom = Math.round(bottom); 3108 fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px"))); 3109 } 3110 3111 function drawForLine(line, fromArg, toArg) { 3112 var lineObj = getLine(doc, line); 3113 var lineLen = lineObj.text.length; 3114 var start, end; 3115 function coords(ch, bias) { 3116 return charCoords(cm, Pos(line, ch), "div", lineObj, bias) 3117 } 3118 3119 iterateBidiSections(getOrder(lineObj, doc.direction), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) { 3120 var leftPos = coords(from, "left"), rightPos, left, right; 3121 if (from == to) { 3122 rightPos = leftPos; 3123 left = right = leftPos.left; 3124 } else { 3125 rightPos = coords(to - 1, "right"); 3126 if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } 3127 left = leftPos.left; 3128 right = rightPos.right; 3129 } 3130 if (fromArg == null && from == 0) { left = leftSide; } 3131 if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part 3132 add(left, leftPos.top, null, leftPos.bottom); 3133 left = leftSide; 3134 if (leftPos.bottom < rightPos.top) { add(left, leftPos.bottom, null, rightPos.top); } 3135 } 3136 if (toArg == null && to == lineLen) { right = rightSide; } 3137 if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) 3138 { start = leftPos; } 3139 if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) 3140 { end = rightPos; } 3141 if (left < leftSide + 1) { left = leftSide; } 3142 add(left, rightPos.top, right - left, rightPos.bottom); 3143 }); 3144 return {start: start, end: end} 3145 } 3146 3147 var sFrom = range$$1.from(), sTo = range$$1.to(); 3148 if (sFrom.line == sTo.line) { 3149 drawForLine(sFrom.line, sFrom.ch, sTo.ch); 3150 } else { 3151 var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
3152 var singleVLine = visualLine(fromLine) == visualLine(toLine); 3153 var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; 3154 var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; 3155 if (singleVLine) { 3156 if (leftEnd.top < rightStart.top - 2) { 3157 add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); 3158 add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); 3159 } else { 3160 add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); 3161 } 3162 } 3163 if (leftEnd.bottom < rightStart.top) 3164 { add(leftSide, leftEnd.bottom, null, rightStart.top); } 3165 } 3166 3167 output.appendChild(fragment); 3168} 3169 3170// Cursor-blinking 3171function restartBlink(cm) { 3172 if (!cm.state.focused) { return } 3173 var display = cm.display; 3174 clearInterval(display.blinker); 3175 var on = true; 3176 display.cursorDiv.style.visibility = ""; 3177 if (cm.options.cursorBlinkRate > 0) 3178 { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; }, 3179 cm.options.cursorBlinkRate); } 3180 else if (cm.options.cursorBlinkRate < 0) 3181 { display.cursorDiv.style.visibility = "hidden"; } 3182} 3183 3184function ensureFocus(cm) { 3185 if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } 3186} 3187 3188function delayBlurEvent(cm) { 3189 cm.state.delayingBlurEvent = true; 3190 setTimeout(function () { if (cm.state.delayingBlurEvent) { 3191 cm.state.delayingBlurEvent = false; 3192 onBlur(cm); 3193 } }, 100); 3194} 3195 3196function onFocus(cm, e) { 3197 if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; } 3198 3199 if (cm.options.readOnly == "nocursor") { return } 3200 if (!cm.state.focused) { 3201 signal(cm, "focus", cm, e); 3202 cm.state.focused = true; 3203 addClass(cm.display.wrapper, "CodeMirror-focused"); 3204 // This test prevents this from firing when a context 3205 // menu is closed (since the input reset would kill the 3206 // select-all detection hack) 3207 if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { 3208 cm.display.input.reset(); 3209 if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730 3210 } 3211 cm.display.input.receivedFocus(); 3212 } 3213 restartBlink(cm); 3214} 3215function onBlur(cm, e) { 3216 if (cm.state.delayingBlurEvent) { return } 3217 3218 if (cm.state.focused) { 3219 signal(cm, "blur", cm, e); 3220 cm.state.focused = false; 3221 rmClass(cm.display.wrapper, "CodeMirror-focused"); 3222 } 3223 clearInterval(cm.display.blinker); 3224 setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150); 3225} 3226 3227// Read the actual heights of the rendered lines, and update their 3228// stored heights to match. 3229function updateHeightsInViewport(cm) { 3230 var display = cm.display; 3231 var prevBottom = display.lineDiv.offsetTop; 3232 for (var i = 0; i < display.view.length; i++) { 3233 var cur = display.view[i], height = (void 0); 3234 if (cur.hidden) { continue } 3235 if (ie && ie_version < 8) { 3236 var bot = cur.node.offsetTop + cur.node.offsetHeight; 3237 height = bot - prevBottom; 3238 prevBottom = bot; 3239 } else { 3240 var box = cur.node.getBoundingClientRect(); 3241 height = box.bottom - box.top; 3242 } 3243 var diff = cur.line.height - height; 3244 if (height < 2) { height = textHeight(display); } 3245 if (diff > .001 || diff < -.001) { 3246 updateLineHeight(cur.line, height); 3247 updateWidgetHeight(cur.line); 3248 if (cur.rest) { for (var j = 0; j < cur.rest.length; j++) 3249 { updateWidgetHeight(cur.rest[j]); } } 3250 } 3251 } 3252} 3253 3254// Read and store the height of line widgets associated with the 3255// given line. 3256function updateWidgetHeight(line) { 3257 if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) 3258 { line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight; } } 3259} 3260 3261// Compute the lines that are visible in a given viewport (defaults 3262// the the current scroll position). viewport may contain top, 3263// height, and ensure (see op.scrollToPos) properties. 3264function visibleLines(display, doc, viewport) { 3265 var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; 3266 top = Math.floor(top - paddingTop(display)); 3267 var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; 3268 3269 var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); 3270 // Ensure is a {from: {line, ch}, to: {line, ch}} object, and 3271 // forces those lines into the viewport (if possible). 3272 if (viewport && viewport.ensure) { 3273 var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; 3274 if (ensureFrom < from) { 3275 from = ensureFrom; 3276 to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); 3277 }
vendor: 81,908 bytes, lines 3277-5422
3277 else if (Math.min(ensureTo, doc.lastLine()) >= to) { 3278 from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); 3279 to = ensureTo; 3280 } 3281 } 3282 return {from: from, to: Math.max(to, from + 1)} 3283} 3284 3285// Re-align line numbers and gutter marks to compensate for 3286// horizontal scrolling. 3287function alignHorizontally(cm) { 3288 var display = cm.display, view = display.view; 3289 if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return } 3290 var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; 3291 var gutterW = display.gutters.offsetWidth, left = comp + "px"; 3292 for (var i = 0; i < view.length; i++) { if (!view[i].hidden) { 3293 if (cm.options.fixedGutter) { 3294 if (view[i].gutter) 3295 { view[i].gutter.style.left = left; } 3296 if (view[i].gutterBackground) 3297 { view[i].gutterBackground.style.left = left; } 3298 } 3299 var align = view[i].alignable; 3300 if (align) { for (var j = 0; j < align.length; j++) 3301 { align[j].style.left = left; } } 3302 } } 3303 if (cm.options.fixedGutter) 3304 { display.gutters.style.left = (comp + gutterW) + "px"; } 3305} 3306 3307// Used to ensure that the line number gutter is still the right 3308// size for the current document size. Returns true when an update 3309// is needed. 3310function maybeUpdateLineNumberWidth(cm) { 3311 if (!cm.options.lineNumbers) { return false } 3312 var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; 3313 if (last.length != display.lineNumChars) { 3314 var test = display.measure.appendChild(elt("div", [elt("div", last)], 3315 "CodeMirror-linenumber CodeMirror-gutter-elt")); 3316 var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; 3317 display.lineGutter.style.width = ""; 3318 display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; 3319 display.lineNumWidth = display.lineNumInnerWidth + padding; 3320 display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; 3321 display.lineGutter.style.width = display.lineNumWidth + "px"; 3322 updateGutterSpace(cm); 3323 return true 3324 } 3325 return false 3326} 3327 3328// SCROLLING THINGS INTO VIEW 3329 3330// If an editor sits on the top or bottom of the window, partially 3331// scrolled out of view, this ensures that the cursor is visible. 3332function maybeScrollWindow(cm, rect) { 3333 if (signalDOMEvent(cm, "scrollCursorIntoView")) { return } 3334 3335 var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; 3336 if (rect.top + box.top < 0) { doScroll = true; } 3337 else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; } 3338 if (doScroll != null && !phantom) { 3339 var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;")); 3340 cm.display.lineSpace.appendChild(scrollNode); 3341 scrollNode.scrollIntoView(doScroll); 3342 cm.display.lineSpace.removeChild(scrollNode); 3343 } 3344} 3345 3346// Scroll a given position into view (immediately), verifying that 3347// it actually became visible (as line heights are accurately 3348// measured, the position of something may 'drift' during drawing). 3349function scrollPosIntoView(cm, pos, end, margin) { 3350 if (margin == null) { margin = 0; } 3351 var rect; 3352 for (var limit = 0; limit < 5; limit++) { 3353 var changed = false; 3354 var coords = cursorCoords(cm, pos); 3355 var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); 3356 rect = {left: Math.min(coords.left, endCoords.left), 3357 top: Math.min(coords.top, endCoords.top) - margin, 3358 right: Math.max(coords.left, endCoords.left), 3359 bottom: Math.max(coords.bottom, endCoords.bottom) + margin}; 3360 var scrollPos = calculateScrollPos(cm, rect); 3361 var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; 3362 if (scrollPos.scrollTop != null) { 3363 updateScrollTop(cm, scrollPos.scrollTop); 3364 if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; } 3365 } 3366 if (scrollPos.scrollLeft != null) { 3367 setScrollLeft(cm, scrollPos.scrollLeft); 3368 if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; } 3369 } 3370 if (!changed) { break } 3371 } 3372 return rect 3373} 3374 3375// Scroll a given set of coordinates into view (immediately). 3376function scrollIntoView(cm, rect) { 3377 var scrollPos = calculateScrollPos(cm, rect); 3378 if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); } 3379 if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); } 3380} 3381 3382// Calculate a new scroll position needed to scroll the given 3383// rectangle into view. Returns an object with scrollTop and 3384// scrollLeft properties. When these are undefined, the 3385// vertical/horizontal position does not need to be adjusted. 3386function calculateScrollPos(cm, rect) { 3387 var display = cm.display, snapMargin = textHeight(cm.display); 3388 if (rect.top < 0) { rect.top = 0; } 3389 var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; 3390 var screen = displayHeight(cm), result = {}; 3391 if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; } 3392 var docBottom = cm.doc.height + paddingVert(display); 3393 var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin; 3394 if (rect.top < screentop) { 3395 result.scrollTop = atTop ? 0 : rect.top; 3396 } else if (rect.bottom > screentop + screen) { 3397 var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen); 3398 if (newTop != screentop) { result.scrollTop = newTop; } 3399 } 3400 3401 var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; 3402 var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); 3403 var tooWide = rect.right - rect.left > screenw; 3404 if (tooWide) { rect.right = rect.left + screenw; } 3405 if (rect.left < 10) 3406 { result.scrollLeft = 0; } 3407 else if (rect.left < screenleft) 3408 { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); } 3409 else if (rect.right > screenw + screenleft - 3) 3410 { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; } 3411 return result 3412} 3413 3414// Store a relative adjustment to the scroll position in the current 3415// operation (to be applied when the operation finishes). 3416function addToScrollTop(cm, top) { 3417 if (top == null) { return } 3418 resolveScrollToPos(cm); 3419 cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; 3420} 3421 3422// Make sure that at the end of the operation the current cursor is 3423// shown. 3424function ensureCursorVisible(cm) { 3425 resolveScrollToPos(cm); 3426 var cur = cm.getCursor(), from = cur, to = cur; 3427 if (!cm.options.lineWrapping) { 3428 from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; 3429 to = Pos(cur.line, cur.ch + 1); 3430 } 3431 cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin}; 3432} 3433 3434function scrollToCoords(cm, x, y) { 3435 if (x != null || y != null) { resolveScrollToPos(cm); } 3436 if (x != null) { cm.curOp.scrollLeft = x; } 3437 if (y != null) { cm.curOp.scrollTop = y; } 3438} 3439 3440function scrollToRange(cm, range$$1) { 3441 resolveScrollToPos(cm); 3442 cm.curOp.scrollToPos = range$$1; 3443} 3444 3445// When an operation has its scrollToPos property set, and another 3446// scroll action is applied before the end of the operation, this 3447// 'simulates' scrolling that position into view in a cheap way, so 3448// that the effect of intermediate scroll commands is not ignored. 3449function resolveScrollToPos(cm) { 3450 var range$$1 = cm.curOp.scrollToPos; 3451 if (range$$1) { 3452 cm.curOp.scrollToPos = null; 3453 var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to); 3454 scrollToCoordsRange(cm, from, to, range$$1.margin); 3455 } 3456} 3457 3458function scrollToCoordsRange(cm, from, to, margin) { 3459 var sPos = calculateScrollPos(cm, { 3460 left: Math.min(from.left, to.left), 3461 top: Math.min(from.top, to.top) - margin, 3462 right: Math.max(from.right, to.right), 3463 bottom: Math.max(from.bottom, to.bottom) + margin 3464 }); 3465 scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); 3466} 3467 3468// Sync the scrollable area and scrollbars, ensure the viewport 3469// covers the visible area. 3470function updateScrollTop(cm, val) { 3471 if (Math.abs(cm.doc.scrollTop - val) < 2) { return } 3472 if (!gecko) { updateDisplaySimple(cm, {top: val}); } 3473 setScrollTop(cm, val, true); 3474 if (gecko) { updateDisplaySimple(cm); } 3475 startWorker(cm, 100); 3476} 3477 3478function setScrollTop(cm, val, forceScroll) { 3479 val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val); 3480 if (cm.display.scroller.scrollTop == val && !forceScroll) { return } 3481 cm.doc.scrollTop = val; 3482 cm.display.scrollbars.setScrollTop(val); 3483 if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; } 3484} 3485 3486// Sync scroller and scrollbar, ensure the gutter elements are 3487// aligned. 3488function setScrollLeft(cm, val, isScroller, forceScroll) { 3489 val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); 3490 if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return } 3491 cm.doc.scrollLeft = val; 3492 alignHorizontally(cm); 3493 if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; } 3494 cm.display.scrollbars.setScrollLeft(val); 3495} 3496 3497// SCROLLBARS 3498 3499// Prepare DOM reads needed to update the scrollbars. Done in one 3500// shot to minimize update/measure roundtrips. 3501function measureForScrollbars(cm) { 3502 var d = cm.display, gutterW = d.gutters.offsetWidth; 3503 var docH = Math.round(cm.doc.height + paddingVert(cm.display)); 3504 return { 3505 clientHeight: d.scroller.clientHeight, 3506 viewHeight: d.wrapper.clientHeight, 3507 scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, 3508 viewWidth: d.wrapper.clientWidth, 3509 barLeft: cm.options.fixedGutter ? gutterW : 0, 3510 docHeight: docH, 3511 scrollHeight: docH + scrollGap(cm) + d.barHeight, 3512 nativeBarWidth: d.nativeBarWidth, 3513 gutterWidth: gutterW 3514 } 3515} 3516 3517var NativeScrollbars = function(place, scroll, cm) { 3518 this.cm = cm; 3519 var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); 3520 var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); 3521 place(vert); place(horiz); 3522 3523 on(vert, "scroll", function () { 3524 if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); } 3525 }); 3526 on(horiz, "scroll", function () { 3527 if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); } 3528 }); 3529 3530 this.checkedZeroWidth = false; 3531 // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). 3532 if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; } 3533}; 3534 3535NativeScrollbars.prototype.update = function (measure) { 3536 var needsH = measure.scrollWidth > measure.clientWidth + 1; 3537 var needsV = measure.scrollHeight > measure.clientHeight + 1; 3538 var sWidth = measure.nativeBarWidth; 3539 3540 if (needsV) { 3541 this.vert.style.display = "block"; 3542 this.vert.style.bottom = needsH ? sWidth + "px" : "0"; 3543 var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); 3544 // A bug in IE8 can cause this value to be negative, so guard it. 3545 this.vert.firstChild.style.height = 3546 Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; 3547 } else { 3548 this.vert.style.display = ""; 3549 this.vert.firstChild.style.height = "0"; 3550 } 3551 3552 if (needsH) { 3553 this.horiz.style.display = "block"; 3554 this.horiz.style.right = needsV ? sWidth + "px" : "0"; 3555 this.horiz.style.left = measure.barLeft + "px"; 3556 var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); 3557 this.horiz.firstChild.style.width = 3558 Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; 3559 } else { 3560 this.horiz.style.display = ""; 3561 this.horiz.firstChild.style.width = "0"; 3562 } 3563 3564 if (!this.checkedZeroWidth && measure.clientHeight > 0) { 3565 if (sWidth == 0) { this.zeroWidthHack(); } 3566 this.checkedZeroWidth = true; 3567 } 3568 3569 return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} 3570}; 3571 3572NativeScrollbars.prototype.setScrollLeft = function (pos) { 3573 if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; } 3574 if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); } 3575}; 3576 3577NativeScrollbars.prototype.setScrollTop = function (pos) { 3578 if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; } 3579 if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); } 3580}; 3581 3582NativeScrollbars.prototype.zeroWidthHack = function () { 3583 var w = mac && !mac_geMountainLion ? "12px" : "18px"; 3584 this.horiz.style.height = this.vert.style.width = w; 3585 this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; 3586 this.disableHoriz = new Delayed; 3587 this.disableVert = new Delayed; 3588}; 3589 3590NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { 3591 bar.style.pointerEvents = "auto"; 3592 function maybeDisable() { 3593 // To find out whether the scrollbar is still visible, we 3594 // check whether the element under the pixel in the bottom 3595 // right corner of the scrollbar box is the scrollbar box 3596 // itself (when the bar is still visible) or its filler child 3597 // (when the bar is hidden). If it is still visible, we keep 3598 // it enabled, if it's hidden, we disable pointer events. 3599 var box = bar.getBoundingClientRect(); 3600 var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) 3601 : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); 3602 if (elt$$1 != bar) { bar.style.pointerEvents = "none"; } 3603 else { delay.set(1000, maybeDisable); } 3604 } 3605 delay.set(1000, maybeDisable); 3606}; 3607 3608NativeScrollbars.prototype.clear = function () { 3609 var parent = this.horiz.parentNode; 3610 parent.removeChild(this.horiz); 3611 parent.removeChild(this.vert); 3612}; 3613 3614var NullScrollbars = function () {}; 3615 3616NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} }; 3617NullScrollbars.prototype.setScrollLeft = function () {}; 3618NullScrollbars.prototype.setScrollTop = function () {}; 3619NullScrollbars.prototype.clear = function () {}; 3620 3621function updateScrollbars(cm, measure) { 3622 if (!measure) { measure = measureForScrollbars(cm); } 3623 var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; 3624 updateScrollbarsInner(cm, measure); 3625 for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { 3626 if (startWidth != cm.display.barWidth && cm.options.lineWrapping) 3627 { updateHeightsInViewport(cm); } 3628 updateScrollbarsInner(cm, measureForScrollbars(cm)); 3629 startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; 3630 } 3631} 3632 3633// Re-synchronize the fake scrollbars with the actual size of the 3634// content. 3635function updateScrollbarsInner(cm, measure) { 3636 var d = cm.display; 3637 var sizes = d.scrollbars.update(measure); 3638 3639 d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; 3640 d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; 3641 d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; 3642 3643 if (sizes.right && sizes.bottom) { 3644 d.scrollbarFiller.style.display = "block"; 3645 d.scrollbarFiller.style.height = sizes.bottom + "px"; 3646 d.scrollbarFiller.style.width = sizes.right + "px"; 3647 } else { d.scrollbarFiller.style.display = ""; } 3648 if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { 3649 d.gutterFiller.style.display = "block"; 3650 d.gutterFiller.style.height = sizes.bottom + "px"; 3651 d.gutterFiller.style.width = measure.gutterWidth + "px"; 3652 } else { d.gutterFiller.style.display = ""; } 3653} 3654 3655var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; 3656 3657function initScrollbars(cm) { 3658 if (cm.display.scrollbars) { 3659 cm.display.scrollbars.clear(); 3660 if (cm.display.scrollbars.addClass) 3661 { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); } 3662 } 3663 3664 cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { 3665 cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); 3666 // Prevent clicks in the scrollbars from killing focus 3667 on(node, "mousedown", function () { 3668 if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); } 3669 }); 3670 node.setAttribute("cm-not-content", "true"); 3671 }, function (pos, axis) { 3672 if (axis == "horizontal") { setScrollLeft(cm, pos); } 3673 else { updateScrollTop(cm, pos); } 3674 }, cm); 3675 if (cm.display.scrollbars.addClass) 3676 { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); } 3677} 3678 3679// Operations are used to wrap a series of changes to the editor 3680// state in such a way that each change won't have to update the 3681// cursor and display (which would be awkward, slow, and 3682// error-prone). Instead, display updates are batched and then all 3683// combined and executed at once. 3684 3685var nextOpId = 0; 3686// Start a new operation. 3687function startOperation(cm) { 3688 cm.curOp = { 3689 cm: cm, 3690 viewChanged: false, // Flag that indicates that lines might need to be redrawn 3691 startHeight: cm.doc.height, // Used to detect need to update scrollbar 3692 forceUpdate: false, // Used to force a redraw 3693 updateInput: null, // Whether to reset the input textarea 3694 typing: false, // Whether this reset should be careful to leave existing text (for compositing) 3695 changeObjs: null, // Accumulated changes, for firing change events 3696 cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on 3697 cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already 3698 selectionChanged: false, // Whether the selection needs to be redrawn 3699 updateMaxLine: false, // Set when the widest line needs to be determined anew 3700 scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet 3701 scrollToPos: null, // Used to scroll to a specific position 3702 focus: false, 3703 id: ++nextOpId // Unique ID 3704 }; 3705 pushOperation(cm.curOp); 3706} 3707 3708// Finish an operation, updating the display and signalling delayed events 3709function endOperation(cm) { 3710 var op = cm.curOp; 3711 finishOperation(op, function (group) { 3712 for (var i = 0; i < group.ops.length; i++) 3713 { group.ops[i].cm.curOp = null; } 3714 endOperations(group); 3715 }); 3716} 3717 3718// The DOM updates done when an operation finishes are batched so 3719// that the minimum number of relayouts are required. 3720function endOperations(group) { 3721 var ops = group.ops; 3722 for (var i = 0; i < ops.length; i++) // Read DOM 3723 { endOperation_R1(ops[i]); } 3724 for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe) 3725 { endOperation_W1(ops[i$1]); } 3726 for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM 3727 { endOperation_R2(ops[i$2]); } 3728 for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe) 3729 { endOperation_W2(ops[i$3]); } 3730 for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM 3731 { endOperation_finish(ops[i$4]); } 3732} 3733 3734function endOperation_R1(op) { 3735 var cm = op.cm, display = cm.display; 3736 maybeClipScrollbars(cm); 3737 if (op.updateMaxLine) { findMaxLine(cm); } 3738 3739 op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || 3740 op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || 3741 op.scrollToPos.to.line >= display.viewTo) || 3742 display.maxLineChanged && cm.options.lineWrapping; 3743 op.update = op.mustUpdate && 3744 new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); 3745} 3746 3747function endOperation_W1(op) { 3748 op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); 3749} 3750 3751function endOperation_R2(op) { 3752 var cm = op.cm, display = cm.display; 3753 if (op.updatedDisplay) { updateHeightsInViewport(cm); } 3754 3755 op.barMeasure = measureForScrollbars(cm); 3756 3757 // If the max line changed since it was last measured, measure it, 3758 // and ensure the document's width matches it. 3759 // updateDisplay_W2 will use these properties to do the actual resizing 3760 if (display.maxLineChanged && !cm.options.lineWrapping) { 3761 op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; 3762 cm.display.sizerWidth = op.adjustWidthTo; 3763 op.barMeasure.scrollWidth = 3764 Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); 3765 op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); 3766 } 3767 3768 if (op.updatedDisplay || op.selectionChanged) 3769 { op.preparedSelection = display.input.prepareSelection(op.focus); } 3770} 3771 3772function endOperation_W2(op) { 3773 var cm = op.cm; 3774 3775 if (op.adjustWidthTo != null) { 3776 cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; 3777 if (op.maxScrollLeft < cm.doc.scrollLeft) 3778 { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); } 3779 cm.display.maxLineChanged = false; 3780 } 3781 3782 var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus()); 3783 if (op.preparedSelection) 3784 { cm.display.input.showSelection(op.preparedSelection, takeFocus); } 3785 if (op.updatedDisplay || op.startHeight != cm.doc.height) 3786 { updateScrollbars(cm, op.barMeasure); } 3787 if (op.updatedDisplay) 3788 { setDocumentHeight(cm, op.barMeasure); } 3789 3790 if (op.selectionChanged) { restartBlink(cm); } 3791 3792 if (cm.state.focused && op.updateInput) 3793 { cm.display.input.reset(op.typing); } 3794 if (takeFocus) { ensureFocus(op.cm); } 3795} 3796 3797function endOperation_finish(op) { 3798 var cm = op.cm, display = cm.display, doc = cm.doc; 3799 3800 if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); } 3801 3802 // Abort mouse wheel delta measurement, when scrolling explicitly 3803 if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) 3804 { display.wheelStartX = display.wheelStartY = null; } 3805 3806 // Propagate the scroll position to the actual DOM scroller 3807 if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); } 3808 3809 if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); } 3810 // If we need to scroll a specific position into view, do so. 3811 if (op.scrollToPos) { 3812 var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), 3813 clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); 3814 maybeScrollWindow(cm, rect); 3815 } 3816 3817 // Fire events for markers that are hidden/unidden by editing or 3818 // undoing 3819 var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; 3820 if (hidden) { for (var i = 0; i < hidden.length; ++i) 3821 { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } } 3822 if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1) 3823 { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } } 3824 3825 if (display.wrapper.offsetHeight) 3826 { doc.scrollTop = cm.display.scroller.scrollTop; } 3827 3828 // Fire change events, and delayed event handlers 3829 if (op.changeObjs) 3830 { signal(cm, "changes", cm, op.changeObjs); } 3831 if (op.update) 3832 { op.update.finish(); } 3833} 3834 3835// Run the given function in an operation 3836function runInOp(cm, f) { 3837 if (cm.curOp) { return f() } 3838 startOperation(cm); 3839 try { return f() } 3840 finally { endOperation(cm); } 3841} 3842// Wraps a function in an operation. Returns the wrapped function. 3843function operation(cm, f) { 3844 return function() { 3845 if (cm.curOp) { return f.apply(cm, arguments) } 3846 startOperation(cm); 3847 try { return f.apply(cm, arguments) } 3848 finally { endOperation(cm); } 3849 } 3850} 3851// Used to add methods to editor and doc instances, wrapping them in 3852// operations. 3853function methodOp(f) { 3854 return function() { 3855 if (this.curOp) { return f.apply(this, arguments) } 3856 startOperation(this); 3857 try { return f.apply(this, arguments) } 3858 finally { endOperation(this); } 3859 } 3860} 3861function docMethodOp(f) { 3862 return function() { 3863 var cm = this.cm; 3864 if (!cm || cm.curOp) { return f.apply(this, arguments) } 3865 startOperation(cm); 3866 try { return f.apply(this, arguments) } 3867 finally { endOperation(cm); } 3868 } 3869} 3870 3871// Updates the display.view data structure for a given change to the 3872// document. From and to are in pre-change coordinates. Lendiff is 3873// the amount of lines added or subtracted by the change. This is 3874// used for changes that span multiple lines, or change the way 3875// lines are divided into visual lines. regLineChange (below) 3876// registers single-line changes. 3877function regChange(cm, from, to, lendiff) { 3878 if (from == null) { from = cm.doc.first; } 3879 if (to == null) { to = cm.doc.first + cm.doc.size; } 3880 if (!lendiff) { lendiff = 0; } 3881 3882 var display = cm.display; 3883 if (lendiff && to < display.viewTo && 3884 (display.updateLineNumbers == null || display.updateLineNumbers > from)) 3885 { display.updateLineNumbers = from; } 3886 3887 cm.curOp.viewChanged = true; 3888 3889 if (from >= display.viewTo) { // Change after 3890 if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) 3891 { resetView(cm); } 3892 } else if (to <= display.viewFrom) { // Change before 3893 if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { 3894 resetView(cm); 3895 } else { 3896 display.viewFrom += lendiff; 3897 display.viewTo += lendiff; 3898 } 3899 } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap 3900 resetView(cm); 3901 } else if (from <= display.viewFrom) { // Top overlap 3902 var cut = viewCuttingPoint(cm, to, to + lendiff, 1); 3903 if (cut) { 3904 display.view = display.view.slice(cut.index); 3905 display.viewFrom = cut.lineN; 3906 display.viewTo += lendiff; 3907 } else { 3908 resetView(cm); 3909 } 3910 } else if (to >= display.viewTo) { // Bottom overlap 3911 var cut$1 = viewCuttingPoint(cm, from, from, -1); 3912 if (cut$1) { 3913 display.view = display.view.slice(0, cut$1.index); 3914 display.viewTo = cut$1.lineN; 3915 } else { 3916 resetView(cm); 3917 } 3918 } else { // Gap in the middle 3919 var cutTop = viewCuttingPoint(cm, from, from, -1); 3920 var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); 3921 if (cutTop && cutBot) { 3922 display.view = display.view.slice(0, cutTop.index) 3923 .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) 3924 .concat(display.view.slice(cutBot.index)); 3925 display.viewTo += lendiff; 3926 } else { 3927 resetView(cm); 3928 } 3929 } 3930 3931 var ext = display.externalMeasured; 3932 if (ext) { 3933 if (to < ext.lineN) 3934 { ext.lineN += lendiff; } 3935 else if (from < ext.lineN + ext.size) 3936 { display.externalMeasured = null; } 3937 } 3938} 3939 3940// Register a change to a single line. Type must be one of "text", 3941// "gutter", "class", "widget" 3942function regLineChange(cm, line, type) { 3943 cm.curOp.viewChanged = true; 3944 var display = cm.display, ext = cm.display.externalMeasured; 3945 if (ext && line >= ext.lineN && line < ext.lineN + ext.size) 3946 { display.externalMeasured = null; } 3947 3948 if (line < display.viewFrom || line >= display.viewTo) { return } 3949 var lineView = display.view[findViewIndex(cm, line)]; 3950 if (lineView.node == null) { return } 3951 var arr = lineView.changes || (lineView.changes = []); 3952 if (indexOf(arr, type) == -1) { arr.push(type); } 3953} 3954 3955// Clear the view. 3956function resetView(cm) { 3957 cm.display.viewFrom = cm.display.viewTo = cm.doc.first; 3958 cm.display.view = []; 3959 cm.display.viewOffset = 0; 3960} 3961 3962function viewCuttingPoint(cm, oldN, newN, dir) { 3963 var index = findViewIndex(cm, oldN), diff, view = cm.display.view; 3964 if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) 3965 { return {index: index, lineN: newN} } 3966 var n = cm.display.viewFrom; 3967 for (var i = 0; i < index; i++) 3968 { n += view[i].size; } 3969 if (n != oldN) { 3970 if (dir > 0) { 3971 if (index == view.length - 1) { return null } 3972 diff = (n + view[index].size) - oldN; 3973 index++; 3974 } else { 3975 diff = n - oldN; 3976 } 3977 oldN += diff; newN += diff; 3978 } 3979 while (visualLineNo(cm.doc, newN) != newN) { 3980 if (index == (dir < 0 ? 0 : view.length - 1)) { return null } 3981 newN += dir * view[index - (dir < 0 ? 1 : 0)].size; 3982 index += dir; 3983 } 3984 return {index: index, lineN: newN} 3985} 3986 3987// Force the view to cover a given range, adding empty view element 3988// or clipping off existing ones as needed. 3989function adjustView(cm, from, to) { 3990 var display = cm.display, view = display.view; 3991 if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { 3992 display.view = buildViewArray(cm, from, to); 3993 display.viewFrom = from; 3994 } else { 3995 if (display.viewFrom > from) 3996 { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); } 3997 else if (display.viewFrom < from) 3998 { display.view = display.view.slice(findViewIndex(cm, from)); } 3999 display.viewFrom = from; 4000 if (display.viewTo < to) 4001 { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); } 4002 else if (display.viewTo > to) 4003 { display.view = display.view.slice(0, findViewIndex(cm, to)); } 4004 } 4005 display.viewTo = to; 4006} 4007 4008// Count the number of lines in the view whose DOM representation is 4009// out of date (or nonexistent). 4010function countDirtyView(cm) { 4011 var view = cm.display.view, dirty = 0; 4012 for (var i = 0; i < view.length; i++) { 4013 var lineView = view[i]; 4014 if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; } 4015 } 4016 return dirty 4017} 4018 4019// HIGHLIGHT WORKER 4020 4021function startWorker(cm, time) { 4022 if (cm.doc.highlightFrontier < cm.display.viewTo) 4023 { cm.state.highlight.set(time, bind(highlightWorker, cm)); } 4024} 4025 4026function highlightWorker(cm) { 4027 var doc = cm.doc; 4028 if (doc.highlightFrontier >= cm.display.viewTo) { return } 4029 var end = +new Date + cm.options.workTime; 4030 var context = getContextBefore(cm, doc.highlightFrontier); 4031 var changedLines = []; 4032 4033 doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { 4034 if (context.line >= cm.display.viewFrom) { // Visible 4035 var oldStyles = line.styles; 4036 var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null; 4037 var highlighted = highlightLine(cm, line, context, true); 4038 if (resetState) { context.state = resetState; } 4039 line.styles = highlighted.styles; 4040 var oldCls = line.styleClasses, newCls = highlighted.classes; 4041 if (newCls) { line.styleClasses = newCls; } 4042 else if (oldCls) { line.styleClasses = null; } 4043 var ischange = !oldStyles || oldStyles.length != line.styles.length || 4044 oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); 4045 for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; } 4046 if (ischange) { changedLines.push(context.line); } 4047 line.stateAfter = context.save(); 4048 context.nextLine(); 4049 } else { 4050 if (line.text.length <= cm.options.maxHighlightLength) 4051 { processLine(cm, line.text, context); } 4052 line.stateAfter = context.line % 5 == 0 ? context.save() : null; 4053 context.nextLine(); 4054 } 4055 if (+new Date > end) { 4056 startWorker(cm, cm.options.workDelay); 4057 return true 4058 } 4059 }); 4060 doc.highlightFrontier = context.line; 4061 doc.modeFrontier = Math.max(doc.modeFrontier, context.line); 4062 if (changedLines.length) { runInOp(cm, function () { 4063 for (var i = 0; i < changedLines.length; i++) 4064 { regLineChange(cm, changedLines[i], "text"); } 4065 }); } 4066} 4067 4068// DISPLAY DRAWING 4069 4070var DisplayUpdate = function(cm, viewport, force) { 4071 var display = cm.display; 4072 4073 this.viewport = viewport; 4074 // Store some values that we'll need later (but don't want to force a relayout for) 4075 this.visible = visibleLines(display, cm.doc, viewport); 4076 this.editorIsHidden = !display.wrapper.offsetWidth; 4077 this.wrapperHeight = display.wrapper.clientHeight; 4078 this.wrapperWidth = display.wrapper.clientWidth; 4079 this.oldDisplayWidth = displayWidth(cm); 4080 this.force = force; 4081 this.dims = getDimensions(cm); 4082 this.events = []; 4083}; 4084 4085DisplayUpdate.prototype.signal = function (emitter, type) { 4086 if (hasHandler(emitter, type)) 4087 { this.events.push(arguments); } 4088}; 4089DisplayUpdate.prototype.finish = function () { 4090 var this$1 = this; 4091 4092 for (var i = 0; i < this.events.length; i++) 4093 { signal.apply(null, this$1.events[i]); } 4094}; 4095 4096function maybeClipScrollbars(cm) { 4097 var display = cm.display; 4098 if (!display.scrollbarsClipped && display.scroller.offsetWidth) { 4099 display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; 4100 display.heightForcer.style.height = scrollGap(cm) + "px"; 4101 display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; 4102 display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; 4103 display.scrollbarsClipped = true; 4104 } 4105} 4106 4107function selectionSnapshot(cm) { 4108 if (cm.hasFocus()) { return null } 4109 var active = activeElt(); 4110 if (!active || !contains(cm.display.lineDiv, active)) { return null } 4111 var result = {activeElt: active}; 4112 if (window.getSelection) { 4113 var sel = window.getSelection(); 4114 if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { 4115 result.anchorNode = sel.anchorNode; 4116 result.anchorOffset = sel.anchorOffset; 4117 result.focusNode = sel.focusNode; 4118 result.focusOffset = sel.focusOffset; 4119 } 4120 } 4121 return result 4122} 4123 4124function restoreSelection(snapshot) { 4125 if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return } 4126 snapshot.activeElt.focus(); 4127 if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { 4128 var sel = window.getSelection(), range$$1 = document.createRange(); 4129 range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset); 4130 range$$1.collapse(false); 4131 sel.removeAllRanges(); 4132 sel.addRange(range$$1); 4133 sel.extend(snapshot.focusNode, snapshot.focusOffset); 4134 } 4135} 4136 4137// Does the actual updating of the line display. Bails out 4138// (returning false) when there is nothing to be done and forced is 4139// false. 4140function updateDisplayIfNeeded(cm, update) { 4141 var display = cm.display, doc = cm.doc; 4142 4143 if (update.editorIsHidden) { 4144 resetView(cm); 4145 return false 4146 } 4147 4148 // Bail out if the visible area is already rendered and nothing changed. 4149 if (!update.force && 4150 update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && 4151 (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && 4152 display.renderedView == display.view && countDirtyView(cm) == 0) 4153 { return false } 4154 4155 if (maybeUpdateLineNumberWidth(cm)) { 4156 resetView(cm); 4157 update.dims = getDimensions(cm); 4158 } 4159 4160 // Compute a suitable new viewport (from & to) 4161 var end = doc.first + doc.size; 4162 var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); 4163 var to = Math.min(end, update.visible.to + cm.options.viewportMargin); 4164 if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); } 4165 if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); } 4166 if (sawCollapsedSpans) { 4167 from = visualLineNo(cm.doc, from); 4168 to = visualLineEndNo(cm.doc, to); 4169 } 4170 4171 var different = from != display.viewFrom || to != display.viewTo || 4172 display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; 4173 adjustView(cm, from, to); 4174 4175 display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); 4176 // Position the mover div to align with the current scroll position 4177 cm.display.mover.style.top = display.viewOffset + "px"; 4178 4179 var toUpdate = countDirtyView(cm); 4180 if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && 4181 (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) 4182 { return false } 4183 4184 // For big changes, we hide the enclosing element during the 4185 // update, since that speeds up the operations on most browsers. 4186 var selSnapshot = selectionSnapshot(cm); 4187 if (toUpdate > 4) { display.lineDiv.style.display = "none"; } 4188 patchDisplay(cm, display.updateLineNumbers, update.dims); 4189 if (toUpdate > 4) { display.lineDiv.style.display = ""; } 4190 display.renderedView = display.view; 4191 // There might have been a widget with a focused element that got 4192 // hidden or updated, if so re-focus it. 4193 restoreSelection(selSnapshot); 4194 4195 // Prevent selection and cursors from interfering with the scroll 4196 // width and height. 4197 removeChildren(display.cursorDiv); 4198 removeChildren(display.selectionDiv); 4199 display.gutters.style.height = display.sizer.style.minHeight = 0; 4200 4201 if (different) { 4202 display.lastWrapHeight = update.wrapperHeight; 4203 display.lastWrapWidth = update.wrapperWidth; 4204 startWorker(cm, 400); 4205 } 4206 4207 display.updateLineNumbers = null; 4208 4209 return true 4210} 4211 4212function postUpdateDisplay(cm, update) { 4213 var viewport = update.viewport; 4214 4215 for (var first = true;; first = false) { 4216 if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { 4217 // Clip forced viewport to actual scrollable area. 4218 if (viewport && viewport.top != null) 4219 { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; } 4220 // Updated line heights might result in the drawn area not 4221 // actually covering the viewport. Keep looping until it does. 4222 update.visible = visibleLines(cm.display, cm.doc, viewport); 4223 if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) 4224 { break } 4225 } 4226 if (!updateDisplayIfNeeded(cm, update)) { break } 4227 updateHeightsInViewport(cm); 4228 var barMeasure = measureForScrollbars(cm); 4229 updateSelection(cm); 4230 updateScrollbars(cm, barMeasure); 4231 setDocumentHeight(cm, barMeasure); 4232 update.force = false; 4233 } 4234 4235 update.signal(cm, "update", cm); 4236 if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { 4237 update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); 4238 cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; 4239 } 4240} 4241 4242function updateDisplaySimple(cm, viewport) { 4243 var update = new DisplayUpdate(cm, viewport); 4244 if (updateDisplayIfNeeded(cm, update)) { 4245 updateHeightsInViewport(cm); 4246 postUpdateDisplay(cm, update); 4247 var barMeasure = measureForScrollbars(cm); 4248 updateSelection(cm); 4249 updateScrollbars(cm, barMeasure); 4250 setDocumentHeight(cm, barMeasure); 4251 update.finish(); 4252 } 4253} 4254 4255// Sync the actual display DOM structure with display.view, removing 4256// nodes for lines that are no longer in view, and creating the ones 4257// that are not there yet, and updating the ones that are out of 4258// date. 4259function patchDisplay(cm, updateNumbersFrom, dims) { 4260 var display = cm.display, lineNumbers = cm.options.lineNumbers; 4261 var container = display.lineDiv, cur = container.firstChild; 4262 4263 function rm(node) { 4264 var next = node.nextSibling; 4265 // Works around a throw-scroll bug in OS X Webkit 4266 if (webkit && mac && cm.display.currentWheelTarget == node) 4267 { node.style.display = "none"; } 4268 else 4269 { node.parentNode.removeChild(node); } 4270 return next 4271 } 4272 4273 var view = display.view, lineN = display.viewFrom; 4274 // Loop over the elements in the view, syncing cur (the DOM nodes 4275 // in display.lineDiv) with the view as we go. 4276 for (var i = 0; i < view.length; i++) { 4277 var lineView = view[i]; 4278 if (lineView.hidden) { 4279 } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet 4280 var node = buildLineElement(cm, lineView, lineN, dims); 4281 container.insertBefore(node, cur); 4282 } else { // Already drawn 4283 while (cur != lineView.node) { cur = rm(cur); } 4284 var updateNumber = lineNumbers && updateNumbersFrom != null && 4285 updateNumbersFrom <= lineN && lineView.lineNumber; 4286 if (lineView.changes) { 4287 if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; } 4288 updateLineForChanges(cm, lineView, lineN, dims); 4289 } 4290 if (updateNumber) { 4291 removeChildren(lineView.lineNumber); 4292 lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); 4293 } 4294 cur = lineView.node.nextSibling; 4295 } 4296 lineN += lineView.size; 4297 } 4298 while (cur) { cur = rm(cur); } 4299} 4300 4301function updateGutterSpace(cm) { 4302 var width = cm.display.gutters.offsetWidth; 4303 cm.display.sizer.style.marginLeft = width + "px"; 4304} 4305 4306function setDocumentHeight(cm, measure) { 4307 cm.display.sizer.style.minHeight = measure.docHeight + "px"; 4308 cm.display.heightForcer.style.top = measure.docHeight + "px"; 4309 cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"; 4310} 4311 4312// Rebuild the gutter elements, ensure the margin to the left of the 4313// code matches their width. 4314function updateGutters(cm) { 4315 var gutters = cm.display.gutters, specs = cm.options.gutters; 4316 removeChildren(gutters); 4317 var i = 0; 4318 for (; i < specs.length; ++i) { 4319 var gutterClass = specs[i]; 4320 var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); 4321 if (gutterClass == "CodeMirror-linenumbers") { 4322 cm.display.lineGutter = gElt; 4323 gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; 4324 } 4325 } 4326 gutters.style.display = i ? "" : "none"; 4327 updateGutterSpace(cm); 4328} 4329 4330// Make sure the gutters options contains the element 4331// "CodeMirror-linenumbers" when the lineNumbers option is true. 4332function setGuttersForLineNumbers(options) { 4333 var found = indexOf(options.gutters, "CodeMirror-linenumbers"); 4334 if (found == -1 && options.lineNumbers) { 4335 options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); 4336 } else if (found > -1 && !options.lineNumbers) { 4337 options.gutters = options.gutters.slice(0); 4338 options.gutters.splice(found, 1); 4339 } 4340} 4341 4342// Since the delta values reported on mouse wheel events are 4343// unstandardized between browsers and even browser versions, and 4344// generally horribly unpredictable, this code starts by measuring 4345// the scroll effect that the first few mouse wheel events have, 4346// and, from that, detects the way it can convert deltas to pixel 4347// offsets afterwards. 4348// 4349// The reason we want to know the amount a wheel event will scroll 4350// is that it gives us a chance to update the display before the 4351// actual scrolling happens, reducing flickering. 4352 4353var wheelSamples = 0; 4354var wheelPixelsPerUnit = null; 4355// Fill in a browser-detected starting value on browsers where we 4356// know one. These don't have to be accurate -- the result of them 4357// being wrong would just be a slight flicker on the first wheel 4358// scroll (if it is large enough). 4359if (ie) { wheelPixelsPerUnit = -.53; } 4360else if (gecko) { wheelPixelsPerUnit = 15; } 4361else if (chrome) { wheelPixelsPerUnit = -.7; } 4362else if (safari) { wheelPixelsPerUnit = -1/3; } 4363 4364function wheelEventDelta(e) { 4365 var dx = e.wheelDeltaX, dy = e.wheelDeltaY; 4366 if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; } 4367 if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; } 4368 else if (dy == null) { dy = e.wheelDelta; } 4369 return {x: dx, y: dy} 4370} 4371function wheelEventPixels(e) { 4372 var delta = wheelEventDelta(e); 4373 delta.x *= wheelPixelsPerUnit; 4374 delta.y *= wheelPixelsPerUnit; 4375 return delta 4376} 4377 4378function onScrollWheel(cm, e) { 4379 var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; 4380 4381 var display = cm.display, scroll = display.scroller; 4382 // Quit if there's nothing to scroll here 4383 var canScrollX = scroll.scrollWidth > scroll.clientWidth; 4384 var canScrollY = scroll.scrollHeight > scroll.clientHeight; 4385 if (!(dx && canScrollX || dy && canScrollY)) { return } 4386 4387 // Webkit browsers on OS X abort momentum scrolls when the target 4388 // of the scroll event is removed from the scrollable element. 4389 // This hack (see related code in patchDisplay) makes sure the 4390 // element is kept around. 4391 if (dy && mac && webkit) { 4392 outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { 4393 for (var i = 0; i < view.length; i++) { 4394 if (view[i].node == cur) { 4395 cm.display.currentWheelTarget = cur; 4396 break outer 4397 } 4398 } 4399 } 4400 } 4401 4402 // On some browsers, horizontal scrolling will cause redraws to 4403 // happen before the gutter has been realigned, causing it to 4404 // wriggle around in a most unseemly way. When we have an 4405 // estimated pixels/delta value, we just handle horizontal 4406 // scrolling entirely here. It'll be slightly off from native, but 4407 // better than glitching out. 4408 if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { 4409 if (dy && canScrollY) 4410 { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); } 4411 setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit)); 4412 // Only prevent default scrolling if vertical scrolling is 4413 // actually possible. Otherwise, it causes vertical scroll 4414 // jitter on OSX trackpads when deltaX is small and deltaY 4415 // is large (issue #3579) 4416 if (!dy || (dy && canScrollY)) 4417 { e_preventDefault(e); } 4418 display.wheelStartX = null; // Abort measurement, if in progress 4419 return 4420 } 4421 4422 // 'Project' the visible viewport to cover the area that is being 4423 // scrolled into view (if we know enough to estimate it). 4424 if (dy && wheelPixelsPerUnit != null) { 4425 var pixels = dy * wheelPixelsPerUnit; 4426 var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; 4427 if (pixels < 0) { top = Math.max(0, top + pixels - 50); } 4428 else { bot = Math.min(cm.doc.height, bot + pixels + 50); } 4429 updateDisplaySimple(cm, {top: top, bottom: bot}); 4430 } 4431 4432 if (wheelSamples < 20) { 4433 if (display.wheelStartX == null) { 4434 display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; 4435 display.wheelDX = dx; display.wheelDY = dy; 4436 setTimeout(function () { 4437 if (display.wheelStartX == null) { return } 4438 var movedX = scroll.scrollLeft - display.wheelStartX; 4439 var movedY = scroll.scrollTop - display.wheelStartY; 4440 var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || 4441 (movedX && display.wheelDX && movedX / display.wheelDX); 4442 display.wheelStartX = display.wheelStartY = null; 4443 if (!sample) { return } 4444 wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); 4445 ++wheelSamples; 4446 }, 200); 4447 } else { 4448 display.wheelDX += dx; display.wheelDY += dy; 4449 } 4450 } 4451} 4452 4453// Selection objects are immutable. A new one is created every time 4454// the selection changes. A selection is one or more non-overlapping 4455// (and non-touching) ranges, sorted, and an integer that indicates 4456// which one is the primary selection (the one that's scrolled into 4457// view, that getCursor returns, etc). 4458var Selection = function(ranges, primIndex) { 4459 this.ranges = ranges; 4460 this.primIndex = primIndex; 4461}; 4462 4463Selection.prototype.primary = function () { return this.ranges[this.primIndex] }; 4464 4465Selection.prototype.equals = function (other) { 4466 var this$1 = this; 4467 4468 if (other == this) { return true } 4469 if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false } 4470 for (var i = 0; i < this.ranges.length; i++) { 4471 var here = this$1.ranges[i], there = other.ranges[i]; 4472 if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false } 4473 } 4474 return true 4475}; 4476 4477Selection.prototype.deepCopy = function () { 4478 var this$1 = this; 4479 4480 var out = []; 4481 for (var i = 0; i < this.ranges.length; i++) 4482 { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); } 4483 return new Selection(out, this.primIndex) 4484}; 4485 4486Selection.prototype.somethingSelected = function () { 4487 var this$1 = this; 4488 4489 for (var i = 0; i < this.ranges.length; i++) 4490 { if (!this$1.ranges[i].empty()) { return true } } 4491 return false 4492}; 4493 4494Selection.prototype.contains = function (pos, end) { 4495 var this$1 = this; 4496 4497 if (!end) { end = pos; } 4498 for (var i = 0; i < this.ranges.length; i++) { 4499 var range = this$1.ranges[i]; 4500 if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) 4501 { return i } 4502 } 4503 return -1 4504}; 4505 4506var Range = function(anchor, head) { 4507 this.anchor = anchor; this.head = head; 4508}; 4509 4510Range.prototype.from = function () { return minPos(this.anchor, this.head) }; 4511Range.prototype.to = function () { return maxPos(this.anchor, this.head) }; 4512Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch }; 4513 4514// Take an unsorted, potentially overlapping set of ranges, and 4515// build a selection out of it. 'Consumes' ranges array (modifying 4516// it). 4517function normalizeSelection(ranges, primIndex) { 4518 var prim = ranges[primIndex]; 4519 ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }); 4520 primIndex = indexOf(ranges, prim); 4521 for (var i = 1; i < ranges.length; i++) { 4522 var cur = ranges[i], prev = ranges[i - 1]; 4523 if (cmp(prev.to(), cur.from()) >= 0) { 4524 var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); 4525 var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; 4526 if (i <= primIndex) { --primIndex; } 4527 ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); 4528 } 4529 } 4530 return new Selection(ranges, primIndex) 4531} 4532 4533function simpleSelection(anchor, head) { 4534 return new Selection([new Range(anchor, head || anchor)], 0) 4535} 4536 4537// Compute the position of the end of a change (its 'to' property 4538// refers to the pre-change end). 4539function changeEnd(change) { 4540 if (!change.text) { return change.to } 4541 return Pos(change.from.line + change.text.length - 1, 4542 lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) 4543} 4544 4545// Adjust a position to refer to the post-change position of the 4546// same text, or the end of the change if the change covers it. 4547function adjustForChange(pos, change) { 4548 if (cmp(pos, change.from) < 0) { return pos } 4549 if (cmp(pos, change.to) <= 0) { return changeEnd(change) } 4550 4551 var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; 4552 if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; } 4553 return Pos(line, ch) 4554} 4555 4556function computeSelAfterChange(doc, change) { 4557 var out = []; 4558 for (var i = 0; i < doc.sel.ranges.length; i++) { 4559 var range = doc.sel.ranges[i]; 4560 out.push(new Range(adjustForChange(range.anchor, change), 4561 adjustForChange(range.head, change))); 4562 } 4563 return normalizeSelection(out, doc.sel.primIndex) 4564} 4565 4566function offsetPos(pos, old, nw) { 4567 if (pos.line == old.line) 4568 { return Pos(nw.line, pos.ch - old.ch + nw.ch) } 4569 else 4570 { return Pos(nw.line + (pos.line - old.line), pos.ch) } 4571} 4572 4573// Used by replaceSelections to allow moving the selection to the 4574// start or around the replaced test. Hint may be "start" or "around". 4575function computeReplacedSel(doc, changes, hint) { 4576 var out = []; 4577 var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; 4578 for (var i = 0; i < changes.length; i++) { 4579 var change = changes[i]; 4580 var from = offsetPos(change.from, oldPrev, newPrev); 4581 var to = offsetPos(changeEnd(change), oldPrev, newPrev); 4582 oldPrev = change.to; 4583 newPrev = to; 4584 if (hint == "around") { 4585 var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; 4586 out[i] = new Range(inv ? to : from, inv ? from : to); 4587 } else { 4588 out[i] = new Range(from, from); 4589 } 4590 } 4591 return new Selection(out, doc.sel.primIndex) 4592} 4593 4594// Used to get the editor into a consistent state again when options change. 4595 4596function loadMode(cm) { 4597 cm.doc.mode = getMode(cm.options, cm.doc.modeOption); 4598 resetModeState(cm); 4599} 4600 4601function resetModeState(cm) { 4602 cm.doc.iter(function (line) { 4603 if (line.stateAfter) { line.stateAfter = null; } 4604 if (line.styles) { line.styles = null; } 4605 }); 4606 cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; 4607 startWorker(cm, 100); 4608 cm.state.modeGen++; 4609 if (cm.curOp) { regChange(cm); } 4610} 4611 4612// DOCUMENT DATA STRUCTURE 4613 4614// By default, updates that start and end at the beginning of a line 4615// are treated specially, in order to make the association of line 4616// widgets and marker elements with the text behave more intuitive. 4617function isWholeLineUpdate(doc, change) { 4618 return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && 4619 (!doc.cm || doc.cm.options.wholeLineUpdateBefore) 4620} 4621 4622// Perform a change on the document data structure. 4623function updateDoc(doc, change, markedSpans, estimateHeight$$1) { 4624 function spansFor(n) {return markedSpans ? markedSpans[n] : null} 4625 function update(line, text, spans) { 4626 updateLine(line, text, spans, estimateHeight$$1); 4627 signalLater(line, "change", line, change); 4628 } 4629 function linesFor(start, end) { 4630 var result = []; 4631 for (var i = start; i < end; ++i) 4632 { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); } 4633 return result 4634 } 4635 4636 var from = change.from, to = change.to, text = change.text; 4637 var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); 4638 var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; 4639 4640 // Adjust the line structure 4641 if (change.full) { 4642 doc.insert(0, linesFor(0, text.length)); 4643 doc.remove(text.length, doc.size - text.length); 4644 } else if (isWholeLineUpdate(doc, change)) { 4645 // This is a whole-line replace. Treated specially to make 4646 // sure line objects move the way they are supposed to. 4647 var added = linesFor(0, text.length - 1); 4648 update(lastLine, lastLine.text, lastSpans); 4649 if (nlines) { doc.remove(from.line, nlines); } 4650 if (added.length) { doc.insert(from.line, added); } 4651 } else if (firstLine == lastLine) { 4652 if (text.length == 1) { 4653 update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); 4654 } else { 4655 var added$1 = linesFor(1, text.length - 1); 4656 added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1)); 4657 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); 4658 doc.insert(from.line + 1, added$1); 4659 } 4660 } else if (text.length == 1) { 4661 update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); 4662 doc.remove(from.line + 1, nlines); 4663 } else { 4664 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); 4665 update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); 4666 var added$2 = linesFor(1, text.length - 1); 4667 if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); } 4668 doc.insert(from.line + 1, added$2); 4669 } 4670 4671 signalLater(doc, "change", doc, change); 4672} 4673 4674// Call f for all linked documents. 4675function linkedDocs(doc, f, sharedHistOnly) { 4676 function propagate(doc, skip, sharedHist) { 4677 if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) { 4678 var rel = doc.linked[i]; 4679 if (rel.doc == skip) { continue } 4680 var shared = sharedHist && rel.sharedHist; 4681 if (sharedHistOnly && !shared) { continue } 4682 f(rel.doc, shared); 4683 propagate(rel.doc, doc, shared); 4684 } } 4685 } 4686 propagate(doc, null, true); 4687} 4688 4689// Attach a document to an editor. 4690function attachDoc(cm, doc) { 4691 if (doc.cm) { throw new Error("This document is already in use.") } 4692 cm.doc = doc; 4693 doc.cm = cm; 4694 estimateLineHeights(cm); 4695 loadMode(cm); 4696 setDirectionClass(cm); 4697 if (!cm.options.lineWrapping) { findMaxLine(cm); } 4698 cm.options.mode = doc.modeOption; 4699 regChange(cm); 4700} 4701 4702function setDirectionClass(cm) { 4703 (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); 4704} 4705 4706function directionChanged(cm) { 4707 runInOp(cm, function () { 4708 setDirectionClass(cm); 4709 regChange(cm); 4710 }); 4711} 4712 4713function History(startGen) { 4714 // Arrays of change events and selections. Doing something adds an 4715 // event to done and clears undo. Undoing moves events from done 4716 // to undone, redoing moves them in the other direction. 4717 this.done = []; this.undone = []; 4718 this.undoDepth = Infinity; 4719 // Used to track when changes can be merged into a single undo 4720 // event 4721 this.lastModTime = this.lastSelTime = 0; 4722 this.lastOp = this.lastSelOp = null; 4723 this.lastOrigin = this.lastSelOrigin = null; 4724 // Used by the isClean() method 4725 this.generation = this.maxGeneration = startGen || 1; 4726} 4727 4728// Create a history change event from an updateDoc-style change 4729// object. 4730function historyChangeFromChange(doc, change) { 4731 var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; 4732 attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); 4733 linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true); 4734 return histChange 4735} 4736 4737// Pop all selection events off the end of a history array. Stop at 4738// a change event. 4739function clearSelectionEvents(array) { 4740 while (array.length) { 4741 var last = lst(array); 4742 if (last.ranges) { array.pop(); } 4743 else { break } 4744 } 4745} 4746 4747// Find the top change event in the history. Pop off selection 4748// events that are in the way. 4749function lastChangeEvent(hist, force) { 4750 if (force) { 4751 clearSelectionEvents(hist.done); 4752 return lst(hist.done) 4753 } else if (hist.done.length && !lst(hist.done).ranges) { 4754 return lst(hist.done) 4755 } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { 4756 hist.done.pop(); 4757 return lst(hist.done) 4758 } 4759} 4760 4761// Register a change in the history. Merges changes that are within 4762// a single operation, or are close together with an origin that 4763// allows merging (starting with "+") into a single event. 4764function addChangeToHistory(doc, change, selAfter, opId) { 4765 var hist = doc.history; 4766 hist.undone.length = 0; 4767 var time = +new Date, cur; 4768 var last; 4769 4770 if ((hist.lastOp == opId || 4771 hist.lastOrigin == change.origin && change.origin && 4772 ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || 4773 change.origin.charAt(0) == "*")) && 4774 (cur = lastChangeEvent(hist, hist.lastOp == opId))) { 4775 // Merge this change into the last event 4776 last = lst(cur.changes); 4777 if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { 4778 // Optimized case for simple insertion -- don't want to add 4779 // new changesets for every character typed 4780 last.to = changeEnd(change); 4781 } else { 4782 // Add new sub-event 4783 cur.changes.push(historyChangeFromChange(doc, change)); 4784 } 4785 } else { 4786 // Can not be merged, start a new event. 4787 var before = lst(hist.done); 4788 if (!before || !before.ranges) 4789 { pushSelectionToHistory(doc.sel, hist.done); } 4790 cur = {changes: [historyChangeFromChange(doc, change)], 4791 generation: hist.generation}; 4792 hist.done.push(cur); 4793 while (hist.done.length > hist.undoDepth) { 4794 hist.done.shift(); 4795 if (!hist.done[0].ranges) { hist.done.shift(); } 4796 } 4797 } 4798 hist.done.push(selAfter); 4799 hist.generation = ++hist.maxGeneration; 4800 hist.lastModTime = hist.lastSelTime = time; 4801 hist.lastOp = hist.lastSelOp = opId; 4802 hist.lastOrigin = hist.lastSelOrigin = change.origin; 4803 4804 if (!last) { signal(doc, "historyAdded"); } 4805} 4806 4807function selectionEventCanBeMerged(doc, origin, prev, sel) { 4808 var ch = origin.charAt(0); 4809 return ch == "*" || 4810 ch == "+" && 4811 prev.ranges.length == sel.ranges.length && 4812 prev.somethingSelected() == sel.somethingSelected() && 4813 new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500) 4814} 4815 4816// Called whenever the selection changes, sets the new selection as 4817// the pending selection in the history, and pushes the old pending 4818// selection into the 'done' array when it was significantly 4819// different (in number of selected ranges, emptiness, or time). 4820function addSelectionToHistory(doc, sel, opId, options) { 4821 var hist = doc.history, origin = options && options.origin; 4822 4823 // A new event is started when the previous origin does not match 4824 // the current, or the origins don't allow matching. Origins 4825 // starting with * are always merged, those starting with + are 4826 // merged when similar and close together in time. 4827 if (opId == hist.lastSelOp || 4828 (origin && hist.lastSelOrigin == origin && 4829 (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || 4830 selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) 4831 { hist.done[hist.done.length - 1] = sel; } 4832 else 4833 { pushSelectionToHistory(sel, hist.done); } 4834 4835 hist.lastSelTime = +new Date; 4836 hist.lastSelOrigin = origin; 4837 hist.lastSelOp = opId; 4838 if (options && options.clearRedo !== false) 4839 { clearSelectionEvents(hist.undone); } 4840} 4841 4842function pushSelectionToHistory(sel, dest) { 4843 var top = lst(dest); 4844 if (!(top && top.ranges && top.equals(sel))) 4845 { dest.push(sel); } 4846} 4847 4848// Used to store marked span information in the history. 4849function attachLocalSpans(doc, change, from, to) { 4850 var existing = change["spans_" + doc.id], n = 0; 4851 doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { 4852 if (line.markedSpans) 4853 { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; } 4854 ++n; 4855 }); 4856} 4857 4858// When un/re-doing restores text containing marked spans, those 4859// that have been explicitly cleared should not be restored. 4860function removeClearedSpans(spans) { 4861 if (!spans) { return null } 4862 var out; 4863 for (var i = 0; i < spans.length; ++i) { 4864 if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } } 4865 else if (out) { out.push(spans[i]); } 4866 } 4867 return !out ? spans : out.length ? out : null 4868} 4869 4870// Retrieve and filter the old marked spans stored in a change event. 4871function getOldSpans(doc, change) { 4872 var found = change["spans_" + doc.id]; 4873 if (!found) { return null } 4874 var nw = []; 4875 for (var i = 0; i < change.text.length; ++i) 4876 { nw.push(removeClearedSpans(found[i])); } 4877 return nw 4878} 4879 4880// Used for un/re-doing changes from the history. Combines the 4881// result of computing the existing spans with the set of spans that 4882// existed in the history (so that deleting around a span and then 4883// undoing brings back the span). 4884function mergeOldSpans(doc, change) { 4885 var old = getOldSpans(doc, change); 4886 var stretched = stretchSpansOverChange(doc, change); 4887 if (!old) { return stretched } 4888 if (!stretched) { return old } 4889 4890 for (var i = 0; i < old.length; ++i) { 4891 var oldCur = old[i], stretchCur = stretched[i]; 4892 if (oldCur && stretchCur) { 4893 spans: for (var j = 0; j < stretchCur.length; ++j) { 4894 var span = stretchCur[j]; 4895 for (var k = 0; k < oldCur.length; ++k) 4896 { if (oldCur[k].marker == span.marker) { continue spans } } 4897 oldCur.push(span); 4898 } 4899 } else if (stretchCur) { 4900 old[i] = stretchCur; 4901 } 4902 } 4903 return old 4904} 4905 4906// Used both to provide a JSON-safe object in .getHistory, and, when 4907// detaching a document, to split the history in two 4908function copyHistoryArray(events, newGroup, instantiateSel) { 4909 var copy = []; 4910 for (var i = 0; i < events.length; ++i) { 4911 var event = events[i]; 4912 if (event.ranges) { 4913 copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); 4914 continue 4915 } 4916 var changes = event.changes, newChanges = []; 4917 copy.push({changes: newChanges}); 4918 for (var j = 0; j < changes.length; ++j) { 4919 var change = changes[j], m = (void 0); 4920 newChanges.push({from: change.from, to: change.to, text: change.text}); 4921 if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) { 4922 if (indexOf(newGroup, Number(m[1])) > -1) { 4923 lst(newChanges)[prop] = change[prop]; 4924 delete change[prop]; 4925 } 4926 } } } 4927 } 4928 } 4929 return copy 4930} 4931 4932// The 'scroll' parameter given to many of these indicated whether 4933// the new cursor position should be scrolled into view after 4934// modifying the selection. 4935 4936// If shift is held or the extend flag is set, extends a range to 4937// include a given position (and optionally a second position). 4938// Otherwise, simply returns the range between the given positions. 4939// Used for cursor motion and such. 4940function extendRange(range, head, other, extend) { 4941 if (extend) { 4942 var anchor = range.anchor; 4943 if (other) { 4944 var posBefore = cmp(head, anchor) < 0; 4945 if (posBefore != (cmp(other, anchor) < 0)) { 4946 anchor = head; 4947 head = other; 4948 } else if (posBefore != (cmp(head, other) < 0)) { 4949 head = other; 4950 } 4951 } 4952 return new Range(anchor, head) 4953 } else { 4954 return new Range(other || head, head) 4955 } 4956} 4957 4958// Extend the primary selection range, discard the rest. 4959function extendSelection(doc, head, other, options, extend) { 4960 if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); } 4961 setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options); 4962} 4963 4964// Extend all selections (pos is an array of selections with length 4965// equal the number of selections) 4966function extendSelections(doc, heads, options) { 4967 var out = []; 4968 var extend = doc.cm && (doc.cm.display.shift || doc.extend); 4969 for (var i = 0; i < doc.sel.ranges.length; i++) 4970 { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); } 4971 var newSel = normalizeSelection(out, doc.sel.primIndex); 4972 setSelection(doc, newSel, options); 4973} 4974 4975// Updates a single range in the selection. 4976function replaceOneSelection(doc, i, range, options) { 4977 var ranges = doc.sel.ranges.slice(0); 4978 ranges[i] = range; 4979 setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); 4980} 4981 4982// Reset the selection to a single range. 4983function setSimpleSelection(doc, anchor, head, options) { 4984 setSelection(doc, simpleSelection(anchor, head), options); 4985} 4986 4987// Give beforeSelectionChange handlers a change to influence a 4988// selection update. 4989function filterSelectionChange(doc, sel, options) { 4990 var obj = { 4991 ranges: sel.ranges, 4992 update: function(ranges) { 4993 var this$1 = this; 4994 4995 this.ranges = []; 4996 for (var i = 0; i < ranges.length; i++) 4997 { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), 4998 clipPos(doc, ranges[i].head)); } 4999 }, 5000 origin: options && options.origin 5001 }; 5002 signal(doc, "beforeSelectionChange", doc, obj); 5003 if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); } 5004 if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) } 5005 else { return sel } 5006} 5007 5008function setSelectionReplaceHistory(doc, sel, options) { 5009 var done = doc.history.done, last = lst(done); 5010 if (last && last.ranges) { 5011 done[done.length - 1] = sel; 5012 setSelectionNoUndo(doc, sel, options); 5013 } else { 5014 setSelection(doc, sel, options); 5015 } 5016} 5017 5018// Set a new selection. 5019function setSelection(doc, sel, options) { 5020 setSelectionNoUndo(doc, sel, options); 5021 addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); 5022} 5023 5024function setSelectionNoUndo(doc, sel, options) { 5025 if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) 5026 { sel = filterSelectionChange(doc, sel, options); } 5027 5028 var bias = options && options.bias || 5029 (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); 5030 setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); 5031 5032 if (!(options && options.scroll === false) && doc.cm) 5033 { ensureCursorVisible(doc.cm); } 5034} 5035 5036function setSelectionInner(doc, sel) { 5037 if (sel.equals(doc.sel)) { return } 5038 5039 doc.sel = sel; 5040 5041 if (doc.cm) { 5042 doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; 5043 signalCursorActivity(doc.cm); 5044 } 5045 signalLater(doc, "cursorActivity", doc); 5046} 5047 5048// Verify that the selection does not partially select any atomic 5049// marked ranges. 5050function reCheckSelection(doc) { 5051 setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); 5052} 5053 5054// Return a selection that does not partially select any atomic 5055// ranges. 5056function skipAtomicInSelection(doc, sel, bias, mayClear) { 5057 var out; 5058 for (var i = 0; i < sel.ranges.length; i++) { 5059 var range = sel.ranges[i]; 5060 var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]; 5061 var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear); 5062 var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear); 5063 if (out || newAnchor != range.anchor || newHead != range.head) { 5064 if (!out) { out = sel.ranges.slice(0, i); } 5065 out[i] = new Range(newAnchor, newHead); 5066 } 5067 } 5068 return out ? normalizeSelection(out, sel.primIndex) : sel 5069} 5070 5071function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { 5072 var line = getLine(doc, pos.line); 5073 if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { 5074 var sp = line.markedSpans[i], m = sp.marker; 5075 if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && 5076 (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) { 5077 if (mayClear) { 5078 signal(m, "beforeCursorEnter"); 5079 if (m.explicitlyCleared) { 5080 if (!line.markedSpans) { break } 5081 else {--i; continue} 5082 } 5083 } 5084 if (!m.atomic) { continue } 5085 5086 if (oldPos) { 5087 var near = m.find(dir < 0 ? 1 : -1), diff = (void 0); 5088 if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft) 5089 { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); } 5090 if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) 5091 { return skipAtomicInner(doc, near, pos, dir, mayClear) } 5092 } 5093 5094 var far = m.find(dir < 0 ? -1 : 1); 5095 if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight) 5096 { far = movePos(doc, far, dir, far.line == pos.line ? line : null); } 5097 return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null 5098 } 5099 } } 5100 return pos 5101} 5102 5103// Ensure a given position is not inside an atomic range. 5104function skipAtomic(doc, pos, oldPos, bias, mayClear) { 5105 var dir = bias || 1; 5106 var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || 5107 (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || 5108 skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || 5109 (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)); 5110 if (!found) { 5111 doc.cantEdit = true; 5112 return Pos(doc.first, 0) 5113 } 5114 return found 5115} 5116 5117function movePos(doc, pos, dir, line) { 5118 if (dir < 0 && pos.ch == 0) { 5119 if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) } 5120 else { return null } 5121 } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { 5122 if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) } 5123 else { return null } 5124 } else { 5125 return new Pos(pos.line, pos.ch + dir) 5126 } 5127} 5128 5129function selectAll(cm) { 5130 cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); 5131} 5132 5133// UPDATING 5134 5135// Allow "beforeChange" event handlers to influence a change 5136function filterChange(doc, change, update) { 5137 var obj = { 5138 canceled: false, 5139 from: change.from, 5140 to: change.to, 5141 text: change.text, 5142 origin: change.origin, 5143 cancel: function () { return obj.canceled = true; } 5144 }; 5145 if (update) { obj.update = function (from, to, text, origin) { 5146 if (from) { obj.from = clipPos(doc, from); } 5147 if (to) { obj.to = clipPos(doc, to); } 5148 if (text) { obj.text = text; } 5149 if (origin !== undefined) { obj.origin = origin; } 5150 }; } 5151 signal(doc, "beforeChange", doc, obj); 5152 if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); } 5153 5154 if (obj.canceled) { return null } 5155 return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} 5156} 5157 5158// Apply a change to a document, and add it to the document's 5159// history, and propagating it to all linked documents. 5160function makeChange(doc, change, ignoreReadOnly) { 5161 if (doc.cm) { 5162 if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) } 5163 if (doc.cm.state.suppressEdits) { return } 5164 } 5165 5166 if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { 5167 change = filterChange(doc, change, true); 5168 if (!change) { return } 5169 } 5170 5171 // Possibly split or suppress the update based on the presence 5172 // of read-only spans in its range. 5173 var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); 5174 if (split) { 5175 for (var i = split.length - 1; i >= 0; --i) 5176 { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}); } 5177 } else { 5178 makeChangeInner(doc, change); 5179 } 5180} 5181 5182function makeChangeInner(doc, change) { 5183 if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return } 5184 var selAfter = computeSelAfterChange(doc, change); 5185 addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); 5186 5187 makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); 5188 var rebased = []; 5189 5190 linkedDocs(doc, function (doc, sharedHist) { 5191 if (!sharedHist && indexOf(rebased, doc.history) == -1) { 5192 rebaseHist(doc.history, change); 5193 rebased.push(doc.history); 5194 } 5195 makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); 5196 }); 5197} 5198 5199// Revert a change stored in a document's history. 5200function makeChangeFromHistory(doc, type, allowSelectionOnly) { 5201 if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return } 5202 5203 var hist = doc.history, event, selAfter = doc.sel; 5204 var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; 5205 5206 // Verify that there is a useable event (so that ctrl-z won't 5207 // needlessly clear selection events) 5208 var i = 0; 5209 for (; i < source.length; i++) { 5210 event = source[i]; 5211 if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) 5212 { break } 5213 } 5214 if (i == source.length) { return } 5215 hist.lastOrigin = hist.lastSelOrigin = null; 5216 5217 for (;;) { 5218 event = source.pop(); 5219 if (event.ranges) { 5220 pushSelectionToHistory(event, dest); 5221 if (allowSelectionOnly && !event.equals(doc.sel)) { 5222 setSelection(doc, event, {clearRedo: false}); 5223 return 5224 } 5225 selAfter = event; 5226 } 5227 else { break } 5228 } 5229 5230 // Build up a reverse change object to add to the opposite history 5231 // stack (redo when undoing, and vice versa). 5232 var antiChanges = []; 5233 pushSelectionToHistory(selAfter, dest); 5234 dest.push({changes: antiChanges, generation: hist.generation}); 5235 hist.generation = event.generation || ++hist.maxGeneration; 5236 5237 var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); 5238 5239 var loop = function ( i ) { 5240 var change = event.changes[i]; 5241 change.origin = type; 5242 if (filter && !filterChange(doc, change, false)) { 5243 source.length = 0; 5244 return {} 5245 } 5246 5247 antiChanges.push(historyChangeFromChange(doc, change)); 5248 5249 var after = i ? computeSelAfterChange(doc, change) : lst(source); 5250 makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); 5251 if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); } 5252 var rebased = []; 5253 5254 // Propagate to the linked documents 5255 linkedDocs(doc, function (doc, sharedHist) { 5256 if (!sharedHist && indexOf(rebased, doc.history) == -1) { 5257 rebaseHist(doc.history, change); 5258 rebased.push(doc.history); 5259 } 5260 makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); 5261 }); 5262 }; 5263 5264 for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { 5265 var returned = loop( i$1 ); 5266 5267 if ( returned ) return returned.v; 5268 } 5269} 5270 5271// Sub-views need their line numbers shifted when text is added 5272// above or below them in the parent document. 5273function shiftDoc(doc, distance) { 5274 if (distance == 0) { return } 5275 doc.first += distance; 5276 doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range( 5277 Pos(range.anchor.line + distance, range.anchor.ch), 5278 Pos(range.head.line + distance, range.head.ch) 5279 ); }), doc.sel.primIndex); 5280 if (doc.cm) { 5281 regChange(doc.cm, doc.first, doc.first - distance, distance); 5282 for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) 5283 { regLineChange(doc.cm, l, "gutter"); } 5284 } 5285} 5286 5287// More lower-level change function, handling only a single document 5288// (not linked ones). 5289function makeChangeSingleDoc(doc, change, selAfter, spans) { 5290 if (doc.cm && !doc.cm.curOp) 5291 { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) } 5292 5293 if (change.to.line < doc.first) { 5294 shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); 5295 return 5296 } 5297 if (change.from.line > doc.lastLine()) { return } 5298 5299 // Clip the change to the size of this doc 5300 if (change.from.line < doc.first) { 5301 var shift = change.text.length - 1 - (doc.first - change.from.line); 5302 shiftDoc(doc, shift); 5303 change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), 5304 text: [lst(change.text)], origin: change.origin}; 5305 } 5306 var last = doc.lastLine(); 5307 if (change.to.line > last) { 5308 change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), 5309 text: [change.text[0]], origin: change.origin}; 5310 } 5311 5312 change.removed = getBetween(doc, change.from, change.to); 5313 5314 if (!selAfter) { selAfter = computeSelAfterChange(doc, change); } 5315 if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); } 5316 else { updateDoc(doc, change, spans); } 5317 setSelectionNoUndo(doc, selAfter, sel_dontScroll); 5318} 5319 5320// Handle the interaction of a change to a document with the editor 5321// that this document is part of. 5322function makeChangeSingleDocInEditor(cm, change, spans) { 5323 var doc = cm.doc, display = cm.display, from = change.from, to = change.to; 5324 5325 var recomputeMaxLength = false, checkWidthStart = from.line; 5326 if (!cm.options.lineWrapping) { 5327 checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); 5328 doc.iter(checkWidthStart, to.line + 1, function (line) { 5329 if (line == display.maxLine) { 5330 recomputeMaxLength = true; 5331 return true 5332 } 5333 }); 5334 } 5335 5336 if (doc.sel.contains(change.from, change.to) > -1) 5337 { signalCursorActivity(cm); } 5338 5339 updateDoc(doc, change, spans, estimateHeight(cm)); 5340 5341 if (!cm.options.lineWrapping) { 5342 doc.iter(checkWidthStart, from.line + change.text.length, function (line) { 5343 var len = lineLength(line); 5344 if (len > display.maxLineLength) { 5345 display.maxLine = line; 5346 display.maxLineLength = len; 5347 display.maxLineChanged = true; 5348 recomputeMaxLength = false; 5349 } 5350 }); 5351 if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; } 5352 } 5353 5354 retreatFrontier(doc, from.line); 5355 startWorker(cm, 400); 5356 5357 var lendiff = change.text.length - (to.line - from.line) - 1; 5358 // Remember that these lines changed, for updating the display 5359 if (change.full) 5360 { regChange(cm); } 5361 else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) 5362 { regLineChange(cm, from.line, "text"); } 5363 else 5364 { regChange(cm, from.line, to.line + 1, lendiff); } 5365 5366 var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); 5367 if (changeHandler || changesHandler) { 5368 var obj = { 5369 from: from, to: to, 5370 text: change.text, 5371 removed: change.removed, 5372 origin: change.origin 5373 }; 5374 if (changeHandler) { signalLater(cm, "change", cm, obj); } 5375 if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); } 5376 } 5377 cm.display.selForContextMenu = null; 5378} 5379 5380function replaceRange(doc, code, from, to, origin) { 5381 if (!to) { to = from; } 5382 if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } 5383 if (typeof code == "string") { code = doc.splitLines(code); } 5384 makeChange(doc, {from: from, to: to, text: code, origin: origin}); 5385} 5386 5387// Rebasing/resetting history to deal with externally-sourced changes 5388 5389function rebaseHistSelSingle(pos, from, to, diff) { 5390 if (to < pos.line) { 5391 pos.line += diff; 5392 } else if (from < pos.line) { 5393 pos.line = from; 5394 pos.ch = 0; 5395 } 5396} 5397 5398// Tries to rebase an array of history events given a change in the 5399// document. If the change touches the same lines as the event, the 5400// event, and everything 'behind' it, is discarded. If the change is 5401// before the event, the event's positions are updated. Uses a 5402// copy-on-write scheme for the positions, to avoid having to 5403// reallocate them all on every rebase, but also avoid problems with 5404// shared position objects being unsafely updated. 5405function rebaseHistArray(array, from, to, diff) { 5406 for (var i = 0; i < array.length; ++i) { 5407 var sub = array[i], ok = true; 5408 if (sub.ranges) { 5409 if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } 5410 for (var j = 0; j < sub.ranges.length; j++) { 5411 rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); 5412 rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); 5413 } 5414 continue 5415 } 5416 for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { 5417 var cur = sub.changes[j$1]; 5418 if (to < cur.from.line) { 5419 cur.from = Pos(cur.from.line + diff, cur.from.ch); 5420 cur.to = Pos(cur.to.line + diff, cur.to.ch); 5421 } else if (from <= cur.to.line) { 5422 ok = false;
5423 break 5424 } 5425 } 5426 if (!ok) { 5427 array.splice(0, i + 1); 5428 i = 0; 5429 } 5430 } 5431} 5432 5433function rebaseHist(hist, change) { 5434 var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; 5435 rebaseHistArray(hist.done, from, to, diff); 5436 rebaseHistArray(hist.undone, from, to, diff); 5437} 5438 5439// Utility for applying a change to a line by handle or number, 5440// returning the number and optionally registering the line as 5441// changed. 5442function changeLine(doc, handle, changeType, op) { 5443 var no = handle, line = handle; 5444 if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); } 5445 else { no = lineNo(handle); } 5446 if (no == null) { return null } 5447 if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); } 5448 return line 5449} 5450 5451// The document is represented as a BTree consisting of leaves, with 5452// chunk of lines in them, and branches, with up to ten leaves or 5453// other branch nodes below them. The top node is always a branch 5454// node, and is the document object itself (meaning it has 5455// additional methods and properties). 5456// 5457// All nodes have parent links. The tree is used both to go from 5458// line numbers to line objects, and to go from objects to numbers. 5459// It also indexes by height, and is used to convert between height 5460// and line object, and to find the total height of the document. 5461// 5462// See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html 5463 5464function LeafChunk(lines) { 5465 var this$1 = this; 5466 5467 this.lines = lines; 5468 this.parent = null; 5469 var height = 0; 5470 for (var i = 0; i < lines.length; ++i) { 5471 lines[i].parent = this$1; 5472 height += lines[i].height; 5473 } 5474 this.height = height; 5475} 5476 5477LeafChunk.prototype = { 5478 chunkSize: function() { return this.lines.length }, 5479 5480 // Remove the n lines at offset 'at'. 5481 removeInner: function(at, n) { 5482 var this$1 = this; 5483 5484 for (var i = at, e = at + n; i < e; ++i) { 5485 var line = this$1.lines[i]; 5486 this$1.height -= line.height; 5487 cleanUpLine(line); 5488 signalLater(line, "delete"); 5489 } 5490 this.lines.splice(at, n); 5491 }, 5492 5493 // Helper used to collapse a small branch into a single leaf. 5494 collapse: function(lines) { 5495 lines.push.apply(lines, this.lines); 5496 }, 5497 5498 // Insert the given array of lines at offset 'at', count them as 5499 // having the given height. 5500 insertInner: function(at, lines, height) { 5501 var this$1 = this; 5502 5503 this.height += height; 5504 this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); 5505 for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; } 5506 }, 5507 5508 // Used to iterate over a part of the tree. 5509 iterN: function(at, n, op) { 5510 var this$1 = this; 5511 5512 for (var e = at + n; at < e; ++at) 5513 { if (op(this$1.lines[at])) { return true } } 5514 } 5515}; 5516 5517function BranchChunk(children) { 5518 var this$1 = this; 5519 5520 this.children = children; 5521 var size = 0, height = 0; 5522 for (var i = 0; i < children.length; ++i) { 5523 var ch = children[i]; 5524 size += ch.chunkSize(); height += ch.height; 5525 ch.parent = this$1; 5526 } 5527 this.size = size; 5528 this.height = height; 5529 this.parent = null; 5530} 5531 5532BranchChunk.prototype = { 5533 chunkSize: function() { return this.size }, 5534 5535 removeInner: function(at, n) { 5536 var this$1 = this; 5537 5538 this.size -= n; 5539 for (var i = 0; i < this.children.length; ++i) { 5540 var child = this$1.children[i], sz = child.chunkSize(); 5541 if (at < sz) { 5542 var rm = Math.min(n, sz - at), oldHeight = child.height; 5543 child.removeInner(at, rm); 5544 this$1.height -= oldHeight - child.height; 5545 if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; } 5546 if ((n -= rm) == 0) { break } 5547 at = 0; 5548 } else { at -= sz; } 5549 } 5550 // If the result is smaller than 25 lines, ensure that it is a 5551 // single leaf node. 5552 if (this.size - n < 25 && 5553 (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { 5554 var lines = []; 5555 this.collapse(lines); 5556 this.children = [new LeafChunk(lines)]; 5557 this.children[0].parent = this; 5558 } 5559 }, 5560 5561 collapse: function(lines) { 5562 var this$1 = this; 5563 5564 for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); } 5565 }, 5566 5567 insertInner: function(at, lines, height) { 5568 var this$1 = this; 5569 5570 this.size += lines.length; 5571 this.height += height; 5572 for (var i = 0; i < this.children.length; ++i) { 5573 var child = this$1.children[i], sz = child.chunkSize(); 5574 if (at <= sz) { 5575 child.insertInner(at, lines, height); 5576 if (child.lines && child.lines.length > 50) { 5577 // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. 5578 // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. 5579 var remaining = child.lines.length % 25 + 25; 5580 for (var pos = remaining; pos < child.lines.length;) { 5581 var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); 5582 child.height -= leaf.height; 5583 this$1.children.splice(++i, 0, leaf); 5584 leaf.parent = this$1; 5585 } 5586 child.lines = child.lines.slice(0, remaining); 5587 this$1.maybeSpill(); 5588 } 5589 break 5590 } 5591 at -= sz; 5592 } 5593 }, 5594 5595 // When a node has grown, check whether it should be split. 5596 maybeSpill: function() { 5597 if (this.children.length <= 10) { return } 5598 var me = this; 5599 do { 5600 var spilled = me.children.splice(me.children.length - 5, 5); 5601 var sibling = new BranchChunk(spilled); 5602 if (!me.parent) { // Become the parent node 5603 var copy = new BranchChunk(me.children); 5604 copy.parent = me; 5605 me.children = [copy, sibling]; 5606 me = copy; 5607 } else { 5608 me.size -= sibling.size; 5609 me.height -= sibling.height; 5610 var myIndex = indexOf(me.parent.children, me); 5611 me.parent.children.splice(myIndex + 1, 0, sibling); 5612 } 5613 sibling.parent = me.parent; 5614 } while (me.children.length > 10) 5615 me.parent.maybeSpill(); 5616 }, 5617 5618 iterN: function(at, n, op) { 5619 var this$1 = this; 5620 5621 for (var i = 0; i < this.children.length; ++i) { 5622 var child = this$1.children[i], sz = child.chunkSize(); 5623 if (at < sz) { 5624 var used = Math.min(n, sz - at); 5625 if (child.iterN(at, used, op)) { return true } 5626 if ((n -= used) == 0) { break } 5627 at = 0; 5628 } else { at -= sz; } 5629 } 5630 } 5631}; 5632 5633// Line widgets are block elements displayed above or below a line. 5634 5635var LineWidget = function(doc, node, options) { 5636 var this$1 = this; 5637 5638 if (options) { for (var opt in options) { if (options.hasOwnProperty(opt)) 5639 { this$1[opt] = options[opt]; } } } 5640 this.doc = doc; 5641 this.node = node; 5642}; 5643
vendor: 50,367 bytes, lines 5644-6887
5644LineWidget.prototype.clear = function () { 5645 var this$1 = this; 5646 5647 var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); 5648 if (no == null || !ws) { return } 5649 for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } } 5650 if (!ws.length) { line.widgets = null; } 5651 var height = widgetHeight(this); 5652 updateLineHeight(line, Math.max(0, line.height - height)); 5653 if (cm) { 5654 runInOp(cm, function () { 5655 adjustScrollWhenAboveVisible(cm, line, -height); 5656 regLineChange(cm, no, "widget"); 5657 }); 5658 signalLater(cm, "lineWidgetCleared", cm, this, no); 5659 } 5660}; 5661 5662LineWidget.prototype.changed = function () { 5663 var this$1 = this; 5664 5665 var oldH = this.height, cm = this.doc.cm, line = this.line; 5666 this.height = null; 5667 var diff = widgetHeight(this) - oldH; 5668 if (!diff) { return } 5669 updateLineHeight(line, line.height + diff); 5670 if (cm) { 5671 runInOp(cm, function () { 5672 cm.curOp.forceUpdate = true; 5673 adjustScrollWhenAboveVisible(cm, line, diff); 5674 signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line)); 5675 }); 5676 } 5677}; 5678eventMixin(LineWidget); 5679 5680function adjustScrollWhenAboveVisible(cm, line, diff) { 5681 if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) 5682 { addToScrollTop(cm, diff); } 5683} 5684 5685function addLineWidget(doc, handle, node, options) { 5686 var widget = new LineWidget(doc, node, options); 5687 var cm = doc.cm; 5688 if (cm && widget.noHScroll) { cm.display.alignWidgets = true; } 5689 changeLine(doc, handle, "widget", function (line) { 5690 var widgets = line.widgets || (line.widgets = []); 5691 if (widget.insertAt == null) { widgets.push(widget); } 5692 else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); } 5693 widget.line = line; 5694 if (cm && !lineIsHidden(doc, line)) { 5695 var aboveVisible = heightAtLine(line) < doc.scrollTop; 5696 updateLineHeight(line, line.height + widgetHeight(widget)); 5697 if (aboveVisible) { addToScrollTop(cm, widget.height); } 5698 cm.curOp.forceUpdate = true; 5699 } 5700 return true 5701 }); 5702 signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); 5703 return widget 5704} 5705 5706// TEXTMARKERS 5707 5708// Created with markText and setBookmark methods. A TextMarker is a 5709// handle that can be used to clear or find a marked position in the 5710// document. Line objects hold arrays (markedSpans) containing 5711// {from, to, marker} object pointing to such marker objects, and 5712// indicating that such a marker is present on that line. Multiple 5713// lines may point to the same marker when it spans across lines. 5714// The spans will have null for their from/to properties when the 5715// marker continues beyond the start/end of the line. Markers have 5716// links back to the lines they currently touch. 5717 5718// Collapsed markers have unique ids, in order to be able to order 5719// them, which is needed for uniquely determining an outer marker 5720// when they overlap (they may nest, but not partially overlap). 5721var nextMarkerId = 0; 5722 5723var TextMarker = function(doc, type) { 5724 this.lines = []; 5725 this.type = type; 5726 this.doc = doc; 5727 this.id = ++nextMarkerId; 5728}; 5729 5730// Clear the marker. 5731TextMarker.prototype.clear = function () { 5732 var this$1 = this; 5733 5734 if (this.explicitlyCleared) { return } 5735 var cm = this.doc.cm, withOp = cm && !cm.curOp; 5736 if (withOp) { startOperation(cm); } 5737 if (hasHandler(this, "clear")) { 5738 var found = this.find(); 5739 if (found) { signalLater(this, "clear", found.from, found.to); } 5740 } 5741 var min = null, max = null; 5742 for (var i = 0; i < this.lines.length; ++i) { 5743 var line = this$1.lines[i]; 5744 var span = getMarkedSpanFor(line.markedSpans, this$1); 5745 if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); } 5746 else if (cm) { 5747 if (span.to != null) { max = lineNo(line); } 5748 if (span.from != null) { min = lineNo(line); } 5749 } 5750 line.markedSpans = removeMarkedSpan(line.markedSpans, span); 5751 if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm) 5752 { updateLineHeight(line, textHeight(cm.display)); } 5753 } 5754 if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) { 5755 var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual); 5756 if (len > cm.display.maxLineLength) { 5757 cm.display.maxLine = visual; 5758 cm.display.maxLineLength = len; 5759 cm.display.maxLineChanged = true; 5760 } 5761 } } 5762 5763 if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); } 5764 this.lines.length = 0; 5765 this.explicitlyCleared = true; 5766 if (this.atomic && this.doc.cantEdit) { 5767 this.doc.cantEdit = false; 5768 if (cm) { reCheckSelection(cm.doc); } 5769 } 5770 if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); } 5771 if (withOp) { endOperation(cm); } 5772 if (this.parent) { this.parent.clear(); } 5773}; 5774 5775// Find the position of the marker in the document. Returns a {from, 5776// to} object by default. Side can be passed to get a specific side 5777// -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the 5778// Pos objects returned contain a line object, rather than a line 5779// number (used to prevent looking up the same line twice). 5780TextMarker.prototype.find = function (side, lineObj) { 5781 var this$1 = this; 5782 5783 if (side == null && this.type == "bookmark") { side = 1; } 5784 var from, to; 5785 for (var i = 0; i < this.lines.length; ++i) { 5786 var line = this$1.lines[i]; 5787 var span = getMarkedSpanFor(line.markedSpans, this$1); 5788 if (span.from != null) { 5789 from = Pos(lineObj ? line : lineNo(line), span.from); 5790 if (side == -1) { return from } 5791 } 5792 if (span.to != null) { 5793 to = Pos(lineObj ? line : lineNo(line), span.to); 5794 if (side == 1) { return to } 5795 } 5796 } 5797 return from && {from: from, to: to} 5798}; 5799 5800// Signals that the marker's widget changed, and surrounding layout 5801// should be recomputed. 5802TextMarker.prototype.changed = function () { 5803 var this$1 = this; 5804 5805 var pos = this.find(-1, true), widget = this, cm = this.doc.cm; 5806 if (!pos || !cm) { return } 5807 runInOp(cm, function () { 5808 var line = pos.line, lineN = lineNo(pos.line); 5809 var view = findViewForLine(cm, lineN); 5810 if (view) { 5811 clearLineMeasurementCacheFor(view); 5812 cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; 5813 } 5814 cm.curOp.updateMaxLine = true; 5815 if (!lineIsHidden(widget.doc, line) && widget.height != null) { 5816 var oldHeight = widget.height; 5817 widget.height = null; 5818 var dHeight = widgetHeight(widget) - oldHeight; 5819 if (dHeight) 5820 { updateLineHeight(line, line.height + dHeight); } 5821 } 5822 signalLater(cm, "markerChanged", cm, this$1); 5823 }); 5824}; 5825 5826TextMarker.prototype.attachLine = function (line) { 5827 if (!this.lines.length && this.doc.cm) { 5828 var op = this.doc.cm.curOp; 5829 if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) 5830 { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); } 5831 } 5832 this.lines.push(line); 5833}; 5834 5835TextMarker.prototype.detachLine = function (line) { 5836 this.lines.splice(indexOf(this.lines, line), 1); 5837 if (!this.lines.length && this.doc.cm) { 5838 var op = this.doc.cm.curOp;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); 5839 } 5840}; 5841eventMixin(TextMarker); 5842 5843// Create a marker, wire it up to the right lines, and 5844function markText(doc, from, to, options, type) { 5845 // Shared markers (across linked documents) are handled separately 5846 // (markTextShared will call out to this again, once per 5847 // document). 5848 if (options && options.shared) { return markTextShared(doc, from, to, options, type) } 5849 // Ensure we are in an operation. 5850 if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) } 5851 5852 var marker = new TextMarker(doc, type), diff = cmp(from, to); 5853 if (options) { copyObj(options, marker, false); } 5854 // Don't connect empty markers unless clearWhenEmpty is false 5855 if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) 5856 { return marker } 5857 if (marker.replacedWith) { 5858 // Showing up as a widget implies collapsed (widget replaces text) 5859 marker.collapsed = true; 5860 marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); 5861 if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); } 5862 if (options.insertLeft) { marker.widgetNode.insertLeft = true; } 5863 } 5864 if (marker.collapsed) { 5865 if (conflictingCollapsedRange(doc, from.line, from, to, marker) || 5866 from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) 5867 { throw new Error("Inserting collapsed marker partially overlapping an existing one") } 5868 seeCollapsedSpans(); 5869 } 5870 5871 if (marker.addToHistory) 5872 { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); } 5873 5874 var curLine = from.line, cm = doc.cm, updateMaxLine; 5875 doc.iter(curLine, to.line + 1, function (line) { 5876 if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) 5877 { updateMaxLine = true; } 5878 if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); } 5879 addMarkedSpan(line, new MarkedSpan(marker, 5880 curLine == from.line ? from.ch : null, 5881 curLine == to.line ? to.ch : null)); 5882 ++curLine; 5883 }); 5884 // lineIsHidden depends on the presence of the spans, so needs a second pass 5885 if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) { 5886 if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); } 5887 }); } 5888 5889 if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); } 5890 5891 if (marker.readOnly) { 5892 seeReadOnlySpans(); 5893 if (doc.history.done.length || doc.history.undone.length) 5894 { doc.clearHistory(); } 5895 } 5896 if (marker.collapsed) { 5897 marker.id = ++nextMarkerId; 5898 marker.atomic = true; 5899 } 5900 if (cm) { 5901 // Sync editor state 5902 if (updateMaxLine) { cm.curOp.updateMaxLine = true; } 5903 if (marker.collapsed) 5904 { regChange(cm, from.line, to.line + 1); } 5905 else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) 5906 { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } } 5907 if (marker.atomic) { reCheckSelection(cm.doc); } 5908 signalLater(cm, "markerAdded", cm, marker); 5909 } 5910 return marker 5911} 5912 5913// SHARED TEXTMARKERS 5914 5915// A shared marker spans multiple linked documents. It is 5916// implemented as a meta-marker-object controlling multiple normal 5917// markers. 5918var SharedTextMarker = function(markers, primary) { 5919 var this$1 = this; 5920 5921 this.markers = markers; 5922 this.primary = primary; 5923 for (var i = 0; i < markers.length; ++i) 5924 { markers[i].parent = this$1; } 5925}; 5926 5927SharedTextMarker.prototype.clear = function () { 5928 var this$1 = this; 5929 5930 if (this.explicitlyCleared) { return } 5931 this.explicitlyCleared = true; 5932 for (var i = 0; i < this.markers.length; ++i) 5933 { this$1.markers[i].clear(); } 5934 signalLater(this, "clear"); 5935}; 5936 5937SharedTextMarker.prototype.find = function (side, lineObj) { 5938 return this.primary.find(side, lineObj) 5939}; 5940eventMixin(SharedTextMarker); 5941 5942function markTextShared(doc, from, to, options, type) { 5943 options = copyObj(options); 5944 options.shared = false; 5945 var markers = [markText(doc, from, to, options, type)], primary = markers[0]; 5946 var widget = options.widgetNode; 5947 linkedDocs(doc, function (doc) { 5948 if (widget) { options.widgetNode = widget.cloneNode(true); } 5949 markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); 5950 for (var i = 0; i < doc.linked.length; ++i) 5951 { if (doc.linked[i].isParent) { return } } 5952 primary = lst(markers); 5953 }); 5954 return new SharedTextMarker(markers, primary) 5955} 5956 5957function findSharedMarkers(doc) { 5958 return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; }) 5959} 5960 5961function copySharedMarkers(doc, markers) { 5962 for (var i = 0; i < markers.length; i++) { 5963 var marker = markers[i], pos = marker.find(); 5964 var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); 5965 if (cmp(mFrom, mTo)) { 5966 var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); 5967 marker.markers.push(subMark); 5968 subMark.parent = marker; 5969 } 5970 } 5971} 5972 5973function detachSharedMarkers(markers) { 5974 var loop = function ( i ) { 5975 var marker = markers[i], linked = [marker.primary.doc]; 5976 linkedDocs(marker.primary.doc, function (d) { return linked.push(d); }); 5977 for (var j = 0; j < marker.markers.length; j++) { 5978 var subMarker = marker.markers[j]; 5979 if (indexOf(linked, subMarker.doc) == -1) { 5980 subMarker.parent = null; 5981 marker.markers.splice(j--, 1); 5982 } 5983 } 5984 }; 5985 5986 for (var i = 0; i < markers.length; i++) loop( i ); 5987} 5988 5989var nextDocId = 0; 5990var Doc = function(text, mode, firstLine, lineSep, direction) { 5991 if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) } 5992 if (firstLine == null) { firstLine = 0; } 5993 5994 BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); 5995 this.first = firstLine; 5996 this.scrollTop = this.scrollLeft = 0; 5997 this.cantEdit = false; 5998 this.cleanGeneration = 1; 5999 this.modeFrontier = this.highlightFrontier = firstLine; 6000 var start = Pos(firstLine, 0); 6001 this.sel = simpleSelection(start); 6002 this.history = new History(null); 6003 this.id = ++nextDocId; 6004 this.modeOption = mode; 6005 this.lineSep = lineSep; 6006 this.direction = (direction == "rtl") ? "rtl" : "ltr"; 6007 this.extend = false; 6008 6009 if (typeof text == "string") { text = this.splitLines(text); } 6010 updateDoc(this, {from: start, to: start, text: text}); 6011 setSelection(this, simpleSelection(start), sel_dontScroll); 6012}; 6013 6014Doc.prototype = createObj(BranchChunk.prototype, { 6015 constructor: Doc, 6016 // Iterate over the document. Supports two forms -- with only one 6017 // argument, it calls that for each line in the document. With 6018 // three, it iterates over the range given by the first two (with 6019 // the second being non-inclusive). 6020 iter: function(from, to, op) { 6021 if (op) { this.iterN(from - this.first, to - from, op); } 6022 else { this.iterN(this.first, this.first + this.size, from); } 6023 }, 6024 6025 // Non-public interface for adding and removing lines. 6026 insert: function(at, lines) { 6027 var height = 0; 6028 for (var i = 0; i < lines.length; ++i) { height += lines[i].height; } 6029 this.insertInner(at - this.first, lines, height); 6030 }, 6031 remove: function(at, n) { this.removeInner(at - this.first, n); }, 6032 6033 // From here, the methods are part of the public interface. Most 6034 // are also available from CodeMirror (editor) instances. 6035 6036 getValue: function(lineSep) { 6037 var lines = getLines(this, this.first, this.first + this.size); 6038 if (lineSep === false) { return lines } 6039 return lines.join(lineSep || this.lineSeparator()) 6040 }, 6041 setValue: docMethodOp(function(code) { 6042 var top = Pos(this.first, 0), last = this.first + this.size - 1; 6043 makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), 6044 text: this.splitLines(code), origin: "setValue", full: true}, true); 6045 if (this.cm) { scrollToCoords(this.cm, 0, 0); } 6046 setSelection(this, simpleSelection(top), sel_dontScroll); 6047 }), 6048 replaceRange: function(code, from, to, origin) { 6049 from = clipPos(this, from); 6050 to = to ? clipPos(this, to) : from; 6051 replaceRange(this, code, from, to, origin); 6052 }, 6053 getRange: function(from, to, lineSep) { 6054 var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); 6055 if (lineSep === false) { return lines } 6056 return lines.join(lineSep || this.lineSeparator()) 6057 }, 6058 6059 getLine: function(line) {var l = this.getLineHandle(line); return l && l.text}, 6060 6061 getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }}, 6062 getLineNumber: function(line) {return lineNo(line)}, 6063 6064 getLineHandleVisualStart: function(line) { 6065 if (typeof line == "number") { line = getLine(this, line); } 6066 return visualLine(line) 6067 }, 6068 6069 lineCount: function() {return this.size}, 6070 firstLine: function() {return this.first}, 6071 lastLine: function() {return this.first + this.size - 1}, 6072 6073 clipPos: function(pos) {return clipPos(this, pos)}, 6074 6075 getCursor: function(start) { 6076 var range$$1 = this.sel.primary(), pos; 6077 if (start == null || start == "head") { pos = range$$1.head; } 6078 else if (start == "anchor") { pos = range$$1.anchor; } 6079 else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); } 6080 else { pos = range$$1.from(); } 6081 return pos 6082 }, 6083 listSelections: function() { return this.sel.ranges }, 6084 somethingSelected: function() {return this.sel.somethingSelected()}, 6085 6086 setCursor: docMethodOp(function(line, ch, options) { 6087 setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); 6088 }), 6089 setSelection: docMethodOp(function(anchor, head, options) { 6090 setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); 6091 }), 6092 extendSelection: docMethodOp(function(head, other, options) { 6093 extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); 6094 }), 6095 extendSelections: docMethodOp(function(heads, options) { 6096 extendSelections(this, clipPosArray(this, heads), options); 6097 }), 6098 extendSelectionsBy: docMethodOp(function(f, options) { 6099 var heads = map(this.sel.ranges, f); 6100 extendSelections(this, clipPosArray(this, heads), options); 6101 }), 6102 setSelections: docMethodOp(function(ranges, primary, options) { 6103 var this$1 = this; 6104 6105 if (!ranges.length) { return } 6106 var out = []; 6107 for (var i = 0; i < ranges.length; i++) 6108 { out[i] = new Range(clipPos(this$1, ranges[i].anchor), 6109 clipPos(this$1, ranges[i].head)); } 6110 if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); } 6111 setSelection(this, normalizeSelection(out, primary), options); 6112 }), 6113 addSelection: docMethodOp(function(anchor, head, options) { 6114 var ranges = this.sel.ranges.slice(0); 6115 ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); 6116 setSelection(this, normalizeSelection(ranges, ranges.length - 1), options); 6117 }), 6118 6119 getSelection: function(lineSep) { 6120 var this$1 = this; 6121 6122 var ranges = this.sel.ranges, lines; 6123 for (var i = 0; i < ranges.length; i++) { 6124 var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()); 6125 lines = lines ? lines.concat(sel) : sel; 6126 } 6127 if (lineSep === false) { return lines } 6128 else { return lines.join(lineSep || this.lineSeparator()) } 6129 }, 6130 getSelections: function(lineSep) { 6131 var this$1 = this; 6132 6133 var parts = [], ranges = this.sel.ranges; 6134 for (var i = 0; i < ranges.length; i++) { 6135 var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()); 6136 if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); } 6137 parts[i] = sel; 6138 } 6139 return parts 6140 }, 6141 replaceSelection: function(code, collapse, origin) { 6142 var dup = []; 6143 for (var i = 0; i < this.sel.ranges.length; i++) 6144 { dup[i] = code; } 6145 this.replaceSelections(dup, collapse, origin || "+input"); 6146 }, 6147 replaceSelections: docMethodOp(function(code, collapse, origin) { 6148 var this$1 = this; 6149 6150 var changes = [], sel = this.sel; 6151 for (var i = 0; i < sel.ranges.length; i++) { 6152 var range$$1 = sel.ranges[i]; 6153 changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin}; 6154 } 6155 var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); 6156 for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) 6157 { makeChange(this$1, changes[i$1]); } 6158 if (newSel) { setSelectionReplaceHistory(this, newSel); } 6159 else if (this.cm) { ensureCursorVisible(this.cm); } 6160 }), 6161 undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), 6162 redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), 6163 undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), 6164 redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), 6165 6166 setExtending: function(val) {this.extend = val;}, 6167 getExtending: function() {return this.extend}, 6168 6169 historySize: function() { 6170 var hist = this.history, done = 0, undone = 0; 6171 for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } } 6172 for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } } 6173 return {undo: done, redo: undone} 6174 }, 6175 clearHistory: function() {this.history = new History(this.history.maxGeneration);}, 6176 6177 markClean: function() { 6178 this.cleanGeneration = this.changeGeneration(true); 6179 }, 6180 changeGeneration: function(forceSplit) { 6181 if (forceSplit) 6182 { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; } 6183 return this.history.generation 6184 }, 6185 isClean: function (gen) { 6186 return this.history.generation == (gen || this.cleanGeneration) 6187 }, 6188 6189 getHistory: function() { 6190 return {done: copyHistoryArray(this.history.done), 6191 undone: copyHistoryArray(this.history.undone)} 6192 }, 6193 setHistory: function(histData) { 6194 var hist = this.history = new History(this.history.maxGeneration); 6195 hist.done = copyHistoryArray(histData.done.slice(0), null, true); 6196 hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); 6197 }, 6198 6199 setGutterMarker: docMethodOp(function(line, gutterID, value) { 6200 return changeLine(this, line, "gutter", function (line) { 6201 var markers = line.gutterMarkers || (line.gutterMarkers = {}); 6202 markers[gutterID] = value; 6203 if (!value && isEmpty(markers)) { line.gutterMarkers = null; } 6204 return true 6205 }) 6206 }), 6207 6208 clearGutter: docMethodOp(function(gutterID) { 6209 var this$1 = this; 6210 6211 this.iter(function (line) { 6212 if (line.gutterMarkers && line.gutterMarkers[gutterID]) { 6213 changeLine(this$1, line, "gutter", function () { 6214 line.gutterMarkers[gutterID] = null; 6215 if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; } 6216 return true 6217 }); 6218 } 6219 }); 6220 }), 6221 6222 lineInfo: function(line) { 6223 var n; 6224 if (typeof line == "number") { 6225 if (!isLine(this, line)) { return null } 6226 n = line; 6227 line = getLine(this, line); 6228 if (!line) { return null } 6229 } else { 6230 n = lineNo(line); 6231 if (n == null) { return null } 6232 } 6233 return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, 6234 textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, 6235 widgets: line.widgets} 6236 }, 6237 6238 addLineClass: docMethodOp(function(handle, where, cls) { 6239 return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { 6240 var prop = where == "text" ? "textClass" 6241 : where == "background" ? "bgClass" 6242 : where == "gutter" ? "gutterClass" : "wrapClass"; 6243 if (!line[prop]) { line[prop] = cls; } 6244 else if (classTest(cls).test(line[prop])) { return false } 6245 else { line[prop] += " " + cls; } 6246 return true 6247 }) 6248 }), 6249 removeLineClass: docMethodOp(function(handle, where, cls) { 6250 return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { 6251 var prop = where == "text" ? "textClass" 6252 : where == "background" ? "bgClass" 6253 : where == "gutter" ? "gutterClass" : "wrapClass"; 6254 var cur = line[prop]; 6255 if (!cur) { return false } 6256 else if (cls == null) { line[prop] = null; } 6257 else { 6258 var found = cur.match(classTest(cls)); 6259 if (!found) { return false } 6260 var end = found.index + found[0].length; 6261 line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; 6262 } 6263 return true 6264 }) 6265 }), 6266 6267 addLineWidget: docMethodOp(function(handle, node, options) { 6268 return addLineWidget(this, handle, node, options) 6269 }), 6270 removeLineWidget: function(widget) { widget.clear(); }, 6271 6272 markText: function(from, to, options) { 6273 return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range") 6274 }, 6275 setBookmark: function(pos, options) { 6276 var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), 6277 insertLeft: options && options.insertLeft, 6278 clearWhenEmpty: false, shared: options && options.shared, 6279 handleMouseEvents: options && options.handleMouseEvents}; 6280 pos = clipPos(this, pos); 6281 return markText(this, pos, pos, realOpts, "bookmark") 6282 }, 6283 findMarksAt: function(pos) { 6284 pos = clipPos(this, pos); 6285 var markers = [], spans = getLine(this, pos.line).markedSpans; 6286 if (spans) { for (var i = 0; i < spans.length; ++i) { 6287 var span = spans[i]; 6288 if ((span.from == null || span.from <= pos.ch) && 6289 (span.to == null || span.to >= pos.ch)) 6290 { markers.push(span.marker.parent || span.marker); } 6291 } } 6292 return markers 6293 }, 6294 findMarks: function(from, to, filter) { 6295 from = clipPos(this, from); to = clipPos(this, to); 6296 var found = [], lineNo$$1 = from.line; 6297 this.iter(from.line, to.line + 1, function (line) { 6298 var spans = line.markedSpans; 6299 if (spans) { for (var i = 0; i < spans.length; i++) { 6300 var span = spans[i]; 6301 if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to || 6302 span.from == null && lineNo$$1 != from.line || 6303 span.from != null && lineNo$$1 == to.line && span.from >= to.ch) && 6304 (!filter || filter(span.marker))) 6305 { found.push(span.marker.parent || span.marker); } 6306 } } 6307 ++lineNo$$1; 6308 }); 6309 return found 6310 }, 6311 getAllMarks: function() { 6312 var markers = []; 6313 this.iter(function (line) { 6314 var sps = line.markedSpans; 6315 if (sps) { for (var i = 0; i < sps.length; ++i) 6316 { if (sps[i].from != null) { markers.push(sps[i].marker); } } } 6317 }); 6318 return markers 6319 }, 6320 6321 posFromIndex: function(off) { 6322 var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length; 6323 this.iter(function (line) { 6324 var sz = line.text.length + sepSize; 6325 if (sz > off) { ch = off; return true } 6326 off -= sz; 6327 ++lineNo$$1; 6328 }); 6329 return clipPos(this, Pos(lineNo$$1, ch)) 6330 }, 6331 indexFromPos: function (coords) { 6332 coords = clipPos(this, coords); 6333 var index = coords.ch; 6334 if (coords.line < this.first || coords.ch < 0) { return 0 } 6335 var sepSize = this.lineSeparator().length; 6336 this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value 6337 index += line.text.length + sepSize; 6338 }); 6339 return index 6340 }, 6341 6342 copy: function(copyHistory) { 6343 var doc = new Doc(getLines(this, this.first, this.first + this.size), 6344 this.modeOption, this.first, this.lineSep, this.direction); 6345 doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; 6346 doc.sel = this.sel; 6347 doc.extend = false; 6348 if (copyHistory) { 6349 doc.history.undoDepth = this.history.undoDepth; 6350 doc.setHistory(this.getHistory()); 6351 } 6352 return doc 6353 }, 6354 6355 linkedDoc: function(options) { 6356 if (!options) { options = {}; } 6357 var from = this.first, to = this.first + this.size; 6358 if (options.from != null && options.from > from) { from = options.from; } 6359 if (options.to != null && options.to < to) { to = options.to; } 6360 var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); 6361 if (options.sharedHist) { copy.history = this.history 6362 ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); 6363 copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; 6364 copySharedMarkers(copy, findSharedMarkers(this)); 6365 return copy 6366 }, 6367 unlinkDoc: function(other) { 6368 var this$1 = this; 6369 6370 if (other instanceof CodeMirror$1) { other = other.doc; } 6371 if (this.linked) { for (var i = 0; i < this.linked.length; ++i) { 6372 var link = this$1.linked[i]; 6373 if (link.doc != other) { continue } 6374 this$1.linked.splice(i, 1); 6375 other.unlinkDoc(this$1); 6376 detachSharedMarkers(findSharedMarkers(this$1)); 6377 break 6378 } } 6379 // If the histories were shared, split them again 6380 if (other.history == this.history) { 6381 var splitIds = [other.id]; 6382 linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true); 6383 other.history = new History(null); 6384 other.history.done = copyHistoryArray(this.history.done, splitIds); 6385 other.history.undone = copyHistoryArray(this.history.undone, splitIds); 6386 } 6387 }, 6388 iterLinkedDocs: function(f) {linkedDocs(this, f);}, 6389 6390 getMode: function() {return this.mode}, 6391 getEditor: function() {return this.cm}, 6392 6393 splitLines: function(str) { 6394 if (this.lineSep) { return str.split(this.lineSep) } 6395 return splitLinesAuto(str) 6396 }, 6397 lineSeparator: function() { return this.lineSep || "\n" }, 6398 6399 setDirection: docMethodOp(function (dir) { 6400 if (dir != "rtl") { dir = "ltr"; } 6401 if (dir == this.direction) { return } 6402 this.direction = dir; 6403 this.iter(function (line) { return line.order = null; }); 6404 if (this.cm) { directionChanged(this.cm); } 6405 }) 6406}); 6407 6408// Public alias. 6409Doc.prototype.eachLine = Doc.prototype.iter; 6410 6411// Kludge to work around strange IE behavior where it'll sometimes 6412// re-fire a series of drag-related events right after the drop (#1551) 6413var lastDrop = 0; 6414 6415function onDrop(e) { 6416 var cm = this; 6417 clearDragCursor(cm); 6418 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) 6419 { return } 6420 e_preventDefault(e); 6421 if (ie) { lastDrop = +new Date; } 6422 var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; 6423 if (!pos || cm.isReadOnly()) { return } 6424 // Might be a file drop, in which case we simply extract the text 6425 // and insert it. 6426 if (files && files.length && window.FileReader && window.File) { 6427 var n = files.length, text = Array(n), read = 0; 6428 var loadFile = function (file, i) { 6429 if (cm.options.allowDropFileTypes && 6430 indexOf(cm.options.allowDropFileTypes, file.type) == -1) 6431 { return } 6432 6433 var reader = new FileReader; 6434 reader.onload = operation(cm, function () { 6435 var content = reader.result; 6436 if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; } 6437 text[i] = content; 6438 if (++read == n) { 6439 pos = clipPos(cm.doc, pos); 6440 var change = {from: pos, to: pos, 6441 text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), 6442 origin: "paste"}; 6443 makeChange(cm.doc, change); 6444 setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); 6445 } 6446 }); 6447 reader.readAsText(file); 6448 }; 6449 for (var i = 0; i < n; ++i) { loadFile(files[i], i); } 6450 } else { // Normal drop 6451 // Don't do a replace if the drop happened inside of the selected text. 6452 if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { 6453 cm.state.draggingText(e); 6454 // Ensure the editor is re-focused 6455 setTimeout(function () { return cm.display.input.focus(); }, 20); 6456 return 6457 } 6458 try { 6459 var text$1 = e.dataTransfer.getData("Text"); 6460 if (text$1) { 6461 var selected; 6462 if (cm.state.draggingText && !cm.state.draggingText.copy) 6463 { selected = cm.listSelections(); } 6464 setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); 6465 if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1) 6466 { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } } 6467 cm.replaceSelection(text$1, "around", "paste"); 6468 cm.display.input.focus(); 6469 } 6470 } 6471 catch(e){} 6472 } 6473} 6474 6475function onDragStart(cm, e) { 6476 if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return } 6477 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } 6478 6479 e.dataTransfer.setData("Text", cm.getSelection()); 6480 e.dataTransfer.effectAllowed = "copyMove"; 6481 6482 // Use dummy image instead of default browsers image. 6483 // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. 6484 if (e.dataTransfer.setDragImage && !safari) { 6485 var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); 6486 img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; 6487 if (presto) { 6488 img.width = img.height = 1; 6489 cm.display.wrapper.appendChild(img); 6490 // Force a relayout, or Opera won't use our image for some obscure reason 6491 img._top = img.offsetTop; 6492 } 6493 e.dataTransfer.setDragImage(img, 0, 0); 6494 if (presto) { img.parentNode.removeChild(img); } 6495 } 6496} 6497 6498function onDragOver(cm, e) { 6499 var pos = posFromMouse(cm, e); 6500 if (!pos) { return } 6501 var frag = document.createDocumentFragment(); 6502 drawSelectionCursor(cm, pos, frag); 6503 if (!cm.display.dragCursor) { 6504 cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); 6505 cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); 6506 } 6507 removeChildrenAndAdd(cm.display.dragCursor, frag); 6508} 6509 6510function clearDragCursor(cm) { 6511 if (cm.display.dragCursor) { 6512 cm.display.lineSpace.removeChild(cm.display.dragCursor); 6513 cm.display.dragCursor = null; 6514 } 6515} 6516 6517// These must be handled carefully, because naively registering a 6518// handler for each editor will cause the editors to never be 6519// garbage collected. 6520 6521function forEachCodeMirror(f) { 6522 if (!document.getElementsByClassName) { return } 6523 var byClass = document.getElementsByClassName("CodeMirror"); 6524 for (var i = 0; i < byClass.length; i++) { 6525 var cm = byClass[i].CodeMirror; 6526 if (cm) { f(cm); } 6527 } 6528} 6529 6530var globalsRegistered = false; 6531function ensureGlobalHandlers() { 6532 if (globalsRegistered) { return } 6533 registerGlobalHandlers(); 6534 globalsRegistered = true; 6535} 6536function registerGlobalHandlers() { 6537 // When the window resizes, we need to refresh active editors. 6538 var resizeTimer; 6539 on(window, "resize", function () { 6540 if (resizeTimer == null) { resizeTimer = setTimeout(function () { 6541 resizeTimer = null; 6542 forEachCodeMirror(onResize); 6543 }, 100); } 6544 }); 6545 // When the window loses focus, we want to show the editor as blurred 6546 on(window, "blur", function () { return forEachCodeMirror(onBlur); }); 6547} 6548// Called when the window resizes 6549function onResize(cm) { 6550 var d = cm.display; 6551 if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) 6552 { return } 6553 // Might be a text scaling operation, clear size caches. 6554 d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; 6555 d.scrollbarsClipped = false; 6556 cm.setSize(); 6557} 6558 6559var keyNames = { 6560 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 6561 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 6562 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 6563 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 6564 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", 6565 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 6566 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", 6567 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" 6568}; 6569 6570// Number keys 6571for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); } 6572// Alphabetic keys 6573for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); } 6574// Function keys 6575for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; } 6576 6577var keyMap = {}; 6578 6579keyMap.basic = { 6580 "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", 6581 "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", 6582 "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", 6583 "Tab": "defaultTab", "Shift-Tab": "indentAuto", 6584 "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", 6585 "Esc": "singleSelection" 6586}; 6587// Note that the save and find-related commands aren't defined by 6588// default. User code or addons can define them. Unknown commands 6589// are simply ignored. 6590keyMap.pcDefault = { 6591 "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", 6592 "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", 6593 "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", 6594 "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", 6595 "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", 6596 "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", 6597 "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", 6598 fallthrough: "basic" 6599}; 6600// Very basic readline/emacs-style bindings, which are standard on Mac. 6601keyMap.emacsy = { 6602 "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", 6603 "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", 6604 "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", 6605 "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", 6606 "Ctrl-O": "openLine" 6607}; 6608keyMap.macDefault = { 6609 "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", 6610 "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", 6611 "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", 6612 "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", 6613 "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", 6614 "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", 6615 "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", 6616 fallthrough: ["basic", "emacsy"] 6617}; 6618keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; 6619 6620// KEYMAP DISPATCH 6621 6622function normalizeKeyName(name) { 6623 var parts = name.split(/-(?!$)/); 6624 name = parts[parts.length - 1]; 6625 var alt, ctrl, shift, cmd; 6626 for (var i = 0; i < parts.length - 1; i++) { 6627 var mod = parts[i]; 6628 if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; } 6629 else if (/^a(lt)?$/i.test(mod)) { alt = true; } 6630 else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; } 6631 else if (/^s(hift)?$/i.test(mod)) { shift = true; } 6632 else { throw new Error("Unrecognized modifier name: " + mod) } 6633 } 6634 if (alt) { name = "Alt-" + name; } 6635 if (ctrl) { name = "Ctrl-" + name; } 6636 if (cmd) { name = "Cmd-" + name; } 6637 if (shift) { name = "Shift-" + name; } 6638 return name 6639} 6640 6641// This is a kludge to keep keymaps mostly working as raw objects 6642// (backwards compatibility) while at the same time support features 6643// like normalization and multi-stroke key bindings. It compiles a 6644// new normalized keymap, and then updates the old object to reflect 6645// this. 6646function normalizeKeyMap(keymap) { 6647 var copy = {}; 6648 for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) { 6649 var value = keymap[keyname]; 6650 if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue } 6651 if (value == "...") { delete keymap[keyname]; continue } 6652 6653 var keys = map(keyname.split(" "), normalizeKeyName); 6654 for (var i = 0; i < keys.length; i++) { 6655 var val = (void 0), name = (void 0); 6656 if (i == keys.length - 1) { 6657 name = keys.join(" "); 6658 val = value; 6659 } else { 6660 name = keys.slice(0, i + 1).join(" "); 6661 val = "..."; 6662 } 6663 var prev = copy[name]; 6664 if (!prev) { copy[name] = val; } 6665 else if (prev != val) { throw new Error("Inconsistent bindings for " + name) } 6666 } 6667 delete keymap[keyname]; 6668 } } 6669 for (var prop in copy) { keymap[prop] = copy[prop]; } 6670 return keymap 6671} 6672 6673function lookupKey(key, map$$1, handle, context) { 6674 map$$1 = getKeyMap(map$$1); 6675 var found = map$$1.call ? map$$1.call(key, context) : map$$1[key]; 6676 if (found === false) { return "nothing" } 6677 if (found === "...") { return "multi" } 6678 if (found != null && handle(found)) { return "handled" } 6679 6680 if (map$$1.fallthrough) { 6681 if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]") 6682 { return lookupKey(key, map$$1.fallthrough, handle, context) } 6683 for (var i = 0; i < map$$1.fallthrough.length; i++) { 6684 var result = lookupKey(key, map$$1.fallthrough[i], handle, context); 6685 if (result) { return result } 6686 } 6687 } 6688} 6689 6690// Modifier key presses don't count as 'real' key presses for the 6691// purpose of keymap fallthrough. 6692function isModifierKey(value) { 6693 var name = typeof value == "string" ? value : keyNames[value.keyCode]; 6694 return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" 6695} 6696 6697function addModifierNames(name, event, noShift) { 6698 var base = name; 6699 if (event.altKey && base != "Alt") { name = "Alt-" + name; } 6700 if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; } 6701 if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; } 6702 if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; } 6703 return name 6704} 6705 6706// Look up the name of a key as indicated by an event object. 6707function keyName(event, noShift) { 6708 if (presto && event.keyCode == 34 && event["char"]) { return false } 6709 var name = keyNames[event.keyCode]; 6710 if (name == null || event.altGraphKey) { return false } 6711 return addModifierNames(name, event, noShift) 6712} 6713 6714function getKeyMap(val) { 6715 return typeof val == "string" ? keyMap[val] : val 6716} 6717 6718// Helper for deleting text near the selection(s), used to implement 6719// backspace, delete, and similar functionality. 6720function deleteNearSelection(cm, compute) { 6721 var ranges = cm.doc.sel.ranges, kill = []; 6722 // Build up a set of ranges to kill first, merging overlapping 6723 // ranges. 6724 for (var i = 0; i < ranges.length; i++) { 6725 var toKill = compute(ranges[i]); 6726 while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { 6727 var replaced = kill.pop(); 6728 if (cmp(replaced.from, toKill.from) < 0) { 6729 toKill.from = replaced.from; 6730 break 6731 } 6732 } 6733 kill.push(toKill); 6734 } 6735 // Next, remove those actual ranges. 6736 runInOp(cm, function () { 6737 for (var i = kill.length - 1; i >= 0; i--) 6738 { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); } 6739 ensureCursorVisible(cm); 6740 }); 6741} 6742 6743// Commands are parameter-less actions that can be performed on an 6744// editor, mostly used for keybindings. 6745var commands = { 6746 selectAll: selectAll, 6747 singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); }, 6748 killLine: function (cm) { return deleteNearSelection(cm, function (range) { 6749 if (range.empty()) { 6750 var len = getLine(cm.doc, range.head.line).text.length; 6751 if (range.head.ch == len && range.head.line < cm.lastLine()) 6752 { return {from: range.head, to: Pos(range.head.line + 1, 0)} } 6753 else 6754 { return {from: range.head, to: Pos(range.head.line, len)} } 6755 } else { 6756 return {from: range.from(), to: range.to()} 6757 } 6758 }); }, 6759 deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({ 6760 from: Pos(range.from().line, 0), 6761 to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) 6762 }); }); }, 6763 delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({ 6764 from: Pos(range.from().line, 0), to: range.from() 6765 }); }); }, 6766 delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { 6767 var top = cm.charCoords(range.head, "div").top + 5; 6768 var leftPos = cm.coordsChar({left: 0, top: top}, "div"); 6769 return {from: leftPos, to: range.from()} 6770 }); }, 6771 delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) { 6772 var top = cm.charCoords(range.head, "div").top + 5; 6773 var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); 6774 return {from: range.from(), to: rightPos } 6775 }); }, 6776 undo: function (cm) { return cm.undo(); }, 6777 redo: function (cm) { return cm.redo(); }, 6778 undoSelection: function (cm) { return cm.undoSelection(); }, 6779 redoSelection: function (cm) { return cm.redoSelection(); }, 6780 goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); }, 6781 goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); }, 6782 goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, 6783 {origin: "+move", bias: 1} 6784 ); }, 6785 goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); }, 6786 {origin: "+move", bias: 1} 6787 ); }, 6788 goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, 6789 {origin: "+move", bias: -1} 6790 ); }, 6791 goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) { 6792 var top = cm.charCoords(range.head, "div").top + 5; 6793 return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") 6794 }, sel_move); }, 6795 goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) { 6796 var top = cm.charCoords(range.head, "div").top + 5; 6797 return cm.coordsChar({left: 0, top: top}, "div") 6798 }, sel_move); }, 6799 goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) { 6800 var top = cm.charCoords(range.head, "div").top + 5; 6801 var pos = cm.coordsChar({left: 0, top: top}, "div"); 6802 if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) } 6803 return pos 6804 }, sel_move); }, 6805 goLineUp: function (cm) { return cm.moveV(-1, "line"); }, 6806 goLineDown: function (cm) { return cm.moveV(1, "line"); }, 6807 goPageUp: function (cm) { return cm.moveV(-1, "page"); }, 6808 goPageDown: function (cm) { return cm.moveV(1, "page"); }, 6809 goCharLeft: function (cm) { return cm.moveH(-1, "char"); }, 6810 goCharRight: function (cm) { return cm.moveH(1, "char"); }, 6811 goColumnLeft: function (cm) { return cm.moveH(-1, "column"); }, 6812 goColumnRight: function (cm) { return cm.moveH(1, "column"); }, 6813 goWordLeft: function (cm) { return cm.moveH(-1, "word"); }, 6814 goGroupRight: function (cm) { return cm.moveH(1, "group"); }, 6815 goGroupLeft: function (cm) { return cm.moveH(-1, "group"); }, 6816 goWordRight: function (cm) { return cm.moveH(1, "word"); }, 6817 delCharBefore: function (cm) { return cm.deleteH(-1, "char"); }, 6818 delCharAfter: function (cm) { return cm.deleteH(1, "char"); }, 6819 delWordBefore: function (cm) { return cm.deleteH(-1, "word"); }, 6820 delWordAfter: function (cm) { return cm.deleteH(1, "word"); }, 6821 delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); }, 6822 delGroupAfter: function (cm) { return cm.deleteH(1, "group"); }, 6823 indentAuto: function (cm) { return cm.indentSelection("smart"); }, 6824 indentMore: function (cm) { return cm.indentSelection("add"); }, 6825 indentLess: function (cm) { return cm.indentSelection("subtract"); }, 6826 insertTab: function (cm) { return cm.replaceSelection("\t"); }, 6827 insertSoftTab: function (cm) { 6828 var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; 6829 for (var i = 0; i < ranges.length; i++) { 6830 var pos = ranges[i].from(); 6831 var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); 6832 spaces.push(spaceStr(tabSize - col % tabSize)); 6833 } 6834 cm.replaceSelections(spaces); 6835 }, 6836 defaultTab: function (cm) { 6837 if (cm.somethingSelected()) { cm.indentSelection("add"); } 6838 else { cm.execCommand("insertTab"); } 6839 }, 6840 // Swap the two chars left and right of each selection's head. 6841 // Move cursor behind the two swapped characters afterwards. 6842 // 6843 // Doesn't consider line feeds a character. 6844 // Doesn't scan more than one line above to find a character. 6845 // Doesn't do anything on an empty line. 6846 // Doesn't do anything with non-empty selections. 6847 transposeChars: function (cm) { return runInOp(cm, function () { 6848 var ranges = cm.listSelections(), newSel = []; 6849 for (var i = 0; i < ranges.length; i++) { 6850 if (!ranges[i].empty()) { continue } 6851 var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; 6852 if (line) { 6853 if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); } 6854 if (cur.ch > 0) { 6855 cur = new Pos(cur.line, cur.ch + 1); 6856 cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), 6857 Pos(cur.line, cur.ch - 2), cur, "+transpose"); 6858 } else if (cur.line > cm.doc.first) { 6859 var prev = getLine(cm.doc, cur.line - 1).text; 6860 if (prev) { 6861 cur = new Pos(cur.line, 1); 6862 cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + 6863 prev.charAt(prev.length - 1), 6864 Pos(cur.line - 1, prev.length - 1), cur, "+transpose"); 6865 } 6866 } 6867 } 6868 newSel.push(new Range(cur, cur)); 6869 } 6870 cm.setSelections(newSel); 6871 }); }, 6872 newlineAndIndent: function (cm) { return runInOp(cm, function () { 6873 var sels = cm.listSelections(); 6874 for (var i = sels.length - 1; i >= 0; i--) 6875 { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); } 6876 sels = cm.listSelections(); 6877 for (var i$1 = 0; i$1 < sels.length; i$1++) 6878 { cm.indentLine(sels[i$1].from().line, null, true); } 6879 ensureCursorVisible(cm); 6880 }); }, 6881 openLine: function (cm) { return cm.replaceSelection("\n", "start"); }, 6882 toggleOverwrite: function (cm) { return cm.toggleOverwrite(); } 6883}; 6884 6885 6886function lineStart(cm, lineN) { 6887 var line = getLine(cm.doc, lineN);
6888 var visual = visualLine(line); 6889 if (visual != line) { lineN = lineNo(visual); } 6890 return endOfLine(true, cm, visual, lineN, 1) 6891} 6892function lineEnd(cm, lineN) { 6893 var line = getLine(cm.doc, lineN); 6894 var visual = visualLineEnd(line); 6895 if (visual != line) { lineN = lineNo(visual); } 6896 return endOfLine(true, cm, line, lineN, -1) 6897} 6898function lineStartSmart(cm, pos) { 6899 var start = lineStart(cm, pos.line); 6900 var line = getLine(cm.doc, start.line); 6901 var order = getOrder(line, cm.doc.direction); 6902 if (!order || order[0].level == 0) { 6903 var firstNonWS = Math.max(0, line.text.search(/\S/)); 6904 var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; 6905 return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky) 6906 } 6907 return start 6908} 6909 6910// Run a handler that was bound to a key. 6911function doHandleBinding(cm, bound, dropShift) { 6912 if (typeof bound == "string") { 6913 bound = commands[bound]; 6914 if (!bound) { return false } 6915 } 6916 // Ensure previous input has been read, so that the handler sees a 6917 // consistent view of the document 6918 cm.display.input.ensurePolled(); 6919 var prevShift = cm.display.shift, done = false; 6920 try { 6921 if (cm.isReadOnly()) { cm.state.suppressEdits = true; } 6922 if (dropShift) { cm.display.shift = false; } 6923 done = bound(cm) != Pass; 6924 } finally { 6925 cm.display.shift = prevShift; 6926 cm.state.suppressEdits = false; 6927 } 6928 return done 6929} 6930 6931function lookupKeyForEditor(cm, name, handle) { 6932 for (var i = 0; i < cm.state.keyMaps.length; i++) { 6933 var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); 6934 if (result) { return result } 6935 } 6936 return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) 6937 || lookupKey(name, cm.options.keyMap, handle, cm) 6938} 6939 6940// Note that, despite the name, this function is also used to check 6941// for bound mouse clicks. 6942 6943var stopSeq = new Delayed; 6944function dispatchKey(cm, name, e, handle) { 6945 var seq = cm.state.keySeq; 6946 if (seq) { 6947 if (isModifierKey(name)) { return "handled" } 6948 stopSeq.set(50, function () { 6949 if (cm.state.keySeq == seq) { 6950 cm.state.keySeq = null; 6951 cm.display.input.reset(); 6952 } 6953 }); 6954 name = seq + " " + name; 6955 } 6956 var result = lookupKeyForEditor(cm, name, handle); 6957 6958 if (result == "multi") 6959 { cm.state.keySeq = name; } 6960 if (result == "handled") 6961 { signalLater(cm, "keyHandled", cm, name, e); } 6962 6963 if (result == "handled" || result == "multi") { 6964 e_preventDefault(e); 6965 restartBlink(cm); 6966 } 6967 6968 if (seq && !result && /\'$/.test(name)) { 6969 e_preventDefault(e); 6970 return true 6971 } 6972 return !!result 6973} 6974 6975// Handle a key from the keydown event. 6976function handleKeyBinding(cm, e) { 6977 var name = keyName(e, true); 6978 if (!name) { return false } 6979 6980 if (e.shiftKey && !cm.state.keySeq) { 6981 // First try to resolve full name (including 'Shift-'). Failing 6982 // that, see if there is a cursor-motion command (starting with
vendor: 94,506 bytes, lines 6983-9499
6983 // 'go') bound to the keyname without 'Shift-'. 6984 return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); }) 6985 || dispatchKey(cm, name, e, function (b) { 6986 if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) 6987 { return doHandleBinding(cm, b) } 6988 }) 6989 } else { 6990 return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }) 6991 } 6992} 6993 6994// Handle a key from the keypress event 6995function handleCharBinding(cm, e, ch) { 6996 return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); }) 6997} 6998 6999var lastStoppedKey = null; 7000function onKeyDown(e) { 7001 var cm = this; 7002 cm.curOp.focus = activeElt(); 7003 if (signalDOMEvent(cm, e)) { return } 7004 // IE does strange things with escape. 7005 if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; } 7006 var code = e.keyCode; 7007 cm.display.shift = code == 16 || e.shiftKey; 7008 var handled = handleKeyBinding(cm, e); 7009 if (presto) { 7010 lastStoppedKey = handled ? code : null; 7011 // Opera has no cut event... we try to at least catch the key combo 7012 if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) 7013 { cm.replaceSelection("", null, "cut"); } 7014 } 7015 7016 // Turn mouse into crosshair when Alt is held on Mac. 7017 if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) 7018 { showCrossHair(cm); } 7019} 7020 7021function showCrossHair(cm) { 7022 var lineDiv = cm.display.lineDiv; 7023 addClass(lineDiv, "CodeMirror-crosshair"); 7024 7025 function up(e) { 7026 if (e.keyCode == 18 || !e.altKey) { 7027 rmClass(lineDiv, "CodeMirror-crosshair"); 7028 off(document, "keyup", up); 7029 off(document, "mouseover", up); 7030 } 7031 } 7032 on(document, "keyup", up); 7033 on(document, "mouseover", up); 7034} 7035 7036function onKeyUp(e) { 7037 if (e.keyCode == 16) { this.doc.sel.shift = false; } 7038 signalDOMEvent(this, e); 7039} 7040 7041function onKeyPress(e) { 7042 var cm = this; 7043 if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return } 7044 var keyCode = e.keyCode, charCode = e.charCode; 7045 if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} 7046 if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return } 7047 var ch = String.fromCharCode(charCode == null ? keyCode : charCode); 7048 // Some browsers fire keypress events for backspace 7049 if (ch == "\x08") { return } 7050 if (handleCharBinding(cm, e, ch)) { return } 7051 cm.display.input.onKeyPress(e); 7052} 7053 7054var DOUBLECLICK_DELAY = 400; 7055 7056var PastClick = function(time, pos, button) { 7057 this.time = time; 7058 this.pos = pos; 7059 this.button = button; 7060}; 7061 7062PastClick.prototype.compare = function (time, pos, button) { 7063 return this.time + DOUBLECLICK_DELAY > time && 7064 cmp(pos, this.pos) == 0 && button == this.button 7065}; 7066 7067var lastClick; 7068var lastDoubleClick; 7069function clickRepeat(pos, button) { 7070 var now = +new Date; 7071 if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { 7072 lastClick = lastDoubleClick = null; 7073 return "triple" 7074 } else if (lastClick && lastClick.compare(now, pos, button)) { 7075 lastDoubleClick = new PastClick(now, pos, button); 7076 lastClick = null; 7077 return "double" 7078 } else { 7079 lastClick = new PastClick(now, pos, button); 7080 lastDoubleClick = null; 7081 return "single" 7082 } 7083} 7084 7085// A mouse down can be a single click, double click, triple click, 7086// start of selection drag, start of text drag, new cursor 7087// (ctrl-click), rectangle drag (alt-drag), or xwin 7088// middle-click-paste. Or it might be a click on something we should 7089// not interfere with, such as a scrollbar or widget. 7090function onMouseDown(e) { 7091 var cm = this, display = cm.display; 7092 if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return } 7093 display.input.ensurePolled(); 7094 display.shift = e.shiftKey; 7095 7096 if (eventInWidget(display, e)) { 7097 if (!webkit) { 7098 // Briefly turn off draggability, to allow widgets to do 7099 // normal dragging things. 7100 display.scroller.draggable = false; 7101 setTimeout(function () { return display.scroller.draggable = true; }, 100); 7102 } 7103 return 7104 } 7105 if (clickInGutter(cm, e)) { return } 7106 var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single"; 7107 window.focus(); 7108 7109 // #3261: make sure, that we're not starting a second selection 7110 if (button == 1 && cm.state.selectingText) 7111 { cm.state.selectingText(e); } 7112 7113 if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return } 7114 7115 if (button == 1) { 7116 if (pos) { leftButtonDown(cm, pos, repeat, e); } 7117 else if (e_target(e) == display.scroller) { e_preventDefault(e); } 7118 } else if (button == 2) { 7119 if (pos) { extendSelection(cm.doc, pos); } 7120 setTimeout(function () { return display.input.focus(); }, 20); 7121 } else if (button == 3) { 7122 if (captureRightClick) { onContextMenu(cm, e); } 7123 else { delayBlurEvent(cm); } 7124 } 7125} 7126 7127function handleMappedButton(cm, button, pos, repeat, event) { 7128 var name = "Click"; 7129 if (repeat == "double") { name = "Double" + name; } 7130 else if (repeat == "triple") { name = "Triple" + name; } 7131 name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; 7132 7133 return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { 7134 if (typeof bound == "string") { bound = commands[bound]; } 7135 if (!bound) { return false } 7136 var done = false; 7137 try { 7138 if (cm.isReadOnly()) { cm.state.suppressEdits = true; } 7139 done = bound(cm, pos) != Pass; 7140 } finally { 7141 cm.state.suppressEdits = false; 7142 } 7143 return done 7144 }) 7145} 7146 7147function configureMouse(cm, repeat, event) { 7148 var option = cm.getOption("configureMouse"); 7149 var value = option ? option(cm, repeat, event) : {}; 7150 if (value.unit == null) { 7151 var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; 7152 value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; 7153 } 7154 if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; } 7155 if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; } 7156 if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); } 7157 return value 7158} 7159 7160function leftButtonDown(cm, pos, repeat, event) { 7161 if (ie) { setTimeout(bind(ensureFocus, cm), 0); } 7162 else { cm.curOp.focus = activeElt(); } 7163 7164 var behavior = configureMouse(cm, repeat, event); 7165 7166 var sel = cm.doc.sel, contained; 7167 if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && 7168 repeat == "single" && (contained = sel.contains(pos)) > -1 && 7169 (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && 7170 (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) 7171 { leftButtonStartDrag(cm, event, pos, behavior); } 7172 else 7173 { leftButtonSelect(cm, event, pos, behavior); } 7174} 7175 7176// Start a text drag. When it ends, see if any dragging actually 7177// happen, and treat as a click if it didn't. 7178function leftButtonStartDrag(cm, event, pos, behavior) { 7179 var display = cm.display, moved = false; 7180 var dragEnd = operation(cm, function (e) { 7181 if (webkit) { display.scroller.draggable = false; } 7182 cm.state.draggingText = false; 7183 off(document, "mouseup", dragEnd); 7184 off(document, "mousemove", mouseMove); 7185 off(display.scroller, "dragstart", dragStart); 7186 off(display.scroller, "drop", dragEnd); 7187 if (!moved) { 7188 e_preventDefault(e); 7189 if (!behavior.addNew) 7190 { extendSelection(cm.doc, pos, null, null, behavior.extend); } 7191 // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) 7192 if (webkit || ie && ie_version == 9) 7193 { setTimeout(function () {document.body.focus(); display.input.focus();}, 20); } 7194 else 7195 { display.input.focus(); } 7196 } 7197 }); 7198 var mouseMove = function(e2) { 7199 moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; 7200 }; 7201 var dragStart = function () { return moved = true; }; 7202 // Let the drag handler handle this. 7203 if (webkit) { display.scroller.draggable = true; } 7204 cm.state.draggingText = dragEnd; 7205 dragEnd.copy = !behavior.moveOnDrag; 7206 // IE's approach to draggable 7207 if (display.scroller.dragDrop) { display.scroller.dragDrop(); } 7208 on(document, "mouseup", dragEnd); 7209 on(document, "mousemove", mouseMove); 7210 on(display.scroller, "dragstart", dragStart); 7211 on(display.scroller, "drop", dragEnd); 7212 7213 delayBlurEvent(cm); 7214 setTimeout(function () { return display.input.focus(); }, 20); 7215} 7216 7217function rangeForUnit(cm, pos, unit) { 7218 if (unit == "char") { return new Range(pos, pos) } 7219 if (unit == "word") { return cm.findWordAt(pos) } 7220 if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) } 7221 var result = unit(cm, pos); 7222 return new Range(result.from, result.to) 7223} 7224 7225// Normal selection, as opposed to text dragging. 7226function leftButtonSelect(cm, event, start, behavior) { 7227 var display = cm.display, doc = cm.doc; 7228 e_preventDefault(event); 7229 7230 var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; 7231 if (behavior.addNew && !behavior.extend) { 7232 ourIndex = doc.sel.contains(start); 7233 if (ourIndex > -1) 7234 { ourRange = ranges[ourIndex]; } 7235 else 7236 { ourRange = new Range(start, start); } 7237 } else { 7238 ourRange = doc.sel.primary(); 7239 ourIndex = doc.sel.primIndex; 7240 } 7241 7242 if (behavior.unit == "rectangle") { 7243 if (!behavior.addNew) { ourRange = new Range(start, start); } 7244 start = posFromMouse(cm, event, true, true); 7245 ourIndex = -1; 7246 } else { 7247 var range$$1 = rangeForUnit(cm, start, behavior.unit); 7248 if (behavior.extend) 7249 { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); } 7250 else 7251 { ourRange = range$$1; } 7252 } 7253 7254 if (!behavior.addNew) { 7255 ourIndex = 0; 7256 setSelection(doc, new Selection([ourRange], 0), sel_mouse); 7257 startSel = doc.sel; 7258 } else if (ourIndex == -1) { 7259 ourIndex = ranges.length; 7260 setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), 7261 {scroll: false, origin: "*mouse"}); 7262 } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { 7263 setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), 7264 {scroll: false, origin: "*mouse"}); 7265 startSel = doc.sel; 7266 } else { 7267 replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); 7268 } 7269 7270 var lastPos = start; 7271 function extendTo(pos) { 7272 if (cmp(lastPos, pos) == 0) { return } 7273 lastPos = pos; 7274 7275 if (behavior.unit == "rectangle") { 7276 var ranges = [], tabSize = cm.options.tabSize; 7277 var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); 7278 var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); 7279 var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); 7280 for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); 7281 line <= end; line++) { 7282 var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); 7283 if (left == right) 7284 { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); } 7285 else if (text.length > leftPos) 7286 { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); } 7287 } 7288 if (!ranges.length) { ranges.push(new Range(start, start)); } 7289 setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), 7290 {origin: "*mouse", scroll: false}); 7291 cm.scrollIntoView(pos); 7292 } else { 7293 var oldRange = ourRange; 7294 var range$$1 = rangeForUnit(cm, pos, behavior.unit); 7295 var anchor = oldRange.anchor, head; 7296 if (cmp(range$$1.anchor, anchor) > 0) { 7297 head = range$$1.head; 7298 anchor = minPos(oldRange.from(), range$$1.anchor); 7299 } else { 7300 head = range$$1.anchor; 7301 anchor = maxPos(oldRange.to(), range$$1.head); 7302 } 7303 var ranges$1 = startSel.ranges.slice(0); 7304 ranges$1[ourIndex] = new Range(clipPos(doc, anchor), head); 7305 setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse); 7306 } 7307 } 7308 7309 var editorSize = display.wrapper.getBoundingClientRect(); 7310 // Used to ensure timeout re-tries don't fire when another extend 7311 // happened in the meantime (clearTimeout isn't reliable -- at 7312 // least on Chrome, the timeouts still happen even when cleared, 7313 // if the clear happens after their scheduled firing time). 7314 var counter = 0; 7315 7316 function extend(e) { 7317 var curCount = ++counter; 7318 var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); 7319 if (!cur) { return } 7320 if (cmp(cur, lastPos) != 0) { 7321 cm.curOp.focus = activeElt(); 7322 extendTo(cur); 7323 var visible = visibleLines(display, doc); 7324 if (cur.line >= visible.to || cur.line < visible.from) 7325 { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); } 7326 } else { 7327 var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; 7328 if (outside) { setTimeout(operation(cm, function () { 7329 if (counter != curCount) { return } 7330 display.scroller.scrollTop += outside; 7331 extend(e); 7332 }), 50); } 7333 } 7334 } 7335 7336 function done(e) { 7337 cm.state.selectingText = false; 7338 counter = Infinity; 7339 e_preventDefault(e); 7340 display.input.focus(); 7341 off(document, "mousemove", move); 7342 off(document, "mouseup", up); 7343 doc.history.lastSelOrigin = null; 7344 } 7345 7346 var move = operation(cm, function (e) { 7347 if (!e_button(e)) { done(e); } 7348 else { extend(e); } 7349 }); 7350 var up = operation(cm, done); 7351 cm.state.selectingText = up; 7352 on(document, "mousemove", move); 7353 on(document, "mouseup", up); 7354} 7355 7356 7357// Determines whether an event happened in the gutter, and fires the 7358// handlers for the corresponding event. 7359function gutterEvent(cm, e, type, prevent) { 7360 var mX, mY; 7361 try { mX = e.clientX; mY = e.clientY; } 7362 catch(e) { return false } 7363 if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false } 7364 if (prevent) { e_preventDefault(e); } 7365 7366 var display = cm.display; 7367 var lineBox = display.lineDiv.getBoundingClientRect(); 7368 7369 if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) } 7370 mY -= lineBox.top - display.viewOffset; 7371 7372 for (var i = 0; i < cm.options.gutters.length; ++i) { 7373 var g = display.gutters.childNodes[i]; 7374 if (g && g.getBoundingClientRect().right >= mX) { 7375 var line = lineAtHeight(cm.doc, mY); 7376 var gutter = cm.options.gutters[i]; 7377 signal(cm, type, cm, line, gutter, e); 7378 return e_defaultPrevented(e) 7379 } 7380 } 7381} 7382 7383function clickInGutter(cm, e) { 7384 return gutterEvent(cm, e, "gutterClick", true) 7385} 7386 7387// CONTEXT MENU HANDLING 7388 7389// To make the context menu work, we need to briefly unhide the 7390// textarea (making it as unobtrusive as possible) to let the 7391// right-click take effect on it. 7392function onContextMenu(cm, e) { 7393 if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return } 7394 if (signalDOMEvent(cm, e, "contextmenu")) { return } 7395 cm.display.input.onContextMenu(e); 7396} 7397 7398function contextMenuInGutter(cm, e) { 7399 if (!hasHandler(cm, "gutterContextMenu")) { return false } 7400 return gutterEvent(cm, e, "gutterContextMenu", false) 7401} 7402 7403function themeChanged(cm) { 7404 cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + 7405 cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); 7406 clearCaches(cm); 7407} 7408 7409var Init = {toString: function(){return "CodeMirror.Init"}}; 7410 7411var defaults = {}; 7412var optionHandlers = {}; 7413 7414function defineOptions(CodeMirror) { 7415 var optionHandlers = CodeMirror.optionHandlers; 7416 7417 function option(name, deflt, handle, notOnInit) { 7418 CodeMirror.defaults[name] = deflt; 7419 if (handle) { optionHandlers[name] = 7420 notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; } 7421 } 7422 7423 CodeMirror.defineOption = option; 7424 7425 // Passed to option handlers when there is no old value. 7426 CodeMirror.Init = Init; 7427 7428 // These two are, on init, called from the constructor because they 7429 // have to be initialized before the editor can start at all. 7430 option("value", "", function (cm, val) { return cm.setValue(val); }, true); 7431 option("mode", null, function (cm, val) { 7432 cm.doc.modeOption = val; 7433 loadMode(cm); 7434 }, true); 7435 7436 option("indentUnit", 2, loadMode, true); 7437 option("indentWithTabs", false); 7438 option("smartIndent", true); 7439 option("tabSize", 4, function (cm) { 7440 resetModeState(cm); 7441 clearCaches(cm); 7442 regChange(cm); 7443 }, true); 7444 option("lineSeparator", null, function (cm, val) { 7445 cm.doc.lineSep = val; 7446 if (!val) { return } 7447 var newBreaks = [], lineNo = cm.doc.first; 7448 cm.doc.iter(function (line) { 7449 for (var pos = 0;;) { 7450 var found = line.text.indexOf(val, pos); 7451 if (found == -1) { break } 7452 pos = found + val.length; 7453 newBreaks.push(Pos(lineNo, found)); 7454 } 7455 lineNo++; 7456 }); 7457 for (var i = newBreaks.length - 1; i >= 0; i--) 7458 { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); } 7459 }); 7460 option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) { 7461 cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); 7462 if (old != Init) { cm.refresh(); } 7463 }); 7464 option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true); 7465 option("electricChars", true); 7466 option("inputStyle", mobile ? "contenteditable" : "textarea", function () { 7467 throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME 7468 }, true); 7469 option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true); 7470 option("rtlMoveVisually", !windows); 7471 option("wholeLineUpdateBefore", true); 7472 7473 option("theme", "default", function (cm) { 7474 themeChanged(cm); 7475 guttersChanged(cm); 7476 }, true); 7477 option("keyMap", "default", function (cm, val, old) { 7478 var next = getKeyMap(val); 7479 var prev = old != Init && getKeyMap(old); 7480 if (prev && prev.detach) { prev.detach(cm, next); } 7481 if (next.attach) { next.attach(cm, prev || null); } 7482 }); 7483 option("extraKeys", null); 7484 option("configureMouse", null); 7485 7486 option("lineWrapping", false, wrappingChanged, true); 7487 option("gutters", [], function (cm) { 7488 setGuttersForLineNumbers(cm.options); 7489 guttersChanged(cm); 7490 }, true); 7491 option("fixedGutter", true, function (cm, val) { 7492 cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; 7493 cm.refresh(); 7494 }, true); 7495 option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true); 7496 option("scrollbarStyle", "native", function (cm) { 7497 initScrollbars(cm); 7498 updateScrollbars(cm); 7499 cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); 7500 cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); 7501 }, true); 7502 option("lineNumbers", false, function (cm) { 7503 setGuttersForLineNumbers(cm.options); 7504 guttersChanged(cm); 7505 }, true); 7506 option("firstLineNumber", 1, guttersChanged, true); 7507 option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true); 7508 option("showCursorWhenSelecting", false, updateSelection, true); 7509 7510 option("resetSelectionOnContextMenu", true); 7511 option("lineWiseCopyCut", true); 7512 option("pasteLinesPerSelection", true); 7513 7514 option("readOnly", false, function (cm, val) { 7515 if (val == "nocursor") { 7516 onBlur(cm); 7517 cm.display.input.blur(); 7518 } 7519 cm.display.input.readOnlyChanged(val); 7520 }); 7521 option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true); 7522 option("dragDrop", true, dragDropChanged); 7523 option("allowDropFileTypes", null); 7524 7525 option("cursorBlinkRate", 530); 7526 option("cursorScrollMargin", 0); 7527 option("cursorHeight", 1, updateSelection, true); 7528 option("singleCursorHeightPerLine", true, updateSelection, true); 7529 option("workTime", 100); 7530 option("workDelay", 100); 7531 option("flattenSpans", true, resetModeState, true); 7532 option("addModeClass", false, resetModeState, true); 7533 option("pollInterval", 100); 7534 option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; }); 7535 option("historyEventDelay", 1250); 7536 option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true); 7537 option("maxHighlightLength", 10000, resetModeState, true); 7538 option("moveInputWithCursor", true, function (cm, val) { 7539 if (!val) { cm.display.input.resetPosition(); } 7540 }); 7541 7542 option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; }); 7543 option("autofocus", null); 7544 option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true); 7545} 7546 7547function guttersChanged(cm) { 7548 updateGutters(cm); 7549 regChange(cm); 7550 alignHorizontally(cm); 7551} 7552 7553function dragDropChanged(cm, value, old) { 7554 var wasOn = old && old != Init; 7555 if (!value != !wasOn) { 7556 var funcs = cm.display.dragFunctions; 7557 var toggle = value ? on : off; 7558 toggle(cm.display.scroller, "dragstart", funcs.start); 7559 toggle(cm.display.scroller, "dragenter", funcs.enter); 7560 toggle(cm.display.scroller, "dragover", funcs.over); 7561 toggle(cm.display.scroller, "dragleave", funcs.leave); 7562 toggle(cm.display.scroller, "drop", funcs.drop); 7563 } 7564} 7565 7566function wrappingChanged(cm) { 7567 if (cm.options.lineWrapping) { 7568 addClass(cm.display.wrapper, "CodeMirror-wrap"); 7569 cm.display.sizer.style.minWidth = ""; 7570 cm.display.sizerWidth = null; 7571 } else { 7572 rmClass(cm.display.wrapper, "CodeMirror-wrap"); 7573 findMaxLine(cm); 7574 } 7575 estimateLineHeights(cm); 7576 regChange(cm); 7577 clearCaches(cm); 7578 setTimeout(function () { return updateScrollbars(cm); }, 100); 7579} 7580 7581// A CodeMirror instance represents an editor. This is the object 7582// that user code is usually dealing with. 7583 7584function CodeMirror$1(place, options) { 7585 var this$1 = this; 7586 7587 if (!(this instanceof CodeMirror$1)) { return new CodeMirror$1(place, options) } 7588 7589 this.options = options = options ? copyObj(options) : {}; 7590 // Determine effective options based on given values and defaults. 7591 copyObj(defaults, options, false); 7592 setGuttersForLineNumbers(options); 7593 7594 var doc = options.value; 7595 if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); } 7596 this.doc = doc; 7597 7598 var input = new CodeMirror$1.inputStyles[options.inputStyle](this); 7599 var display = this.display = new Display(place, doc, input); 7600 display.wrapper.CodeMirror = this; 7601 updateGutters(this); 7602 themeChanged(this); 7603 if (options.lineWrapping) 7604 { this.display.wrapper.className += " CodeMirror-wrap"; } 7605 initScrollbars(this); 7606 7607 this.state = { 7608 keyMaps: [], // stores maps added by addKeyMap 7609 overlays: [], // highlighting overlays, as added by addOverlay 7610 modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info 7611 overwrite: false, 7612 delayingBlurEvent: false, 7613 focused: false, 7614 suppressEdits: false, // used to disable editing during key handlers when in readOnly mode 7615 pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll 7616 selectingText: false, 7617 draggingText: false, 7618 highlight: new Delayed(), // stores highlight worker timeout 7619 keySeq: null, // Unfinished key sequence 7620 specialChars: null 7621 }; 7622 7623 if (options.autofocus && !mobile) { display.input.focus(); } 7624 7625 // Override magic textarea content restore that IE sometimes does 7626 // on our hidden textarea on reload 7627 if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); } 7628 7629 registerEventHandlers(this); 7630 ensureGlobalHandlers(); 7631 7632 startOperation(this); 7633 this.curOp.forceUpdate = true; 7634 attachDoc(this, doc); 7635 7636 if ((options.autofocus && !mobile) || this.hasFocus()) 7637 { setTimeout(bind(onFocus, this), 20); } 7638 else 7639 { onBlur(this); } 7640 7641 for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt)) 7642 { optionHandlers[opt](this$1, options[opt], Init); } } 7643 maybeUpdateLineNumberWidth(this); 7644 if (options.finishInit) { options.finishInit(this); } 7645 for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); } 7646 endOperation(this); 7647 // Suppress optimizelegibility in Webkit, since it breaks text 7648 // measuring on line wrapping boundaries. 7649 if (webkit && options.lineWrapping && 7650 getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") 7651 { display.lineDiv.style.textRendering = "auto"; } 7652} 7653 7654// The default configuration options. 7655CodeMirror$1.defaults = defaults; 7656// Functions to run when options are changed. 7657CodeMirror$1.optionHandlers = optionHandlers; 7658 7659// Attach the necessary event handlers when initializing the editor 7660function registerEventHandlers(cm) { 7661 var d = cm.display; 7662 on(d.scroller, "mousedown", operation(cm, onMouseDown)); 7663 // Older IE's will not fire a second mousedown for a double click 7664 if (ie && ie_version < 11) 7665 { on(d.scroller, "dblclick", operation(cm, function (e) { 7666 if (signalDOMEvent(cm, e)) { return } 7667 var pos = posFromMouse(cm, e); 7668 if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return } 7669 e_preventDefault(e); 7670 var word = cm.findWordAt(pos); 7671 extendSelection(cm.doc, word.anchor, word.head); 7672 })); } 7673 else 7674 { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); } 7675 // Some browsers fire contextmenu *after* opening the menu, at 7676 // which point we can't mess with it anymore. Context menu is 7677 // handled in onMouseDown for these browsers. 7678 if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); } 7679 7680 // Used to suppress mouse event handling when a touch happens 7681 var touchFinished, prevTouch = {end: 0}; 7682 function finishTouch() { 7683 if (d.activeTouch) { 7684 touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000); 7685 prevTouch = d.activeTouch; 7686 prevTouch.end = +new Date; 7687 } 7688 } 7689 function isMouseLikeTouchEvent(e) { 7690 if (e.touches.length != 1) { return false } 7691 var touch = e.touches[0]; 7692 return touch.radiusX <= 1 && touch.radiusY <= 1 7693 } 7694 function farAway(touch, other) { 7695 if (other.left == null) { return true } 7696 var dx = other.left - touch.left, dy = other.top - touch.top; 7697 return dx * dx + dy * dy > 20 * 20 7698 } 7699 on(d.scroller, "touchstart", function (e) { 7700 if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) { 7701 d.input.ensurePolled(); 7702 clearTimeout(touchFinished); 7703 var now = +new Date; 7704 d.activeTouch = {start: now, moved: false, 7705 prev: now - prevTouch.end <= 300 ? prevTouch : null}; 7706 if (e.touches.length == 1) { 7707 d.activeTouch.left = e.touches[0].pageX; 7708 d.activeTouch.top = e.touches[0].pageY; 7709 } 7710 } 7711 }); 7712 on(d.scroller, "touchmove", function () { 7713 if (d.activeTouch) { d.activeTouch.moved = true; } 7714 }); 7715 on(d.scroller, "touchend", function (e) { 7716 var touch = d.activeTouch; 7717 if (touch && !eventInWidget(d, e) && touch.left != null && 7718 !touch.moved && new Date - touch.start < 300) { 7719 var pos = cm.coordsChar(d.activeTouch, "page"), range; 7720 if (!touch.prev || farAway(touch, touch.prev)) // Single tap 7721 { range = new Range(pos, pos); } 7722 else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap 7723 { range = cm.findWordAt(pos); } 7724 else // Triple tap 7725 { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); } 7726 cm.setSelection(range.anchor, range.head); 7727 cm.focus(); 7728 e_preventDefault(e); 7729 } 7730 finishTouch(); 7731 }); 7732 on(d.scroller, "touchcancel", finishTouch); 7733 7734 // Sync scrolling between fake scrollbars and real scrollable 7735 // area, ensure viewport is updated when scrolling. 7736 on(d.scroller, "scroll", function () { 7737 if (d.scroller.clientHeight) { 7738 updateScrollTop(cm, d.scroller.scrollTop); 7739 setScrollLeft(cm, d.scroller.scrollLeft, true); 7740 signal(cm, "scroll", cm); 7741 } 7742 }); 7743 7744 // Listen to wheel events in order to try and update the viewport on time. 7745 on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); }); 7746 on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); }); 7747 7748 // Prevent wrapper from ever scrolling 7749 on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); 7750 7751 d.dragFunctions = { 7752 enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }}, 7753 over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, 7754 start: function (e) { return onDragStart(cm, e); }, 7755 drop: operation(cm, onDrop), 7756 leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }} 7757 }; 7758 7759 var inp = d.input.getField(); 7760 on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); }); 7761 on(inp, "keydown", operation(cm, onKeyDown)); 7762 on(inp, "keypress", operation(cm, onKeyPress)); 7763 on(inp, "focus", function (e) { return onFocus(cm, e); }); 7764 on(inp, "blur", function (e) { return onBlur(cm, e); }); 7765} 7766 7767var initHooks = []; 7768CodeMirror$1.defineInitHook = function (f) { return initHooks.push(f); }; 7769 7770// Indent the given line. The how parameter can be "smart", 7771// "add"/null, "subtract", or "prev". When aggressive is false 7772// (typically set to true for forced single-line indents), empty 7773// lines are not indented, and places where the mode returns Pass 7774// are left alone. 7775function indentLine(cm, n, how, aggressive) { 7776 var doc = cm.doc, state; 7777 if (how == null) { how = "add"; } 7778 if (how == "smart") { 7779 // Fall back to "prev" when the mode doesn't have an indentation 7780 // method. 7781 if (!doc.mode.indent) { how = "prev"; } 7782 else { state = getContextBefore(cm, n).state; } 7783 } 7784 7785 var tabSize = cm.options.tabSize; 7786 var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); 7787 if (line.stateAfter) { line.stateAfter = null; } 7788 var curSpaceString = line.text.match(/^\s*/)[0], indentation; 7789 if (!aggressive && !/\S/.test(line.text)) { 7790 indentation = 0; 7791 how = "not"; 7792 } else if (how == "smart") { 7793 indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); 7794 if (indentation == Pass || indentation > 150) { 7795 if (!aggressive) { return } 7796 how = "prev"; 7797 } 7798 } 7799 if (how == "prev") { 7800 if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); } 7801 else { indentation = 0; } 7802 } else if (how == "add") { 7803 indentation = curSpace + cm.options.indentUnit; 7804 } else if (how == "subtract") { 7805 indentation = curSpace - cm.options.indentUnit; 7806 } else if (typeof how == "number") { 7807 indentation = curSpace + how; 7808 } 7809 indentation = Math.max(0, indentation); 7810 7811 var indentString = "", pos = 0; 7812 if (cm.options.indentWithTabs) 7813 { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} } 7814 if (pos < indentation) { indentString += spaceStr(indentation - pos); } 7815 7816 if (indentString != curSpaceString) { 7817 replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); 7818 line.stateAfter = null; 7819 return true 7820 } else { 7821 // Ensure that, if the cursor was in the whitespace at the start 7822 // of the line, it is moved to the end of that space. 7823 for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) { 7824 var range = doc.sel.ranges[i$1]; 7825 if (range.head.line == n && range.head.ch < curSpaceString.length) { 7826 var pos$1 = Pos(n, curSpaceString.length); 7827 replaceOneSelection(doc, i$1, new Range(pos$1, pos$1)); 7828 break 7829 } 7830 } 7831 } 7832} 7833 7834// This will be set to a {lineWise: bool, text: [string]} object, so 7835// that, when pasting, we know what kind of selections the copied 7836// text was made out of. 7837var lastCopied = null; 7838 7839function setLastCopied(newLastCopied) { 7840 lastCopied = newLastCopied; 7841} 7842 7843function applyTextInput(cm, inserted, deleted, sel, origin) { 7844 var doc = cm.doc; 7845 cm.display.shift = false; 7846 if (!sel) { sel = doc.sel; } 7847 7848 var paste = cm.state.pasteIncoming || origin == "paste"; 7849 var textLines = splitLinesAuto(inserted), multiPaste = null; 7850 // When pasing N lines into N selections, insert one line per selection 7851 if (paste && sel.ranges.length > 1) { 7852 if (lastCopied && lastCopied.text.join("\n") == inserted) { 7853 if (sel.ranges.length % lastCopied.text.length == 0) { 7854 multiPaste = []; 7855 for (var i = 0; i < lastCopied.text.length; i++) 7856 { multiPaste.push(doc.splitLines(lastCopied.text[i])); } 7857 } 7858 } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { 7859 multiPaste = map(textLines, function (l) { return [l]; }); 7860 } 7861 } 7862 7863 var updateInput; 7864 // Normal behavior is to insert the new text into every selection 7865 for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) { 7866 var range$$1 = sel.ranges[i$1]; 7867 var from = range$$1.from(), to = range$$1.to(); 7868 if (range$$1.empty()) { 7869 if (deleted && deleted > 0) // Handle deletion 7870 { from = Pos(from.line, from.ch - deleted); } 7871 else if (cm.state.overwrite && !paste) // Handle overwrite 7872 { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); } 7873 else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) 7874 { from = to = Pos(from.line, 0); } 7875 } 7876 updateInput = cm.curOp.updateInput; 7877 var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, 7878 origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; 7879 makeChange(cm.doc, changeEvent); 7880 signalLater(cm, "inputRead", cm, changeEvent); 7881 } 7882 if (inserted && !paste) 7883 { triggerElectric(cm, inserted); } 7884 7885 ensureCursorVisible(cm); 7886 cm.curOp.updateInput = updateInput; 7887 cm.curOp.typing = true; 7888 cm.state.pasteIncoming = cm.state.cutIncoming = false; 7889} 7890 7891function handlePaste(e, cm) { 7892 var pasted = e.clipboardData && e.clipboardData.getData("Text"); 7893 if (pasted) { 7894 e.preventDefault(); 7895 if (!cm.isReadOnly() && !cm.options.disableInput) 7896 { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); } 7897 return true 7898 } 7899} 7900 7901function triggerElectric(cm, inserted) { 7902 // When an 'electric' character is inserted, immediately trigger a reindent 7903 if (!cm.options.electricChars || !cm.options.smartIndent) { return } 7904 var sel = cm.doc.sel; 7905 7906 for (var i = sel.ranges.length - 1; i >= 0; i--) { 7907 var range$$1 = sel.ranges[i]; 7908 if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue } 7909 var mode = cm.getModeAt(range$$1.head); 7910 var indented = false; 7911 if (mode.electricChars) { 7912 for (var j = 0; j < mode.electricChars.length; j++) 7913 { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { 7914 indented = indentLine(cm, range$$1.head.line, "smart"); 7915 break 7916 } } 7917 } else if (mode.electricInput) { 7918 if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch))) 7919 { indented = indentLine(cm, range$$1.head.line, "smart"); } 7920 } 7921 if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); } 7922 } 7923} 7924 7925function copyableRanges(cm) { 7926 var text = [], ranges = []; 7927 for (var i = 0; i < cm.doc.sel.ranges.length; i++) { 7928 var line = cm.doc.sel.ranges[i].head.line; 7929 var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; 7930 ranges.push(lineRange); 7931 text.push(cm.getRange(lineRange.anchor, lineRange.head)); 7932 } 7933 return {text: text, ranges: ranges} 7934} 7935 7936function disableBrowserMagic(field, spellcheck) { 7937 field.setAttribute("autocorrect", "off"); 7938 field.setAttribute("autocapitalize", "off"); 7939 field.setAttribute("spellcheck", !!spellcheck); 7940} 7941 7942function hiddenTextarea() { 7943 var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"); 7944 var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); 7945 // The textarea is kept positioned near the cursor to prevent the 7946 // fact that it'll be scrolled into view on input from scrolling 7947 // our fake cursor out of view. On webkit, when wrap=off, paste is 7948 // very slow. So make the area wide instead. 7949 if (webkit) { te.style.width = "1000px"; } 7950 else { te.setAttribute("wrap", "off"); } 7951 // If border: 0; -- iOS fails to open keyboard (issue #1287) 7952 if (ios) { te.style.border = "1px solid black"; } 7953 disableBrowserMagic(te); 7954 return div 7955} 7956 7957// The publicly visible API. Note that methodOp(f) means 7958// 'wrap f in an operation, performed on its `this` parameter'. 7959 7960// This is not the complete set of editor methods. Most of the 7961// methods defined on the Doc type are also injected into 7962// CodeMirror.prototype, for backwards compatibility and 7963// convenience. 7964 7965var addEditorMethods = function(CodeMirror) { 7966 var optionHandlers = CodeMirror.optionHandlers; 7967 7968 var helpers = CodeMirror.helpers = {}; 7969 7970 CodeMirror.prototype = { 7971 constructor: CodeMirror, 7972 focus: function(){window.focus(); this.display.input.focus();}, 7973 7974 setOption: function(option, value) { 7975 var options = this.options, old = options[option]; 7976 if (options[option] == value && option != "mode") { return } 7977 options[option] = value; 7978 if (optionHandlers.hasOwnProperty(option)) 7979 { operation(this, optionHandlers[option])(this, value, old); } 7980 signal(this, "optionChange", this, option); 7981 }, 7982 7983 getOption: function(option) {return this.options[option]}, 7984 getDoc: function() {return this.doc}, 7985 7986 addKeyMap: function(map$$1, bottom) { 7987 this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1)); 7988 }, 7989 removeKeyMap: function(map$$1) { 7990 var maps = this.state.keyMaps; 7991 for (var i = 0; i < maps.length; ++i) 7992 { if (maps[i] == map$$1 || maps[i].name == map$$1) { 7993 maps.splice(i, 1); 7994 return true 7995 } } 7996 }, 7997 7998 addOverlay: methodOp(function(spec, options) { 7999 var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); 8000 if (mode.startState) { throw new Error("Overlays may not be stateful.") } 8001 insertSorted(this.state.overlays, 8002 {mode: mode, modeSpec: spec, opaque: options && options.opaque, 8003 priority: (options && options.priority) || 0}, 8004 function (overlay) { return overlay.priority; }); 8005 this.state.modeGen++; 8006 regChange(this); 8007 }), 8008 removeOverlay: methodOp(function(spec) { 8009 var this$1 = this; 8010 8011 var overlays = this.state.overlays; 8012 for (var i = 0; i < overlays.length; ++i) { 8013 var cur = overlays[i].modeSpec; 8014 if (cur == spec || typeof spec == "string" && cur.name == spec) { 8015 overlays.splice(i, 1); 8016 this$1.state.modeGen++; 8017 regChange(this$1); 8018 return 8019 } 8020 } 8021 }), 8022 8023 indentLine: methodOp(function(n, dir, aggressive) { 8024 if (typeof dir != "string" && typeof dir != "number") { 8025 if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; } 8026 else { dir = dir ? "add" : "subtract"; } 8027 } 8028 if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); } 8029 }), 8030 indentSelection: methodOp(function(how) { 8031 var this$1 = this; 8032 8033 var ranges = this.doc.sel.ranges, end = -1; 8034 for (var i = 0; i < ranges.length; i++) { 8035 var range$$1 = ranges[i]; 8036 if (!range$$1.empty()) { 8037 var from = range$$1.from(), to = range$$1.to(); 8038 var start = Math.max(end, from.line); 8039 end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; 8040 for (var j = start; j < end; ++j) 8041 { indentLine(this$1, j, how); } 8042 var newRanges = this$1.doc.sel.ranges; 8043 if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) 8044 { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); } 8045 } else if (range$$1.head.line > end) { 8046 indentLine(this$1, range$$1.head.line, how, true); 8047 end = range$$1.head.line; 8048 if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); } 8049 } 8050 } 8051 }), 8052 8053 // Fetch the parser token for a given character. Useful for hacks 8054 // that want to inspect the mode state (say, for completion). 8055 getTokenAt: function(pos, precise) { 8056 return takeToken(this, pos, precise) 8057 }, 8058 8059 getLineTokens: function(line, precise) { 8060 return takeToken(this, Pos(line), precise, true) 8061 }, 8062 8063 getTokenTypeAt: function(pos) { 8064 pos = clipPos(this.doc, pos); 8065 var styles = getLineStyles(this, getLine(this.doc, pos.line)); 8066 var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; 8067 var type; 8068 if (ch == 0) { type = styles[2]; } 8069 else { for (;;) { 8070 var mid = (before + after) >> 1; 8071 if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; } 8072 else if (styles[mid * 2 + 1] < ch) { before = mid + 1; } 8073 else { type = styles[mid * 2 + 2]; break } 8074 } } 8075 var cut = type ? type.indexOf("overlay ") : -1; 8076 return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1) 8077 }, 8078 8079 getModeAt: function(pos) { 8080 var mode = this.doc.mode; 8081 if (!mode.innerMode) { return mode } 8082 return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode 8083 }, 8084 8085 getHelper: function(pos, type) { 8086 return this.getHelpers(pos, type)[0] 8087 }, 8088 8089 getHelpers: function(pos, type) { 8090 var this$1 = this; 8091 8092 var found = []; 8093 if (!helpers.hasOwnProperty(type)) { return found } 8094 var help = helpers[type], mode = this.getModeAt(pos); 8095 if (typeof mode[type] == "string") { 8096 if (help[mode[type]]) { found.push(help[mode[type]]); } 8097 } else if (mode[type]) { 8098 for (var i = 0; i < mode[type].length; i++) { 8099 var val = help[mode[type][i]]; 8100 if (val) { found.push(val); } 8101 } 8102 } else if (mode.helperType && help[mode.helperType]) { 8103 found.push(help[mode.helperType]); 8104 } else if (help[mode.name]) { 8105 found.push(help[mode.name]); 8106 } 8107 for (var i$1 = 0; i$1 < help._global.length; i$1++) { 8108 var cur = help._global[i$1]; 8109 if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1) 8110 { found.push(cur.val); } 8111 } 8112 return found 8113 }, 8114 8115 getStateAfter: function(line, precise) { 8116 var doc = this.doc; 8117 line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); 8118 return getContextBefore(this, line + 1, precise).state 8119 }, 8120 8121 cursorCoords: function(start, mode) { 8122 var pos, range$$1 = this.doc.sel.primary(); 8123 if (start == null) { pos = range$$1.head; } 8124 else if (typeof start == "object") { pos = clipPos(this.doc, start); } 8125 else { pos = start ? range$$1.from() : range$$1.to(); } 8126 return cursorCoords(this, pos, mode || "page") 8127 }, 8128 8129 charCoords: function(pos, mode) { 8130 return charCoords(this, clipPos(this.doc, pos), mode || "page") 8131 }, 8132 8133 coordsChar: function(coords, mode) { 8134 coords = fromCoordSystem(this, coords, mode || "page"); 8135 return coordsChar(this, coords.left, coords.top) 8136 }, 8137 8138 lineAtHeight: function(height, mode) { 8139 height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; 8140 return lineAtHeight(this.doc, height + this.display.viewOffset) 8141 }, 8142 heightAtLine: function(line, mode, includeWidgets) { 8143 var end = false, lineObj; 8144 if (typeof line == "number") { 8145 var last = this.doc.first + this.doc.size - 1; 8146 if (line < this.doc.first) { line = this.doc.first; } 8147 else if (line > last) { line = last; end = true; } 8148 lineObj = getLine(this.doc, line); 8149 } else { 8150 lineObj = line; 8151 } 8152 return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top + 8153 (end ? this.doc.height - heightAtLine(lineObj) : 0) 8154 }, 8155 8156 defaultTextHeight: function() { return textHeight(this.display) }, 8157 defaultCharWidth: function() { return charWidth(this.display) }, 8158 8159 getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, 8160 8161 addWidget: function(pos, node, scroll, vert, horiz) { 8162 var display = this.display; 8163 pos = cursorCoords(this, clipPos(this.doc, pos)); 8164 var top = pos.bottom, left = pos.left; 8165 node.style.position = "absolute"; 8166 node.setAttribute("cm-ignore-events", "true"); 8167 this.display.input.setUneditable(node); 8168 display.sizer.appendChild(node); 8169 if (vert == "over") { 8170 top = pos.top; 8171 } else if (vert == "above" || vert == "near") { 8172 var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), 8173 hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); 8174 // Default to positioning above (if specified and possible); otherwise default to positioning below 8175 if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) 8176 { top = pos.top - node.offsetHeight; } 8177 else if (pos.bottom + node.offsetHeight <= vspace) 8178 { top = pos.bottom; } 8179 if (left + node.offsetWidth > hspace) 8180 { left = hspace - node.offsetWidth; } 8181 } 8182 node.style.top = top + "px"; 8183 node.style.left = node.style.right = ""; 8184 if (horiz == "right") { 8185 left = display.sizer.clientWidth - node.offsetWidth; 8186 node.style.right = "0px"; 8187 } else { 8188 if (horiz == "left") { left = 0; } 8189 else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; } 8190 node.style.left = left + "px"; 8191 } 8192 if (scroll) 8193 { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); } 8194 }, 8195 8196 triggerOnKeyDown: methodOp(onKeyDown), 8197 triggerOnKeyPress: methodOp(onKeyPress), 8198 triggerOnKeyUp: onKeyUp, 8199 triggerOnMouseDown: methodOp(onMouseDown), 8200 8201 execCommand: function(cmd) { 8202 if (commands.hasOwnProperty(cmd)) 8203 { return commands[cmd].call(null, this) } 8204 }, 8205 8206 triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), 8207 8208 findPosH: function(from, amount, unit, visually) { 8209 var this$1 = this; 8210 8211 var dir = 1; 8212 if (amount < 0) { dir = -1; amount = -amount; } 8213 var cur = clipPos(this.doc, from); 8214 for (var i = 0; i < amount; ++i) { 8215 cur = findPosH(this$1.doc, cur, dir, unit, visually); 8216 if (cur.hitSide) { break } 8217 } 8218 return cur 8219 }, 8220 8221 moveH: methodOp(function(dir, unit) { 8222 var this$1 = this; 8223 8224 this.extendSelectionsBy(function (range$$1) { 8225 if (this$1.display.shift || this$1.doc.extend || range$$1.empty()) 8226 { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) } 8227 else 8228 { return dir < 0 ? range$$1.from() : range$$1.to() } 8229 }, sel_move); 8230 }), 8231 8232 deleteH: methodOp(function(dir, unit) { 8233 var sel = this.doc.sel, doc = this.doc; 8234 if (sel.somethingSelected()) 8235 { doc.replaceSelection("", null, "+delete"); } 8236 else 8237 { deleteNearSelection(this, function (range$$1) { 8238 var other = findPosH(doc, range$$1.head, dir, unit, false); 8239 return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other} 8240 }); } 8241 }), 8242 8243 findPosV: function(from, amount, unit, goalColumn) { 8244 var this$1 = this; 8245 8246 var dir = 1, x = goalColumn; 8247 if (amount < 0) { dir = -1; amount = -amount; } 8248 var cur = clipPos(this.doc, from); 8249 for (var i = 0; i < amount; ++i) { 8250 var coords = cursorCoords(this$1, cur, "div"); 8251 if (x == null) { x = coords.left; } 8252 else { coords.left = x; } 8253 cur = findPosV(this$1, coords, dir, unit); 8254 if (cur.hitSide) { break } 8255 } 8256 return cur 8257 }, 8258 8259 moveV: methodOp(function(dir, unit) { 8260 var this$1 = this; 8261 8262 var doc = this.doc, goals = []; 8263 var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected(); 8264 doc.extendSelectionsBy(function (range$$1) { 8265 if (collapse) 8266 { return dir < 0 ? range$$1.from() : range$$1.to() } 8267 var headPos = cursorCoords(this$1, range$$1.head, "div"); 8268 if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; } 8269 goals.push(headPos.left); 8270 var pos = findPosV(this$1, headPos, dir, unit); 8271 if (unit == "page" && range$$1 == doc.sel.primary()) 8272 { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); } 8273 return pos 8274 }, sel_move); 8275 if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++) 8276 { doc.sel.ranges[i].goalColumn = goals[i]; } } 8277 }), 8278 8279 // Find the word at the given position (as returned by coordsChar). 8280 findWordAt: function(pos) { 8281 var doc = this.doc, line = getLine(doc, pos.line).text; 8282 var start = pos.ch, end = pos.ch; 8283 if (line) { 8284 var helper = this.getHelper(pos, "wordChars"); 8285 if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; } 8286 var startChar = line.charAt(start); 8287 var check = isWordChar(startChar, helper) 8288 ? function (ch) { return isWordChar(ch, helper); } 8289 : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); } 8290 : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }; 8291 while (start > 0 && check(line.charAt(start - 1))) { --start; } 8292 while (end < line.length && check(line.charAt(end))) { ++end; } 8293 } 8294 return new Range(Pos(pos.line, start), Pos(pos.line, end)) 8295 }, 8296 8297 toggleOverwrite: function(value) { 8298 if (value != null && value == this.state.overwrite) { return } 8299 if (this.state.overwrite = !this.state.overwrite) 8300 { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); } 8301 else 8302 { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); } 8303 8304 signal(this, "overwriteToggle", this, this.state.overwrite); 8305 }, 8306 hasFocus: function() { return this.display.input.getField() == activeElt() }, 8307 isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, 8308 8309 scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }), 8310 getScrollInfo: function() { 8311 var scroller = this.display.scroller; 8312 return {left: scroller.scrollLeft, top: scroller.scrollTop, 8313 height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, 8314 width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, 8315 clientHeight: displayHeight(this), clientWidth: displayWidth(this)} 8316 }, 8317 8318 scrollIntoView: methodOp(function(range$$1, margin) { 8319 if (range$$1 == null) { 8320 range$$1 = {from: this.doc.sel.primary().head, to: null}; 8321 if (margin == null) { margin = this.options.cursorScrollMargin; } 8322 } else if (typeof range$$1 == "number") { 8323 range$$1 = {from: Pos(range$$1, 0), to: null}; 8324 } else if (range$$1.from == null) { 8325 range$$1 = {from: range$$1, to: null}; 8326 } 8327 if (!range$$1.to) { range$$1.to = range$$1.from; } 8328 range$$1.margin = margin || 0; 8329 8330 if (range$$1.from.line != null) { 8331 scrollToRange(this, range$$1); 8332 } else { 8333 scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin); 8334 } 8335 }), 8336 8337 setSize: methodOp(function(width, height) { 8338 var this$1 = this; 8339 8340 var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }; 8341 if (width != null) { this.display.wrapper.style.width = interpret(width); } 8342 if (height != null) { this.display.wrapper.style.height = interpret(height); } 8343 if (this.options.lineWrapping) { clearLineMeasurementCache(this); } 8344 var lineNo$$1 = this.display.viewFrom; 8345 this.doc.iter(lineNo$$1, this.display.viewTo, function (line) { 8346 if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) 8347 { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } } 8348 ++lineNo$$1; 8349 }); 8350 this.curOp.forceUpdate = true; 8351 signal(this, "refresh", this); 8352 }), 8353 8354 operation: function(f){return runInOp(this, f)}, 8355 8356 refresh: methodOp(function() { 8357 var oldHeight = this.display.cachedTextHeight; 8358 regChange(this); 8359 this.curOp.forceUpdate = true; 8360 clearCaches(this); 8361 scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); 8362 updateGutterSpace(this); 8363 if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) 8364 { estimateLineHeights(this); } 8365 signal(this, "refresh", this); 8366 }), 8367 8368 swapDoc: methodOp(function(doc) { 8369 var old = this.doc; 8370 old.cm = null; 8371 attachDoc(this, doc); 8372 clearCaches(this); 8373 this.display.input.reset(); 8374 scrollToCoords(this, doc.scrollLeft, doc.scrollTop); 8375 this.curOp.forceScroll = true; 8376 signalLater(this, "swapDoc", this, old); 8377 return old 8378 }), 8379 8380 getInputField: function(){return this.display.input.getField()}, 8381 getWrapperElement: function(){return this.display.wrapper}, 8382 getScrollerElement: function(){return this.display.scroller}, 8383 getGutterElement: function(){return this.display.gutters} 8384 }; 8385 eventMixin(CodeMirror); 8386 8387 CodeMirror.registerHelper = function(type, name, value) { 8388 if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; } 8389 helpers[type][name] = value; 8390 }; 8391 CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { 8392 CodeMirror.registerHelper(type, name, value); 8393 helpers[type]._global.push({pred: predicate, val: value}); 8394 }; 8395}; 8396 8397// Used for horizontal relative motion. Dir is -1 or 1 (left or 8398// right), unit can be "char", "column" (like char, but doesn't 8399// cross line boundaries), "word" (across next word), or "group" (to 8400// the start of next group of word or non-word-non-whitespace 8401// chars). The visually param controls whether, in right-to-left 8402// text, direction 1 means to move towards the next index in the 8403// string, or towards the character to the right of the current 8404// position. The resulting position will have a hitSide=true 8405// property if it reached the end of the document. 8406function findPosH(doc, pos, dir, unit, visually) { 8407 var oldPos = pos; 8408 var origDir = dir; 8409 var lineObj = getLine(doc, pos.line); 8410 function findNextLine() { 8411 var l = pos.line + dir; 8412 if (l < doc.first || l >= doc.first + doc.size) { return false } 8413 pos = new Pos(l, pos.ch, pos.sticky); 8414 return lineObj = getLine(doc, l) 8415 } 8416 function moveOnce(boundToLine) { 8417 var next; 8418 if (visually) { 8419 next = moveVisually(doc.cm, lineObj, pos, dir); 8420 } else { 8421 next = moveLogically(lineObj, pos, dir); 8422 } 8423 if (next == null) { 8424 if (!boundToLine && findNextLine()) 8425 { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); } 8426 else 8427 { return false } 8428 } else { 8429 pos = next; 8430 } 8431 return true 8432 } 8433 8434 if (unit == "char") { 8435 moveOnce(); 8436 } else if (unit == "column") { 8437 moveOnce(true); 8438 } else if (unit == "word" || unit == "group") { 8439 var sawType = null, group = unit == "group"; 8440 var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); 8441 for (var first = true;; first = false) { 8442 if (dir < 0 && !moveOnce(!first)) { break } 8443 var cur = lineObj.text.charAt(pos.ch) || "\n"; 8444 var type = isWordChar(cur, helper) ? "w" 8445 : group && cur == "\n" ? "n" 8446 : !group || /\s/.test(cur) ? null 8447 : "p"; 8448 if (group && !first && !type) { type = "s"; } 8449 if (sawType && sawType != type) { 8450 if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";} 8451 break 8452 } 8453 8454 if (type) { sawType = type; } 8455 if (dir > 0 && !moveOnce(!first)) { break } 8456 } 8457 } 8458 var result = skipAtomic(doc, pos, oldPos, origDir, true); 8459 if (equalCursorPos(oldPos, result)) { result.hitSide = true; } 8460 return result 8461} 8462 8463// For relative vertical movement. Dir may be -1 or 1. Unit can be 8464// "page" or "line". The resulting position will have a hitSide=true 8465// property if it reached the end of the document. 8466function findPosV(cm, pos, dir, unit) { 8467 var doc = cm.doc, x = pos.left, y; 8468 if (unit == "page") { 8469 var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); 8470 var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3); 8471 y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; 8472 8473 } else if (unit == "line") { 8474 y = dir > 0 ? pos.bottom + 3 : pos.top - 3; 8475 } 8476 var target; 8477 for (;;) { 8478 target = coordsChar(cm, x, y); 8479 if (!target.outside) { break } 8480 if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break } 8481 y += dir * 5; 8482 } 8483 return target 8484} 8485 8486// CONTENTEDITABLE INPUT STYLE 8487 8488var ContentEditableInput = function(cm) { 8489 this.cm = cm; 8490 this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; 8491 this.polling = new Delayed(); 8492 this.composing = null; 8493 this.gracePeriod = false; 8494 this.readDOMTimeout = null; 8495}; 8496 8497ContentEditableInput.prototype.init = function (display) { 8498 var this$1 = this; 8499 8500 var input = this, cm = input.cm; 8501 var div = input.div = display.lineDiv; 8502 disableBrowserMagic(div, cm.options.spellcheck); 8503 8504 on(div, "paste", function (e) { 8505 if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } 8506 // IE doesn't fire input events, so we schedule a read for the pasted content in this way 8507 if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); } 8508 }); 8509 8510 on(div, "compositionstart", function (e) { 8511 this$1.composing = {data: e.data, done: false}; 8512 }); 8513 on(div, "compositionupdate", function (e) { 8514 if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; } 8515 }); 8516 on(div, "compositionend", function (e) { 8517 if (this$1.composing) { 8518 if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); } 8519 this$1.composing.done = true; 8520 } 8521 }); 8522 8523 on(div, "touchstart", function () { return input.forceCompositionEnd(); }); 8524 8525 on(div, "input", function () { 8526 if (!this$1.composing) { this$1.readFromDOMSoon(); } 8527 }); 8528 8529 function onCopyCut(e) { 8530 if (signalDOMEvent(cm, e)) { return } 8531 if (cm.somethingSelected()) { 8532 setLastCopied({lineWise: false, text: cm.getSelections()}); 8533 if (e.type == "cut") { cm.replaceSelection("", null, "cut"); } 8534 } else if (!cm.options.lineWiseCopyCut) { 8535 return 8536 } else { 8537 var ranges = copyableRanges(cm); 8538 setLastCopied({lineWise: true, text: ranges.text}); 8539 if (e.type == "cut") { 8540 cm.operation(function () { 8541 cm.setSelections(ranges.ranges, 0, sel_dontScroll); 8542 cm.replaceSelection("", null, "cut"); 8543 }); 8544 } 8545 } 8546 if (e.clipboardData) { 8547 e.clipboardData.clearData(); 8548 var content = lastCopied.text.join("\n"); 8549 // iOS exposes the clipboard API, but seems to discard content inserted into it 8550 e.clipboardData.setData("Text", content); 8551 if (e.clipboardData.getData("Text") == content) { 8552 e.preventDefault(); 8553 return 8554 } 8555 } 8556 // Old-fashioned briefly-focus-a-textarea hack 8557 var kludge = hiddenTextarea(), te = kludge.firstChild; 8558 cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); 8559 te.value = lastCopied.text.join("\n"); 8560 var hadFocus = document.activeElement; 8561 selectInput(te); 8562 setTimeout(function () { 8563 cm.display.lineSpace.removeChild(kludge); 8564 hadFocus.focus(); 8565 if (hadFocus == div) { input.showPrimarySelection(); } 8566 }, 50); 8567 } 8568 on(div, "copy", onCopyCut); 8569 on(div, "cut", onCopyCut); 8570}; 8571 8572ContentEditableInput.prototype.prepareSelection = function () { 8573 var result = prepareSelection(this.cm, false); 8574 result.focus = this.cm.state.focused; 8575 return result 8576}; 8577 8578ContentEditableInput.prototype.showSelection = function (info, takeFocus) { 8579 if (!info || !this.cm.display.view.length) { return } 8580 if (info.focus || takeFocus) { this.showPrimarySelection(); } 8581 this.showMultipleSelections(info); 8582}; 8583 8584ContentEditableInput.prototype.showPrimarySelection = function () { 8585 var sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary(); 8586 var from = prim.from(), to = prim.to(); 8587 8588 if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { 8589 sel.removeAllRanges(); 8590 return 8591 } 8592 8593 var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); 8594 var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); 8595 if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && 8596 cmp(minPos(curAnchor, curFocus), from) == 0 && 8597 cmp(maxPos(curAnchor, curFocus), to) == 0) 8598 { return } 8599 8600 var view = cm.display.view; 8601 var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) || 8602 {node: view[0].measure.map[2], offset: 0}; 8603 var end = to.line < cm.display.viewTo && posToDOM(cm, to); 8604 if (!end) { 8605 var measure = view[view.length - 1].measure; 8606 var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; 8607 end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]}; 8608 } 8609 8610 if (!start || !end) { 8611 sel.removeAllRanges(); 8612 return 8613 } 8614 8615 var old = sel.rangeCount && sel.getRangeAt(0), rng; 8616 try { rng = range(start.node, start.offset, end.offset, end.node); } 8617 catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible 8618 if (rng) { 8619 if (!gecko && cm.state.focused) { 8620 sel.collapse(start.node, start.offset); 8621 if (!rng.collapsed) { 8622 sel.removeAllRanges(); 8623 sel.addRange(rng); 8624 } 8625 } else { 8626 sel.removeAllRanges(); 8627 sel.addRange(rng); 8628 } 8629 if (old && sel.anchorNode == null) { sel.addRange(old); } 8630 else if (gecko) { this.startGracePeriod(); } 8631 } 8632 this.rememberSelection(); 8633}; 8634 8635ContentEditableInput.prototype.startGracePeriod = function () { 8636 var this$1 = this; 8637 8638 clearTimeout(this.gracePeriod); 8639 this.gracePeriod = setTimeout(function () { 8640 this$1.gracePeriod = false; 8641 if (this$1.selectionChanged()) 8642 { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); } 8643 }, 20); 8644}; 8645 8646ContentEditableInput.prototype.showMultipleSelections = function (info) { 8647 removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); 8648 removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); 8649}; 8650 8651ContentEditableInput.prototype.rememberSelection = function () { 8652 var sel = window.getSelection(); 8653 this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; 8654 this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; 8655}; 8656 8657ContentEditableInput.prototype.selectionInEditor = function () { 8658 var sel = window.getSelection(); 8659 if (!sel.rangeCount) { return false } 8660 var node = sel.getRangeAt(0).commonAncestorContainer; 8661 return contains(this.div, node) 8662}; 8663 8664ContentEditableInput.prototype.focus = function () { 8665 if (this.cm.options.readOnly != "nocursor") { 8666 if (!this.selectionInEditor()) 8667 { this.showSelection(this.prepareSelection(), true); } 8668 this.div.focus(); 8669 } 8670}; 8671ContentEditableInput.prototype.blur = function () { this.div.blur(); }; 8672ContentEditableInput.prototype.getField = function () { return this.div }; 8673 8674ContentEditableInput.prototype.supportsTouch = function () { return true }; 8675 8676ContentEditableInput.prototype.receivedFocus = function () { 8677 var input = this; 8678 if (this.selectionInEditor()) 8679 { this.pollSelection(); } 8680 else 8681 { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); } 8682 8683 function poll() { 8684 if (input.cm.state.focused) { 8685 input.pollSelection(); 8686 input.polling.set(input.cm.options.pollInterval, poll); 8687 } 8688 } 8689 this.polling.set(this.cm.options.pollInterval, poll); 8690}; 8691 8692ContentEditableInput.prototype.selectionChanged = function () { 8693 var sel = window.getSelection(); 8694 return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || 8695 sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset 8696}; 8697 8698ContentEditableInput.prototype.pollSelection = function () { 8699 if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return } 8700 var sel = window.getSelection(), cm = this.cm; 8701 // On Android Chrome (version 56, at least), backspacing into an 8702 // uneditable block element will put the cursor in that element, 8703 // and then, because it's not editable, hide the virtual keyboard. 8704 // Because Android doesn't allow us to actually detect backspace 8705 // presses in a sane way, this code checks for when that happens 8706 // and simulates a backspace press in this case. 8707 if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) { 8708 this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs}); 8709 this.blur(); 8710 this.focus(); 8711 return 8712 } 8713 if (this.composing) { return } 8714 this.rememberSelection(); 8715 var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); 8716 var head = domToPos(cm, sel.focusNode, sel.focusOffset); 8717 if (anchor && head) { runInOp(cm, function () { 8718 setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); 8719 if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; } 8720 }); } 8721}; 8722 8723ContentEditableInput.prototype.pollContent = function () { 8724 if (this.readDOMTimeout != null) { 8725 clearTimeout(this.readDOMTimeout); 8726 this.readDOMTimeout = null; 8727 } 8728 8729 var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); 8730 var from = sel.from(), to = sel.to(); 8731 if (from.ch == 0 && from.line > cm.firstLine()) 8732 { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); } 8733 if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) 8734 { to = Pos(to.line + 1, 0); } 8735 if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false } 8736 8737 var fromIndex, fromLine, fromNode; 8738 if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { 8739 fromLine = lineNo(display.view[0].line); 8740 fromNode = display.view[0].node; 8741 } else { 8742 fromLine = lineNo(display.view[fromIndex].line); 8743 fromNode = display.view[fromIndex - 1].node.nextSibling; 8744 } 8745 var toIndex = findViewIndex(cm, to.line); 8746 var toLine, toNode; 8747 if (toIndex == display.view.length - 1) { 8748 toLine = display.viewTo - 1; 8749 toNode = display.lineDiv.lastChild; 8750 } else { 8751 toLine = lineNo(display.view[toIndex + 1].line) - 1; 8752 toNode = display.view[toIndex + 1].node.previousSibling; 8753 } 8754 8755 if (!fromNode) { return false } 8756 var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); 8757 var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); 8758 while (newText.length > 1 && oldText.length > 1) { 8759 if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } 8760 else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } 8761 else { break } 8762 } 8763 8764 var cutFront = 0, cutEnd = 0; 8765 var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); 8766 while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) 8767 { ++cutFront; } 8768 var newBot = lst(newText), oldBot = lst(oldText); 8769 var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), 8770 oldBot.length - (oldText.length == 1 ? cutFront : 0)); 8771 while (cutEnd < maxCutEnd && 8772 newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) 8773 { ++cutEnd; } 8774 // Try to move start of change to start of selection if ambiguous 8775 if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { 8776 while (cutFront && cutFront > from.ch && 8777 newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { 8778 cutFront--; 8779 cutEnd++; 8780 } 8781 } 8782 8783 newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); 8784 newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); 8785 8786 var chFrom = Pos(fromLine, cutFront); 8787 var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); 8788 if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { 8789 replaceRange(cm.doc, newText, chFrom, chTo, "+input"); 8790 return true 8791 } 8792}; 8793 8794ContentEditableInput.prototype.ensurePolled = function () { 8795 this.forceCompositionEnd(); 8796}; 8797ContentEditableInput.prototype.reset = function () { 8798 this.forceCompositionEnd(); 8799}; 8800ContentEditableInput.prototype.forceCompositionEnd = function () { 8801 if (!this.composing) { return } 8802 clearTimeout(this.readDOMTimeout); 8803 this.composing = null; 8804 this.updateFromDOM(); 8805 this.div.blur(); 8806 this.div.focus(); 8807}; 8808ContentEditableInput.prototype.readFromDOMSoon = function () { 8809 var this$1 = this; 8810 8811 if (this.readDOMTimeout != null) { return } 8812 this.readDOMTimeout = setTimeout(function () { 8813 this$1.readDOMTimeout = null; 8814 if (this$1.composing) { 8815 if (this$1.composing.done) { this$1.composing = null; } 8816 else { return } 8817 } 8818 this$1.updateFromDOM(); 8819 }, 80); 8820}; 8821 8822ContentEditableInput.prototype.updateFromDOM = function () { 8823 var this$1 = this; 8824 8825 if (this.cm.isReadOnly() || !this.pollContent()) 8826 { runInOp(this.cm, function () { return regChange(this$1.cm); }); } 8827}; 8828 8829ContentEditableInput.prototype.setUneditable = function (node) { 8830 node.contentEditable = "false"; 8831}; 8832 8833ContentEditableInput.prototype.onKeyPress = function (e) { 8834 if (e.charCode == 0) { return } 8835 e.preventDefault(); 8836 if (!this.cm.isReadOnly()) 8837 { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); } 8838}; 8839 8840ContentEditableInput.prototype.readOnlyChanged = function (val) { 8841 this.div.contentEditable = String(val != "nocursor"); 8842}; 8843 8844ContentEditableInput.prototype.onContextMenu = function () {}; 8845ContentEditableInput.prototype.resetPosition = function () {}; 8846 8847ContentEditableInput.prototype.needsContentAttribute = true; 8848 8849function posToDOM(cm, pos) { 8850 var view = findViewForLine(cm, pos.line); 8851 if (!view || view.hidden) { return null } 8852 var line = getLine(cm.doc, pos.line); 8853 var info = mapFromLineView(view, line, pos.line); 8854 8855 var order = getOrder(line, cm.doc.direction), side = "left"; 8856 if (order) { 8857 var partPos = getBidiPartAt(order, pos.ch); 8858 side = partPos % 2 ? "right" : "left"; 8859 } 8860 var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); 8861 result.offset = result.collapse == "right" ? result.end : result.start; 8862 return result 8863} 8864 8865function isInGutter(node) { 8866 for (var scan = node; scan; scan = scan.parentNode) 8867 { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } } 8868 return false 8869} 8870 8871function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos } 8872 8873function domTextBetween(cm, from, to, fromLine, toLine) { 8874 var text = "", closing = false, lineSep = cm.doc.lineSeparator(); 8875 function recognizeMarker(id) { return function (marker) { return marker.id == id; } } 8876 function close() { 8877 if (closing) { 8878 text += lineSep; 8879 closing = false; 8880 } 8881 } 8882 function addText(str) { 8883 if (str) { 8884 close(); 8885 text += str; 8886 } 8887 } 8888 function walk(node) { 8889 if (node.nodeType == 1) { 8890 var cmText = node.getAttribute("cm-text"); 8891 if (cmText != null) { 8892 addText(cmText || node.textContent.replace(/\u200b/g, "")); 8893 return 8894 } 8895 var markerID = node.getAttribute("cm-marker"), range$$1; 8896 if (markerID) { 8897 var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); 8898 if (found.length && (range$$1 = found[0].find())) 8899 { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); } 8900 return 8901 } 8902 if (node.getAttribute("contenteditable") == "false") { return } 8903 var isBlock = /^(pre|div|p)$/i.test(node.nodeName); 8904 if (isBlock) { close(); } 8905 for (var i = 0; i < node.childNodes.length; i++) 8906 { walk(node.childNodes[i]); } 8907 if (isBlock) { closing = true; } 8908 } else if (node.nodeType == 3) { 8909 addText(node.nodeValue); 8910 } 8911 } 8912 for (;;) { 8913 walk(from); 8914 if (from == to) { break } 8915 from = from.nextSibling; 8916 } 8917 return text 8918} 8919 8920function domToPos(cm, node, offset) { 8921 var lineNode; 8922 if (node == cm.display.lineDiv) { 8923 lineNode = cm.display.lineDiv.childNodes[offset]; 8924 if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) } 8925 node = null; offset = 0; 8926 } else { 8927 for (lineNode = node;; lineNode = lineNode.parentNode) { 8928 if (!lineNode || lineNode == cm.display.lineDiv) { return null } 8929 if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break } 8930 } 8931 } 8932 for (var i = 0; i < cm.display.view.length; i++) { 8933 var lineView = cm.display.view[i]; 8934 if (lineView.node == lineNode) 8935 { return locateNodeInLineView(lineView, node, offset) } 8936 } 8937} 8938 8939function locateNodeInLineView(lineView, node, offset) { 8940 var wrapper = lineView.text.firstChild, bad = false; 8941 if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) } 8942 if (node == wrapper) { 8943 bad = true; 8944 node = wrapper.childNodes[offset]; 8945 offset = 0; 8946 if (!node) { 8947 var line = lineView.rest ? lst(lineView.rest) : lineView.line; 8948 return badPos(Pos(lineNo(line), line.text.length), bad) 8949 } 8950 } 8951 8952 var textNode = node.nodeType == 3 ? node : null, topNode = node; 8953 if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { 8954 textNode = node.firstChild; 8955 if (offset) { offset = textNode.nodeValue.length; } 8956 } 8957 while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; } 8958 var measure = lineView.measure, maps = measure.maps; 8959 8960 function find(textNode, topNode, offset) { 8961 for (var i = -1; i < (maps ? maps.length : 0); i++) { 8962 var map$$1 = i < 0 ? measure.map : maps[i]; 8963 for (var j = 0; j < map$$1.length; j += 3) { 8964 var curNode = map$$1[j + 2]; 8965 if (curNode == textNode || curNode == topNode) { 8966 var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); 8967 var ch = map$$1[j] + offset; 8968 if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; } 8969 return Pos(line, ch) 8970 } 8971 } 8972 } 8973 } 8974 var found = find(textNode, topNode, offset); 8975 if (found) { return badPos(found, bad) } 8976 8977 // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems 8978 for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { 8979 found = find(after, after.firstChild, 0); 8980 if (found) 8981 { return badPos(Pos(found.line, found.ch - dist), bad) } 8982 else 8983 { dist += after.textContent.length; } 8984 } 8985 for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { 8986 found = find(before, before.firstChild, -1); 8987 if (found) 8988 { return badPos(Pos(found.line, found.ch + dist$1), bad) } 8989 else 8990 { dist$1 += before.textContent.length; } 8991 } 8992} 8993 8994// TEXTAREA INPUT STYLE 8995 8996var TextareaInput = function(cm) { 8997 this.cm = cm; 8998 // See input.poll and input.reset 8999 this.prevInput = ""; 9000 9001 // Flag that indicates whether we expect input to appear real soon 9002 // now (after some event like 'keypress' or 'input') and are 9003 // polling intensively. 9004 this.pollingFast = false; 9005 // Self-resetting timeout for the poller 9006 this.polling = new Delayed(); 9007 // Tracks when input.reset has punted to just putting a short 9008 // string into the textarea instead of the full selection. 9009 this.inaccurateSelection = false; 9010 // Used to work around IE issue with selection being forgotten when focus moves away from textarea 9011 this.hasSelection = false; 9012 this.composing = null; 9013}; 9014 9015TextareaInput.prototype.init = function (display) { 9016 var this$1 = this; 9017 9018 var input = this, cm = this.cm; 9019 9020 // Wraps and hides input textarea 9021 var div = this.wrapper = hiddenTextarea(); 9022 // The semihidden textarea that is focused when the editor is 9023 // focused, and receives input. 9024 var te = this.textarea = div.firstChild; 9025 display.wrapper.insertBefore(div, display.wrapper.firstChild); 9026 9027 // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) 9028 if (ios) { te.style.width = "0px"; } 9029 9030 on(te, "input", function () { 9031 if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; } 9032 input.poll(); 9033 }); 9034 9035 on(te, "paste", function (e) { 9036 if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } 9037 9038 cm.state.pasteIncoming = true; 9039 input.fastPoll(); 9040 }); 9041 9042 function prepareCopyCut(e) { 9043 if (signalDOMEvent(cm, e)) { return } 9044 if (cm.somethingSelected()) { 9045 setLastCopied({lineWise: false, text: cm.getSelections()}); 9046 if (input.inaccurateSelection) { 9047 input.prevInput = ""; 9048 input.inaccurateSelection = false; 9049 te.value = lastCopied.text.join("\n"); 9050 selectInput(te); 9051 } 9052 } else if (!cm.options.lineWiseCopyCut) { 9053 return 9054 } else { 9055 var ranges = copyableRanges(cm); 9056 setLastCopied({lineWise: true, text: ranges.text}); 9057 if (e.type == "cut") { 9058 cm.setSelections(ranges.ranges, null, sel_dontScroll); 9059 } else { 9060 input.prevInput = ""; 9061 te.value = ranges.text.join("\n"); 9062 selectInput(te); 9063 } 9064 } 9065 if (e.type == "cut") { cm.state.cutIncoming = true; } 9066 } 9067 on(te, "cut", prepareCopyCut); 9068 on(te, "copy", prepareCopyCut); 9069 9070 on(display.scroller, "paste", function (e) { 9071 if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return } 9072 cm.state.pasteIncoming = true; 9073 input.focus(); 9074 }); 9075 9076 // Prevent normal selection in the editor (we handle our own) 9077 on(display.lineSpace, "selectstart", function (e) { 9078 if (!eventInWidget(display, e)) { e_preventDefault(e); } 9079 }); 9080 9081 on(te, "compositionstart", function () { 9082 var start = cm.getCursor("from"); 9083 if (input.composing) { input.composing.range.clear(); } 9084 input.composing = { 9085 start: start, 9086 range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) 9087 }; 9088 }); 9089 on(te, "compositionend", function () { 9090 if (input.composing) { 9091 input.poll(); 9092 input.composing.range.clear(); 9093 input.composing = null; 9094 } 9095 }); 9096}; 9097 9098TextareaInput.prototype.prepareSelection = function () { 9099 // Redraw the selection and/or cursor 9100 var cm = this.cm, display = cm.display, doc = cm.doc; 9101 var result = prepareSelection(cm); 9102 9103 // Move the hidden textarea near the cursor to prevent scrolling artifacts 9104 if (cm.options.moveInputWithCursor) { 9105 var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); 9106 var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); 9107 result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, 9108 headPos.top + lineOff.top - wrapOff.top)); 9109 result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, 9110 headPos.left + lineOff.left - wrapOff.left)); 9111 } 9112 9113 return result 9114}; 9115 9116TextareaInput.prototype.showSelection = function (drawn) { 9117 var cm = this.cm, display = cm.display; 9118 removeChildrenAndAdd(display.cursorDiv, drawn.cursors); 9119 removeChildrenAndAdd(display.selectionDiv, drawn.selection); 9120 if (drawn.teTop != null) { 9121 this.wrapper.style.top = drawn.teTop + "px"; 9122 this.wrapper.style.left = drawn.teLeft + "px"; 9123 } 9124}; 9125 9126// Reset the input to correspond to the selection (or to be empty, 9127// when not typing and nothing is selected) 9128TextareaInput.prototype.reset = function (typing) { 9129 if (this.contextMenuPending || this.composing) { return } 9130 var minimal, selected, cm = this.cm, doc = cm.doc; 9131 if (cm.somethingSelected()) { 9132 this.prevInput = ""; 9133 var range$$1 = doc.sel.primary(); 9134 minimal = hasCopyEvent && 9135 (range$$1.to().line - range$$1.from().line > 100 || (selected = cm.getSelection()).length > 1000); 9136 var content = minimal ? "-" : selected || cm.getSelection(); 9137 this.textarea.value = content; 9138 if (cm.state.focused) { selectInput(this.textarea); } 9139 if (ie && ie_version >= 9) { this.hasSelection = content; } 9140 } else if (!typing) { 9141 this.prevInput = this.textarea.value = ""; 9142 if (ie && ie_version >= 9) { this.hasSelection = null; } 9143 } 9144 this.inaccurateSelection = minimal; 9145}; 9146 9147TextareaInput.prototype.getField = function () { return this.textarea }; 9148 9149TextareaInput.prototype.supportsTouch = function () { return false }; 9150 9151TextareaInput.prototype.focus = function () { 9152 if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { 9153 try { this.textarea.focus(); } 9154 catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM 9155 } 9156}; 9157 9158TextareaInput.prototype.blur = function () { this.textarea.blur(); }; 9159 9160TextareaInput.prototype.resetPosition = function () { 9161 this.wrapper.style.top = this.wrapper.style.left = 0; 9162}; 9163 9164TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); }; 9165 9166// Poll for input changes, using the normal rate of polling. This 9167// runs as long as the editor is focused. 9168TextareaInput.prototype.slowPoll = function () { 9169 var this$1 = this; 9170 9171 if (this.pollingFast) { return } 9172 this.polling.set(this.cm.options.pollInterval, function () { 9173 this$1.poll(); 9174 if (this$1.cm.state.focused) { this$1.slowPoll(); } 9175 }); 9176}; 9177 9178// When an event has just come in that is likely to add or change 9179// something in the input textarea, we poll faster, to ensure that 9180// the change appears on the screen quickly. 9181TextareaInput.prototype.fastPoll = function () { 9182 var missed = false, input = this; 9183 input.pollingFast = true; 9184 function p() { 9185 var changed = input.poll(); 9186 if (!changed && !missed) {missed = true; input.polling.set(60, p);} 9187 else {input.pollingFast = false; input.slowPoll();} 9188 } 9189 input.polling.set(20, p); 9190}; 9191 9192// Read input from the textarea, and update the document to match. 9193// When something is selected, it is present in the textarea, and 9194// selected (unless it is huge, in which case a placeholder is 9195// used). When nothing is selected, the cursor sits after previously 9196// seen text (can be empty), which is stored in prevInput (we must 9197// not reset the textarea when typing, because that breaks IME). 9198TextareaInput.prototype.poll = function () { 9199 var this$1 = this; 9200 9201 var cm = this.cm, input = this.textarea, prevInput = this.prevInput; 9202 // Since this is called a *lot*, try to bail out as cheaply as 9203 // possible when it is clear that nothing happened. hasSelection 9204 // will be the case when there is a lot of text in the textarea, 9205 // in which case reading its value would be expensive. 9206 if (this.contextMenuPending || !cm.state.focused || 9207 (hasSelection(input) && !prevInput && !this.composing) || 9208 cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) 9209 { return false } 9210 9211 var text = input.value; 9212 // If nothing changed, bail. 9213 if (text == prevInput && !cm.somethingSelected()) { return false } 9214 // Work around nonsensical selection resetting in IE9/10, and 9215 // inexplicable appearance of private area unicode characters on 9216 // some key combos in Mac (#2689). 9217 if (ie && ie_version >= 9 && this.hasSelection === text || 9218 mac && /[\uf700-\uf7ff]/.test(text)) { 9219 cm.display.input.reset(); 9220 return false 9221 } 9222 9223 if (cm.doc.sel == cm.display.selForContextMenu) { 9224 var first = text.charCodeAt(0); 9225 if (first == 0x200b && !prevInput) { prevInput = "\u200b"; } 9226 if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") } 9227 } 9228 // Find the part of the input that is actually new 9229 var same = 0, l = Math.min(prevInput.length, text.length); 9230 while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; } 9231 9232 runInOp(cm, function () { 9233 applyTextInput(cm, text.slice(same), prevInput.length - same, 9234 null, this$1.composing ? "*compose" : null); 9235 9236 // Don't leave long text in the textarea, since it makes further polling slow 9237 if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; } 9238 else { this$1.prevInput = text; } 9239 9240 if (this$1.composing) { 9241 this$1.composing.range.clear(); 9242 this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), 9243 {className: "CodeMirror-composing"}); 9244 } 9245 }); 9246 return true 9247}; 9248 9249TextareaInput.prototype.ensurePolled = function () { 9250 if (this.pollingFast && this.poll()) { this.pollingFast = false; } 9251}; 9252 9253TextareaInput.prototype.onKeyPress = function () { 9254 if (ie && ie_version >= 9) { this.hasSelection = null; } 9255 this.fastPoll(); 9256}; 9257 9258TextareaInput.prototype.onContextMenu = function (e) { 9259 var input = this, cm = input.cm, display = cm.display, te = input.textarea; 9260 var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; 9261 if (!pos || presto) { return } // Opera is difficult. 9262 9263 // Reset the current text selection only if the click is done outside of the selection 9264 // and 'resetSelectionOnContextMenu' option is true. 9265 var reset = cm.options.resetSelectionOnContextMenu; 9266 if (reset && cm.doc.sel.contains(pos) == -1) 9267 { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); } 9268 9269 var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText; 9270 input.wrapper.style.cssText = "position: absolute"; 9271 var wrapperBox = input.wrapper.getBoundingClientRect(); 9272 te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; 9273 var oldScrollY; 9274 if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712) 9275 display.input.focus(); 9276 if (webkit) { window.scrollTo(null, oldScrollY); } 9277 display.input.reset(); 9278 // Adds "Select all" to context menu in FF 9279 if (!cm.somethingSelected()) { te.value = input.prevInput = " "; } 9280 input.contextMenuPending = true; 9281 display.selForContextMenu = cm.doc.sel; 9282 clearTimeout(display.detectingSelectAll); 9283 9284 // Select-all will be greyed out if there's nothing to select, so 9285 // this adds a zero-width space so that we can later check whether 9286 // it got selected. 9287 function prepareSelectAllHack() { 9288 if (te.selectionStart != null) { 9289 var selected = cm.somethingSelected(); 9290 var extval = "\u200b" + (selected ? te.value : ""); 9291 te.value = "\u21da"; // Used to catch context-menu undo 9292 te.value = extval; 9293 input.prevInput = selected ? "" : "\u200b"; 9294 te.selectionStart = 1; te.selectionEnd = extval.length; 9295 // Re-set this, in case some other handler touched the 9296 // selection in the meantime. 9297 display.selForContextMenu = cm.doc.sel; 9298 } 9299 } 9300 function rehide() { 9301 input.contextMenuPending = false; 9302 input.wrapper.style.cssText = oldWrapperCSS; 9303 te.style.cssText = oldCSS; 9304 if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); } 9305 9306 // Try to detect the user choosing select-all 9307 if (te.selectionStart != null) { 9308 if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); } 9309 var i = 0, poll = function () { 9310 if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && 9311 te.selectionEnd > 0 && input.prevInput == "\u200b") { 9312 operation(cm, selectAll)(cm); 9313 } else if (i++ < 10) { 9314 display.detectingSelectAll = setTimeout(poll, 500); 9315 } else { 9316 display.selForContextMenu = null; 9317 display.input.reset(); 9318 } 9319 }; 9320 display.detectingSelectAll = setTimeout(poll, 200); 9321 } 9322 } 9323 9324 if (ie && ie_version >= 9) { prepareSelectAllHack(); } 9325 if (captureRightClick) { 9326 e_stop(e); 9327 var mouseup = function () { 9328 off(window, "mouseup", mouseup); 9329 setTimeout(rehide, 20); 9330 }; 9331 on(window, "mouseup", mouseup); 9332 } else { 9333 setTimeout(rehide, 50); 9334 } 9335}; 9336 9337TextareaInput.prototype.readOnlyChanged = function (val) { 9338 if (!val) { this.reset(); } 9339 this.textarea.disabled = val == "nocursor"; 9340}; 9341 9342TextareaInput.prototype.setUneditable = function () {}; 9343 9344TextareaInput.prototype.needsContentAttribute = false; 9345 9346function fromTextArea(textarea, options) { 9347 options = options ? copyObj(options) : {}; 9348 options.value = textarea.value; 9349 if (!options.tabindex && textarea.tabIndex) 9350 { options.tabindex = textarea.tabIndex; } 9351 if (!options.placeholder && textarea.placeholder) 9352 { options.placeholder = textarea.placeholder; } 9353 // Set autofocus to true if this textarea is focused, or if it has 9354 // autofocus and no other element is focused. 9355 if (options.autofocus == null) { 9356 var hasFocus = activeElt(); 9357 options.autofocus = hasFocus == textarea || 9358 textarea.getAttribute("autofocus") != null && hasFocus == document.body; 9359 } 9360 9361 function save() {textarea.value = cm.getValue();} 9362 9363 var realSubmit; 9364 if (textarea.form) { 9365 on(textarea.form, "submit", save); 9366 // Deplorable hack to make the submit method do the right thing. 9367 if (!options.leaveSubmitMethodAlone) { 9368 var form = textarea.form; 9369 realSubmit = form.submit; 9370 try { 9371 var wrappedSubmit = form.submit = function () { 9372 save(); 9373 form.submit = realSubmit; 9374 form.submit(); 9375 form.submit = wrappedSubmit; 9376 }; 9377 } catch(e) {} 9378 } 9379 } 9380 9381 options.finishInit = function (cm) { 9382 cm.save = save; 9383 cm.getTextArea = function () { return textarea; }; 9384 cm.toTextArea = function () { 9385 cm.toTextArea = isNaN; // Prevent this from being ran twice 9386 save(); 9387 textarea.parentNode.removeChild(cm.getWrapperElement()); 9388 textarea.style.display = ""; 9389 if (textarea.form) { 9390 off(textarea.form, "submit", save); 9391 if (typeof textarea.form.submit == "function") 9392 { textarea.form.submit = realSubmit; } 9393 } 9394 }; 9395 }; 9396 9397 textarea.style.display = "none"; 9398 var cm = CodeMirror$1(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); }, 9399 options); 9400 return cm 9401} 9402 9403function addLegacyProps(CodeMirror) { 9404 CodeMirror.off = off; 9405 CodeMirror.on = on; 9406 CodeMirror.wheelEventPixels = wheelEventPixels; 9407 CodeMirror.Doc = Doc; 9408 CodeMirror.splitLines = splitLinesAuto; 9409 CodeMirror.countColumn = countColumn; 9410 CodeMirror.findColumn = findColumn; 9411 CodeMirror.isWordChar = isWordCharBasic; 9412 CodeMirror.Pass = Pass; 9413 CodeMirror.signal = signal; 9414 CodeMirror.Line = Line; 9415 CodeMirror.changeEnd = changeEnd; 9416 CodeMirror.scrollbarModel = scrollbarModel; 9417 CodeMirror.Pos = Pos; 9418 CodeMirror.cmpPos = cmp; 9419 CodeMirror.modes = modes; 9420 CodeMirror.mimeModes = mimeModes; 9421 CodeMirror.resolveMode = resolveMode; 9422 CodeMirror.getMode = getMode; 9423 CodeMirror.modeExtensions = modeExtensions; 9424 CodeMirror.extendMode = extendMode; 9425 CodeMirror.copyState = copyState; 9426 CodeMirror.startState = startState; 9427 CodeMirror.innerMode = innerMode; 9428 CodeMirror.commands = commands; 9429 CodeMirror.keyMap = keyMap; 9430 CodeMirror.keyName = keyName; 9431 CodeMirror.isModifierKey = isModifierKey; 9432 CodeMirror.lookupKey = lookupKey; 9433 CodeMirror.normalizeKeyMap = normalizeKeyMap; 9434 CodeMirror.StringStream = StringStream; 9435 CodeMirror.SharedTextMarker = SharedTextMarker; 9436 CodeMirror.TextMarker = TextMarker; 9437 CodeMirror.LineWidget = LineWidget; 9438 CodeMirror.e_preventDefault = e_preventDefault; 9439 CodeMirror.e_stopPropagation = e_stopPropagation; 9440 CodeMirror.e_stop = e_stop; 9441 CodeMirror.addClass = addClass; 9442 CodeMirror.contains = contains; 9443 CodeMirror.rmClass = rmClass; 9444 CodeMirror.keyNames = keyNames; 9445} 9446 9447// EDITOR CONSTRUCTOR 9448 9449defineOptions(CodeMirror$1); 9450 9451addEditorMethods(CodeMirror$1); 9452 9453// Set up methods on CodeMirror's prototype to redirect to the editor's document. 9454var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); 9455for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) 9456 { CodeMirror$1.prototype[prop] = (function(method) { 9457 return function() {return method.apply(this.doc, arguments)} 9458 })(Doc.prototype[prop]); } } 9459 9460eventMixin(Doc); 9461 9462// INPUT HANDLING 9463 9464CodeMirror$1.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; 9465 9466// MODE DEFINITION AND QUERYING 9467 9468// Extra arguments are stored as the mode's dependencies, which is 9469// used by (legacy) mechanisms like loadmode.js to automatically 9470// load a mode. (Preferred mechanism is the require/define calls.) 9471CodeMirror$1.defineMode = function(name/*, mode, â¦*/) { 9472 if (!CodeMirror$1.defaults.mode && name != "null") { CodeMirror$1.defaults.mode = name; } 9473 defineMode.apply(this, arguments); 9474}; 9475 9476CodeMirror$1.defineMIME = defineMIME; 9477 9478// Minimal default mode. 9479CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }); 9480CodeMirror$1.defineMIME("text/plain", "null"); 9481 9482// EXTENSIONS 9483 9484CodeMirror$1.defineExtension = function (name, func) { 9485 CodeMirror$1.prototype[name] = func; 9486}; 9487CodeMirror$1.defineDocExtension = function (name, func) { 9488 Doc.prototype[name] = func; 9489}; 9490 9491CodeMirror$1.fromTextArea = fromTextArea; 9492 9493addLegacyProps(CodeMirror$1); 9494 9495CodeMirror$1.version = "5.27.2"; 9496 9497return CodeMirror$1; 9498 9499})));
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.