codemirror.js (363564B)
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(mod) { 11 if (typeof exports == "object" && typeof module == "object") // CommonJS 12 module.exports = mod(); 13 else if (typeof define == "function" && define.amd) // AMD 14 return define([], mod); 15 else // Plain browser env 16 (this || window).CodeMirror = mod(); 17 })(function() { 18 "use strict"; 19 20 // BROWSER SNIFFING 21 22 // Kludges for bugs and behavior differences that can't be feature 23 // detected are enabled based on userAgent etc sniffing. 24 var userAgent = navigator.userAgent; 25 var platform = navigator.platform; 26 27 var gecko = /gecko\/\d/i.test(userAgent); 28 var ie_upto10 = /MSIE \d/.test(userAgent); 29 var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); 30 var ie = ie_upto10 || ie_11up; 31 var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]); 32 var webkit = /WebKit\//.test(userAgent); 33 var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); 34 var chrome = /Chrome\//.test(userAgent); 35 var presto = /Opera\//.test(userAgent); 36 var safari = /Apple Computer/.test(navigator.vendor); 37 var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); 38 var phantom = /PhantomJS/.test(userAgent); 39 40 var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent); 41 // This is woefully incomplete. Suggestions for alternative methods welcome. 42 var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); 43 var mac = ios || /Mac/.test(platform); 44 var chromeOS = /\bCrOS\b/.test(userAgent); 45 var windows = /win/i.test(platform); 46 47 var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); 48 if (presto_version) presto_version = Number(presto_version[1]); 49 if (presto_version && presto_version >= 15) { presto = false; webkit = true; } 50 // Some browsers use the wrong event properties to signal cmd/ctrl on OS X 51 var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); 52 var captureRightClick = gecko || (ie && ie_version >= 9); 53 54 // Optimize some code when these features are not used. 55 var sawReadOnlySpans = false, sawCollapsedSpans = false; 56 57 // EDITOR CONSTRUCTOR 58 59 // A CodeMirror instance represents an editor. This is the object 60 // that user code is usually dealing with. 61 62 function CodeMirror(place, options) { 63 if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); 64 65 this.options = options = options ? copyObj(options) : {}; 66 // Determine effective options based on given values and defaults. 67 copyObj(defaults, options, false); 68 setGuttersForLineNumbers(options); 69 70 var doc = options.value; 71 if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator); 72 this.doc = doc; 73 74 var input = new CodeMirror.inputStyles[options.inputStyle](this); 75 var display = this.display = new Display(place, doc, input); 76 display.wrapper.CodeMirror = this; 77 updateGutters(this); 78 themeChanged(this); 79 if (options.lineWrapping) 80 this.display.wrapper.className += " CodeMirror-wrap"; 81 if (options.autofocus && !mobile) display.input.focus(); 82 initScrollbars(this); 83 84 this.state = { 85 keyMaps: [], // stores maps added by addKeyMap 86 overlays: [], // highlighting overlays, as added by addOverlay 87 modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info 88 overwrite: false, 89 delayingBlurEvent: false, 90 focused: false, 91 suppressEdits: false, // used to disable editing during key handlers when in readOnly mode 92 pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll 93 selectingText: false, 94 draggingText: false, 95 highlight: new Delayed(), // stores highlight worker timeout 96 keySeq: null, // Unfinished key sequence 97 specialChars: null 98 }; 99 100 var cm = this; 101 102 // Override magic textarea content restore that IE sometimes does 103 // on our hidden textarea on reload 104 if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20); 105 106 registerEventHandlers(this); 107 ensureGlobalHandlers(); 108 109 startOperation(this); 110 this.curOp.forceUpdate = true; 111 attachDoc(this, doc); 112 113 if ((options.autofocus && !mobile) || cm.hasFocus()) 114 setTimeout(bind(onFocus, this), 20); 115 else 116 onBlur(this); 117 118 for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt)) 119 optionHandlers[opt](this, options[opt], Init); 120 maybeUpdateLineNumberWidth(this); 121 if (options.finishInit) options.finishInit(this); 122 for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); 123 endOperation(this); 124 // Suppress optimizelegibility in Webkit, since it breaks text 125 // measuring on line wrapping boundaries. 126 if (webkit && options.lineWrapping && 127 getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") 128 display.lineDiv.style.textRendering = "auto"; 129 } 130 131 // DISPLAY CONSTRUCTOR 132 133 // The display handles the DOM integration, both for input reading 134 // and content drawing. It holds references to DOM nodes and 135 // display-related state. 136 137 function Display(place, doc, input) { 138 var d = this; 139 this.input = input; 140 141 // Covers bottom-right square when both scrollbars are present. 142 d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); 143 d.scrollbarFiller.setAttribute("cm-not-content", "true"); 144 // Covers bottom of gutter when coverGutterNextToScrollbar is on 145 // and h scrollbar is present. 146 d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); 147 d.gutterFiller.setAttribute("cm-not-content", "true"); 148 // Will contain the actual code, positioned to cover the viewport. 149 d.lineDiv = elt("div", null, "CodeMirror-code"); 150 // Elements are added to these to represent selection and cursors. 151 d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); 152 d.cursorDiv = elt("div", null, "CodeMirror-cursors"); 153 // A visibility: hidden element used to find the size of things. 154 d.measure = elt("div", null, "CodeMirror-measure"); 155 // When lines outside of the viewport are measured, they are drawn in this. 156 d.lineMeasure = elt("div", null, "CodeMirror-measure"); 157 // Wraps everything that needs to exist inside the vertically-padded coordinate system 158 d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], 159 null, "position: relative; outline: none"); 160 // Moved around its parent to cover visible view. 161 d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); 162 // Set to the height of the document, allowing scrolling. 163 d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); 164 d.sizerWidth = null; 165 // Behavior of elts with overflow: auto and padding is 166 // inconsistent across browsers. This is used to ensure the 167 // scrollable area is big enough. 168 d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); 169 // Will contain the gutters, if any. 170 d.gutters = elt("div", null, "CodeMirror-gutters"); 171 d.lineGutter = null; 172 // Actual scrollable element. 173 d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); 174 d.scroller.setAttribute("tabIndex", "-1"); 175 // The element in which the editor lives. 176 d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); 177 178 // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) 179 if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } 180 if (!webkit && !(gecko && mobile)) d.scroller.draggable = true; 181 182 if (place) { 183 if (place.appendChild) place.appendChild(d.wrapper); 184 else place(d.wrapper); 185 } 186 187 // Current rendered range (may be bigger than the view window). 188 d.viewFrom = d.viewTo = doc.first; 189 d.reportedViewFrom = d.reportedViewTo = doc.first; 190 // Information about the rendered lines. 191 d.view = []; 192 d.renderedView = null; 193 // Holds info about a single rendered line when it was rendered 194 // for measurement, while not in view. 195 d.externalMeasured = null; 196 // Empty space (in pixels) above the view 197 d.viewOffset = 0; 198 d.lastWrapHeight = d.lastWrapWidth = 0; 199 d.updateLineNumbers = null; 200 201 d.nativeBarWidth = d.barHeight = d.barWidth = 0; 202 d.scrollbarsClipped = false; 203 204 // Used to only resize the line number gutter when necessary (when 205 // the amount of lines crosses a boundary that makes its width change) 206 d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; 207 // Set to true when a non-horizontal-scrolling line widget is 208 // added. As an optimization, line widget aligning is skipped when 209 // this is false. 210 d.alignWidgets = false; 211 212 d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; 213 214 // Tracks the maximum line length so that the horizontal scrollbar 215 // can be kept static when scrolling. 216 d.maxLine = null; 217 d.maxLineLength = 0; 218 d.maxLineChanged = false; 219 220 // Used for measuring wheel scrolling granularity 221 d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; 222 223 // True when shift is held down. 224 d.shift = false; 225 226 // Used to track whether anything happened since the context menu 227 // was opened. 228 d.selForContextMenu = null; 229 230 d.activeTouch = null; 231 232 input.init(d); 233 } 234 235 // STATE UPDATES 236 237 // Used to get the editor into a consistent state again when options change. 238 239 function loadMode(cm) { 240 cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); 241 resetModeState(cm); 242 } 243 244 function resetModeState(cm) { 245 cm.doc.iter(function(line) { 246 if (line.stateAfter) line.stateAfter = null; 247 if (line.styles) line.styles = null; 248 }); 249 cm.doc.frontier = cm.doc.first; 250 startWorker(cm, 100); 251 cm.state.modeGen++; 252 if (cm.curOp) regChange(cm); 253 } 254 255 function wrappingChanged(cm) { 256 if (cm.options.lineWrapping) { 257 addClass(cm.display.wrapper, "CodeMirror-wrap"); 258 cm.display.sizer.style.minWidth = ""; 259 cm.display.sizerWidth = null; 260 } else { 261 rmClass(cm.display.wrapper, "CodeMirror-wrap"); 262 findMaxLine(cm); 263 } 264 estimateLineHeights(cm); 265 regChange(cm); 266 clearCaches(cm); 267 setTimeout(function(){updateScrollbars(cm);}, 100); 268 } 269 270 // Returns a function that estimates the height of a line, to use as 271 // first approximation until the line becomes visible (and is thus 272 // properly measurable). 273 function estimateHeight(cm) { 274 var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; 275 var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); 276 return function(line) { 277 if (lineIsHidden(cm.doc, line)) return 0; 278 279 var widgetsHeight = 0; 280 if (line.widgets) for (var i = 0; i < line.widgets.length; i++) { 281 if (line.widgets[i].height) widgetsHeight += line.widgets[i].height; 282 } 283 284 if (wrapping) 285 return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th; 286 else 287 return widgetsHeight + th; 288 }; 289 } 290 291 function estimateLineHeights(cm) { 292 var doc = cm.doc, est = estimateHeight(cm); 293 doc.iter(function(line) { 294 var estHeight = est(line); 295 if (estHeight != line.height) updateLineHeight(line, estHeight); 296 }); 297 } 298 299 function themeChanged(cm) { 300 cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + 301 cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); 302 clearCaches(cm); 303 } 304 305 function guttersChanged(cm) { 306 updateGutters(cm); 307 regChange(cm); 308 setTimeout(function(){alignHorizontally(cm);}, 20); 309 } 310 311 // Rebuild the gutter elements, ensure the margin to the left of the 312 // code matches their width. 313 function updateGutters(cm) { 314 var gutters = cm.display.gutters, specs = cm.options.gutters; 315 removeChildren(gutters); 316 for (var i = 0; i < specs.length; ++i) { 317 var gutterClass = specs[i]; 318 var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); 319 if (gutterClass == "CodeMirror-linenumbers") { 320 cm.display.lineGutter = gElt; 321 gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; 322 } 323 } 324 gutters.style.display = i ? "" : "none"; 325 updateGutterSpace(cm); 326 } 327 328 function updateGutterSpace(cm) { 329 var width = cm.display.gutters.offsetWidth; 330 cm.display.sizer.style.marginLeft = width + "px"; 331 } 332 333 // Compute the character length of a line, taking into account 334 // collapsed ranges (see markText) that might hide parts, and join 335 // other lines onto it. 336 function lineLength(line) { 337 if (line.height == 0) return 0; 338 var len = line.text.length, merged, cur = line; 339 while (merged = collapsedSpanAtStart(cur)) { 340 var found = merged.find(0, true); 341 cur = found.from.line; 342 len += found.from.ch - found.to.ch; 343 } 344 cur = line; 345 while (merged = collapsedSpanAtEnd(cur)) { 346 var found = merged.find(0, true); 347 len -= cur.text.length - found.from.ch; 348 cur = found.to.line; 349 len += cur.text.length - found.to.ch; 350 } 351 return len; 352 } 353 354 // Find the longest line in the document. 355 function findMaxLine(cm) { 356 var d = cm.display, doc = cm.doc; 357 d.maxLine = getLine(doc, doc.first); 358 d.maxLineLength = lineLength(d.maxLine); 359 d.maxLineChanged = true; 360 doc.iter(function(line) { 361 var len = lineLength(line); 362 if (len > d.maxLineLength) { 363 d.maxLineLength = len; 364 d.maxLine = line; 365 } 366 }); 367 } 368 369 // Make sure the gutters options contains the element 370 // "CodeMirror-linenumbers" when the lineNumbers option is true. 371 function setGuttersForLineNumbers(options) { 372 var found = indexOf(options.gutters, "CodeMirror-linenumbers"); 373 if (found == -1 && options.lineNumbers) { 374 options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); 375 } else if (found > -1 && !options.lineNumbers) { 376 options.gutters = options.gutters.slice(0); 377 options.gutters.splice(found, 1); 378 } 379 } 380 381 // SCROLLBARS 382 383 // Prepare DOM reads needed to update the scrollbars. Done in one 384 // shot to minimize update/measure roundtrips. 385 function measureForScrollbars(cm) { 386 var d = cm.display, gutterW = d.gutters.offsetWidth; 387 var docH = Math.round(cm.doc.height + paddingVert(cm.display)); 388 return { 389 clientHeight: d.scroller.clientHeight, 390 viewHeight: d.wrapper.clientHeight, 391 scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, 392 viewWidth: d.wrapper.clientWidth, 393 barLeft: cm.options.fixedGutter ? gutterW : 0, 394 docHeight: docH, 395 scrollHeight: docH + scrollGap(cm) + d.barHeight, 396 nativeBarWidth: d.nativeBarWidth, 397 gutterWidth: gutterW 398 }; 399 } 400 401 function NativeScrollbars(place, scroll, cm) { 402 this.cm = cm; 403 var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); 404 var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); 405 place(vert); place(horiz); 406 407 on(vert, "scroll", function() { 408 if (vert.clientHeight) scroll(vert.scrollTop, "vertical"); 409 }); 410 on(horiz, "scroll", function() { 411 if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal"); 412 }); 413 414 this.checkedZeroWidth = false; 415 // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). 416 if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; 417 } 418 419 NativeScrollbars.prototype = copyObj({ 420 update: function(measure) { 421 var needsH = measure.scrollWidth > measure.clientWidth + 1; 422 var needsV = measure.scrollHeight > measure.clientHeight + 1; 423 var sWidth = measure.nativeBarWidth; 424 425 if (needsV) { 426 this.vert.style.display = "block"; 427 this.vert.style.bottom = needsH ? sWidth + "px" : "0"; 428 var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); 429 // A bug in IE8 can cause this value to be negative, so guard it. 430 this.vert.firstChild.style.height = 431 Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; 432 } else { 433 this.vert.style.display = ""; 434 this.vert.firstChild.style.height = "0"; 435 } 436 437 if (needsH) { 438 this.horiz.style.display = "block"; 439 this.horiz.style.right = needsV ? sWidth + "px" : "0"; 440 this.horiz.style.left = measure.barLeft + "px"; 441 var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); 442 this.horiz.firstChild.style.width = 443 (measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; 444 } else { 445 this.horiz.style.display = ""; 446 this.horiz.firstChild.style.width = "0"; 447 } 448 449 if (!this.checkedZeroWidth && measure.clientHeight > 0) { 450 if (sWidth == 0) this.zeroWidthHack(); 451 this.checkedZeroWidth = true; 452 } 453 454 return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}; 455 }, 456 setScrollLeft: function(pos) { 457 if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos; 458 if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz); 459 }, 460 setScrollTop: function(pos) { 461 if (this.vert.scrollTop != pos) this.vert.scrollTop = pos; 462 if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert); 463 }, 464 zeroWidthHack: function() { 465 var w = mac && !mac_geMountainLion ? "12px" : "18px"; 466 this.horiz.style.height = this.vert.style.width = w; 467 this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; 468 this.disableHoriz = new Delayed; 469 this.disableVert = new Delayed; 470 }, 471 enableZeroWidthBar: function(bar, delay) { 472 bar.style.pointerEvents = "auto"; 473 function maybeDisable() { 474 // To find out whether the scrollbar is still visible, we 475 // check whether the element under the pixel in the bottom 476 // left corner of the scrollbar box is the scrollbar box 477 // itself (when the bar is still visible) or its filler child 478 // (when the bar is hidden). If it is still visible, we keep 479 // it enabled, if it's hidden, we disable pointer events. 480 var box = bar.getBoundingClientRect(); 481 var elt = document.elementFromPoint(box.left + 1, box.bottom - 1); 482 if (elt != bar) bar.style.pointerEvents = "none"; 483 else delay.set(1000, maybeDisable); 484 } 485 delay.set(1000, maybeDisable); 486 }, 487 clear: function() { 488 var parent = this.horiz.parentNode; 489 parent.removeChild(this.horiz); 490 parent.removeChild(this.vert); 491 } 492 }, NativeScrollbars.prototype); 493 494 function NullScrollbars() {} 495 496 NullScrollbars.prototype = copyObj({ 497 update: function() { return {bottom: 0, right: 0}; }, 498 setScrollLeft: function() {}, 499 setScrollTop: function() {}, 500 clear: function() {} 501 }, NullScrollbars.prototype); 502 503 CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; 504 505 function initScrollbars(cm) { 506 if (cm.display.scrollbars) { 507 cm.display.scrollbars.clear(); 508 if (cm.display.scrollbars.addClass) 509 rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); 510 } 511 512 cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) { 513 cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); 514 // Prevent clicks in the scrollbars from killing focus 515 on(node, "mousedown", function() { 516 if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0); 517 }); 518 node.setAttribute("cm-not-content", "true"); 519 }, function(pos, axis) { 520 if (axis == "horizontal") setScrollLeft(cm, pos); 521 else setScrollTop(cm, pos); 522 }, cm); 523 if (cm.display.scrollbars.addClass) 524 addClass(cm.display.wrapper, cm.display.scrollbars.addClass); 525 } 526 527 function updateScrollbars(cm, measure) { 528 if (!measure) measure = measureForScrollbars(cm); 529 var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; 530 updateScrollbarsInner(cm, measure); 531 for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { 532 if (startWidth != cm.display.barWidth && cm.options.lineWrapping) 533 updateHeightsInViewport(cm); 534 updateScrollbarsInner(cm, measureForScrollbars(cm)); 535 startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; 536 } 537 } 538 539 // Re-synchronize the fake scrollbars with the actual size of the 540 // content. 541 function updateScrollbarsInner(cm, measure) { 542 var d = cm.display; 543 var sizes = d.scrollbars.update(measure); 544 545 d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; 546 d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; 547 d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent" 548 549 if (sizes.right && sizes.bottom) { 550 d.scrollbarFiller.style.display = "block"; 551 d.scrollbarFiller.style.height = sizes.bottom + "px"; 552 d.scrollbarFiller.style.width = sizes.right + "px"; 553 } else d.scrollbarFiller.style.display = ""; 554 if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { 555 d.gutterFiller.style.display = "block"; 556 d.gutterFiller.style.height = sizes.bottom + "px"; 557 d.gutterFiller.style.width = measure.gutterWidth + "px"; 558 } else d.gutterFiller.style.display = ""; 559 } 560 561 // Compute the lines that are visible in a given viewport (defaults 562 // the the current scroll position). viewport may contain top, 563 // height, and ensure (see op.scrollToPos) properties. 564 function visibleLines(display, doc, viewport) { 565 var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; 566 top = Math.floor(top - paddingTop(display)); 567 var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; 568 569 var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); 570 // Ensure is a {from: {line, ch}, to: {line, ch}} object, and 571 // forces those lines into the viewport (if possible). 572 if (viewport && viewport.ensure) { 573 var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; 574 if (ensureFrom < from) { 575 from = ensureFrom; 576 to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); 577 } else if (Math.min(ensureTo, doc.lastLine()) >= to) { 578 from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); 579 to = ensureTo; 580 } 581 } 582 return {from: from, to: Math.max(to, from + 1)}; 583 } 584 585 // LINE NUMBERS 586 587 // Re-align line numbers and gutter marks to compensate for 588 // horizontal scrolling. 589 function alignHorizontally(cm) { 590 var display = cm.display, view = display.view; 591 if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; 592 var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; 593 var gutterW = display.gutters.offsetWidth, left = comp + "px"; 594 for (var i = 0; i < view.length; i++) if (!view[i].hidden) { 595 if (cm.options.fixedGutter && view[i].gutter) 596 view[i].gutter.style.left = left; 597 var align = view[i].alignable; 598 if (align) for (var j = 0; j < align.length; j++) 599 align[j].style.left = left; 600 } 601 if (cm.options.fixedGutter) 602 display.gutters.style.left = (comp + gutterW) + "px"; 603 } 604 605 // Used to ensure that the line number gutter is still the right 606 // size for the current document size. Returns true when an update 607 // is needed. 608 function maybeUpdateLineNumberWidth(cm) { 609 if (!cm.options.lineNumbers) return false; 610 var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; 611 if (last.length != display.lineNumChars) { 612 var test = display.measure.appendChild(elt("div", [elt("div", last)], 613 "CodeMirror-linenumber CodeMirror-gutter-elt")); 614 var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; 615 display.lineGutter.style.width = ""; 616 display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; 617 display.lineNumWidth = display.lineNumInnerWidth + padding; 618 display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; 619 display.lineGutter.style.width = display.lineNumWidth + "px"; 620 updateGutterSpace(cm); 621 return true; 622 } 623 return false; 624 } 625 626 function lineNumberFor(options, i) { 627 return String(options.lineNumberFormatter(i + options.firstLineNumber)); 628 } 629 630 // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, 631 // but using getBoundingClientRect to get a sub-pixel-accurate 632 // result. 633 function compensateForHScroll(display) { 634 return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; 635 } 636 637 // DISPLAY DRAWING 638 639 function DisplayUpdate(cm, viewport, force) { 640 var display = cm.display; 641 642 this.viewport = viewport; 643 // Store some values that we'll need later (but don't want to force a relayout for) 644 this.visible = visibleLines(display, cm.doc, viewport); 645 this.editorIsHidden = !display.wrapper.offsetWidth; 646 this.wrapperHeight = display.wrapper.clientHeight; 647 this.wrapperWidth = display.wrapper.clientWidth; 648 this.oldDisplayWidth = displayWidth(cm); 649 this.force = force; 650 this.dims = getDimensions(cm); 651 this.events = []; 652 } 653 654 DisplayUpdate.prototype.signal = function(emitter, type) { 655 if (hasHandler(emitter, type)) 656 this.events.push(arguments); 657 }; 658 DisplayUpdate.prototype.finish = function() { 659 for (var i = 0; i < this.events.length; i++) 660 signal.apply(null, this.events[i]); 661 }; 662 663 function maybeClipScrollbars(cm) { 664 var display = cm.display; 665 if (!display.scrollbarsClipped && display.scroller.offsetWidth) { 666 display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; 667 display.heightForcer.style.height = scrollGap(cm) + "px"; 668 display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; 669 display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; 670 display.scrollbarsClipped = true; 671 } 672 } 673 674 // Does the actual updating of the line display. Bails out 675 // (returning false) when there is nothing to be done and forced is 676 // false. 677 function updateDisplayIfNeeded(cm, update) { 678 var display = cm.display, doc = cm.doc; 679 680 if (update.editorIsHidden) { 681 resetView(cm); 682 return false; 683 } 684 685 // Bail out if the visible area is already rendered and nothing changed. 686 if (!update.force && 687 update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && 688 (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && 689 display.renderedView == display.view && countDirtyView(cm) == 0) 690 return false; 691 692 if (maybeUpdateLineNumberWidth(cm)) { 693 resetView(cm); 694 update.dims = getDimensions(cm); 695 } 696 697 // Compute a suitable new viewport (from & to) 698 var end = doc.first + doc.size; 699 var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); 700 var to = Math.min(end, update.visible.to + cm.options.viewportMargin); 701 if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom); 702 if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo); 703 if (sawCollapsedSpans) { 704 from = visualLineNo(cm.doc, from); 705 to = visualLineEndNo(cm.doc, to); 706 } 707 708 var different = from != display.viewFrom || to != display.viewTo || 709 display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; 710 adjustView(cm, from, to); 711 712 display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); 713 // Position the mover div to align with the current scroll position 714 cm.display.mover.style.top = display.viewOffset + "px"; 715 716 var toUpdate = countDirtyView(cm); 717 if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && 718 (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) 719 return false; 720 721 // For big changes, we hide the enclosing element during the 722 // update, since that speeds up the operations on most browsers. 723 var focused = activeElt(); 724 if (toUpdate > 4) display.lineDiv.style.display = "none"; 725 patchDisplay(cm, display.updateLineNumbers, update.dims); 726 if (toUpdate > 4) display.lineDiv.style.display = ""; 727 display.renderedView = display.view; 728 // There might have been a widget with a focused element that got 729 // hidden or updated, if so re-focus it. 730 if (focused && activeElt() != focused && focused.offsetHeight) focused.focus(); 731 732 // Prevent selection and cursors from interfering with the scroll 733 // width and height. 734 removeChildren(display.cursorDiv); 735 removeChildren(display.selectionDiv); 736 display.gutters.style.height = display.sizer.style.minHeight = 0; 737 738 if (different) { 739 display.lastWrapHeight = update.wrapperHeight; 740 display.lastWrapWidth = update.wrapperWidth; 741 startWorker(cm, 400); 742 } 743 744 display.updateLineNumbers = null; 745 746 return true; 747 } 748 749 function postUpdateDisplay(cm, update) { 750 var viewport = update.viewport; 751 752 for (var first = true;; first = false) { 753 if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { 754 // Clip forced viewport to actual scrollable area. 755 if (viewport && viewport.top != null) 756 viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; 757 // Updated line heights might result in the drawn area not 758 // actually covering the viewport. Keep looping until it does. 759 update.visible = visibleLines(cm.display, cm.doc, viewport); 760 if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) 761 break; 762 } 763 if (!updateDisplayIfNeeded(cm, update)) break; 764 updateHeightsInViewport(cm); 765 var barMeasure = measureForScrollbars(cm); 766 updateSelection(cm); 767 updateScrollbars(cm, barMeasure); 768 setDocumentHeight(cm, barMeasure); 769 } 770 771 update.signal(cm, "update", cm); 772 if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { 773 update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); 774 cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; 775 } 776 } 777 778 function updateDisplaySimple(cm, viewport) { 779 var update = new DisplayUpdate(cm, viewport); 780 if (updateDisplayIfNeeded(cm, update)) { 781 updateHeightsInViewport(cm); 782 postUpdateDisplay(cm, update); 783 var barMeasure = measureForScrollbars(cm); 784 updateSelection(cm); 785 updateScrollbars(cm, barMeasure); 786 setDocumentHeight(cm, barMeasure); 787 update.finish(); 788 } 789 } 790 791 function setDocumentHeight(cm, measure) { 792 cm.display.sizer.style.minHeight = measure.docHeight + "px"; 793 cm.display.heightForcer.style.top = measure.docHeight + "px"; 794 cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"; 795 } 796 797 // Read the actual heights of the rendered lines, and update their 798 // stored heights to match. 799 function updateHeightsInViewport(cm) { 800 var display = cm.display; 801 var prevBottom = display.lineDiv.offsetTop; 802 for (var i = 0; i < display.view.length; i++) { 803 var cur = display.view[i], height; 804 if (cur.hidden) continue; 805 if (ie && ie_version < 8) { 806 var bot = cur.node.offsetTop + cur.node.offsetHeight; 807 height = bot - prevBottom; 808 prevBottom = bot; 809 } else { 810 var box = cur.node.getBoundingClientRect(); 811 height = box.bottom - box.top; 812 } 813 var diff = cur.line.height - height; 814 if (height < 2) height = textHeight(display); 815 if (diff > .001 || diff < -.001) { 816 updateLineHeight(cur.line, height); 817 updateWidgetHeight(cur.line); 818 if (cur.rest) for (var j = 0; j < cur.rest.length; j++) 819 updateWidgetHeight(cur.rest[j]); 820 } 821 } 822 } 823 824 // Read and store the height of line widgets associated with the 825 // given line. 826 function updateWidgetHeight(line) { 827 if (line.widgets) for (var i = 0; i < line.widgets.length; ++i) 828 line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight; 829 } 830 831 // Do a bulk-read of the DOM positions and sizes needed to draw the 832 // view, so that we don't interleave reading and writing to the DOM. 833 function getDimensions(cm) { 834 var d = cm.display, left = {}, width = {}; 835 var gutterLeft = d.gutters.clientLeft; 836 for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { 837 left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; 838 width[cm.options.gutters[i]] = n.clientWidth; 839 } 840 return {fixedPos: compensateForHScroll(d), 841 gutterTotalWidth: d.gutters.offsetWidth, 842 gutterLeft: left, 843 gutterWidth: width, 844 wrapperWidth: d.wrapper.clientWidth}; 845 } 846 847 // Sync the actual display DOM structure with display.view, removing 848 // nodes for lines that are no longer in view, and creating the ones 849 // that are not there yet, and updating the ones that are out of 850 // date. 851 function patchDisplay(cm, updateNumbersFrom, dims) { 852 var display = cm.display, lineNumbers = cm.options.lineNumbers; 853 var container = display.lineDiv, cur = container.firstChild; 854 855 function rm(node) { 856 var next = node.nextSibling; 857 // Works around a throw-scroll bug in OS X Webkit 858 if (webkit && mac && cm.display.currentWheelTarget == node) 859 node.style.display = "none"; 860 else 861 node.parentNode.removeChild(node); 862 return next; 863 } 864 865 var view = display.view, lineN = display.viewFrom; 866 // Loop over the elements in the view, syncing cur (the DOM nodes 867 // in display.lineDiv) with the view as we go. 868 for (var i = 0; i < view.length; i++) { 869 var lineView = view[i]; 870 if (lineView.hidden) { 871 } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet 872 var node = buildLineElement(cm, lineView, lineN, dims); 873 container.insertBefore(node, cur); 874 } else { // Already drawn 875 while (cur != lineView.node) cur = rm(cur); 876 var updateNumber = lineNumbers && updateNumbersFrom != null && 877 updateNumbersFrom <= lineN && lineView.lineNumber; 878 if (lineView.changes) { 879 if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false; 880 updateLineForChanges(cm, lineView, lineN, dims); 881 } 882 if (updateNumber) { 883 removeChildren(lineView.lineNumber); 884 lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); 885 } 886 cur = lineView.node.nextSibling; 887 } 888 lineN += lineView.size; 889 } 890 while (cur) cur = rm(cur); 891 } 892 893 // When an aspect of a line changes, a string is added to 894 // lineView.changes. This updates the relevant part of the line's 895 // DOM structure. 896 function updateLineForChanges(cm, lineView, lineN, dims) { 897 for (var j = 0; j < lineView.changes.length; j++) { 898 var type = lineView.changes[j]; 899 if (type == "text") updateLineText(cm, lineView); 900 else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims); 901 else if (type == "class") updateLineClasses(lineView); 902 else if (type == "widget") updateLineWidgets(cm, lineView, dims); 903 } 904 lineView.changes = null; 905 } 906 907 // Lines with gutter elements, widgets or a background class need to 908 // be wrapped, and have the extra elements added to the wrapper div 909 function ensureLineWrapped(lineView) { 910 if (lineView.node == lineView.text) { 911 lineView.node = elt("div", null, null, "position: relative"); 912 if (lineView.text.parentNode) 913 lineView.text.parentNode.replaceChild(lineView.node, lineView.text); 914 lineView.node.appendChild(lineView.text); 915 if (ie && ie_version < 8) lineView.node.style.zIndex = 2; 916 } 917 return lineView.node; 918 } 919 920 function updateLineBackground(lineView) { 921 var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; 922 if (cls) cls += " CodeMirror-linebackground"; 923 if (lineView.background) { 924 if (cls) lineView.background.className = cls; 925 else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } 926 } else if (cls) { 927 var wrap = ensureLineWrapped(lineView); 928 lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); 929 } 930 } 931 932 // Wrapper around buildLineContent which will reuse the structure 933 // in display.externalMeasured when possible. 934 function getLineContent(cm, lineView) { 935 var ext = cm.display.externalMeasured; 936 if (ext && ext.line == lineView.line) { 937 cm.display.externalMeasured = null; 938 lineView.measure = ext.measure; 939 return ext.built; 940 } 941 return buildLineContent(cm, lineView); 942 } 943 944 // Redraw the line's text. Interacts with the background and text 945 // classes because the mode may output tokens that influence these 946 // classes. 947 function updateLineText(cm, lineView) { 948 var cls = lineView.text.className; 949 var built = getLineContent(cm, lineView); 950 if (lineView.text == lineView.node) lineView.node = built.pre; 951 lineView.text.parentNode.replaceChild(built.pre, lineView.text); 952 lineView.text = built.pre; 953 if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { 954 lineView.bgClass = built.bgClass; 955 lineView.textClass = built.textClass; 956 updateLineClasses(lineView); 957 } else if (cls) { 958 lineView.text.className = cls; 959 } 960 } 961 962 function updateLineClasses(lineView) { 963 updateLineBackground(lineView); 964 if (lineView.line.wrapClass) 965 ensureLineWrapped(lineView).className = lineView.line.wrapClass; 966 else if (lineView.node != lineView.text) 967 lineView.node.className = ""; 968 var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; 969 lineView.text.className = textClass || ""; 970 } 971 972 function updateLineGutter(cm, lineView, lineN, dims) { 973 if (lineView.gutter) { 974 lineView.node.removeChild(lineView.gutter); 975 lineView.gutter = null; 976 } 977 if (lineView.gutterBackground) { 978 lineView.node.removeChild(lineView.gutterBackground); 979 lineView.gutterBackground = null; 980 } 981 if (lineView.line.gutterClass) { 982 var wrap = ensureLineWrapped(lineView); 983 lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, 984 "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + 985 "px; width: " + dims.gutterTotalWidth + "px"); 986 wrap.insertBefore(lineView.gutterBackground, lineView.text); 987 } 988 var markers = lineView.line.gutterMarkers; 989 if (cm.options.lineNumbers || markers) { 990 var wrap = ensureLineWrapped(lineView); 991 var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + 992 (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"); 993 cm.display.input.setUneditable(gutterWrap); 994 wrap.insertBefore(gutterWrap, lineView.text); 995 if (lineView.line.gutterClass) 996 gutterWrap.className += " " + lineView.line.gutterClass; 997 if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) 998 lineView.lineNumber = gutterWrap.appendChild( 999 elt("div", lineNumberFor(cm.options, lineN), 1000 "CodeMirror-linenumber CodeMirror-gutter-elt", 1001 "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " 1002 + cm.display.lineNumInnerWidth + "px")); 1003 if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) { 1004 var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; 1005 if (found) 1006 gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + 1007 dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); 1008 } 1009 } 1010 } 1011 1012 function updateLineWidgets(cm, lineView, dims) { 1013 if (lineView.alignable) lineView.alignable = null; 1014 for (var node = lineView.node.firstChild, next; node; node = next) { 1015 var next = node.nextSibling; 1016 if (node.className == "CodeMirror-linewidget") 1017 lineView.node.removeChild(node); 1018 } 1019 insertLineWidgets(cm, lineView, dims); 1020 } 1021 1022 // Build a line's DOM representation from scratch 1023 function buildLineElement(cm, lineView, lineN, dims) { 1024 var built = getLineContent(cm, lineView); 1025 lineView.text = lineView.node = built.pre; 1026 if (built.bgClass) lineView.bgClass = built.bgClass; 1027 if (built.textClass) lineView.textClass = built.textClass; 1028 1029 updateLineClasses(lineView); 1030 updateLineGutter(cm, lineView, lineN, dims); 1031 insertLineWidgets(cm, lineView, dims); 1032 return lineView.node; 1033 } 1034 1035 // A lineView may contain multiple logical lines (when merged by 1036 // collapsed spans). The widgets for all of them need to be drawn. 1037 function insertLineWidgets(cm, lineView, dims) { 1038 insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); 1039 if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) 1040 insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); 1041 } 1042 1043 function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { 1044 if (!line.widgets) return; 1045 var wrap = ensureLineWrapped(lineView); 1046 for (var i = 0, ws = line.widgets; i < ws.length; ++i) { 1047 var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); 1048 if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true"); 1049 positionLineWidget(widget, node, lineView, dims); 1050 cm.display.input.setUneditable(node); 1051 if (allowAbove && widget.above) 1052 wrap.insertBefore(node, lineView.gutter || lineView.text); 1053 else 1054 wrap.appendChild(node); 1055 signalLater(widget, "redraw"); 1056 } 1057 } 1058 1059 function positionLineWidget(widget, node, lineView, dims) { 1060 if (widget.noHScroll) { 1061 (lineView.alignable || (lineView.alignable = [])).push(node); 1062 var width = dims.wrapperWidth; 1063 node.style.left = dims.fixedPos + "px"; 1064 if (!widget.coverGutter) { 1065 width -= dims.gutterTotalWidth; 1066 node.style.paddingLeft = dims.gutterTotalWidth + "px"; 1067 } 1068 node.style.width = width + "px"; 1069 } 1070 if (widget.coverGutter) { 1071 node.style.zIndex = 5; 1072 node.style.position = "relative"; 1073 if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; 1074 } 1075 } 1076 1077 // POSITION OBJECT 1078 1079 // A Pos instance represents a position within the text. 1080 var Pos = CodeMirror.Pos = function(line, ch) { 1081 if (!(this instanceof Pos)) return new Pos(line, ch); 1082 this.line = line; this.ch = ch; 1083 }; 1084 1085 // Compare two positions, return 0 if they are the same, a negative 1086 // number when a is less, and a positive number otherwise. 1087 var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; }; 1088 1089 function copyPos(x) {return Pos(x.line, x.ch);} 1090 function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; } 1091 function minPos(a, b) { return cmp(a, b) < 0 ? a : b; } 1092 1093 // INPUT HANDLING 1094 1095 function ensureFocus(cm) { 1096 if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } 1097 } 1098 1099 // This will be set to a {lineWise: bool, text: [string]} object, so 1100 // that, when pasting, we know what kind of selections the copied 1101 // text was made out of. 1102 var lastCopied = null; 1103 1104 function applyTextInput(cm, inserted, deleted, sel, origin) { 1105 var doc = cm.doc; 1106 cm.display.shift = false; 1107 if (!sel) sel = doc.sel; 1108 1109 var paste = cm.state.pasteIncoming || origin == "paste"; 1110 var textLines = doc.splitLines(inserted), multiPaste = null 1111 // When pasing N lines into N selections, insert one line per selection 1112 if (paste && sel.ranges.length > 1) { 1113 if (lastCopied && lastCopied.text.join("\n") == inserted) { 1114 if (sel.ranges.length % lastCopied.text.length == 0) { 1115 multiPaste = []; 1116 for (var i = 0; i < lastCopied.text.length; i++) 1117 multiPaste.push(doc.splitLines(lastCopied.text[i])); 1118 } 1119 } else if (textLines.length == sel.ranges.length) { 1120 multiPaste = map(textLines, function(l) { return [l]; }); 1121 } 1122 } 1123 1124 // Normal behavior is to insert the new text into every selection 1125 for (var i = sel.ranges.length - 1; i >= 0; i--) { 1126 var range = sel.ranges[i]; 1127 var from = range.from(), to = range.to(); 1128 if (range.empty()) { 1129 if (deleted && deleted > 0) // Handle deletion 1130 from = Pos(from.line, from.ch - deleted); 1131 else if (cm.state.overwrite && !paste) // Handle overwrite 1132 to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); 1133 else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) 1134 from = to = Pos(from.line, 0) 1135 } 1136 var updateInput = cm.curOp.updateInput; 1137 var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines, 1138 origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; 1139 makeChange(cm.doc, changeEvent); 1140 signalLater(cm, "inputRead", cm, changeEvent); 1141 } 1142 if (inserted && !paste) 1143 triggerElectric(cm, inserted); 1144 1145 ensureCursorVisible(cm); 1146 cm.curOp.updateInput = updateInput; 1147 cm.curOp.typing = true; 1148 cm.state.pasteIncoming = cm.state.cutIncoming = false; 1149 } 1150 1151 function handlePaste(e, cm) { 1152 var pasted = e.clipboardData && e.clipboardData.getData("text/plain"); 1153 if (pasted) { 1154 e.preventDefault(); 1155 if (!cm.isReadOnly() && !cm.options.disableInput) 1156 runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); }); 1157 return true; 1158 } 1159 } 1160 1161 function triggerElectric(cm, inserted) { 1162 // When an 'electric' character is inserted, immediately trigger a reindent 1163 if (!cm.options.electricChars || !cm.options.smartIndent) return; 1164 var sel = cm.doc.sel; 1165 1166 for (var i = sel.ranges.length - 1; i >= 0; i--) { 1167 var range = sel.ranges[i]; 1168 if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue; 1169 var mode = cm.getModeAt(range.head); 1170 var indented = false; 1171 if (mode.electricChars) { 1172 for (var j = 0; j < mode.electricChars.length; j++) 1173 if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { 1174 indented = indentLine(cm, range.head.line, "smart"); 1175 break; 1176 } 1177 } else if (mode.electricInput) { 1178 if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) 1179 indented = indentLine(cm, range.head.line, "smart"); 1180 } 1181 if (indented) signalLater(cm, "electricInput", cm, range.head.line); 1182 } 1183 } 1184 1185 function copyableRanges(cm) { 1186 var text = [], ranges = []; 1187 for (var i = 0; i < cm.doc.sel.ranges.length; i++) { 1188 var line = cm.doc.sel.ranges[i].head.line; 1189 var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; 1190 ranges.push(lineRange); 1191 text.push(cm.getRange(lineRange.anchor, lineRange.head)); 1192 } 1193 return {text: text, ranges: ranges}; 1194 } 1195 1196 function disableBrowserMagic(field) { 1197 field.setAttribute("autocorrect", "off"); 1198 field.setAttribute("autocapitalize", "off"); 1199 field.setAttribute("spellcheck", "false"); 1200 } 1201 1202 // TEXTAREA INPUT STYLE 1203 1204 function TextareaInput(cm) { 1205 this.cm = cm; 1206 // See input.poll and input.reset 1207 this.prevInput = ""; 1208 1209 // Flag that indicates whether we expect input to appear real soon 1210 // now (after some event like 'keypress' or 'input') and are 1211 // polling intensively. 1212 this.pollingFast = false; 1213 // Self-resetting timeout for the poller 1214 this.polling = new Delayed(); 1215 // Tracks when input.reset has punted to just putting a short 1216 // string into the textarea instead of the full selection. 1217 this.inaccurateSelection = false; 1218 // Used to work around IE issue with selection being forgotten when focus moves away from textarea 1219 this.hasSelection = false; 1220 this.composing = null; 1221 }; 1222 1223 function hiddenTextarea() { 1224 var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none"); 1225 var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); 1226 // The textarea is kept positioned near the cursor to prevent the 1227 // fact that it'll be scrolled into view on input from scrolling 1228 // our fake cursor out of view. On webkit, when wrap=off, paste is 1229 // very slow. So make the area wide instead. 1230 if (webkit) te.style.width = "1000px"; 1231 else te.setAttribute("wrap", "off"); 1232 // If border: 0; -- iOS fails to open keyboard (issue #1287) 1233 if (ios) te.style.border = "1px solid black"; 1234 disableBrowserMagic(te); 1235 return div; 1236 } 1237 1238 TextareaInput.prototype = copyObj({ 1239 init: function(display) { 1240 var input = this, cm = this.cm; 1241 1242 // Wraps and hides input textarea 1243 var div = this.wrapper = hiddenTextarea(); 1244 // The semihidden textarea that is focused when the editor is 1245 // focused, and receives input. 1246 var te = this.textarea = div.firstChild; 1247 display.wrapper.insertBefore(div, display.wrapper.firstChild); 1248 1249 // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) 1250 if (ios) te.style.width = "0px"; 1251 1252 on(te, "input", function() { 1253 if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null; 1254 input.poll(); 1255 }); 1256 1257 on(te, "paste", function(e) { 1258 if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return 1259 1260 cm.state.pasteIncoming = true; 1261 input.fastPoll(); 1262 }); 1263 1264 function prepareCopyCut(e) { 1265 if (signalDOMEvent(cm, e)) return 1266 if (cm.somethingSelected()) { 1267 lastCopied = {lineWise: false, text: cm.getSelections()}; 1268 if (input.inaccurateSelection) { 1269 input.prevInput = ""; 1270 input.inaccurateSelection = false; 1271 te.value = lastCopied.text.join("\n"); 1272 selectInput(te); 1273 } 1274 } else if (!cm.options.lineWiseCopyCut) { 1275 return; 1276 } else { 1277 var ranges = copyableRanges(cm); 1278 lastCopied = {lineWise: true, text: ranges.text}; 1279 if (e.type == "cut") { 1280 cm.setSelections(ranges.ranges, null, sel_dontScroll); 1281 } else { 1282 input.prevInput = ""; 1283 te.value = ranges.text.join("\n"); 1284 selectInput(te); 1285 } 1286 } 1287 if (e.type == "cut") cm.state.cutIncoming = true; 1288 } 1289 on(te, "cut", prepareCopyCut); 1290 on(te, "copy", prepareCopyCut); 1291 1292 on(display.scroller, "paste", function(e) { 1293 if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return; 1294 cm.state.pasteIncoming = true; 1295 input.focus(); 1296 }); 1297 1298 // Prevent normal selection in the editor (we handle our own) 1299 on(display.lineSpace, "selectstart", function(e) { 1300 if (!eventInWidget(display, e)) e_preventDefault(e); 1301 }); 1302 1303 on(te, "compositionstart", function() { 1304 var start = cm.getCursor("from"); 1305 if (input.composing) input.composing.range.clear() 1306 input.composing = { 1307 start: start, 1308 range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) 1309 }; 1310 }); 1311 on(te, "compositionend", function() { 1312 if (input.composing) { 1313 input.poll(); 1314 input.composing.range.clear(); 1315 input.composing = null; 1316 } 1317 }); 1318 }, 1319 1320 prepareSelection: function() { 1321 // Redraw the selection and/or cursor 1322 var cm = this.cm, display = cm.display, doc = cm.doc; 1323 var result = prepareSelection(cm); 1324 1325 // Move the hidden textarea near the cursor to prevent scrolling artifacts 1326 if (cm.options.moveInputWithCursor) { 1327 var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); 1328 var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); 1329 result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, 1330 headPos.top + lineOff.top - wrapOff.top)); 1331 result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, 1332 headPos.left + lineOff.left - wrapOff.left)); 1333 } 1334 1335 return result; 1336 }, 1337 1338 showSelection: function(drawn) { 1339 var cm = this.cm, display = cm.display; 1340 removeChildrenAndAdd(display.cursorDiv, drawn.cursors); 1341 removeChildrenAndAdd(display.selectionDiv, drawn.selection); 1342 if (drawn.teTop != null) { 1343 this.wrapper.style.top = drawn.teTop + "px"; 1344 this.wrapper.style.left = drawn.teLeft + "px"; 1345 } 1346 }, 1347 1348 // Reset the input to correspond to the selection (or to be empty, 1349 // when not typing and nothing is selected) 1350 reset: function(typing) { 1351 if (this.contextMenuPending) return; 1352 var minimal, selected, cm = this.cm, doc = cm.doc; 1353 if (cm.somethingSelected()) { 1354 this.prevInput = ""; 1355 var range = doc.sel.primary(); 1356 minimal = hasCopyEvent && 1357 (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000); 1358 var content = minimal ? "-" : selected || cm.getSelection(); 1359 this.textarea.value = content; 1360 if (cm.state.focused) selectInput(this.textarea); 1361 if (ie && ie_version >= 9) this.hasSelection = content; 1362 } else if (!typing) { 1363 this.prevInput = this.textarea.value = ""; 1364 if (ie && ie_version >= 9) this.hasSelection = null; 1365 } 1366 this.inaccurateSelection = minimal; 1367 }, 1368 1369 getField: function() { return this.textarea; }, 1370 1371 supportsTouch: function() { return false; }, 1372 1373 focus: function() { 1374 if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { 1375 try { this.textarea.focus(); } 1376 catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM 1377 } 1378 }, 1379 1380 blur: function() { this.textarea.blur(); }, 1381 1382 resetPosition: function() { 1383 this.wrapper.style.top = this.wrapper.style.left = 0; 1384 }, 1385 1386 receivedFocus: function() { this.slowPoll(); }, 1387 1388 // Poll for input changes, using the normal rate of polling. This 1389 // runs as long as the editor is focused. 1390 slowPoll: function() { 1391 var input = this; 1392 if (input.pollingFast) return; 1393 input.polling.set(this.cm.options.pollInterval, function() { 1394 input.poll(); 1395 if (input.cm.state.focused) input.slowPoll(); 1396 }); 1397 }, 1398 1399 // When an event has just come in that is likely to add or change 1400 // something in the input textarea, we poll faster, to ensure that 1401 // the change appears on the screen quickly. 1402 fastPoll: function() { 1403 var missed = false, input = this; 1404 input.pollingFast = true; 1405 function p() { 1406 var changed = input.poll(); 1407 if (!changed && !missed) {missed = true; input.polling.set(60, p);} 1408 else {input.pollingFast = false; input.slowPoll();} 1409 } 1410 input.polling.set(20, p); 1411 }, 1412 1413 // Read input from the textarea, and update the document to match. 1414 // When something is selected, it is present in the textarea, and 1415 // selected (unless it is huge, in which case a placeholder is 1416 // used). When nothing is selected, the cursor sits after previously 1417 // seen text (can be empty), which is stored in prevInput (we must 1418 // not reset the textarea when typing, because that breaks IME). 1419 poll: function() { 1420 var cm = this.cm, input = this.textarea, prevInput = this.prevInput; 1421 // Since this is called a *lot*, try to bail out as cheaply as 1422 // possible when it is clear that nothing happened. hasSelection 1423 // will be the case when there is a lot of text in the textarea, 1424 // in which case reading its value would be expensive. 1425 if (this.contextMenuPending || !cm.state.focused || 1426 (hasSelection(input) && !prevInput && !this.composing) || 1427 cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) 1428 return false; 1429 1430 var text = input.value; 1431 // If nothing changed, bail. 1432 if (text == prevInput && !cm.somethingSelected()) return false; 1433 // Work around nonsensical selection resetting in IE9/10, and 1434 // inexplicable appearance of private area unicode characters on 1435 // some key combos in Mac (#2689). 1436 if (ie && ie_version >= 9 && this.hasSelection === text || 1437 mac && /[\uf700-\uf7ff]/.test(text)) { 1438 cm.display.input.reset(); 1439 return false; 1440 } 1441 1442 if (cm.doc.sel == cm.display.selForContextMenu) { 1443 var first = text.charCodeAt(0); 1444 if (first == 0x200b && !prevInput) prevInput = "\u200b"; 1445 if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); } 1446 } 1447 // Find the part of the input that is actually new 1448 var same = 0, l = Math.min(prevInput.length, text.length); 1449 while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; 1450 1451 var self = this; 1452 runInOp(cm, function() { 1453 applyTextInput(cm, text.slice(same), prevInput.length - same, 1454 null, self.composing ? "*compose" : null); 1455 1456 // Don't leave long text in the textarea, since it makes further polling slow 1457 if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = ""; 1458 else self.prevInput = text; 1459 1460 if (self.composing) { 1461 self.composing.range.clear(); 1462 self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"), 1463 {className: "CodeMirror-composing"}); 1464 } 1465 }); 1466 return true; 1467 }, 1468 1469 ensurePolled: function() { 1470 if (this.pollingFast && this.poll()) this.pollingFast = false; 1471 }, 1472 1473 onKeyPress: function() { 1474 if (ie && ie_version >= 9) this.hasSelection = null; 1475 this.fastPoll(); 1476 }, 1477 1478 onContextMenu: function(e) { 1479 var input = this, cm = input.cm, display = cm.display, te = input.textarea; 1480 var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; 1481 if (!pos || presto) return; // Opera is difficult. 1482 1483 // Reset the current text selection only if the click is done outside of the selection 1484 // and 'resetSelectionOnContextMenu' option is true. 1485 var reset = cm.options.resetSelectionOnContextMenu; 1486 if (reset && cm.doc.sel.contains(pos) == -1) 1487 operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); 1488 1489 var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText; 1490 input.wrapper.style.cssText = "position: absolute" 1491 var wrapperBox = input.wrapper.getBoundingClientRect() 1492 te.style.cssText = "position: absolute; width: 30px; height: 30px; top: " + (e.clientY - wrapperBox.top - 5) + 1493 "px; left: " + (e.clientX - wrapperBox.left - 5) + "px; z-index: 1000; background: " + 1494 (ie ? "rgba(255, 255, 255, .05)" : "transparent") + 1495 "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; 1496 if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712) 1497 display.input.focus(); 1498 if (webkit) window.scrollTo(null, oldScrollY); 1499 display.input.reset(); 1500 // Adds "Select all" to context menu in FF 1501 if (!cm.somethingSelected()) te.value = input.prevInput = " "; 1502 input.contextMenuPending = true; 1503 display.selForContextMenu = cm.doc.sel; 1504 clearTimeout(display.detectingSelectAll); 1505 1506 // Select-all will be greyed out if there's nothing to select, so 1507 // this adds a zero-width space so that we can later check whether 1508 // it got selected. 1509 function prepareSelectAllHack() { 1510 if (te.selectionStart != null) { 1511 var selected = cm.somethingSelected(); 1512 var extval = "\u200b" + (selected ? te.value : ""); 1513 te.value = "\u21da"; // Used to catch context-menu undo 1514 te.value = extval; 1515 input.prevInput = selected ? "" : "\u200b"; 1516 te.selectionStart = 1; te.selectionEnd = extval.length; 1517 // Re-set this, in case some other handler touched the 1518 // selection in the meantime. 1519 display.selForContextMenu = cm.doc.sel; 1520 } 1521 } 1522 function rehide() { 1523 input.contextMenuPending = false; 1524 input.wrapper.style.cssText = oldWrapperCSS 1525 te.style.cssText = oldCSS; 1526 if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); 1527 1528 // Try to detect the user choosing select-all 1529 if (te.selectionStart != null) { 1530 if (!ie || (ie && ie_version < 9)) prepareSelectAllHack(); 1531 var i = 0, poll = function() { 1532 if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && 1533 te.selectionEnd > 0 && input.prevInput == "\u200b") 1534 operation(cm, commands.selectAll)(cm); 1535 else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500); 1536 else display.input.reset(); 1537 }; 1538 display.detectingSelectAll = setTimeout(poll, 200); 1539 } 1540 } 1541 1542 if (ie && ie_version >= 9) prepareSelectAllHack(); 1543 if (captureRightClick) { 1544 e_stop(e); 1545 var mouseup = function() { 1546 off(window, "mouseup", mouseup); 1547 setTimeout(rehide, 20); 1548 }; 1549 on(window, "mouseup", mouseup); 1550 } else { 1551 setTimeout(rehide, 50); 1552 } 1553 }, 1554 1555 readOnlyChanged: function(val) { 1556 if (!val) this.reset(); 1557 }, 1558 1559 setUneditable: nothing, 1560 1561 needsContentAttribute: false 1562 }, TextareaInput.prototype); 1563 1564 // CONTENTEDITABLE INPUT STYLE 1565 1566 function ContentEditableInput(cm) { 1567 this.cm = cm; 1568 this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; 1569 this.polling = new Delayed(); 1570 this.gracePeriod = false; 1571 } 1572 1573 ContentEditableInput.prototype = copyObj({ 1574 init: function(display) { 1575 var input = this, cm = input.cm; 1576 var div = input.div = display.lineDiv; 1577 disableBrowserMagic(div); 1578 1579 on(div, "paste", function(e) { 1580 if (!signalDOMEvent(cm, e)) handlePaste(e, cm); 1581 }) 1582 1583 on(div, "compositionstart", function(e) { 1584 var data = e.data; 1585 input.composing = {sel: cm.doc.sel, data: data, startData: data}; 1586 if (!data) return; 1587 var prim = cm.doc.sel.primary(); 1588 var line = cm.getLine(prim.head.line); 1589 var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length)); 1590 if (found > -1 && found <= prim.head.ch) 1591 input.composing.sel = simpleSelection(Pos(prim.head.line, found), 1592 Pos(prim.head.line, found + data.length)); 1593 }); 1594 on(div, "compositionupdate", function(e) { 1595 input.composing.data = e.data; 1596 }); 1597 on(div, "compositionend", function(e) { 1598 var ours = input.composing; 1599 if (!ours) return; 1600 if (e.data != ours.startData && !/\u200b/.test(e.data)) 1601 ours.data = e.data; 1602 // Need a small delay to prevent other code (input event, 1603 // selection polling) from doing damage when fired right after 1604 // compositionend. 1605 setTimeout(function() { 1606 if (!ours.handled) 1607 input.applyComposition(ours); 1608 if (input.composing == ours) 1609 input.composing = null; 1610 }, 50); 1611 }); 1612 1613 on(div, "touchstart", function() { 1614 input.forceCompositionEnd(); 1615 }); 1616 1617 on(div, "input", function() { 1618 if (input.composing) return; 1619 if (cm.isReadOnly() || !input.pollContent()) 1620 runInOp(input.cm, function() {regChange(cm);}); 1621 }); 1622 1623 function onCopyCut(e) { 1624 if (signalDOMEvent(cm, e)) return 1625 if (cm.somethingSelected()) { 1626 lastCopied = {lineWise: false, text: cm.getSelections()}; 1627 if (e.type == "cut") cm.replaceSelection("", null, "cut"); 1628 } else if (!cm.options.lineWiseCopyCut) { 1629 return; 1630 } else { 1631 var ranges = copyableRanges(cm); 1632 lastCopied = {lineWise: true, text: ranges.text}; 1633 if (e.type == "cut") { 1634 cm.operation(function() { 1635 cm.setSelections(ranges.ranges, 0, sel_dontScroll); 1636 cm.replaceSelection("", null, "cut"); 1637 }); 1638 } 1639 } 1640 // iOS exposes the clipboard API, but seems to discard content inserted into it 1641 if (e.clipboardData && !ios) { 1642 e.preventDefault(); 1643 e.clipboardData.clearData(); 1644 e.clipboardData.setData("text/plain", lastCopied.text.join("\n")); 1645 } else { 1646 // Old-fashioned briefly-focus-a-textarea hack 1647 var kludge = hiddenTextarea(), te = kludge.firstChild; 1648 cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); 1649 te.value = lastCopied.text.join("\n"); 1650 var hadFocus = document.activeElement; 1651 selectInput(te); 1652 setTimeout(function() { 1653 cm.display.lineSpace.removeChild(kludge); 1654 hadFocus.focus(); 1655 }, 50); 1656 } 1657 } 1658 on(div, "copy", onCopyCut); 1659 on(div, "cut", onCopyCut); 1660 }, 1661 1662 prepareSelection: function() { 1663 var result = prepareSelection(this.cm, false); 1664 result.focus = this.cm.state.focused; 1665 return result; 1666 }, 1667 1668 showSelection: function(info, takeFocus) { 1669 if (!info || !this.cm.display.view.length) return; 1670 if (info.focus || takeFocus) this.showPrimarySelection(); 1671 this.showMultipleSelections(info); 1672 }, 1673 1674 showPrimarySelection: function() { 1675 var sel = window.getSelection(), prim = this.cm.doc.sel.primary(); 1676 var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset); 1677 var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset); 1678 if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && 1679 cmp(minPos(curAnchor, curFocus), prim.from()) == 0 && 1680 cmp(maxPos(curAnchor, curFocus), prim.to()) == 0) 1681 return; 1682 1683 var start = posToDOM(this.cm, prim.from()); 1684 var end = posToDOM(this.cm, prim.to()); 1685 if (!start && !end) return; 1686 1687 var view = this.cm.display.view; 1688 var old = sel.rangeCount && sel.getRangeAt(0); 1689 if (!start) { 1690 start = {node: view[0].measure.map[2], offset: 0}; 1691 } else if (!end) { // FIXME dangerously hacky 1692 var measure = view[view.length - 1].measure; 1693 var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; 1694 end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}; 1695 } 1696 1697 try { var rng = range(start.node, start.offset, end.offset, end.node); } 1698 catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible 1699 if (rng) { 1700 if (!gecko && this.cm.state.focused) { 1701 sel.collapse(start.node, start.offset); 1702 if (!rng.collapsed) sel.addRange(rng); 1703 } else { 1704 sel.removeAllRanges(); 1705 sel.addRange(rng); 1706 } 1707 if (old && sel.anchorNode == null) sel.addRange(old); 1708 else if (gecko) this.startGracePeriod(); 1709 } 1710 this.rememberSelection(); 1711 }, 1712 1713 startGracePeriod: function() { 1714 var input = this; 1715 clearTimeout(this.gracePeriod); 1716 this.gracePeriod = setTimeout(function() { 1717 input.gracePeriod = false; 1718 if (input.selectionChanged()) 1719 input.cm.operation(function() { input.cm.curOp.selectionChanged = true; }); 1720 }, 20); 1721 }, 1722 1723 showMultipleSelections: function(info) { 1724 removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); 1725 removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); 1726 }, 1727 1728 rememberSelection: function() { 1729 var sel = window.getSelection(); 1730 this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; 1731 this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; 1732 }, 1733 1734 selectionInEditor: function() { 1735 var sel = window.getSelection(); 1736 if (!sel.rangeCount) return false; 1737 var node = sel.getRangeAt(0).commonAncestorContainer; 1738 return contains(this.div, node); 1739 }, 1740 1741 focus: function() { 1742 if (this.cm.options.readOnly != "nocursor") this.div.focus(); 1743 }, 1744 blur: function() { this.div.blur(); }, 1745 getField: function() { return this.div; }, 1746 1747 supportsTouch: function() { return true; }, 1748 1749 receivedFocus: function() { 1750 var input = this; 1751 if (this.selectionInEditor()) 1752 this.pollSelection(); 1753 else 1754 runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; }); 1755 1756 function poll() { 1757 if (input.cm.state.focused) { 1758 input.pollSelection(); 1759 input.polling.set(input.cm.options.pollInterval, poll); 1760 } 1761 } 1762 this.polling.set(this.cm.options.pollInterval, poll); 1763 }, 1764 1765 selectionChanged: function() { 1766 var sel = window.getSelection(); 1767 return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || 1768 sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; 1769 }, 1770 1771 pollSelection: function() { 1772 if (!this.composing && !this.gracePeriod && this.selectionChanged()) { 1773 var sel = window.getSelection(), cm = this.cm; 1774 this.rememberSelection(); 1775 var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); 1776 var head = domToPos(cm, sel.focusNode, sel.focusOffset); 1777 if (anchor && head) runInOp(cm, function() { 1778 setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); 1779 if (anchor.bad || head.bad) cm.curOp.selectionChanged = true; 1780 }); 1781 } 1782 }, 1783 1784 pollContent: function() { 1785 var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); 1786 var from = sel.from(), to = sel.to(); 1787 if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false; 1788 1789 var fromIndex; 1790 if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { 1791 var fromLine = lineNo(display.view[0].line); 1792 var fromNode = display.view[0].node; 1793 } else { 1794 var fromLine = lineNo(display.view[fromIndex].line); 1795 var fromNode = display.view[fromIndex - 1].node.nextSibling; 1796 } 1797 var toIndex = findViewIndex(cm, to.line); 1798 if (toIndex == display.view.length - 1) { 1799 var toLine = display.viewTo - 1; 1800 var toNode = display.lineDiv.lastChild; 1801 } else { 1802 var toLine = lineNo(display.view[toIndex + 1].line) - 1; 1803 var toNode = display.view[toIndex + 1].node.previousSibling; 1804 } 1805 1806 var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); 1807 var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); 1808 while (newText.length > 1 && oldText.length > 1) { 1809 if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } 1810 else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } 1811 else break; 1812 } 1813 1814 var cutFront = 0, cutEnd = 0; 1815 var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); 1816 while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) 1817 ++cutFront; 1818 var newBot = lst(newText), oldBot = lst(oldText); 1819 var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), 1820 oldBot.length - (oldText.length == 1 ? cutFront : 0)); 1821 while (cutEnd < maxCutEnd && 1822 newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) 1823 ++cutEnd; 1824 1825 newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd); 1826 newText[0] = newText[0].slice(cutFront); 1827 1828 var chFrom = Pos(fromLine, cutFront); 1829 var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); 1830 if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { 1831 replaceRange(cm.doc, newText, chFrom, chTo, "+input"); 1832 return true; 1833 } 1834 }, 1835 1836 ensurePolled: function() { 1837 this.forceCompositionEnd(); 1838 }, 1839 reset: function() { 1840 this.forceCompositionEnd(); 1841 }, 1842 forceCompositionEnd: function() { 1843 if (!this.composing || this.composing.handled) return; 1844 this.applyComposition(this.composing); 1845 this.composing.handled = true; 1846 this.div.blur(); 1847 this.div.focus(); 1848 }, 1849 applyComposition: function(composing) { 1850 if (this.cm.isReadOnly()) 1851 operation(this.cm, regChange)(this.cm) 1852 else if (composing.data && composing.data != composing.startData) 1853 operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel); 1854 }, 1855 1856 setUneditable: function(node) { 1857 node.contentEditable = "false" 1858 }, 1859 1860 onKeyPress: function(e) { 1861 e.preventDefault(); 1862 if (!this.cm.isReadOnly()) 1863 operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); 1864 }, 1865 1866 readOnlyChanged: function(val) { 1867 this.div.contentEditable = String(val != "nocursor") 1868 }, 1869 1870 onContextMenu: nothing, 1871 resetPosition: nothing, 1872 1873 needsContentAttribute: true 1874 }, ContentEditableInput.prototype); 1875 1876 function posToDOM(cm, pos) { 1877 var view = findViewForLine(cm, pos.line); 1878 if (!view || view.hidden) return null; 1879 var line = getLine(cm.doc, pos.line); 1880 var info = mapFromLineView(view, line, pos.line); 1881 1882 var order = getOrder(line), side = "left"; 1883 if (order) { 1884 var partPos = getBidiPartAt(order, pos.ch); 1885 side = partPos % 2 ? "right" : "left"; 1886 } 1887 var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); 1888 result.offset = result.collapse == "right" ? result.end : result.start; 1889 return result; 1890 } 1891 1892 function badPos(pos, bad) { if (bad) pos.bad = true; return pos; } 1893 1894 function domToPos(cm, node, offset) { 1895 var lineNode; 1896 if (node == cm.display.lineDiv) { 1897 lineNode = cm.display.lineDiv.childNodes[offset]; 1898 if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); 1899 node = null; offset = 0; 1900 } else { 1901 for (lineNode = node;; lineNode = lineNode.parentNode) { 1902 if (!lineNode || lineNode == cm.display.lineDiv) return null; 1903 if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break; 1904 } 1905 } 1906 for (var i = 0; i < cm.display.view.length; i++) { 1907 var lineView = cm.display.view[i]; 1908 if (lineView.node == lineNode) 1909 return locateNodeInLineView(lineView, node, offset); 1910 } 1911 } 1912 1913 function locateNodeInLineView(lineView, node, offset) { 1914 var wrapper = lineView.text.firstChild, bad = false; 1915 if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true); 1916 if (node == wrapper) { 1917 bad = true; 1918 node = wrapper.childNodes[offset]; 1919 offset = 0; 1920 if (!node) { 1921 var line = lineView.rest ? lst(lineView.rest) : lineView.line; 1922 return badPos(Pos(lineNo(line), line.text.length), bad); 1923 } 1924 } 1925 1926 var textNode = node.nodeType == 3 ? node : null, topNode = node; 1927 if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { 1928 textNode = node.firstChild; 1929 if (offset) offset = textNode.nodeValue.length; 1930 } 1931 while (topNode.parentNode != wrapper) topNode = topNode.parentNode; 1932 var measure = lineView.measure, maps = measure.maps; 1933 1934 function find(textNode, topNode, offset) { 1935 for (var i = -1; i < (maps ? maps.length : 0); i++) { 1936 var map = i < 0 ? measure.map : maps[i]; 1937 for (var j = 0; j < map.length; j += 3) { 1938 var curNode = map[j + 2]; 1939 if (curNode == textNode || curNode == topNode) { 1940 var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); 1941 var ch = map[j] + offset; 1942 if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)]; 1943 return Pos(line, ch); 1944 } 1945 } 1946 } 1947 } 1948 var found = find(textNode, topNode, offset); 1949 if (found) return badPos(found, bad); 1950 1951 // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems 1952 for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { 1953 found = find(after, after.firstChild, 0); 1954 if (found) 1955 return badPos(Pos(found.line, found.ch - dist), bad); 1956 else 1957 dist += after.textContent.length; 1958 } 1959 for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) { 1960 found = find(before, before.firstChild, -1); 1961 if (found) 1962 return badPos(Pos(found.line, found.ch + dist), bad); 1963 else 1964 dist += after.textContent.length; 1965 } 1966 } 1967 1968 function domTextBetween(cm, from, to, fromLine, toLine) { 1969 var text = "", closing = false, lineSep = cm.doc.lineSeparator(); 1970 function recognizeMarker(id) { return function(marker) { return marker.id == id; }; } 1971 function walk(node) { 1972 if (node.nodeType == 1) { 1973 var cmText = node.getAttribute("cm-text"); 1974 if (cmText != null) { 1975 if (cmText == "") cmText = node.textContent.replace(/\u200b/g, ""); 1976 text += cmText; 1977 return; 1978 } 1979 var markerID = node.getAttribute("cm-marker"), range; 1980 if (markerID) { 1981 var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); 1982 if (found.length && (range = found[0].find())) 1983 text += getBetween(cm.doc, range.from, range.to).join(lineSep); 1984 return; 1985 } 1986 if (node.getAttribute("contenteditable") == "false") return; 1987 for (var i = 0; i < node.childNodes.length; i++) 1988 walk(node.childNodes[i]); 1989 if (/^(pre|div|p)$/i.test(node.nodeName)) 1990 closing = true; 1991 } else if (node.nodeType == 3) { 1992 var val = node.nodeValue; 1993 if (!val) return; 1994 if (closing) { 1995 text += lineSep; 1996 closing = false; 1997 } 1998 text += val; 1999 } 2000 } 2001 for (;;) { 2002 walk(from); 2003 if (from == to) break; 2004 from = from.nextSibling; 2005 } 2006 return text; 2007 } 2008 2009 CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; 2010 2011 // SELECTION / CURSOR 2012 2013 // Selection objects are immutable. A new one is created every time 2014 // the selection changes. A selection is one or more non-overlapping 2015 // (and non-touching) ranges, sorted, and an integer that indicates 2016 // which one is the primary selection (the one that's scrolled into 2017 // view, that getCursor returns, etc). 2018 function Selection(ranges, primIndex) { 2019 this.ranges = ranges; 2020 this.primIndex = primIndex; 2021 } 2022 2023 Selection.prototype = { 2024 primary: function() { return this.ranges[this.primIndex]; }, 2025 equals: function(other) { 2026 if (other == this) return true; 2027 if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false; 2028 for (var i = 0; i < this.ranges.length; i++) { 2029 var here = this.ranges[i], there = other.ranges[i]; 2030 if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false; 2031 } 2032 return true; 2033 }, 2034 deepCopy: function() { 2035 for (var out = [], i = 0; i < this.ranges.length; i++) 2036 out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); 2037 return new Selection(out, this.primIndex); 2038 }, 2039 somethingSelected: function() { 2040 for (var i = 0; i < this.ranges.length; i++) 2041 if (!this.ranges[i].empty()) return true; 2042 return false; 2043 }, 2044 contains: function(pos, end) { 2045 if (!end) end = pos; 2046 for (var i = 0; i < this.ranges.length; i++) { 2047 var range = this.ranges[i]; 2048 if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) 2049 return i; 2050 } 2051 return -1; 2052 } 2053 }; 2054 2055 function Range(anchor, head) { 2056 this.anchor = anchor; this.head = head; 2057 } 2058 2059 Range.prototype = { 2060 from: function() { return minPos(this.anchor, this.head); }, 2061 to: function() { return maxPos(this.anchor, this.head); }, 2062 empty: function() { 2063 return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; 2064 } 2065 }; 2066 2067 // Take an unsorted, potentially overlapping set of ranges, and 2068 // build a selection out of it. 'Consumes' ranges array (modifying 2069 // it). 2070 function normalizeSelection(ranges, primIndex) { 2071 var prim = ranges[primIndex]; 2072 ranges.sort(function(a, b) { return cmp(a.from(), b.from()); }); 2073 primIndex = indexOf(ranges, prim); 2074 for (var i = 1; i < ranges.length; i++) { 2075 var cur = ranges[i], prev = ranges[i - 1]; 2076 if (cmp(prev.to(), cur.from()) >= 0) { 2077 var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); 2078 var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; 2079 if (i <= primIndex) --primIndex; 2080 ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); 2081 } 2082 } 2083 return new Selection(ranges, primIndex); 2084 } 2085 2086 function simpleSelection(anchor, head) { 2087 return new Selection([new Range(anchor, head || anchor)], 0); 2088 } 2089 2090 // Most of the external API clips given positions to make sure they 2091 // actually exist within the document. 2092 function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} 2093 function clipPos(doc, pos) { 2094 if (pos.line < doc.first) return Pos(doc.first, 0); 2095 var last = doc.first + doc.size - 1; 2096 if (pos.line > last) return Pos(last, getLine(doc, last).text.length); 2097 return clipToLen(pos, getLine(doc, pos.line).text.length); 2098 } 2099 function clipToLen(pos, linelen) { 2100 var ch = pos.ch; 2101 if (ch == null || ch > linelen) return Pos(pos.line, linelen); 2102 else if (ch < 0) return Pos(pos.line, 0); 2103 else return pos; 2104 } 2105 function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} 2106 function clipPosArray(doc, array) { 2107 for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]); 2108 return out; 2109 } 2110 2111 // SELECTION UPDATES 2112 2113 // The 'scroll' parameter given to many of these indicated whether 2114 // the new cursor position should be scrolled into view after 2115 // modifying the selection. 2116 2117 // If shift is held or the extend flag is set, extends a range to 2118 // include a given position (and optionally a second position). 2119 // Otherwise, simply returns the range between the given positions. 2120 // Used for cursor motion and such. 2121 function extendRange(doc, range, head, other) { 2122 if (doc.cm && doc.cm.display.shift || doc.extend) { 2123 var anchor = range.anchor; 2124 if (other) { 2125 var posBefore = cmp(head, anchor) < 0; 2126 if (posBefore != (cmp(other, anchor) < 0)) { 2127 anchor = head; 2128 head = other; 2129 } else if (posBefore != (cmp(head, other) < 0)) { 2130 head = other; 2131 } 2132 } 2133 return new Range(anchor, head); 2134 } else { 2135 return new Range(other || head, head); 2136 } 2137 } 2138 2139 // Extend the primary selection range, discard the rest. 2140 function extendSelection(doc, head, other, options) { 2141 setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options); 2142 } 2143 2144 // Extend all selections (pos is an array of selections with length 2145 // equal the number of selections) 2146 function extendSelections(doc, heads, options) { 2147 for (var out = [], i = 0; i < doc.sel.ranges.length; i++) 2148 out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null); 2149 var newSel = normalizeSelection(out, doc.sel.primIndex); 2150 setSelection(doc, newSel, options); 2151 } 2152 2153 // Updates a single range in the selection. 2154 function replaceOneSelection(doc, i, range, options) { 2155 var ranges = doc.sel.ranges.slice(0); 2156 ranges[i] = range; 2157 setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); 2158 } 2159 2160 // Reset the selection to a single range. 2161 function setSimpleSelection(doc, anchor, head, options) { 2162 setSelection(doc, simpleSelection(anchor, head), options); 2163 } 2164 2165 // Give beforeSelectionChange handlers a change to influence a 2166 // selection update. 2167 function filterSelectionChange(doc, sel, options) { 2168 var obj = { 2169 ranges: sel.ranges, 2170 update: function(ranges) { 2171 this.ranges = []; 2172 for (var i = 0; i < ranges.length; i++) 2173 this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), 2174 clipPos(doc, ranges[i].head)); 2175 }, 2176 origin: options && options.origin 2177 }; 2178 signal(doc, "beforeSelectionChange", doc, obj); 2179 if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); 2180 if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1); 2181 else return sel; 2182 } 2183 2184 function setSelectionReplaceHistory(doc, sel, options) { 2185 var done = doc.history.done, last = lst(done); 2186 if (last && last.ranges) { 2187 done[done.length - 1] = sel; 2188 setSelectionNoUndo(doc, sel, options); 2189 } else { 2190 setSelection(doc, sel, options); 2191 } 2192 } 2193 2194 // Set a new selection. 2195 function setSelection(doc, sel, options) { 2196 setSelectionNoUndo(doc, sel, options); 2197 addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); 2198 } 2199 2200 function setSelectionNoUndo(doc, sel, options) { 2201 if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) 2202 sel = filterSelectionChange(doc, sel, options); 2203 2204 var bias = options && options.bias || 2205 (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); 2206 setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); 2207 2208 if (!(options && options.scroll === false) && doc.cm) 2209 ensureCursorVisible(doc.cm); 2210 } 2211 2212 function setSelectionInner(doc, sel) { 2213 if (sel.equals(doc.sel)) return; 2214 2215 doc.sel = sel; 2216 2217 if (doc.cm) { 2218 doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; 2219 signalCursorActivity(doc.cm); 2220 } 2221 signalLater(doc, "cursorActivity", doc); 2222 } 2223 2224 // Verify that the selection does not partially select any atomic 2225 // marked ranges. 2226 function reCheckSelection(doc) { 2227 setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll); 2228 } 2229 2230 // Return a selection that does not partially select any atomic 2231 // ranges. 2232 function skipAtomicInSelection(doc, sel, bias, mayClear) { 2233 var out; 2234 for (var i = 0; i < sel.ranges.length; i++) { 2235 var range = sel.ranges[i]; 2236 var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]; 2237 var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear); 2238 var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear); 2239 if (out || newAnchor != range.anchor || newHead != range.head) { 2240 if (!out) out = sel.ranges.slice(0, i); 2241 out[i] = new Range(newAnchor, newHead); 2242 } 2243 } 2244 return out ? normalizeSelection(out, sel.primIndex) : sel; 2245 } 2246 2247 function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { 2248 var line = getLine(doc, pos.line); 2249 if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { 2250 var sp = line.markedSpans[i], m = sp.marker; 2251 if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && 2252 (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) { 2253 if (mayClear) { 2254 signal(m, "beforeCursorEnter"); 2255 if (m.explicitlyCleared) { 2256 if (!line.markedSpans) break; 2257 else {--i; continue;} 2258 } 2259 } 2260 if (!m.atomic) continue; 2261 2262 if (oldPos) { 2263 var near = m.find(dir < 0 ? 1 : -1), diff; 2264 if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft) 2265 near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); 2266 if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) 2267 return skipAtomicInner(doc, near, pos, dir, mayClear); 2268 } 2269 2270 var far = m.find(dir < 0 ? -1 : 1); 2271 if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight) 2272 far = movePos(doc, far, dir, far.line == pos.line ? line : null); 2273 return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null; 2274 } 2275 } 2276 return pos; 2277 } 2278 2279 // Ensure a given position is not inside an atomic range. 2280 function skipAtomic(doc, pos, oldPos, bias, mayClear) { 2281 var dir = bias || 1; 2282 var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || 2283 (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || 2284 skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || 2285 (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)); 2286 if (!found) { 2287 doc.cantEdit = true; 2288 return Pos(doc.first, 0); 2289 } 2290 return found; 2291 } 2292 2293 function movePos(doc, pos, dir, line) { 2294 if (dir < 0 && pos.ch == 0) { 2295 if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1)); 2296 else return null; 2297 } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { 2298 if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0); 2299 else return null; 2300 } else { 2301 return new Pos(pos.line, pos.ch + dir); 2302 } 2303 } 2304 2305 // SELECTION DRAWING 2306 2307 function updateSelection(cm) { 2308 cm.display.input.showSelection(cm.display.input.prepareSelection()); 2309 } 2310 2311 function prepareSelection(cm, primary) { 2312 var doc = cm.doc, result = {}; 2313 var curFragment = result.cursors = document.createDocumentFragment(); 2314 var selFragment = result.selection = document.createDocumentFragment(); 2315 2316 for (var i = 0; i < doc.sel.ranges.length; i++) { 2317 if (primary === false && i == doc.sel.primIndex) continue; 2318 var range = doc.sel.ranges[i]; 2319 if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) continue; 2320 var collapsed = range.empty(); 2321 if (collapsed || cm.options.showCursorWhenSelecting) 2322 drawSelectionCursor(cm, range.head, curFragment); 2323 if (!collapsed) 2324 drawSelectionRange(cm, range, selFragment); 2325 } 2326 return result; 2327 } 2328 2329 // Draws a cursor for the given range 2330 function drawSelectionCursor(cm, head, output) { 2331 var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); 2332 2333 var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); 2334 cursor.style.left = pos.left + "px"; 2335 cursor.style.top = pos.top + "px"; 2336 cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; 2337 2338 if (pos.other) { 2339 // Secondary cursor, shown when on a 'jump' in bi-directional text 2340 var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); 2341 otherCursor.style.display = ""; 2342 otherCursor.style.left = pos.other.left + "px"; 2343 otherCursor.style.top = pos.other.top + "px"; 2344 otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; 2345 } 2346 } 2347 2348 // Draws the given range as a highlighted selection 2349 function drawSelectionRange(cm, range, output) { 2350 var display = cm.display, doc = cm.doc; 2351 var fragment = document.createDocumentFragment(); 2352 var padding = paddingH(cm.display), leftSide = padding.left; 2353 var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; 2354 2355 function add(left, top, width, bottom) { 2356 if (top < 0) top = 0; 2357 top = Math.round(top); 2358 bottom = Math.round(bottom); 2359 fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + 2360 "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) + 2361 "px; height: " + (bottom - top) + "px")); 2362 } 2363 2364 function drawForLine(line, fromArg, toArg) { 2365 var lineObj = getLine(doc, line); 2366 var lineLen = lineObj.text.length; 2367 var start, end; 2368 function coords(ch, bias) { 2369 return charCoords(cm, Pos(line, ch), "div", lineObj, bias); 2370 } 2371 2372 iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { 2373 var leftPos = coords(from, "left"), rightPos, left, right; 2374 if (from == to) { 2375 rightPos = leftPos; 2376 left = right = leftPos.left; 2377 } else { 2378 rightPos = coords(to - 1, "right"); 2379 if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } 2380 left = leftPos.left; 2381 right = rightPos.right; 2382 } 2383 if (fromArg == null && from == 0) left = leftSide; 2384 if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part 2385 add(left, leftPos.top, null, leftPos.bottom); 2386 left = leftSide; 2387 if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); 2388 } 2389 if (toArg == null && to == lineLen) right = rightSide; 2390 if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) 2391 start = leftPos; 2392 if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) 2393 end = rightPos; 2394 if (left < leftSide + 1) left = leftSide; 2395 add(left, rightPos.top, right - left, rightPos.bottom); 2396 }); 2397 return {start: start, end: end}; 2398 } 2399 2400 var sFrom = range.from(), sTo = range.to(); 2401 if (sFrom.line == sTo.line) { 2402 drawForLine(sFrom.line, sFrom.ch, sTo.ch); 2403 } else { 2404 var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); 2405 var singleVLine = visualLine(fromLine) == visualLine(toLine); 2406 var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; 2407 var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; 2408 if (singleVLine) { 2409 if (leftEnd.top < rightStart.top - 2) { 2410 add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); 2411 add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); 2412 } else { 2413 add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); 2414 } 2415 } 2416 if (leftEnd.bottom < rightStart.top) 2417 add(leftSide, leftEnd.bottom, null, rightStart.top); 2418 } 2419 2420 output.appendChild(fragment); 2421 } 2422 2423 // Cursor-blinking 2424 function restartBlink(cm) { 2425 if (!cm.state.focused) return; 2426 var display = cm.display; 2427 clearInterval(display.blinker); 2428 var on = true; 2429 display.cursorDiv.style.visibility = ""; 2430 if (cm.options.cursorBlinkRate > 0) 2431 display.blinker = setInterval(function() { 2432 display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; 2433 }, cm.options.cursorBlinkRate); 2434 else if (cm.options.cursorBlinkRate < 0) 2435 display.cursorDiv.style.visibility = "hidden"; 2436 } 2437 2438 // HIGHLIGHT WORKER 2439 2440 function startWorker(cm, time) { 2441 if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) 2442 cm.state.highlight.set(time, bind(highlightWorker, cm)); 2443 } 2444 2445 function highlightWorker(cm) { 2446 var doc = cm.doc; 2447 if (doc.frontier < doc.first) doc.frontier = doc.first; 2448 if (doc.frontier >= cm.display.viewTo) return; 2449 var end = +new Date + cm.options.workTime; 2450 var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); 2451 var changedLines = []; 2452 2453 doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) { 2454 if (doc.frontier >= cm.display.viewFrom) { // Visible 2455 var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength; 2456 var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true); 2457 line.styles = highlighted.styles; 2458 var oldCls = line.styleClasses, newCls = highlighted.classes; 2459 if (newCls) line.styleClasses = newCls; 2460 else if (oldCls) line.styleClasses = null; 2461 var ischange = !oldStyles || oldStyles.length != line.styles.length || 2462 oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); 2463 for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; 2464 if (ischange) changedLines.push(doc.frontier); 2465 line.stateAfter = tooLong ? state : copyState(doc.mode, state); 2466 } else { 2467 if (line.text.length <= cm.options.maxHighlightLength) 2468 processLine(cm, line.text, state); 2469 line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; 2470 } 2471 ++doc.frontier; 2472 if (+new Date > end) { 2473 startWorker(cm, cm.options.workDelay); 2474 return true; 2475 } 2476 }); 2477 if (changedLines.length) runInOp(cm, function() { 2478 for (var i = 0; i < changedLines.length; i++) 2479 regLineChange(cm, changedLines[i], "text"); 2480 }); 2481 } 2482 2483 // Finds the line to start with when starting a parse. Tries to 2484 // find a line with a stateAfter, so that it can start with a 2485 // valid state. If that fails, it returns the line with the 2486 // smallest indentation, which tends to need the least context to 2487 // parse correctly. 2488 function findStartLine(cm, n, precise) { 2489 var minindent, minline, doc = cm.doc; 2490 var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); 2491 for (var search = n; search > lim; --search) { 2492 if (search <= doc.first) return doc.first; 2493 var line = getLine(doc, search - 1); 2494 if (line.stateAfter && (!precise || search <= doc.frontier)) return search; 2495 var indented = countColumn(line.text, null, cm.options.tabSize); 2496 if (minline == null || minindent > indented) { 2497 minline = search - 1; 2498 minindent = indented; 2499 } 2500 } 2501 return minline; 2502 } 2503 2504 function getStateBefore(cm, n, precise) { 2505 var doc = cm.doc, display = cm.display; 2506 if (!doc.mode.startState) return true; 2507 var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter; 2508 if (!state) state = startState(doc.mode); 2509 else state = copyState(doc.mode, state); 2510 doc.iter(pos, n, function(line) { 2511 processLine(cm, line.text, state); 2512 var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo; 2513 line.stateAfter = save ? copyState(doc.mode, state) : null; 2514 ++pos; 2515 }); 2516 if (precise) doc.frontier = pos; 2517 return state; 2518 } 2519 2520 // POSITION MEASUREMENT 2521 2522 function paddingTop(display) {return display.lineSpace.offsetTop;} 2523 function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} 2524 function paddingH(display) { 2525 if (display.cachedPaddingH) return display.cachedPaddingH; 2526 var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); 2527 var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; 2528 var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; 2529 if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data; 2530 return data; 2531 } 2532 2533 function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; } 2534 function displayWidth(cm) { 2535 return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; 2536 } 2537 function displayHeight(cm) { 2538 return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; 2539 } 2540 2541 // Ensure the lineView.wrapping.heights array is populated. This is 2542 // an array of bottom offsets for the lines that make up a drawn 2543 // line. When lineWrapping is on, there might be more than one 2544 // height. 2545 function ensureLineHeights(cm, lineView, rect) { 2546 var wrapping = cm.options.lineWrapping; 2547 var curWidth = wrapping && displayWidth(cm); 2548 if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { 2549 var heights = lineView.measure.heights = []; 2550 if (wrapping) { 2551 lineView.measure.width = curWidth; 2552 var rects = lineView.text.firstChild.getClientRects(); 2553 for (var i = 0; i < rects.length - 1; i++) { 2554 var cur = rects[i], next = rects[i + 1]; 2555 if (Math.abs(cur.bottom - next.bottom) > 2) 2556 heights.push((cur.bottom + next.top) / 2 - rect.top); 2557 } 2558 } 2559 heights.push(rect.bottom - rect.top); 2560 } 2561 } 2562 2563 // Find a line map (mapping character offsets to text nodes) and a 2564 // measurement cache for the given line number. (A line view might 2565 // contain multiple lines when collapsed ranges are present.) 2566 function mapFromLineView(lineView, line, lineN) { 2567 if (lineView.line == line) 2568 return {map: lineView.measure.map, cache: lineView.measure.cache}; 2569 for (var i = 0; i < lineView.rest.length; i++) 2570 if (lineView.rest[i] == line) 2571 return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]}; 2572 for (var i = 0; i < lineView.rest.length; i++) 2573 if (lineNo(lineView.rest[i]) > lineN) 2574 return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true}; 2575 } 2576 2577 // Render a line into the hidden node display.externalMeasured. Used 2578 // when measurement is needed for a line that's not in the viewport. 2579 function updateExternalMeasurement(cm, line) { 2580 line = visualLine(line); 2581 var lineN = lineNo(line); 2582 var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); 2583 view.lineN = lineN; 2584 var built = view.built = buildLineContent(cm, view); 2585 view.text = built.pre; 2586 removeChildrenAndAdd(cm.display.lineMeasure, built.pre); 2587 return view; 2588 } 2589 2590 // Get a {top, bottom, left, right} box (in line-local coordinates) 2591 // for a given character. 2592 function measureChar(cm, line, ch, bias) { 2593 return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); 2594 } 2595 2596 // Find a line view that corresponds to the given line number. 2597 function findViewForLine(cm, lineN) { 2598 if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) 2599 return cm.display.view[findViewIndex(cm, lineN)]; 2600 var ext = cm.display.externalMeasured; 2601 if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) 2602 return ext; 2603 } 2604 2605 // Measurement can be split in two steps, the set-up work that 2606 // applies to the whole line, and the measurement of the actual 2607 // character. Functions like coordsChar, that need to do a lot of 2608 // measurements in a row, can thus ensure that the set-up work is 2609 // only done once. 2610 function prepareMeasureForLine(cm, line) { 2611 var lineN = lineNo(line); 2612 var view = findViewForLine(cm, lineN); 2613 if (view && !view.text) { 2614 view = null; 2615 } else if (view && view.changes) { 2616 updateLineForChanges(cm, view, lineN, getDimensions(cm)); 2617 cm.curOp.forceUpdate = true; 2618 } 2619 if (!view) 2620 view = updateExternalMeasurement(cm, line); 2621 2622 var info = mapFromLineView(view, line, lineN); 2623 return { 2624 line: line, view: view, rect: null, 2625 map: info.map, cache: info.cache, before: info.before, 2626 hasHeights: false 2627 }; 2628 } 2629 2630 // Given a prepared measurement object, measures the position of an 2631 // actual character (or fetches it from the cache). 2632 function measureCharPrepared(cm, prepared, ch, bias, varHeight) { 2633 if (prepared.before) ch = -1; 2634 var key = ch + (bias || ""), found; 2635 if (prepared.cache.hasOwnProperty(key)) { 2636 found = prepared.cache[key]; 2637 } else { 2638 if (!prepared.rect) 2639 prepared.rect = prepared.view.text.getBoundingClientRect(); 2640 if (!prepared.hasHeights) { 2641 ensureLineHeights(cm, prepared.view, prepared.rect); 2642 prepared.hasHeights = true; 2643 } 2644 found = measureCharInner(cm, prepared, ch, bias); 2645 if (!found.bogus) prepared.cache[key] = found; 2646 } 2647 return {left: found.left, right: found.right, 2648 top: varHeight ? found.rtop : found.top, 2649 bottom: varHeight ? found.rbottom : found.bottom}; 2650 } 2651 2652 var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; 2653 2654 function nodeAndOffsetInLineMap(map, ch, bias) { 2655 var node, start, end, collapse; 2656 // First, search the line map for the text node corresponding to, 2657 // or closest to, the target character. 2658 for (var i = 0; i < map.length; i += 3) { 2659 var mStart = map[i], mEnd = map[i + 1]; 2660 if (ch < mStart) { 2661 start = 0; end = 1; 2662 collapse = "left"; 2663 } else if (ch < mEnd) { 2664 start = ch - mStart; 2665 end = start + 1; 2666 } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { 2667 end = mEnd - mStart; 2668 start = end - 1; 2669 if (ch >= mEnd) collapse = "right"; 2670 } 2671 if (start != null) { 2672 node = map[i + 2]; 2673 if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) 2674 collapse = bias; 2675 if (bias == "left" && start == 0) 2676 while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { 2677 node = map[(i -= 3) + 2]; 2678 collapse = "left"; 2679 } 2680 if (bias == "right" && start == mEnd - mStart) 2681 while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { 2682 node = map[(i += 3) + 2]; 2683 collapse = "right"; 2684 } 2685 break; 2686 } 2687 } 2688 return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}; 2689 } 2690 2691 function measureCharInner(cm, prepared, ch, bias) { 2692 var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); 2693 var node = place.node, start = place.start, end = place.end, collapse = place.collapse; 2694 2695 var rect; 2696 if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. 2697 for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned 2698 while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start; 2699 while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end; 2700 if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { 2701 rect = node.parentNode.getBoundingClientRect(); 2702 } else if (ie && cm.options.lineWrapping) { 2703 var rects = range(node, start, end).getClientRects(); 2704 if (rects.length) 2705 rect = rects[bias == "right" ? rects.length - 1 : 0]; 2706 else 2707 rect = nullRect; 2708 } else { 2709 rect = range(node, start, end).getBoundingClientRect() || nullRect; 2710 } 2711 if (rect.left || rect.right || start == 0) break; 2712 end = start; 2713 start = start - 1; 2714 collapse = "right"; 2715 } 2716 if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect); 2717 } else { // If it is a widget, simply get the box for the whole widget. 2718 if (start > 0) collapse = bias = "right"; 2719 var rects; 2720 if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) 2721 rect = rects[bias == "right" ? rects.length - 1 : 0]; 2722 else 2723 rect = node.getBoundingClientRect(); 2724 } 2725 if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { 2726 var rSpan = node.parentNode.getClientRects()[0]; 2727 if (rSpan) 2728 rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; 2729 else 2730 rect = nullRect; 2731 } 2732 2733 var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; 2734 var mid = (rtop + rbot) / 2; 2735 var heights = prepared.view.measure.heights; 2736 for (var i = 0; i < heights.length - 1; i++) 2737 if (mid < heights[i]) break; 2738 var top = i ? heights[i - 1] : 0, bot = heights[i]; 2739 var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, 2740 right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, 2741 top: top, bottom: bot}; 2742 if (!rect.left && !rect.right) result.bogus = true; 2743 if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } 2744 2745 return result; 2746 } 2747 2748 // Work around problem with bounding client rects on ranges being 2749 // returned incorrectly when zoomed on IE10 and below. 2750 function maybeUpdateRectForZooming(measure, rect) { 2751 if (!window.screen || screen.logicalXDPI == null || 2752 screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) 2753 return rect; 2754 var scaleX = screen.logicalXDPI / screen.deviceXDPI; 2755 var scaleY = screen.logicalYDPI / screen.deviceYDPI; 2756 return {left: rect.left * scaleX, right: rect.right * scaleX, 2757 top: rect.top * scaleY, bottom: rect.bottom * scaleY}; 2758 } 2759 2760 function clearLineMeasurementCacheFor(lineView) { 2761 if (lineView.measure) { 2762 lineView.measure.cache = {}; 2763 lineView.measure.heights = null; 2764 if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) 2765 lineView.measure.caches[i] = {}; 2766 } 2767 } 2768 2769 function clearLineMeasurementCache(cm) { 2770 cm.display.externalMeasure = null; 2771 removeChildren(cm.display.lineMeasure); 2772 for (var i = 0; i < cm.display.view.length; i++) 2773 clearLineMeasurementCacheFor(cm.display.view[i]); 2774 } 2775 2776 function clearCaches(cm) { 2777 clearLineMeasurementCache(cm); 2778 cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; 2779 if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; 2780 cm.display.lineNumChars = null; 2781 } 2782 2783 function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } 2784 function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } 2785 2786 // Converts a {top, bottom, left, right} box from line-local 2787 // coordinates into another coordinate system. Context may be one of 2788 // "line", "div" (display.lineDiv), "local"/null (editor), "window", 2789 // or "page". 2790 function intoCoordSystem(cm, lineObj, rect, context) { 2791 if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { 2792 var size = widgetHeight(lineObj.widgets[i]); 2793 rect.top += size; rect.bottom += size; 2794 } 2795 if (context == "line") return rect; 2796 if (!context) context = "local"; 2797 var yOff = heightAtLine(lineObj); 2798 if (context == "local") yOff += paddingTop(cm.display); 2799 else yOff -= cm.display.viewOffset; 2800 if (context == "page" || context == "window") { 2801 var lOff = cm.display.lineSpace.getBoundingClientRect(); 2802 yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); 2803 var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); 2804 rect.left += xOff; rect.right += xOff; 2805 } 2806 rect.top += yOff; rect.bottom += yOff; 2807 return rect; 2808 } 2809 2810 // Coverts a box from "div" coords to another coordinate system. 2811 // Context may be "window", "page", "div", or "local"/null. 2812 function fromCoordSystem(cm, coords, context) { 2813 if (context == "div") return coords; 2814 var left = coords.left, top = coords.top; 2815 // First move into "page" coordinate system 2816 if (context == "page") { 2817 left -= pageScrollX(); 2818 top -= pageScrollY(); 2819 } else if (context == "local" || !context) { 2820 var localBox = cm.display.sizer.getBoundingClientRect(); 2821 left += localBox.left; 2822 top += localBox.top; 2823 } 2824 2825 var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); 2826 return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; 2827 } 2828 2829 function charCoords(cm, pos, context, lineObj, bias) { 2830 if (!lineObj) lineObj = getLine(cm.doc, pos.line); 2831 return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); 2832 } 2833 2834 // Returns a box for a given cursor position, which may have an 2835 // 'other' property containing the position of the secondary cursor 2836 // on a bidi boundary. 2837 function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { 2838 lineObj = lineObj || getLine(cm.doc, pos.line); 2839 if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj); 2840 function get(ch, right) { 2841 var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); 2842 if (right) m.left = m.right; else m.right = m.left; 2843 return intoCoordSystem(cm, lineObj, m, context); 2844 } 2845 function getBidi(ch, partPos) { 2846 var part = order[partPos], right = part.level % 2; 2847 if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { 2848 part = order[--partPos]; 2849 ch = bidiRight(part) - (part.level % 2 ? 0 : 1); 2850 right = true; 2851 } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { 2852 part = order[++partPos]; 2853 ch = bidiLeft(part) - part.level % 2; 2854 right = false; 2855 } 2856 if (right && ch == part.to && ch > part.from) return get(ch - 1); 2857 return get(ch, right); 2858 } 2859 var order = getOrder(lineObj), ch = pos.ch; 2860 if (!order) return get(ch); 2861 var partPos = getBidiPartAt(order, ch); 2862 var val = getBidi(ch, partPos); 2863 if (bidiOther != null) val.other = getBidi(ch, bidiOther); 2864 return val; 2865 } 2866 2867 // Used to cheaply estimate the coordinates for a position. Used for 2868 // intermediate scroll updates. 2869 function estimateCoords(cm, pos) { 2870 var left = 0, pos = clipPos(cm.doc, pos); 2871 if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch; 2872 var lineObj = getLine(cm.doc, pos.line); 2873 var top = heightAtLine(lineObj) + paddingTop(cm.display); 2874 return {left: left, right: left, top: top, bottom: top + lineObj.height}; 2875 } 2876 2877 // Positions returned by coordsChar contain some extra information. 2878 // xRel is the relative x position of the input coordinates compared 2879 // to the found position (so xRel > 0 means the coordinates are to 2880 // the right of the character position, for example). When outside 2881 // is true, that means the coordinates lie outside the line's 2882 // vertical range. 2883 function PosWithInfo(line, ch, outside, xRel) { 2884 var pos = Pos(line, ch); 2885 pos.xRel = xRel; 2886 if (outside) pos.outside = true; 2887 return pos; 2888 } 2889 2890 // Compute the character position closest to the given coordinates. 2891 // Input must be lineSpace-local ("div" coordinate system). 2892 function coordsChar(cm, x, y) { 2893 var doc = cm.doc; 2894 y += cm.display.viewOffset; 2895 if (y < 0) return PosWithInfo(doc.first, 0, true, -1); 2896 var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; 2897 if (lineN > last) 2898 return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1); 2899 if (x < 0) x = 0; 2900 2901 var lineObj = getLine(doc, lineN); 2902 for (;;) { 2903 var found = coordsCharInner(cm, lineObj, lineN, x, y); 2904 var merged = collapsedSpanAtEnd(lineObj); 2905 var mergedPos = merged && merged.find(0, true); 2906 if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) 2907 lineN = lineNo(lineObj = mergedPos.to.line); 2908 else 2909 return found; 2910 } 2911 } 2912 2913 function coordsCharInner(cm, lineObj, lineNo, x, y) { 2914 var innerOff = y - heightAtLine(lineObj); 2915 var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; 2916 var preparedMeasure = prepareMeasureForLine(cm, lineObj); 2917 2918 function getX(ch) { 2919 var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure); 2920 wrongLine = true; 2921 if (innerOff > sp.bottom) return sp.left - adjust; 2922 else if (innerOff < sp.top) return sp.left + adjust; 2923 else wrongLine = false; 2924 return sp.left; 2925 } 2926 2927 var bidi = getOrder(lineObj), dist = lineObj.text.length; 2928 var from = lineLeft(lineObj), to = lineRight(lineObj); 2929 var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; 2930 2931 if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); 2932 // Do a binary search between these bounds. 2933 for (;;) { 2934 if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { 2935 var ch = x < fromX || x - fromX <= toX - x ? from : to; 2936 var xDiff = x - (ch == from ? fromX : toX); 2937 while (isExtendingChar(lineObj.text.charAt(ch))) ++ch; 2938 var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, 2939 xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0); 2940 return pos; 2941 } 2942 var step = Math.ceil(dist / 2), middle = from + step; 2943 if (bidi) { 2944 middle = from; 2945 for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); 2946 } 2947 var middleX = getX(middle); 2948 if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} 2949 else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} 2950 } 2951 } 2952 2953 var measureText; 2954 // Compute the default text height. 2955 function textHeight(display) { 2956 if (display.cachedTextHeight != null) return display.cachedTextHeight; 2957 if (measureText == null) { 2958 measureText = elt("pre"); 2959 // Measure a bunch of lines, for browsers that compute 2960 // fractional heights. 2961 for (var i = 0; i < 49; ++i) { 2962 measureText.appendChild(document.createTextNode("x")); 2963 measureText.appendChild(elt("br")); 2964 } 2965 measureText.appendChild(document.createTextNode("x")); 2966 } 2967 removeChildrenAndAdd(display.measure, measureText); 2968 var height = measureText.offsetHeight / 50; 2969 if (height > 3) display.cachedTextHeight = height; 2970 removeChildren(display.measure); 2971 return height || 1; 2972 } 2973 2974 // Compute the default character width. 2975 function charWidth(display) { 2976 if (display.cachedCharWidth != null) return display.cachedCharWidth; 2977 var anchor = elt("span", "xxxxxxxxxx"); 2978 var pre = elt("pre", [anchor]); 2979 removeChildrenAndAdd(display.measure, pre); 2980 var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; 2981 if (width > 2) display.cachedCharWidth = width; 2982 return width || 10; 2983 } 2984 2985 // OPERATIONS 2986 2987 // Operations are used to wrap a series of changes to the editor 2988 // state in such a way that each change won't have to update the 2989 // cursor and display (which would be awkward, slow, and 2990 // error-prone). Instead, display updates are batched and then all 2991 // combined and executed at once. 2992 2993 var operationGroup = null; 2994 2995 var nextOpId = 0; 2996 // Start a new operation. 2997 function startOperation(cm) { 2998 cm.curOp = { 2999 cm: cm, 3000 viewChanged: false, // Flag that indicates that lines might need to be redrawn 3001 startHeight: cm.doc.height, // Used to detect need to update scrollbar 3002 forceUpdate: false, // Used to force a redraw 3003 updateInput: null, // Whether to reset the input textarea 3004 typing: false, // Whether this reset should be careful to leave existing text (for compositing) 3005 changeObjs: null, // Accumulated changes, for firing change events 3006 cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on 3007 cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already 3008 selectionChanged: false, // Whether the selection needs to be redrawn 3009 updateMaxLine: false, // Set when the widest line needs to be determined anew 3010 scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet 3011 scrollToPos: null, // Used to scroll to a specific position 3012 focus: false, 3013 id: ++nextOpId // Unique ID 3014 }; 3015 if (operationGroup) { 3016 operationGroup.ops.push(cm.curOp); 3017 } else { 3018 cm.curOp.ownsGroup = operationGroup = { 3019 ops: [cm.curOp], 3020 delayedCallbacks: [] 3021 }; 3022 } 3023 } 3024 3025 function fireCallbacksForOps(group) { 3026 // Calls delayed callbacks and cursorActivity handlers until no 3027 // new ones appear 3028 var callbacks = group.delayedCallbacks, i = 0; 3029 do { 3030 for (; i < callbacks.length; i++) 3031 callbacks[i].call(null); 3032 for (var j = 0; j < group.ops.length; j++) { 3033 var op = group.ops[j]; 3034 if (op.cursorActivityHandlers) 3035 while (op.cursorActivityCalled < op.cursorActivityHandlers.length) 3036 op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); 3037 } 3038 } while (i < callbacks.length); 3039 } 3040 3041 // Finish an operation, updating the display and signalling delayed events 3042 function endOperation(cm) { 3043 var op = cm.curOp, group = op.ownsGroup; 3044 if (!group) return; 3045 3046 try { fireCallbacksForOps(group); } 3047 finally { 3048 operationGroup = null; 3049 for (var i = 0; i < group.ops.length; i++) 3050 group.ops[i].cm.curOp = null; 3051 endOperations(group); 3052 } 3053 } 3054 3055 // The DOM updates done when an operation finishes are batched so 3056 // that the minimum number of relayouts are required. 3057 function endOperations(group) { 3058 var ops = group.ops; 3059 for (var i = 0; i < ops.length; i++) // Read DOM 3060 endOperation_R1(ops[i]); 3061 for (var i = 0; i < ops.length; i++) // Write DOM (maybe) 3062 endOperation_W1(ops[i]); 3063 for (var i = 0; i < ops.length; i++) // Read DOM 3064 endOperation_R2(ops[i]); 3065 for (var i = 0; i < ops.length; i++) // Write DOM (maybe) 3066 endOperation_W2(ops[i]); 3067 for (var i = 0; i < ops.length; i++) // Read DOM 3068 endOperation_finish(ops[i]); 3069 } 3070 3071 function endOperation_R1(op) { 3072 var cm = op.cm, display = cm.display; 3073 maybeClipScrollbars(cm); 3074 if (op.updateMaxLine) findMaxLine(cm); 3075 3076 op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || 3077 op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || 3078 op.scrollToPos.to.line >= display.viewTo) || 3079 display.maxLineChanged && cm.options.lineWrapping; 3080 op.update = op.mustUpdate && 3081 new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); 3082 } 3083 3084 function endOperation_W1(op) { 3085 op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); 3086 } 3087 3088 function endOperation_R2(op) { 3089 var cm = op.cm, display = cm.display; 3090 if (op.updatedDisplay) updateHeightsInViewport(cm); 3091 3092 op.barMeasure = measureForScrollbars(cm); 3093 3094 // If the max line changed since it was last measured, measure it, 3095 // and ensure the document's width matches it. 3096 // updateDisplay_W2 will use these properties to do the actual resizing 3097 if (display.maxLineChanged && !cm.options.lineWrapping) { 3098 op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; 3099 cm.display.sizerWidth = op.adjustWidthTo; 3100 op.barMeasure.scrollWidth = 3101 Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); 3102 op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); 3103 } 3104 3105 if (op.updatedDisplay || op.selectionChanged) 3106 op.preparedSelection = display.input.prepareSelection(op.focus); 3107 } 3108 3109 function endOperation_W2(op) { 3110 var cm = op.cm; 3111 3112 if (op.adjustWidthTo != null) { 3113 cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; 3114 if (op.maxScrollLeft < cm.doc.scrollLeft) 3115 setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); 3116 cm.display.maxLineChanged = false; 3117 } 3118 3119 var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus()) 3120 if (op.preparedSelection) 3121 cm.display.input.showSelection(op.preparedSelection, takeFocus); 3122 if (op.updatedDisplay || op.startHeight != cm.doc.height) 3123 updateScrollbars(cm, op.barMeasure); 3124 if (op.updatedDisplay) 3125 setDocumentHeight(cm, op.barMeasure); 3126 3127 if (op.selectionChanged) restartBlink(cm); 3128 3129 if (cm.state.focused && op.updateInput) 3130 cm.display.input.reset(op.typing); 3131 if (takeFocus) ensureFocus(op.cm); 3132 } 3133 3134 function endOperation_finish(op) { 3135 var cm = op.cm, display = cm.display, doc = cm.doc; 3136 3137 if (op.updatedDisplay) postUpdateDisplay(cm, op.update); 3138 3139 // Abort mouse wheel delta measurement, when scrolling explicitly 3140 if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) 3141 display.wheelStartX = display.wheelStartY = null; 3142 3143 // Propagate the scroll position to the actual DOM scroller 3144 if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) { 3145 doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)); 3146 display.scrollbars.setScrollTop(doc.scrollTop); 3147 display.scroller.scrollTop = doc.scrollTop; 3148 } 3149 if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) { 3150 doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft)); 3151 display.scrollbars.setScrollLeft(doc.scrollLeft); 3152 display.scroller.scrollLeft = doc.scrollLeft; 3153 alignHorizontally(cm); 3154 } 3155 // If we need to scroll a specific position into view, do so. 3156 if (op.scrollToPos) { 3157 var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), 3158 clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); 3159 if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords); 3160 } 3161 3162 // Fire events for markers that are hidden/unidden by editing or 3163 // undoing 3164 var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; 3165 if (hidden) for (var i = 0; i < hidden.length; ++i) 3166 if (!hidden[i].lines.length) signal(hidden[i], "hide"); 3167 if (unhidden) for (var i = 0; i < unhidden.length; ++i) 3168 if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); 3169 3170 if (display.wrapper.offsetHeight) 3171 doc.scrollTop = cm.display.scroller.scrollTop; 3172 3173 // Fire change events, and delayed event handlers 3174 if (op.changeObjs) 3175 signal(cm, "changes", cm, op.changeObjs); 3176 if (op.update) 3177 op.update.finish(); 3178 } 3179 3180 // Run the given function in an operation 3181 function runInOp(cm, f) { 3182 if (cm.curOp) return f(); 3183 startOperation(cm); 3184 try { return f(); } 3185 finally { endOperation(cm); } 3186 } 3187 // Wraps a function in an operation. Returns the wrapped function. 3188 function operation(cm, f) { 3189 return function() { 3190 if (cm.curOp) return f.apply(cm, arguments); 3191 startOperation(cm); 3192 try { return f.apply(cm, arguments); } 3193 finally { endOperation(cm); } 3194 }; 3195 } 3196 // Used to add methods to editor and doc instances, wrapping them in 3197 // operations. 3198 function methodOp(f) { 3199 return function() { 3200 if (this.curOp) return f.apply(this, arguments); 3201 startOperation(this); 3202 try { return f.apply(this, arguments); } 3203 finally { endOperation(this); } 3204 }; 3205 } 3206 function docMethodOp(f) { 3207 return function() { 3208 var cm = this.cm; 3209 if (!cm || cm.curOp) return f.apply(this, arguments); 3210 startOperation(cm); 3211 try { return f.apply(this, arguments); } 3212 finally { endOperation(cm); } 3213 }; 3214 } 3215 3216 // VIEW TRACKING 3217 3218 // These objects are used to represent the visible (currently drawn) 3219 // part of the document. A LineView may correspond to multiple 3220 // logical lines, if those are connected by collapsed ranges. 3221 function LineView(doc, line, lineN) { 3222 // The starting line 3223 this.line = line; 3224 // Continuing lines, if any 3225 this.rest = visualLineContinued(line); 3226 // Number of logical lines in this visual line 3227 this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; 3228 this.node = this.text = null; 3229 this.hidden = lineIsHidden(doc, line); 3230 } 3231 3232 // Create a range of LineView objects for the given lines. 3233 function buildViewArray(cm, from, to) { 3234 var array = [], nextPos; 3235 for (var pos = from; pos < to; pos = nextPos) { 3236 var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); 3237 nextPos = pos + view.size; 3238 array.push(view); 3239 } 3240 return array; 3241 } 3242 3243 // Updates the display.view data structure for a given change to the 3244 // document. From and to are in pre-change coordinates. Lendiff is 3245 // the amount of lines added or subtracted by the change. This is 3246 // used for changes that span multiple lines, or change the way 3247 // lines are divided into visual lines. regLineChange (below) 3248 // registers single-line changes. 3249 function regChange(cm, from, to, lendiff) { 3250 if (from == null) from = cm.doc.first; 3251 if (to == null) to = cm.doc.first + cm.doc.size; 3252 if (!lendiff) lendiff = 0; 3253 3254 var display = cm.display; 3255 if (lendiff && to < display.viewTo && 3256 (display.updateLineNumbers == null || display.updateLineNumbers > from)) 3257 display.updateLineNumbers = from; 3258 3259 cm.curOp.viewChanged = true; 3260 3261 if (from >= display.viewTo) { // Change after 3262 if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) 3263 resetView(cm); 3264 } else if (to <= display.viewFrom) { // Change before 3265 if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { 3266 resetView(cm); 3267 } else { 3268 display.viewFrom += lendiff; 3269 display.viewTo += lendiff; 3270 } 3271 } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap 3272 resetView(cm); 3273 } else if (from <= display.viewFrom) { // Top overlap 3274 var cut = viewCuttingPoint(cm, to, to + lendiff, 1); 3275 if (cut) { 3276 display.view = display.view.slice(cut.index); 3277 display.viewFrom = cut.lineN; 3278 display.viewTo += lendiff; 3279 } else { 3280 resetView(cm); 3281 } 3282 } else if (to >= display.viewTo) { // Bottom overlap 3283 var cut = viewCuttingPoint(cm, from, from, -1); 3284 if (cut) { 3285 display.view = display.view.slice(0, cut.index); 3286 display.viewTo = cut.lineN; 3287 } else { 3288 resetView(cm); 3289 } 3290 } else { // Gap in the middle 3291 var cutTop = viewCuttingPoint(cm, from, from, -1); 3292 var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); 3293 if (cutTop && cutBot) { 3294 display.view = display.view.slice(0, cutTop.index) 3295 .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) 3296 .concat(display.view.slice(cutBot.index)); 3297 display.viewTo += lendiff; 3298 } else { 3299 resetView(cm); 3300 } 3301 } 3302 3303 var ext = display.externalMeasured; 3304 if (ext) { 3305 if (to < ext.lineN) 3306 ext.lineN += lendiff; 3307 else if (from < ext.lineN + ext.size) 3308 display.externalMeasured = null; 3309 } 3310 } 3311 3312 // Register a change to a single line. Type must be one of "text", 3313 // "gutter", "class", "widget" 3314 function regLineChange(cm, line, type) { 3315 cm.curOp.viewChanged = true; 3316 var display = cm.display, ext = cm.display.externalMeasured; 3317 if (ext && line >= ext.lineN && line < ext.lineN + ext.size) 3318 display.externalMeasured = null; 3319 3320 if (line < display.viewFrom || line >= display.viewTo) return; 3321 var lineView = display.view[findViewIndex(cm, line)]; 3322 if (lineView.node == null) return; 3323 var arr = lineView.changes || (lineView.changes = []); 3324 if (indexOf(arr, type) == -1) arr.push(type); 3325 } 3326 3327 // Clear the view. 3328 function resetView(cm) { 3329 cm.display.viewFrom = cm.display.viewTo = cm.doc.first; 3330 cm.display.view = []; 3331 cm.display.viewOffset = 0; 3332 } 3333 3334 // Find the view element corresponding to a given line. Return null 3335 // when the line isn't visible. 3336 function findViewIndex(cm, n) { 3337 if (n >= cm.display.viewTo) return null; 3338 n -= cm.display.viewFrom; 3339 if (n < 0) return null; 3340 var view = cm.display.view; 3341 for (var i = 0; i < view.length; i++) { 3342 n -= view[i].size; 3343 if (n < 0) return i; 3344 } 3345 } 3346 3347 function viewCuttingPoint(cm, oldN, newN, dir) { 3348 var index = findViewIndex(cm, oldN), diff, view = cm.display.view; 3349 if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) 3350 return {index: index, lineN: newN}; 3351 for (var i = 0, n = cm.display.viewFrom; i < index; i++) 3352 n += view[i].size; 3353 if (n != oldN) { 3354 if (dir > 0) { 3355 if (index == view.length - 1) return null; 3356 diff = (n + view[index].size) - oldN; 3357 index++; 3358 } else { 3359 diff = n - oldN; 3360 } 3361 oldN += diff; newN += diff; 3362 } 3363 while (visualLineNo(cm.doc, newN) != newN) { 3364 if (index == (dir < 0 ? 0 : view.length - 1)) return null; 3365 newN += dir * view[index - (dir < 0 ? 1 : 0)].size; 3366 index += dir; 3367 } 3368 return {index: index, lineN: newN}; 3369 } 3370 3371 // Force the view to cover a given range, adding empty view element 3372 // or clipping off existing ones as needed. 3373 function adjustView(cm, from, to) { 3374 var display = cm.display, view = display.view; 3375 if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { 3376 display.view = buildViewArray(cm, from, to); 3377 display.viewFrom = from; 3378 } else { 3379 if (display.viewFrom > from) 3380 display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); 3381 else if (display.viewFrom < from) 3382 display.view = display.view.slice(findViewIndex(cm, from)); 3383 display.viewFrom = from; 3384 if (display.viewTo < to) 3385 display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); 3386 else if (display.viewTo > to) 3387 display.view = display.view.slice(0, findViewIndex(cm, to)); 3388 } 3389 display.viewTo = to; 3390 } 3391 3392 // Count the number of lines in the view whose DOM representation is 3393 // out of date (or nonexistent). 3394 function countDirtyView(cm) { 3395 var view = cm.display.view, dirty = 0; 3396 for (var i = 0; i < view.length; i++) { 3397 var lineView = view[i]; 3398 if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty; 3399 } 3400 return dirty; 3401 } 3402 3403 // EVENT HANDLERS 3404 3405 // Attach the necessary event handlers when initializing the editor 3406 function registerEventHandlers(cm) { 3407 var d = cm.display; 3408 on(d.scroller, "mousedown", operation(cm, onMouseDown)); 3409 // Older IE's will not fire a second mousedown for a double click 3410 if (ie && ie_version < 11) 3411 on(d.scroller, "dblclick", operation(cm, function(e) { 3412 if (signalDOMEvent(cm, e)) return; 3413 var pos = posFromMouse(cm, e); 3414 if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; 3415 e_preventDefault(e); 3416 var word = cm.findWordAt(pos); 3417 extendSelection(cm.doc, word.anchor, word.head); 3418 })); 3419 else 3420 on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); }); 3421 // Some browsers fire contextmenu *after* opening the menu, at 3422 // which point we can't mess with it anymore. Context menu is 3423 // handled in onMouseDown for these browsers. 3424 if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); 3425 3426 // Used to suppress mouse event handling when a touch happens 3427 var touchFinished, prevTouch = {end: 0}; 3428 function finishTouch() { 3429 if (d.activeTouch) { 3430 touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000); 3431 prevTouch = d.activeTouch; 3432 prevTouch.end = +new Date; 3433 } 3434 }; 3435 function isMouseLikeTouchEvent(e) { 3436 if (e.touches.length != 1) return false; 3437 var touch = e.touches[0]; 3438 return touch.radiusX <= 1 && touch.radiusY <= 1; 3439 } 3440 function farAway(touch, other) { 3441 if (other.left == null) return true; 3442 var dx = other.left - touch.left, dy = other.top - touch.top; 3443 return dx * dx + dy * dy > 20 * 20; 3444 } 3445 on(d.scroller, "touchstart", function(e) { 3446 if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) { 3447 clearTimeout(touchFinished); 3448 var now = +new Date; 3449 d.activeTouch = {start: now, moved: false, 3450 prev: now - prevTouch.end <= 300 ? prevTouch : null}; 3451 if (e.touches.length == 1) { 3452 d.activeTouch.left = e.touches[0].pageX; 3453 d.activeTouch.top = e.touches[0].pageY; 3454 } 3455 } 3456 }); 3457 on(d.scroller, "touchmove", function() { 3458 if (d.activeTouch) d.activeTouch.moved = true; 3459 }); 3460 on(d.scroller, "touchend", function(e) { 3461 var touch = d.activeTouch; 3462 if (touch && !eventInWidget(d, e) && touch.left != null && 3463 !touch.moved && new Date - touch.start < 300) { 3464 var pos = cm.coordsChar(d.activeTouch, "page"), range; 3465 if (!touch.prev || farAway(touch, touch.prev)) // Single tap 3466 range = new Range(pos, pos); 3467 else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap 3468 range = cm.findWordAt(pos); 3469 else // Triple tap 3470 range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); 3471 cm.setSelection(range.anchor, range.head); 3472 cm.focus(); 3473 e_preventDefault(e); 3474 } 3475 finishTouch(); 3476 }); 3477 on(d.scroller, "touchcancel", finishTouch); 3478 3479 // Sync scrolling between fake scrollbars and real scrollable 3480 // area, ensure viewport is updated when scrolling. 3481 on(d.scroller, "scroll", function() { 3482 if (d.scroller.clientHeight) { 3483 setScrollTop(cm, d.scroller.scrollTop); 3484 setScrollLeft(cm, d.scroller.scrollLeft, true); 3485 signal(cm, "scroll", cm); 3486 } 3487 }); 3488 3489 // Listen to wheel events in order to try and update the viewport on time. 3490 on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); 3491 on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); 3492 3493 // Prevent wrapper from ever scrolling 3494 on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); 3495 3496 d.dragFunctions = { 3497 enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);}, 3498 over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, 3499 start: function(e){onDragStart(cm, e);}, 3500 drop: operation(cm, onDrop), 3501 leave: function(e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }} 3502 }; 3503 3504 var inp = d.input.getField(); 3505 on(inp, "keyup", function(e) { onKeyUp.call(cm, e); }); 3506 on(inp, "keydown", operation(cm, onKeyDown)); 3507 on(inp, "keypress", operation(cm, onKeyPress)); 3508 on(inp, "focus", bind(onFocus, cm)); 3509 on(inp, "blur", bind(onBlur, cm)); 3510 } 3511 3512 function dragDropChanged(cm, value, old) { 3513 var wasOn = old && old != CodeMirror.Init; 3514 if (!value != !wasOn) { 3515 var funcs = cm.display.dragFunctions; 3516 var toggle = value ? on : off; 3517 toggle(cm.display.scroller, "dragstart", funcs.start); 3518 toggle(cm.display.scroller, "dragenter", funcs.enter); 3519 toggle(cm.display.scroller, "dragover", funcs.over); 3520 toggle(cm.display.scroller, "dragleave", funcs.leave); 3521 toggle(cm.display.scroller, "drop", funcs.drop); 3522 } 3523 } 3524 3525 // Called when the window resizes 3526 function onResize(cm) { 3527 var d = cm.display; 3528 if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) 3529 return; 3530 // Might be a text scaling operation, clear size caches. 3531 d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; 3532 d.scrollbarsClipped = false; 3533 cm.setSize(); 3534 } 3535 3536 // MOUSE EVENTS 3537 3538 // Return true when the given mouse event happened in a widget 3539 function eventInWidget(display, e) { 3540 for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { 3541 if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || 3542 (n.parentNode == display.sizer && n != display.mover)) 3543 return true; 3544 } 3545 } 3546 3547 // Given a mouse event, find the corresponding position. If liberal 3548 // is false, it checks whether a gutter or scrollbar was clicked, 3549 // and returns null if it was. forRect is used by rectangular 3550 // selections, and tries to estimate a character position even for 3551 // coordinates beyond the right of the text. 3552 function posFromMouse(cm, e, liberal, forRect) { 3553 var display = cm.display; 3554 if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null; 3555 3556 var x, y, space = display.lineSpace.getBoundingClientRect(); 3557 // Fails unpredictably on IE[67] when mouse is dragged around quickly. 3558 try { x = e.clientX - space.left; y = e.clientY - space.top; } 3559 catch (e) { return null; } 3560 var coords = coordsChar(cm, x, y), line; 3561 if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { 3562 var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; 3563 coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); 3564 } 3565 return coords; 3566 } 3567 3568 // A mouse down can be a single click, double click, triple click, 3569 // start of selection drag, start of text drag, new cursor 3570 // (ctrl-click), rectangle drag (alt-drag), or xwin 3571 // middle-click-paste. Or it might be a click on something we should 3572 // not interfere with, such as a scrollbar or widget. 3573 function onMouseDown(e) { 3574 var cm = this, display = cm.display; 3575 if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) return; 3576 display.shift = e.shiftKey; 3577 3578 if (eventInWidget(display, e)) { 3579 if (!webkit) { 3580 // Briefly turn off draggability, to allow widgets to do 3581 // normal dragging things. 3582 display.scroller.draggable = false; 3583 setTimeout(function(){display.scroller.draggable = true;}, 100); 3584 } 3585 return; 3586 } 3587 if (clickInGutter(cm, e)) return; 3588 var start = posFromMouse(cm, e); 3589 window.focus(); 3590 3591 switch (e_button(e)) { 3592 case 1: 3593 // #3261: make sure, that we're not starting a second selection 3594 if (cm.state.selectingText) 3595 cm.state.selectingText(e); 3596 else if (start) 3597 leftButtonDown(cm, e, start); 3598 else if (e_target(e) == display.scroller) 3599 e_preventDefault(e); 3600 break; 3601 case 2: 3602 if (webkit) cm.state.lastMiddleDown = +new Date; 3603 if (start) extendSelection(cm.doc, start); 3604 setTimeout(function() {display.input.focus();}, 20); 3605 e_preventDefault(e); 3606 break; 3607 case 3: 3608 if (captureRightClick) onContextMenu(cm, e); 3609 else delayBlurEvent(cm); 3610 break; 3611 } 3612 } 3613 3614 var lastClick, lastDoubleClick; 3615 function leftButtonDown(cm, e, start) { 3616 if (ie) setTimeout(bind(ensureFocus, cm), 0); 3617 else cm.curOp.focus = activeElt(); 3618 3619 var now = +new Date, type; 3620 if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { 3621 type = "triple"; 3622 } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { 3623 type = "double"; 3624 lastDoubleClick = {time: now, pos: start}; 3625 } else { 3626 type = "single"; 3627 lastClick = {time: now, pos: start}; 3628 } 3629 3630 var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained; 3631 if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && 3632 type == "single" && (contained = sel.contains(start)) > -1 && 3633 (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) && 3634 (cmp(contained.to(), start) > 0 || start.xRel < 0)) 3635 leftButtonStartDrag(cm, e, start, modifier); 3636 else 3637 leftButtonSelect(cm, e, start, type, modifier); 3638 } 3639 3640 // Start a text drag. When it ends, see if any dragging actually 3641 // happen, and treat as a click if it didn't. 3642 function leftButtonStartDrag(cm, e, start, modifier) { 3643 var display = cm.display, startTime = +new Date; 3644 var dragEnd = operation(cm, function(e2) { 3645 if (webkit) display.scroller.draggable = false; 3646 cm.state.draggingText = false; 3647 off(document, "mouseup", dragEnd); 3648 off(display.scroller, "drop", dragEnd); 3649 if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { 3650 e_preventDefault(e2); 3651 if (!modifier && +new Date - 200 < startTime) 3652 extendSelection(cm.doc, start); 3653 // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) 3654 if (webkit || ie && ie_version == 9) 3655 setTimeout(function() {document.body.focus(); display.input.focus();}, 20); 3656 else 3657 display.input.focus(); 3658 } 3659 }); 3660 // Let the drag handler handle this. 3661 if (webkit) display.scroller.draggable = true; 3662 cm.state.draggingText = dragEnd; 3663 // IE's approach to draggable 3664 if (display.scroller.dragDrop) display.scroller.dragDrop(); 3665 on(document, "mouseup", dragEnd); 3666 on(display.scroller, "drop", dragEnd); 3667 } 3668 3669 // Normal selection, as opposed to text dragging. 3670 function leftButtonSelect(cm, e, start, type, addNew) { 3671 var display = cm.display, doc = cm.doc; 3672 e_preventDefault(e); 3673 3674 var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; 3675 if (addNew && !e.shiftKey) { 3676 ourIndex = doc.sel.contains(start); 3677 if (ourIndex > -1) 3678 ourRange = ranges[ourIndex]; 3679 else 3680 ourRange = new Range(start, start); 3681 } else { 3682 ourRange = doc.sel.primary(); 3683 ourIndex = doc.sel.primIndex; 3684 } 3685 3686 if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) { 3687 type = "rect"; 3688 if (!addNew) ourRange = new Range(start, start); 3689 start = posFromMouse(cm, e, true, true); 3690 ourIndex = -1; 3691 } else if (type == "double") { 3692 var word = cm.findWordAt(start); 3693 if (cm.display.shift || doc.extend) 3694 ourRange = extendRange(doc, ourRange, word.anchor, word.head); 3695 else 3696 ourRange = word; 3697 } else if (type == "triple") { 3698 var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))); 3699 if (cm.display.shift || doc.extend) 3700 ourRange = extendRange(doc, ourRange, line.anchor, line.head); 3701 else 3702 ourRange = line; 3703 } else { 3704 ourRange = extendRange(doc, ourRange, start); 3705 } 3706 3707 if (!addNew) { 3708 ourIndex = 0; 3709 setSelection(doc, new Selection([ourRange], 0), sel_mouse); 3710 startSel = doc.sel; 3711 } else if (ourIndex == -1) { 3712 ourIndex = ranges.length; 3713 setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), 3714 {scroll: false, origin: "*mouse"}); 3715 } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) { 3716 setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), 3717 {scroll: false, origin: "*mouse"}); 3718 startSel = doc.sel; 3719 } else { 3720 replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); 3721 } 3722 3723 var lastPos = start; 3724 function extendTo(pos) { 3725 if (cmp(lastPos, pos) == 0) return; 3726 lastPos = pos; 3727 3728 if (type == "rect") { 3729 var ranges = [], tabSize = cm.options.tabSize; 3730 var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); 3731 var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); 3732 var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); 3733 for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); 3734 line <= end; line++) { 3735 var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); 3736 if (left == right) 3737 ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); 3738 else if (text.length > leftPos) 3739 ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); 3740 } 3741 if (!ranges.length) ranges.push(new Range(start, start)); 3742 setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), 3743 {origin: "*mouse", scroll: false}); 3744 cm.scrollIntoView(pos); 3745 } else { 3746 var oldRange = ourRange; 3747 var anchor = oldRange.anchor, head = pos; 3748 if (type != "single") { 3749 if (type == "double") 3750 var range = cm.findWordAt(pos); 3751 else 3752 var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))); 3753 if (cmp(range.anchor, anchor) > 0) { 3754 head = range.head; 3755 anchor = minPos(oldRange.from(), range.anchor); 3756 } else { 3757 head = range.anchor; 3758 anchor = maxPos(oldRange.to(), range.head); 3759 } 3760 } 3761 var ranges = startSel.ranges.slice(0); 3762 ranges[ourIndex] = new Range(clipPos(doc, anchor), head); 3763 setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse); 3764 } 3765 } 3766 3767 var editorSize = display.wrapper.getBoundingClientRect(); 3768 // Used to ensure timeout re-tries don't fire when another extend 3769 // happened in the meantime (clearTimeout isn't reliable -- at 3770 // least on Chrome, the timeouts still happen even when cleared, 3771 // if the clear happens after their scheduled firing time). 3772 var counter = 0; 3773 3774 function extend(e) { 3775 var curCount = ++counter; 3776 var cur = posFromMouse(cm, e, true, type == "rect"); 3777 if (!cur) return; 3778 if (cmp(cur, lastPos) != 0) { 3779 cm.curOp.focus = activeElt(); 3780 extendTo(cur); 3781 var visible = visibleLines(display, doc); 3782 if (cur.line >= visible.to || cur.line < visible.from) 3783 setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); 3784 } else { 3785 var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; 3786 if (outside) setTimeout(operation(cm, function() { 3787 if (counter != curCount) return; 3788 display.scroller.scrollTop += outside; 3789 extend(e); 3790 }), 50); 3791 } 3792 } 3793 3794 function done(e) { 3795 cm.state.selectingText = false; 3796 counter = Infinity; 3797 e_preventDefault(e); 3798 display.input.focus(); 3799 off(document, "mousemove", move); 3800 off(document, "mouseup", up); 3801 doc.history.lastSelOrigin = null; 3802 } 3803 3804 var move = operation(cm, function(e) { 3805 if (!e_button(e)) done(e); 3806 else extend(e); 3807 }); 3808 var up = operation(cm, done); 3809 cm.state.selectingText = up; 3810 on(document, "mousemove", move); 3811 on(document, "mouseup", up); 3812 } 3813 3814 // Determines whether an event happened in the gutter, and fires the 3815 // handlers for the corresponding event. 3816 function gutterEvent(cm, e, type, prevent) { 3817 try { var mX = e.clientX, mY = e.clientY; } 3818 catch(e) { return false; } 3819 if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false; 3820 if (prevent) e_preventDefault(e); 3821 3822 var display = cm.display; 3823 var lineBox = display.lineDiv.getBoundingClientRect(); 3824 3825 if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e); 3826 mY -= lineBox.top - display.viewOffset; 3827 3828 for (var i = 0; i < cm.options.gutters.length; ++i) { 3829 var g = display.gutters.childNodes[i]; 3830 if (g && g.getBoundingClientRect().right >= mX) { 3831 var line = lineAtHeight(cm.doc, mY); 3832 var gutter = cm.options.gutters[i]; 3833 signal(cm, type, cm, line, gutter, e); 3834 return e_defaultPrevented(e); 3835 } 3836 } 3837 } 3838 3839 function clickInGutter(cm, e) { 3840 return gutterEvent(cm, e, "gutterClick", true); 3841 } 3842 3843 // Kludge to work around strange IE behavior where it'll sometimes 3844 // re-fire a series of drag-related events right after the drop (#1551) 3845 var lastDrop = 0; 3846 3847 function onDrop(e) { 3848 var cm = this; 3849 clearDragCursor(cm); 3850 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) 3851 return; 3852 e_preventDefault(e); 3853 if (ie) lastDrop = +new Date; 3854 var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; 3855 if (!pos || cm.isReadOnly()) return; 3856 // Might be a file drop, in which case we simply extract the text 3857 // and insert it. 3858 if (files && files.length && window.FileReader && window.File) { 3859 var n = files.length, text = Array(n), read = 0; 3860 var loadFile = function(file, i) { 3861 if (cm.options.allowDropFileTypes && 3862 indexOf(cm.options.allowDropFileTypes, file.type) == -1) 3863 return; 3864 3865 var reader = new FileReader; 3866 reader.onload = operation(cm, function() { 3867 var content = reader.result; 3868 if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = ""; 3869 text[i] = content; 3870 if (++read == n) { 3871 pos = clipPos(cm.doc, pos); 3872 var change = {from: pos, to: pos, 3873 text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), 3874 origin: "paste"}; 3875 makeChange(cm.doc, change); 3876 setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); 3877 } 3878 }); 3879 reader.readAsText(file); 3880 }; 3881 for (var i = 0; i < n; ++i) loadFile(files[i], i); 3882 } else { // Normal drop 3883 // Don't do a replace if the drop happened inside of the selected text. 3884 if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { 3885 cm.state.draggingText(e); 3886 // Ensure the editor is re-focused 3887 setTimeout(function() {cm.display.input.focus();}, 20); 3888 return; 3889 } 3890 try { 3891 var text = e.dataTransfer.getData("Text"); 3892 if (text) { 3893 if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey)) 3894 var selected = cm.listSelections(); 3895 setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); 3896 if (selected) for (var i = 0; i < selected.length; ++i) 3897 replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag"); 3898 cm.replaceSelection(text, "around", "paste"); 3899 cm.display.input.focus(); 3900 } 3901 } 3902 catch(e){} 3903 } 3904 } 3905 3906 function onDragStart(cm, e) { 3907 if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } 3908 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; 3909 3910 e.dataTransfer.setData("Text", cm.getSelection()); 3911 e.dataTransfer.effectAllowed = "copyMove" 3912 3913 // Use dummy image instead of default browsers image. 3914 // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. 3915 if (e.dataTransfer.setDragImage && !safari) { 3916 var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); 3917 img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; 3918 if (presto) { 3919 img.width = img.height = 1; 3920 cm.display.wrapper.appendChild(img); 3921 // Force a relayout, or Opera won't use our image for some obscure reason 3922 img._top = img.offsetTop; 3923 } 3924 e.dataTransfer.setDragImage(img, 0, 0); 3925 if (presto) img.parentNode.removeChild(img); 3926 } 3927 } 3928 3929 function onDragOver(cm, e) { 3930 var pos = posFromMouse(cm, e); 3931 if (!pos) return; 3932 var frag = document.createDocumentFragment(); 3933 drawSelectionCursor(cm, pos, frag); 3934 if (!cm.display.dragCursor) { 3935 cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); 3936 cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); 3937 } 3938 removeChildrenAndAdd(cm.display.dragCursor, frag); 3939 } 3940 3941 function clearDragCursor(cm) { 3942 if (cm.display.dragCursor) { 3943 cm.display.lineSpace.removeChild(cm.display.dragCursor); 3944 cm.display.dragCursor = null; 3945 } 3946 } 3947 3948 // SCROLL EVENTS 3949 3950 // Sync the scrollable area and scrollbars, ensure the viewport 3951 // covers the visible area. 3952 function setScrollTop(cm, val) { 3953 if (Math.abs(cm.doc.scrollTop - val) < 2) return; 3954 cm.doc.scrollTop = val; 3955 if (!gecko) updateDisplaySimple(cm, {top: val}); 3956 if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; 3957 cm.display.scrollbars.setScrollTop(val); 3958 if (gecko) updateDisplaySimple(cm); 3959 startWorker(cm, 100); 3960 } 3961 // Sync scroller and scrollbar, ensure the gutter elements are 3962 // aligned. 3963 function setScrollLeft(cm, val, isScroller) { 3964 if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; 3965 val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); 3966 cm.doc.scrollLeft = val; 3967 alignHorizontally(cm); 3968 if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; 3969 cm.display.scrollbars.setScrollLeft(val); 3970 } 3971 3972 // Since the delta values reported on mouse wheel events are 3973 // unstandardized between browsers and even browser versions, and 3974 // generally horribly unpredictable, this code starts by measuring 3975 // the scroll effect that the first few mouse wheel events have, 3976 // and, from that, detects the way it can convert deltas to pixel 3977 // offsets afterwards. 3978 // 3979 // The reason we want to know the amount a wheel event will scroll 3980 // is that it gives us a chance to update the display before the 3981 // actual scrolling happens, reducing flickering. 3982 3983 var wheelSamples = 0, wheelPixelsPerUnit = null; 3984 // Fill in a browser-detected starting value on browsers where we 3985 // know one. These don't have to be accurate -- the result of them 3986 // being wrong would just be a slight flicker on the first wheel 3987 // scroll (if it is large enough). 3988 if (ie) wheelPixelsPerUnit = -.53; 3989 else if (gecko) wheelPixelsPerUnit = 15; 3990 else if (chrome) wheelPixelsPerUnit = -.7; 3991 else if (safari) wheelPixelsPerUnit = -1/3; 3992 3993 var wheelEventDelta = function(e) { 3994 var dx = e.wheelDeltaX, dy = e.wheelDeltaY; 3995 if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; 3996 if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; 3997 else if (dy == null) dy = e.wheelDelta; 3998 return {x: dx, y: dy}; 3999 }; 4000 CodeMirror.wheelEventPixels = function(e) { 4001 var delta = wheelEventDelta(e); 4002 delta.x *= wheelPixelsPerUnit; 4003 delta.y *= wheelPixelsPerUnit; 4004 return delta; 4005 }; 4006 4007 function onScrollWheel(cm, e) { 4008 var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; 4009 4010 var display = cm.display, scroll = display.scroller; 4011 // Quit if there's nothing to scroll here 4012 var canScrollX = scroll.scrollWidth > scroll.clientWidth; 4013 var canScrollY = scroll.scrollHeight > scroll.clientHeight; 4014 if (!(dx && canScrollX || dy && canScrollY)) return; 4015 4016 // Webkit browsers on OS X abort momentum scrolls when the target 4017 // of the scroll event is removed from the scrollable element. 4018 // This hack (see related code in patchDisplay) makes sure the 4019 // element is kept around. 4020 if (dy && mac && webkit) { 4021 outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { 4022 for (var i = 0; i < view.length; i++) { 4023 if (view[i].node == cur) { 4024 cm.display.currentWheelTarget = cur; 4025 break outer; 4026 } 4027 } 4028 } 4029 } 4030 4031 // On some browsers, horizontal scrolling will cause redraws to 4032 // happen before the gutter has been realigned, causing it to 4033 // wriggle around in a most unseemly way. When we have an 4034 // estimated pixels/delta value, we just handle horizontal 4035 // scrolling entirely here. It'll be slightly off from native, but 4036 // better than glitching out. 4037 if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { 4038 if (dy && canScrollY) 4039 setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); 4040 setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); 4041 // Only prevent default scrolling if vertical scrolling is 4042 // actually possible. Otherwise, it causes vertical scroll 4043 // jitter on OSX trackpads when deltaX is small and deltaY 4044 // is large (issue #3579) 4045 if (!dy || (dy && canScrollY)) 4046 e_preventDefault(e); 4047 display.wheelStartX = null; // Abort measurement, if in progress 4048 return; 4049 } 4050 4051 // 'Project' the visible viewport to cover the area that is being 4052 // scrolled into view (if we know enough to estimate it). 4053 if (dy && wheelPixelsPerUnit != null) { 4054 var pixels = dy * wheelPixelsPerUnit; 4055 var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; 4056 if (pixels < 0) top = Math.max(0, top + pixels - 50); 4057 else bot = Math.min(cm.doc.height, bot + pixels + 50); 4058 updateDisplaySimple(cm, {top: top, bottom: bot}); 4059 } 4060 4061 if (wheelSamples < 20) { 4062 if (display.wheelStartX == null) { 4063 display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; 4064 display.wheelDX = dx; display.wheelDY = dy; 4065 setTimeout(function() { 4066 if (display.wheelStartX == null) return; 4067 var movedX = scroll.scrollLeft - display.wheelStartX; 4068 var movedY = scroll.scrollTop - display.wheelStartY; 4069 var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || 4070 (movedX && display.wheelDX && movedX / display.wheelDX); 4071 display.wheelStartX = display.wheelStartY = null; 4072 if (!sample) return; 4073 wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); 4074 ++wheelSamples; 4075 }, 200); 4076 } else { 4077 display.wheelDX += dx; display.wheelDY += dy; 4078 } 4079 } 4080 } 4081 4082 // KEY EVENTS 4083 4084 // Run a handler that was bound to a key. 4085 function doHandleBinding(cm, bound, dropShift) { 4086 if (typeof bound == "string") { 4087 bound = commands[bound]; 4088 if (!bound) return false; 4089 } 4090 // Ensure previous input has been read, so that the handler sees a 4091 // consistent view of the document 4092 cm.display.input.ensurePolled(); 4093 var prevShift = cm.display.shift, done = false; 4094 try { 4095 if (cm.isReadOnly()) cm.state.suppressEdits = true; 4096 if (dropShift) cm.display.shift = false; 4097 done = bound(cm) != Pass; 4098 } finally { 4099 cm.display.shift = prevShift; 4100 cm.state.suppressEdits = false; 4101 } 4102 return done; 4103 } 4104 4105 function lookupKeyForEditor(cm, name, handle) { 4106 for (var i = 0; i < cm.state.keyMaps.length; i++) { 4107 var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); 4108 if (result) return result; 4109 } 4110 return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) 4111 || lookupKey(name, cm.options.keyMap, handle, cm); 4112 } 4113 4114 var stopSeq = new Delayed; 4115 function dispatchKey(cm, name, e, handle) { 4116 var seq = cm.state.keySeq; 4117 if (seq) { 4118 if (isModifierKey(name)) return "handled"; 4119 stopSeq.set(50, function() { 4120 if (cm.state.keySeq == seq) { 4121 cm.state.keySeq = null; 4122 cm.display.input.reset(); 4123 } 4124 }); 4125 name = seq + " " + name; 4126 } 4127 var result = lookupKeyForEditor(cm, name, handle); 4128 4129 if (result == "multi") 4130 cm.state.keySeq = name; 4131 if (result == "handled") 4132 signalLater(cm, "keyHandled", cm, name, e); 4133 4134 if (result == "handled" || result == "multi") { 4135 e_preventDefault(e); 4136 restartBlink(cm); 4137 } 4138 4139 if (seq && !result && /\'$/.test(name)) { 4140 e_preventDefault(e); 4141 return true; 4142 } 4143 return !!result; 4144 } 4145 4146 // Handle a key from the keydown event. 4147 function handleKeyBinding(cm, e) { 4148 var name = keyName(e, true); 4149 if (!name) return false; 4150 4151 if (e.shiftKey && !cm.state.keySeq) { 4152 // First try to resolve full name (including 'Shift-'). Failing 4153 // that, see if there is a cursor-motion command (starting with 4154 // 'go') bound to the keyname without 'Shift-'. 4155 return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);}) 4156 || dispatchKey(cm, name, e, function(b) { 4157 if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) 4158 return doHandleBinding(cm, b); 4159 }); 4160 } else { 4161 return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); }); 4162 } 4163 } 4164 4165 // Handle a key from the keypress event 4166 function handleCharBinding(cm, e, ch) { 4167 return dispatchKey(cm, "'" + ch + "'", e, 4168 function(b) { return doHandleBinding(cm, b, true); }); 4169 } 4170 4171 var lastStoppedKey = null; 4172 function onKeyDown(e) { 4173 var cm = this; 4174 cm.curOp.focus = activeElt(); 4175 if (signalDOMEvent(cm, e)) return; 4176 // IE does strange things with escape. 4177 if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false; 4178 var code = e.keyCode; 4179 cm.display.shift = code == 16 || e.shiftKey; 4180 var handled = handleKeyBinding(cm, e); 4181 if (presto) { 4182 lastStoppedKey = handled ? code : null; 4183 // Opera has no cut event... we try to at least catch the key combo 4184 if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) 4185 cm.replaceSelection("", null, "cut"); 4186 } 4187 4188 // Turn mouse into crosshair when Alt is held on Mac. 4189 if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) 4190 showCrossHair(cm); 4191 } 4192 4193 function showCrossHair(cm) { 4194 var lineDiv = cm.display.lineDiv; 4195 addClass(lineDiv, "CodeMirror-crosshair"); 4196 4197 function up(e) { 4198 if (e.keyCode == 18 || !e.altKey) { 4199 rmClass(lineDiv, "CodeMirror-crosshair"); 4200 off(document, "keyup", up); 4201 off(document, "mouseover", up); 4202 } 4203 } 4204 on(document, "keyup", up); 4205 on(document, "mouseover", up); 4206 } 4207 4208 function onKeyUp(e) { 4209 if (e.keyCode == 16) this.doc.sel.shift = false; 4210 signalDOMEvent(this, e); 4211 } 4212 4213 function onKeyPress(e) { 4214 var cm = this; 4215 if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return; 4216 var keyCode = e.keyCode, charCode = e.charCode; 4217 if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} 4218 if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return; 4219 var ch = String.fromCharCode(charCode == null ? keyCode : charCode); 4220 if (handleCharBinding(cm, e, ch)) return; 4221 cm.display.input.onKeyPress(e); 4222 } 4223 4224 // FOCUS/BLUR EVENTS 4225 4226 function delayBlurEvent(cm) { 4227 cm.state.delayingBlurEvent = true; 4228 setTimeout(function() { 4229 if (cm.state.delayingBlurEvent) { 4230 cm.state.delayingBlurEvent = false; 4231 onBlur(cm); 4232 } 4233 }, 100); 4234 } 4235 4236 function onFocus(cm) { 4237 if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false; 4238 4239 if (cm.options.readOnly == "nocursor") return; 4240 if (!cm.state.focused) { 4241 signal(cm, "focus", cm); 4242 cm.state.focused = true; 4243 addClass(cm.display.wrapper, "CodeMirror-focused"); 4244 // This test prevents this from firing when a context 4245 // menu is closed (since the input reset would kill the 4246 // select-all detection hack) 4247 if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { 4248 cm.display.input.reset(); 4249 if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730 4250 } 4251 cm.display.input.receivedFocus(); 4252 } 4253 restartBlink(cm); 4254 } 4255 function onBlur(cm) { 4256 if (cm.state.delayingBlurEvent) return; 4257 4258 if (cm.state.focused) { 4259 signal(cm, "blur", cm); 4260 cm.state.focused = false; 4261 rmClass(cm.display.wrapper, "CodeMirror-focused"); 4262 } 4263 clearInterval(cm.display.blinker); 4264 setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150); 4265 } 4266 4267 // CONTEXT MENU HANDLING 4268 4269 // To make the context menu work, we need to briefly unhide the 4270 // textarea (making it as unobtrusive as possible) to let the 4271 // right-click take effect on it. 4272 function onContextMenu(cm, e) { 4273 if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return; 4274 if (signalDOMEvent(cm, e, "contextmenu")) return; 4275 cm.display.input.onContextMenu(e); 4276 } 4277 4278 function contextMenuInGutter(cm, e) { 4279 if (!hasHandler(cm, "gutterContextMenu")) return false; 4280 return gutterEvent(cm, e, "gutterContextMenu", false); 4281 } 4282 4283 // UPDATING 4284 4285 // Compute the position of the end of a change (its 'to' property 4286 // refers to the pre-change end). 4287 var changeEnd = CodeMirror.changeEnd = function(change) { 4288 if (!change.text) return change.to; 4289 return Pos(change.from.line + change.text.length - 1, 4290 lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); 4291 }; 4292 4293 // Adjust a position to refer to the post-change position of the 4294 // same text, or the end of the change if the change covers it. 4295 function adjustForChange(pos, change) { 4296 if (cmp(pos, change.from) < 0) return pos; 4297 if (cmp(pos, change.to) <= 0) return changeEnd(change); 4298 4299 var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; 4300 if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch; 4301 return Pos(line, ch); 4302 } 4303 4304 function computeSelAfterChange(doc, change) { 4305 var out = []; 4306 for (var i = 0; i < doc.sel.ranges.length; i++) { 4307 var range = doc.sel.ranges[i]; 4308 out.push(new Range(adjustForChange(range.anchor, change), 4309 adjustForChange(range.head, change))); 4310 } 4311 return normalizeSelection(out, doc.sel.primIndex); 4312 } 4313 4314 function offsetPos(pos, old, nw) { 4315 if (pos.line == old.line) 4316 return Pos(nw.line, pos.ch - old.ch + nw.ch); 4317 else 4318 return Pos(nw.line + (pos.line - old.line), pos.ch); 4319 } 4320 4321 // Used by replaceSelections to allow moving the selection to the 4322 // start or around the replaced test. Hint may be "start" or "around". 4323 function computeReplacedSel(doc, changes, hint) { 4324 var out = []; 4325 var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; 4326 for (var i = 0; i < changes.length; i++) { 4327 var change = changes[i]; 4328 var from = offsetPos(change.from, oldPrev, newPrev); 4329 var to = offsetPos(changeEnd(change), oldPrev, newPrev); 4330 oldPrev = change.to; 4331 newPrev = to; 4332 if (hint == "around") { 4333 var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; 4334 out[i] = new Range(inv ? to : from, inv ? from : to); 4335 } else { 4336 out[i] = new Range(from, from); 4337 } 4338 } 4339 return new Selection(out, doc.sel.primIndex); 4340 } 4341 4342 // Allow "beforeChange" event handlers to influence a change 4343 function filterChange(doc, change, update) { 4344 var obj = { 4345 canceled: false, 4346 from: change.from, 4347 to: change.to, 4348 text: change.text, 4349 origin: change.origin, 4350 cancel: function() { this.canceled = true; } 4351 }; 4352 if (update) obj.update = function(from, to, text, origin) { 4353 if (from) this.from = clipPos(doc, from); 4354 if (to) this.to = clipPos(doc, to); 4355 if (text) this.text = text; 4356 if (origin !== undefined) this.origin = origin; 4357 }; 4358 signal(doc, "beforeChange", doc, obj); 4359 if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); 4360 4361 if (obj.canceled) return null; 4362 return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; 4363 } 4364 4365 // Apply a change to a document, and add it to the document's 4366 // history, and propagating it to all linked documents. 4367 function makeChange(doc, change, ignoreReadOnly) { 4368 if (doc.cm) { 4369 if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); 4370 if (doc.cm.state.suppressEdits) return; 4371 } 4372 4373 if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { 4374 change = filterChange(doc, change, true); 4375 if (!change) return; 4376 } 4377 4378 // Possibly split or suppress the update based on the presence 4379 // of read-only spans in its range. 4380 var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); 4381 if (split) { 4382 for (var i = split.length - 1; i >= 0; --i) 4383 makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}); 4384 } else { 4385 makeChangeInner(doc, change); 4386 } 4387 } 4388 4389 function makeChangeInner(doc, change) { 4390 if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return; 4391 var selAfter = computeSelAfterChange(doc, change); 4392 addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); 4393 4394 makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); 4395 var rebased = []; 4396 4397 linkedDocs(doc, function(doc, sharedHist) { 4398 if (!sharedHist && indexOf(rebased, doc.history) == -1) { 4399 rebaseHist(doc.history, change); 4400 rebased.push(doc.history); 4401 } 4402 makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); 4403 }); 4404 } 4405 4406 // Revert a change stored in a document's history. 4407 function makeChangeFromHistory(doc, type, allowSelectionOnly) { 4408 if (doc.cm && doc.cm.state.suppressEdits) return; 4409 4410 var hist = doc.history, event, selAfter = doc.sel; 4411 var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; 4412 4413 // Verify that there is a useable event (so that ctrl-z won't 4414 // needlessly clear selection events) 4415 for (var i = 0; i < source.length; i++) { 4416 event = source[i]; 4417 if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) 4418 break; 4419 } 4420 if (i == source.length) return; 4421 hist.lastOrigin = hist.lastSelOrigin = null; 4422 4423 for (;;) { 4424 event = source.pop(); 4425 if (event.ranges) { 4426 pushSelectionToHistory(event, dest); 4427 if (allowSelectionOnly && !event.equals(doc.sel)) { 4428 setSelection(doc, event, {clearRedo: false}); 4429 return; 4430 } 4431 selAfter = event; 4432 } 4433 else break; 4434 } 4435 4436 // Build up a reverse change object to add to the opposite history 4437 // stack (redo when undoing, and vice versa). 4438 var antiChanges = []; 4439 pushSelectionToHistory(selAfter, dest); 4440 dest.push({changes: antiChanges, generation: hist.generation}); 4441 hist.generation = event.generation || ++hist.maxGeneration; 4442 4443 var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); 4444 4445 for (var i = event.changes.length - 1; i >= 0; --i) { 4446 var change = event.changes[i]; 4447 change.origin = type; 4448 if (filter && !filterChange(doc, change, false)) { 4449 source.length = 0; 4450 return; 4451 } 4452 4453 antiChanges.push(historyChangeFromChange(doc, change)); 4454 4455 var after = i ? computeSelAfterChange(doc, change) : lst(source); 4456 makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); 4457 if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); 4458 var rebased = []; 4459 4460 // Propagate to the linked documents 4461 linkedDocs(doc, function(doc, sharedHist) { 4462 if (!sharedHist && indexOf(rebased, doc.history) == -1) { 4463 rebaseHist(doc.history, change); 4464 rebased.push(doc.history); 4465 } 4466 makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); 4467 }); 4468 } 4469 } 4470 4471 // Sub-views need their line numbers shifted when text is added 4472 // above or below them in the parent document. 4473 function shiftDoc(doc, distance) { 4474 if (distance == 0) return; 4475 doc.first += distance; 4476 doc.sel = new Selection(map(doc.sel.ranges, function(range) { 4477 return new Range(Pos(range.anchor.line + distance, range.anchor.ch), 4478 Pos(range.head.line + distance, range.head.ch)); 4479 }), doc.sel.primIndex); 4480 if (doc.cm) { 4481 regChange(doc.cm, doc.first, doc.first - distance, distance); 4482 for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) 4483 regLineChange(doc.cm, l, "gutter"); 4484 } 4485 } 4486 4487 // More lower-level change function, handling only a single document 4488 // (not linked ones). 4489 function makeChangeSingleDoc(doc, change, selAfter, spans) { 4490 if (doc.cm && !doc.cm.curOp) 4491 return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); 4492 4493 if (change.to.line < doc.first) { 4494 shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); 4495 return; 4496 } 4497 if (change.from.line > doc.lastLine()) return; 4498 4499 // Clip the change to the size of this doc 4500 if (change.from.line < doc.first) { 4501 var shift = change.text.length - 1 - (doc.first - change.from.line); 4502 shiftDoc(doc, shift); 4503 change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), 4504 text: [lst(change.text)], origin: change.origin}; 4505 } 4506 var last = doc.lastLine(); 4507 if (change.to.line > last) { 4508 change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), 4509 text: [change.text[0]], origin: change.origin}; 4510 } 4511 4512 change.removed = getBetween(doc, change.from, change.to); 4513 4514 if (!selAfter) selAfter = computeSelAfterChange(doc, change); 4515 if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans); 4516 else updateDoc(doc, change, spans); 4517 setSelectionNoUndo(doc, selAfter, sel_dontScroll); 4518 } 4519 4520 // Handle the interaction of a change to a document with the editor 4521 // that this document is part of. 4522 function makeChangeSingleDocInEditor(cm, change, spans) { 4523 var doc = cm.doc, display = cm.display, from = change.from, to = change.to; 4524 4525 var recomputeMaxLength = false, checkWidthStart = from.line; 4526 if (!cm.options.lineWrapping) { 4527 checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); 4528 doc.iter(checkWidthStart, to.line + 1, function(line) { 4529 if (line == display.maxLine) { 4530 recomputeMaxLength = true; 4531 return true; 4532 } 4533 }); 4534 } 4535 4536 if (doc.sel.contains(change.from, change.to) > -1) 4537 signalCursorActivity(cm); 4538 4539 updateDoc(doc, change, spans, estimateHeight(cm)); 4540 4541 if (!cm.options.lineWrapping) { 4542 doc.iter(checkWidthStart, from.line + change.text.length, function(line) { 4543 var len = lineLength(line); 4544 if (len > display.maxLineLength) { 4545 display.maxLine = line; 4546 display.maxLineLength = len; 4547 display.maxLineChanged = true; 4548 recomputeMaxLength = false; 4549 } 4550 }); 4551 if (recomputeMaxLength) cm.curOp.updateMaxLine = true; 4552 } 4553 4554 // Adjust frontier, schedule worker 4555 doc.frontier = Math.min(doc.frontier, from.line); 4556 startWorker(cm, 400); 4557 4558 var lendiff = change.text.length - (to.line - from.line) - 1; 4559 // Remember that these lines changed, for updating the display 4560 if (change.full) 4561 regChange(cm); 4562 else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) 4563 regLineChange(cm, from.line, "text"); 4564 else 4565 regChange(cm, from.line, to.line + 1, lendiff); 4566 4567 var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); 4568 if (changeHandler || changesHandler) { 4569 var obj = { 4570 from: from, to: to, 4571 text: change.text, 4572 removed: change.removed, 4573 origin: change.origin 4574 }; 4575 if (changeHandler) signalLater(cm, "change", cm, obj); 4576 if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); 4577 } 4578 cm.display.selForContextMenu = null; 4579 } 4580 4581 function replaceRange(doc, code, from, to, origin) { 4582 if (!to) to = from; 4583 if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } 4584 if (typeof code == "string") code = doc.splitLines(code); 4585 makeChange(doc, {from: from, to: to, text: code, origin: origin}); 4586 } 4587 4588 // SCROLLING THINGS INTO VIEW 4589 4590 // If an editor sits on the top or bottom of the window, partially 4591 // scrolled out of view, this ensures that the cursor is visible. 4592 function maybeScrollWindow(cm, coords) { 4593 if (signalDOMEvent(cm, "scrollCursorIntoView")) return; 4594 4595 var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; 4596 if (coords.top + box.top < 0) doScroll = true; 4597 else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; 4598 if (doScroll != null && !phantom) { 4599 var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " + 4600 (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " + 4601 (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " + 4602 coords.left + "px; width: 2px;"); 4603 cm.display.lineSpace.appendChild(scrollNode); 4604 scrollNode.scrollIntoView(doScroll); 4605 cm.display.lineSpace.removeChild(scrollNode); 4606 } 4607 } 4608 4609 // Scroll a given position into view (immediately), verifying that 4610 // it actually became visible (as line heights are accurately 4611 // measured, the position of something may 'drift' during drawing). 4612 function scrollPosIntoView(cm, pos, end, margin) { 4613 if (margin == null) margin = 0; 4614 for (var limit = 0; limit < 5; limit++) { 4615 var changed = false, coords = cursorCoords(cm, pos); 4616 var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); 4617 var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), 4618 Math.min(coords.top, endCoords.top) - margin, 4619 Math.max(coords.left, endCoords.left), 4620 Math.max(coords.bottom, endCoords.bottom) + margin); 4621 var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; 4622 if (scrollPos.scrollTop != null) { 4623 setScrollTop(cm, scrollPos.scrollTop); 4624 if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; 4625 } 4626 if (scrollPos.scrollLeft != null) { 4627 setScrollLeft(cm, scrollPos.scrollLeft); 4628 if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; 4629 } 4630 if (!changed) break; 4631 } 4632 return coords; 4633 } 4634 4635 // Scroll a given set of coordinates into view (immediately). 4636 function scrollIntoView(cm, x1, y1, x2, y2) { 4637 var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); 4638 if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); 4639 if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); 4640 } 4641 4642 // Calculate a new scroll position needed to scroll the given 4643 // rectangle into view. Returns an object with scrollTop and 4644 // scrollLeft properties. When these are undefined, the 4645 // vertical/horizontal position does not need to be adjusted. 4646 function calculateScrollPos(cm, x1, y1, x2, y2) { 4647 var display = cm.display, snapMargin = textHeight(cm.display); 4648 if (y1 < 0) y1 = 0; 4649 var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; 4650 var screen = displayHeight(cm), result = {}; 4651 if (y2 - y1 > screen) y2 = y1 + screen; 4652 var docBottom = cm.doc.height + paddingVert(display); 4653 var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; 4654 if (y1 < screentop) { 4655 result.scrollTop = atTop ? 0 : y1; 4656 } else if (y2 > screentop + screen) { 4657 var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); 4658 if (newTop != screentop) result.scrollTop = newTop; 4659 } 4660 4661 var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; 4662 var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); 4663 var tooWide = x2 - x1 > screenw; 4664 if (tooWide) x2 = x1 + screenw; 4665 if (x1 < 10) 4666 result.scrollLeft = 0; 4667 else if (x1 < screenleft) 4668 result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)); 4669 else if (x2 > screenw + screenleft - 3) 4670 result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw; 4671 return result; 4672 } 4673 4674 // Store a relative adjustment to the scroll position in the current 4675 // operation (to be applied when the operation finishes). 4676 function addToScrollPos(cm, left, top) { 4677 if (left != null || top != null) resolveScrollToPos(cm); 4678 if (left != null) 4679 cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left; 4680 if (top != null) 4681 cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; 4682 } 4683 4684 // Make sure that at the end of the operation the current cursor is 4685 // shown. 4686 function ensureCursorVisible(cm) { 4687 resolveScrollToPos(cm); 4688 var cur = cm.getCursor(), from = cur, to = cur; 4689 if (!cm.options.lineWrapping) { 4690 from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; 4691 to = Pos(cur.line, cur.ch + 1); 4692 } 4693 cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}; 4694 } 4695 4696 // When an operation has its scrollToPos property set, and another 4697 // scroll action is applied before the end of the operation, this 4698 // 'simulates' scrolling that position into view in a cheap way, so 4699 // that the effect of intermediate scroll commands is not ignored. 4700 function resolveScrollToPos(cm) { 4701 var range = cm.curOp.scrollToPos; 4702 if (range) { 4703 cm.curOp.scrollToPos = null; 4704 var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); 4705 var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), 4706 Math.min(from.top, to.top) - range.margin, 4707 Math.max(from.right, to.right), 4708 Math.max(from.bottom, to.bottom) + range.margin); 4709 cm.scrollTo(sPos.scrollLeft, sPos.scrollTop); 4710 } 4711 } 4712 4713 // API UTILITIES 4714 4715 // Indent the given line. The how parameter can be "smart", 4716 // "add"/null, "subtract", or "prev". When aggressive is false 4717 // (typically set to true for forced single-line indents), empty 4718 // lines are not indented, and places where the mode returns Pass 4719 // are left alone. 4720 function indentLine(cm, n, how, aggressive) { 4721 var doc = cm.doc, state; 4722 if (how == null) how = "add"; 4723 if (how == "smart") { 4724 // Fall back to "prev" when the mode doesn't have an indentation 4725 // method. 4726 if (!doc.mode.indent) how = "prev"; 4727 else state = getStateBefore(cm, n); 4728 } 4729 4730 var tabSize = cm.options.tabSize; 4731 var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); 4732 if (line.stateAfter) line.stateAfter = null; 4733 var curSpaceString = line.text.match(/^\s*/)[0], indentation; 4734 if (!aggressive && !/\S/.test(line.text)) { 4735 indentation = 0; 4736 how = "not"; 4737 } else if (how == "smart") { 4738 indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); 4739 if (indentation == Pass || indentation > 150) { 4740 if (!aggressive) return; 4741 how = "prev"; 4742 } 4743 } 4744 if (how == "prev") { 4745 if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); 4746 else indentation = 0; 4747 } else if (how == "add") { 4748 indentation = curSpace + cm.options.indentUnit; 4749 } else if (how == "subtract") { 4750 indentation = curSpace - cm.options.indentUnit; 4751 } else if (typeof how == "number") { 4752 indentation = curSpace + how; 4753 } 4754 indentation = Math.max(0, indentation); 4755 4756 var indentString = "", pos = 0; 4757 if (cm.options.indentWithTabs) 4758 for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} 4759 if (pos < indentation) indentString += spaceStr(indentation - pos); 4760 4761 if (indentString != curSpaceString) { 4762 replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); 4763 line.stateAfter = null; 4764 return true; 4765 } else { 4766 // Ensure that, if the cursor was in the whitespace at the start 4767 // of the line, it is moved to the end of that space. 4768 for (var i = 0; i < doc.sel.ranges.length; i++) { 4769 var range = doc.sel.ranges[i]; 4770 if (range.head.line == n && range.head.ch < curSpaceString.length) { 4771 var pos = Pos(n, curSpaceString.length); 4772 replaceOneSelection(doc, i, new Range(pos, pos)); 4773 break; 4774 } 4775 } 4776 } 4777 } 4778 4779 // Utility for applying a change to a line by handle or number, 4780 // returning the number and optionally registering the line as 4781 // changed. 4782 function changeLine(doc, handle, changeType, op) { 4783 var no = handle, line = handle; 4784 if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); 4785 else no = lineNo(handle); 4786 if (no == null) return null; 4787 if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType); 4788 return line; 4789 } 4790 4791 // Helper for deleting text near the selection(s), used to implement 4792 // backspace, delete, and similar functionality. 4793 function deleteNearSelection(cm, compute) { 4794 var ranges = cm.doc.sel.ranges, kill = []; 4795 // Build up a set of ranges to kill first, merging overlapping 4796 // ranges. 4797 for (var i = 0; i < ranges.length; i++) { 4798 var toKill = compute(ranges[i]); 4799 while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { 4800 var replaced = kill.pop(); 4801 if (cmp(replaced.from, toKill.from) < 0) { 4802 toKill.from = replaced.from; 4803 break; 4804 } 4805 } 4806 kill.push(toKill); 4807 } 4808 // Next, remove those actual ranges. 4809 runInOp(cm, function() { 4810 for (var i = kill.length - 1; i >= 0; i--) 4811 replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); 4812 ensureCursorVisible(cm); 4813 }); 4814 } 4815 4816 // Used for horizontal relative motion. Dir is -1 or 1 (left or 4817 // right), unit can be "char", "column" (like char, but doesn't 4818 // cross line boundaries), "word" (across next word), or "group" (to 4819 // the start of next group of word or non-word-non-whitespace 4820 // chars). The visually param controls whether, in right-to-left 4821 // text, direction 1 means to move towards the next index in the 4822 // string, or towards the character to the right of the current 4823 // position. The resulting position will have a hitSide=true 4824 // property if it reached the end of the document. 4825 function findPosH(doc, pos, dir, unit, visually) { 4826 var line = pos.line, ch = pos.ch, origDir = dir; 4827 var lineObj = getLine(doc, line); 4828 function findNextLine() { 4829 var l = line + dir; 4830 if (l < doc.first || l >= doc.first + doc.size) return false 4831 line = l; 4832 return lineObj = getLine(doc, l); 4833 } 4834 function moveOnce(boundToLine) { 4835 var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); 4836 if (next == null) { 4837 if (!boundToLine && findNextLine()) { 4838 if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); 4839 else ch = dir < 0 ? lineObj.text.length : 0; 4840 } else return false 4841 } else ch = next; 4842 return true; 4843 } 4844 4845 if (unit == "char") { 4846 moveOnce() 4847 } else if (unit == "column") { 4848 moveOnce(true) 4849 } else if (unit == "word" || unit == "group") { 4850 var sawType = null, group = unit == "group"; 4851 var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); 4852 for (var first = true;; first = false) { 4853 if (dir < 0 && !moveOnce(!first)) break; 4854 var cur = lineObj.text.charAt(ch) || "\n"; 4855 var type = isWordChar(cur, helper) ? "w" 4856 : group && cur == "\n" ? "n" 4857 : !group || /\s/.test(cur) ? null 4858 : "p"; 4859 if (group && !first && !type) type = "s"; 4860 if (sawType && sawType != type) { 4861 if (dir < 0) {dir = 1; moveOnce();} 4862 break; 4863 } 4864 4865 if (type) sawType = type; 4866 if (dir > 0 && !moveOnce(!first)) break; 4867 } 4868 } 4869 var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true); 4870 if (!cmp(pos, result)) result.hitSide = true; 4871 return result; 4872 } 4873 4874 // For relative vertical movement. Dir may be -1 or 1. Unit can be 4875 // "page" or "line". The resulting position will have a hitSide=true 4876 // property if it reached the end of the document. 4877 function findPosV(cm, pos, dir, unit) { 4878 var doc = cm.doc, x = pos.left, y; 4879 if (unit == "page") { 4880 var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); 4881 y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display)); 4882 } else if (unit == "line") { 4883 y = dir > 0 ? pos.bottom + 3 : pos.top - 3; 4884 } 4885 for (;;) { 4886 var target = coordsChar(cm, x, y); 4887 if (!target.outside) break; 4888 if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } 4889 y += dir * 5; 4890 } 4891 return target; 4892 } 4893 4894 // EDITOR METHODS 4895 4896 // The publicly visible API. Note that methodOp(f) means 4897 // 'wrap f in an operation, performed on its `this` parameter'. 4898 4899 // This is not the complete set of editor methods. Most of the 4900 // methods defined on the Doc type are also injected into 4901 // CodeMirror.prototype, for backwards compatibility and 4902 // convenience. 4903 4904 CodeMirror.prototype = { 4905 constructor: CodeMirror, 4906 focus: function(){window.focus(); this.display.input.focus();}, 4907 4908 setOption: function(option, value) { 4909 var options = this.options, old = options[option]; 4910 if (options[option] == value && option != "mode") return; 4911 options[option] = value; 4912 if (optionHandlers.hasOwnProperty(option)) 4913 operation(this, optionHandlers[option])(this, value, old); 4914 }, 4915 4916 getOption: function(option) {return this.options[option];}, 4917 getDoc: function() {return this.doc;}, 4918 4919 addKeyMap: function(map, bottom) { 4920 this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)); 4921 }, 4922 removeKeyMap: function(map) { 4923 var maps = this.state.keyMaps; 4924 for (var i = 0; i < maps.length; ++i) 4925 if (maps[i] == map || maps[i].name == map) { 4926 maps.splice(i, 1); 4927 return true; 4928 } 4929 }, 4930 4931 addOverlay: methodOp(function(spec, options) { 4932 var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); 4933 if (mode.startState) throw new Error("Overlays may not be stateful."); 4934 this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); 4935 this.state.modeGen++; 4936 regChange(this); 4937 }), 4938 removeOverlay: methodOp(function(spec) { 4939 var overlays = this.state.overlays; 4940 for (var i = 0; i < overlays.length; ++i) { 4941 var cur = overlays[i].modeSpec; 4942 if (cur == spec || typeof spec == "string" && cur.name == spec) { 4943 overlays.splice(i, 1); 4944 this.state.modeGen++; 4945 regChange(this); 4946 return; 4947 } 4948 } 4949 }), 4950 4951 indentLine: methodOp(function(n, dir, aggressive) { 4952 if (typeof dir != "string" && typeof dir != "number") { 4953 if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; 4954 else dir = dir ? "add" : "subtract"; 4955 } 4956 if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); 4957 }), 4958 indentSelection: methodOp(function(how) { 4959 var ranges = this.doc.sel.ranges, end = -1; 4960 for (var i = 0; i < ranges.length; i++) { 4961 var range = ranges[i]; 4962 if (!range.empty()) { 4963 var from = range.from(), to = range.to(); 4964 var start = Math.max(end, from.line); 4965 end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; 4966 for (var j = start; j < end; ++j) 4967 indentLine(this, j, how); 4968 var newRanges = this.doc.sel.ranges; 4969 if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) 4970 replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); 4971 } else if (range.head.line > end) { 4972 indentLine(this, range.head.line, how, true); 4973 end = range.head.line; 4974 if (i == this.doc.sel.primIndex) ensureCursorVisible(this); 4975 } 4976 } 4977 }), 4978 4979 // Fetch the parser token for a given character. Useful for hacks 4980 // that want to inspect the mode state (say, for completion). 4981 getTokenAt: function(pos, precise) { 4982 return takeToken(this, pos, precise); 4983 }, 4984 4985 getLineTokens: function(line, precise) { 4986 return takeToken(this, Pos(line), precise, true); 4987 }, 4988 4989 getTokenTypeAt: function(pos) { 4990 pos = clipPos(this.doc, pos); 4991 var styles = getLineStyles(this, getLine(this.doc, pos.line)); 4992 var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; 4993 var type; 4994 if (ch == 0) type = styles[2]; 4995 else for (;;) { 4996 var mid = (before + after) >> 1; 4997 if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; 4998 else if (styles[mid * 2 + 1] < ch) before = mid + 1; 4999 else { type = styles[mid * 2 + 2]; break; } 5000 } 5001 var cut = type ? type.indexOf("cm-overlay ") : -1; 5002 return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); 5003 }, 5004 5005 getModeAt: function(pos) { 5006 var mode = this.doc.mode; 5007 if (!mode.innerMode) return mode; 5008 return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; 5009 }, 5010 5011 getHelper: function(pos, type) { 5012 return this.getHelpers(pos, type)[0]; 5013 }, 5014 5015 getHelpers: function(pos, type) { 5016 var found = []; 5017 if (!helpers.hasOwnProperty(type)) return found; 5018 var help = helpers[type], mode = this.getModeAt(pos); 5019 if (typeof mode[type] == "string") { 5020 if (help[mode[type]]) found.push(help[mode[type]]); 5021 } else if (mode[type]) { 5022 for (var i = 0; i < mode[type].length; i++) { 5023 var val = help[mode[type][i]]; 5024 if (val) found.push(val); 5025 } 5026 } else if (mode.helperType && help[mode.helperType]) { 5027 found.push(help[mode.helperType]); 5028 } else if (help[mode.name]) { 5029 found.push(help[mode.name]); 5030 } 5031 for (var i = 0; i < help._global.length; i++) { 5032 var cur = help._global[i]; 5033 if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) 5034 found.push(cur.val); 5035 } 5036 return found; 5037 }, 5038 5039 getStateAfter: function(line, precise) { 5040 var doc = this.doc; 5041 line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); 5042 return getStateBefore(this, line + 1, precise); 5043 }, 5044 5045 cursorCoords: function(start, mode) { 5046 var pos, range = this.doc.sel.primary(); 5047 if (start == null) pos = range.head; 5048 else if (typeof start == "object") pos = clipPos(this.doc, start); 5049 else pos = start ? range.from() : range.to(); 5050 return cursorCoords(this, pos, mode || "page"); 5051 }, 5052 5053 charCoords: function(pos, mode) { 5054 return charCoords(this, clipPos(this.doc, pos), mode || "page"); 5055 }, 5056 5057 coordsChar: function(coords, mode) { 5058 coords = fromCoordSystem(this, coords, mode || "page"); 5059 return coordsChar(this, coords.left, coords.top); 5060 }, 5061 5062 lineAtHeight: function(height, mode) { 5063 height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; 5064 return lineAtHeight(this.doc, height + this.display.viewOffset); 5065 }, 5066 heightAtLine: function(line, mode) { 5067 var end = false, lineObj; 5068 if (typeof line == "number") { 5069 var last = this.doc.first + this.doc.size - 1; 5070 if (line < this.doc.first) line = this.doc.first; 5071 else if (line > last) { line = last; end = true; } 5072 lineObj = getLine(this.doc, line); 5073 } else { 5074 lineObj = line; 5075 } 5076 return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top + 5077 (end ? this.doc.height - heightAtLine(lineObj) : 0); 5078 }, 5079 5080 defaultTextHeight: function() { return textHeight(this.display); }, 5081 defaultCharWidth: function() { return charWidth(this.display); }, 5082 5083 setGutterMarker: methodOp(function(line, gutterID, value) { 5084 return changeLine(this.doc, line, "gutter", function(line) { 5085 var markers = line.gutterMarkers || (line.gutterMarkers = {}); 5086 markers[gutterID] = value; 5087 if (!value && isEmpty(markers)) line.gutterMarkers = null; 5088 return true; 5089 }); 5090 }), 5091 5092 clearGutter: methodOp(function(gutterID) { 5093 var cm = this, doc = cm.doc, i = doc.first; 5094 doc.iter(function(line) { 5095 if (line.gutterMarkers && line.gutterMarkers[gutterID]) { 5096 line.gutterMarkers[gutterID] = null; 5097 regLineChange(cm, i, "gutter"); 5098 if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; 5099 } 5100 ++i; 5101 }); 5102 }), 5103 5104 lineInfo: function(line) { 5105 if (typeof line == "number") { 5106 if (!isLine(this.doc, line)) return null; 5107 var n = line; 5108 line = getLine(this.doc, line); 5109 if (!line) return null; 5110 } else { 5111 var n = lineNo(line); 5112 if (n == null) return null; 5113 } 5114 return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, 5115 textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, 5116 widgets: line.widgets}; 5117 }, 5118 5119 getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};}, 5120 5121 addWidget: function(pos, node, scroll, vert, horiz) { 5122 var display = this.display; 5123 pos = cursorCoords(this, clipPos(this.doc, pos)); 5124 var top = pos.bottom, left = pos.left; 5125 node.style.position = "absolute"; 5126 node.setAttribute("cm-ignore-events", "true"); 5127 this.display.input.setUneditable(node); 5128 display.sizer.appendChild(node); 5129 if (vert == "over") { 5130 top = pos.top; 5131 } else if (vert == "above" || vert == "near") { 5132 var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), 5133 hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); 5134 // Default to positioning above (if specified and possible); otherwise default to positioning below 5135 if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) 5136 top = pos.top - node.offsetHeight; 5137 else if (pos.bottom + node.offsetHeight <= vspace) 5138 top = pos.bottom; 5139 if (left + node.offsetWidth > hspace) 5140 left = hspace - node.offsetWidth; 5141 } 5142 node.style.top = top + "px"; 5143 node.style.left = node.style.right = ""; 5144 if (horiz == "right") { 5145 left = display.sizer.clientWidth - node.offsetWidth; 5146 node.style.right = "0px"; 5147 } else { 5148 if (horiz == "left") left = 0; 5149 else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; 5150 node.style.left = left + "px"; 5151 } 5152 if (scroll) 5153 scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight); 5154 }, 5155 5156 triggerOnKeyDown: methodOp(onKeyDown), 5157 triggerOnKeyPress: methodOp(onKeyPress), 5158 triggerOnKeyUp: onKeyUp, 5159 5160 execCommand: function(cmd) { 5161 if (commands.hasOwnProperty(cmd)) 5162 return commands[cmd].call(null, this); 5163 }, 5164 5165 triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), 5166 5167 findPosH: function(from, amount, unit, visually) { 5168 var dir = 1; 5169 if (amount < 0) { dir = -1; amount = -amount; } 5170 for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { 5171 cur = findPosH(this.doc, cur, dir, unit, visually); 5172 if (cur.hitSide) break; 5173 } 5174 return cur; 5175 }, 5176 5177 moveH: methodOp(function(dir, unit) { 5178 var cm = this; 5179 cm.extendSelectionsBy(function(range) { 5180 if (cm.display.shift || cm.doc.extend || range.empty()) 5181 return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually); 5182 else 5183 return dir < 0 ? range.from() : range.to(); 5184 }, sel_move); 5185 }), 5186 5187 deleteH: methodOp(function(dir, unit) { 5188 var sel = this.doc.sel, doc = this.doc; 5189 if (sel.somethingSelected()) 5190 doc.replaceSelection("", null, "+delete"); 5191 else 5192 deleteNearSelection(this, function(range) { 5193 var other = findPosH(doc, range.head, dir, unit, false); 5194 return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}; 5195 }); 5196 }), 5197 5198 findPosV: function(from, amount, unit, goalColumn) { 5199 var dir = 1, x = goalColumn; 5200 if (amount < 0) { dir = -1; amount = -amount; } 5201 for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { 5202 var coords = cursorCoords(this, cur, "div"); 5203 if (x == null) x = coords.left; 5204 else coords.left = x; 5205 cur = findPosV(this, coords, dir, unit); 5206 if (cur.hitSide) break; 5207 } 5208 return cur; 5209 }, 5210 5211 moveV: methodOp(function(dir, unit) { 5212 var cm = this, doc = this.doc, goals = []; 5213 var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected(); 5214 doc.extendSelectionsBy(function(range) { 5215 if (collapse) 5216 return dir < 0 ? range.from() : range.to(); 5217 var headPos = cursorCoords(cm, range.head, "div"); 5218 if (range.goalColumn != null) headPos.left = range.goalColumn; 5219 goals.push(headPos.left); 5220 var pos = findPosV(cm, headPos, dir, unit); 5221 if (unit == "page" && range == doc.sel.primary()) 5222 addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top); 5223 return pos; 5224 }, sel_move); 5225 if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++) 5226 doc.sel.ranges[i].goalColumn = goals[i]; 5227 }), 5228 5229 // Find the word at the given position (as returned by coordsChar). 5230 findWordAt: function(pos) { 5231 var doc = this.doc, line = getLine(doc, pos.line).text; 5232 var start = pos.ch, end = pos.ch; 5233 if (line) { 5234 var helper = this.getHelper(pos, "wordChars"); 5235 if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; 5236 var startChar = line.charAt(start); 5237 var check = isWordChar(startChar, helper) 5238 ? function(ch) { return isWordChar(ch, helper); } 5239 : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} 5240 : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; 5241 while (start > 0 && check(line.charAt(start - 1))) --start; 5242 while (end < line.length && check(line.charAt(end))) ++end; 5243 } 5244 return new Range(Pos(pos.line, start), Pos(pos.line, end)); 5245 }, 5246 5247 toggleOverwrite: function(value) { 5248 if (value != null && value == this.state.overwrite) return; 5249 if (this.state.overwrite = !this.state.overwrite) 5250 addClass(this.display.cursorDiv, "CodeMirror-overwrite"); 5251 else 5252 rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); 5253 5254 signal(this, "overwriteToggle", this, this.state.overwrite); 5255 }, 5256 hasFocus: function() { return this.display.input.getField() == activeElt(); }, 5257 isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit); }, 5258 5259 scrollTo: methodOp(function(x, y) { 5260 if (x != null || y != null) resolveScrollToPos(this); 5261 if (x != null) this.curOp.scrollLeft = x; 5262 if (y != null) this.curOp.scrollTop = y; 5263 }), 5264 getScrollInfo: function() { 5265 var scroller = this.display.scroller; 5266 return {left: scroller.scrollLeft, top: scroller.scrollTop, 5267 height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, 5268 width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, 5269 clientHeight: displayHeight(this), clientWidth: displayWidth(this)}; 5270 }, 5271 5272 scrollIntoView: methodOp(function(range, margin) { 5273 if (range == null) { 5274 range = {from: this.doc.sel.primary().head, to: null}; 5275 if (margin == null) margin = this.options.cursorScrollMargin; 5276 } else if (typeof range == "number") { 5277 range = {from: Pos(range, 0), to: null}; 5278 } else if (range.from == null) { 5279 range = {from: range, to: null}; 5280 } 5281 if (!range.to) range.to = range.from; 5282 range.margin = margin || 0; 5283 5284 if (range.from.line != null) { 5285 resolveScrollToPos(this); 5286 this.curOp.scrollToPos = range; 5287 } else { 5288 var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left), 5289 Math.min(range.from.top, range.to.top) - range.margin, 5290 Math.max(range.from.right, range.to.right), 5291 Math.max(range.from.bottom, range.to.bottom) + range.margin); 5292 this.scrollTo(sPos.scrollLeft, sPos.scrollTop); 5293 } 5294 }), 5295 5296 setSize: methodOp(function(width, height) { 5297 var cm = this; 5298 function interpret(val) { 5299 return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; 5300 } 5301 if (width != null) cm.display.wrapper.style.width = interpret(width); 5302 if (height != null) cm.display.wrapper.style.height = interpret(height); 5303 if (cm.options.lineWrapping) clearLineMeasurementCache(this); 5304 var lineNo = cm.display.viewFrom; 5305 cm.doc.iter(lineNo, cm.display.viewTo, function(line) { 5306 if (line.widgets) for (var i = 0; i < line.widgets.length; i++) 5307 if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; } 5308 ++lineNo; 5309 }); 5310 cm.curOp.forceUpdate = true; 5311 signal(cm, "refresh", this); 5312 }), 5313 5314 operation: function(f){return runInOp(this, f);}, 5315 5316 refresh: methodOp(function() { 5317 var oldHeight = this.display.cachedTextHeight; 5318 regChange(this); 5319 this.curOp.forceUpdate = true; 5320 clearCaches(this); 5321 this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop); 5322 updateGutterSpace(this); 5323 if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) 5324 estimateLineHeights(this); 5325 signal(this, "refresh", this); 5326 }), 5327 5328 swapDoc: methodOp(function(doc) { 5329 var old = this.doc; 5330 old.cm = null; 5331 attachDoc(this, doc); 5332 clearCaches(this); 5333 this.display.input.reset(); 5334 this.scrollTo(doc.scrollLeft, doc.scrollTop); 5335 this.curOp.forceScroll = true; 5336 signalLater(this, "swapDoc", this, old); 5337 return old; 5338 }), 5339 5340 getInputField: function(){return this.display.input.getField();}, 5341 getWrapperElement: function(){return this.display.wrapper;}, 5342 getScrollerElement: function(){return this.display.scroller;}, 5343 getGutterElement: function(){return this.display.gutters;} 5344 }; 5345 eventMixin(CodeMirror); 5346 5347 // OPTION DEFAULTS 5348 5349 // The default configuration options. 5350 var defaults = CodeMirror.defaults = {}; 5351 // Functions to run when options are changed. 5352 var optionHandlers = CodeMirror.optionHandlers = {}; 5353 5354 function option(name, deflt, handle, notOnInit) { 5355 CodeMirror.defaults[name] = deflt; 5356 if (handle) optionHandlers[name] = 5357 notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; 5358 } 5359 5360 // Passed to option handlers when there is no old value. 5361 var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; 5362 5363 // These two are, on init, called from the constructor because they 5364 // have to be initialized before the editor can start at all. 5365 option("value", "", function(cm, val) { 5366 cm.setValue(val); 5367 }, true); 5368 option("mode", null, function(cm, val) { 5369 cm.doc.modeOption = val; 5370 loadMode(cm); 5371 }, true); 5372 5373 option("indentUnit", 2, loadMode, true); 5374 option("indentWithTabs", false); 5375 option("smartIndent", true); 5376 option("tabSize", 4, function(cm) { 5377 resetModeState(cm); 5378 clearCaches(cm); 5379 regChange(cm); 5380 }, true); 5381 option("lineSeparator", null, function(cm, val) { 5382 cm.doc.lineSep = val; 5383 if (!val) return; 5384 var newBreaks = [], lineNo = cm.doc.first; 5385 cm.doc.iter(function(line) { 5386 for (var pos = 0;;) { 5387 var found = line.text.indexOf(val, pos); 5388 if (found == -1) break; 5389 pos = found + val.length; 5390 newBreaks.push(Pos(lineNo, found)); 5391 } 5392 lineNo++; 5393 }); 5394 for (var i = newBreaks.length - 1; i >= 0; i--) 5395 replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) 5396 }); 5397 option("specialChars", /[\u0000-\u001f\u007f\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) { 5398 cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); 5399 if (old != CodeMirror.Init) cm.refresh(); 5400 }); 5401 option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true); 5402 option("electricChars", true); 5403 option("inputStyle", mobile ? "contenteditable" : "textarea", function() { 5404 throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME 5405 }, true); 5406 option("rtlMoveVisually", !windows); 5407 option("wholeLineUpdateBefore", true); 5408 5409 option("theme", "default", function(cm) { 5410 themeChanged(cm); 5411 guttersChanged(cm); 5412 }, true); 5413 option("keyMap", "default", function(cm, val, old) { 5414 var next = getKeyMap(val); 5415 var prev = old != CodeMirror.Init && getKeyMap(old); 5416 if (prev && prev.detach) prev.detach(cm, next); 5417 if (next.attach) next.attach(cm, prev || null); 5418 }); 5419 option("extraKeys", null); 5420 5421 option("lineWrapping", false, wrappingChanged, true); 5422 option("gutters", [], function(cm) { 5423 setGuttersForLineNumbers(cm.options); 5424 guttersChanged(cm); 5425 }, true); 5426 option("fixedGutter", true, function(cm, val) { 5427 cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; 5428 cm.refresh(); 5429 }, true); 5430 option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true); 5431 option("scrollbarStyle", "native", function(cm) { 5432 initScrollbars(cm); 5433 updateScrollbars(cm); 5434 cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); 5435 cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); 5436 }, true); 5437 option("lineNumbers", false, function(cm) { 5438 setGuttersForLineNumbers(cm.options); 5439 guttersChanged(cm); 5440 }, true); 5441 option("firstLineNumber", 1, guttersChanged, true); 5442 option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true); 5443 option("showCursorWhenSelecting", false, updateSelection, true); 5444 5445 option("resetSelectionOnContextMenu", true); 5446 option("lineWiseCopyCut", true); 5447 5448 option("readOnly", false, function(cm, val) { 5449 if (val == "nocursor") { 5450 onBlur(cm); 5451 cm.display.input.blur(); 5452 cm.display.disabled = true; 5453 } else { 5454 cm.display.disabled = false; 5455 } 5456 cm.display.input.readOnlyChanged(val) 5457 }); 5458 option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true); 5459 option("dragDrop", true, dragDropChanged); 5460 option("allowDropFileTypes", null); 5461 5462 option("cursorBlinkRate", 530); 5463 option("cursorScrollMargin", 0); 5464 option("cursorHeight", 1, updateSelection, true); 5465 option("singleCursorHeightPerLine", true, updateSelection, true); 5466 option("workTime", 100); 5467 option("workDelay", 100); 5468 option("flattenSpans", true, resetModeState, true); 5469 option("addModeClass", false, resetModeState, true); 5470 option("pollInterval", 100); 5471 option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;}); 5472 option("historyEventDelay", 1250); 5473 option("viewportMargin", 10, function(cm){cm.refresh();}, true); 5474 option("maxHighlightLength", 10000, resetModeState, true); 5475 option("moveInputWithCursor", true, function(cm, val) { 5476 if (!val) cm.display.input.resetPosition(); 5477 }); 5478 5479 option("tabindex", null, function(cm, val) { 5480 cm.display.input.getField().tabIndex = val || ""; 5481 }); 5482 option("autofocus", null); 5483 5484 // MODE DEFINITION AND QUERYING 5485 5486 // Known modes, by name and by MIME 5487 var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; 5488 5489 // Extra arguments are stored as the mode's dependencies, which is 5490 // used by (legacy) mechanisms like loadmode.js to automatically 5491 // load a mode. (Preferred mechanism is the require/define calls.) 5492 CodeMirror.defineMode = function(name, mode) { 5493 if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; 5494 if (arguments.length > 2) 5495 mode.dependencies = Array.prototype.slice.call(arguments, 2); 5496 modes[name] = mode; 5497 }; 5498 5499 CodeMirror.defineMIME = function(mime, spec) { 5500 mimeModes[mime] = spec; 5501 }; 5502 5503 // Given a MIME type, a {name, ...options} config object, or a name 5504 // string, return a mode config object. 5505 CodeMirror.resolveMode = function(spec) { 5506 if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { 5507 spec = mimeModes[spec]; 5508 } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { 5509 var found = mimeModes[spec.name]; 5510 if (typeof found == "string") found = {name: found}; 5511 spec = createObj(found, spec); 5512 spec.name = found.name; 5513 } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { 5514 return CodeMirror.resolveMode("application/xml"); 5515 } 5516 if (typeof spec == "string") return {name: spec}; 5517 else return spec || {name: "null"}; 5518 }; 5519 5520 // Given a mode spec (anything that resolveMode accepts), find and 5521 // initialize an actual mode object. 5522 CodeMirror.getMode = function(options, spec) { 5523 var spec = CodeMirror.resolveMode(spec); 5524 var mfactory = modes[spec.name]; 5525 if (!mfactory) return CodeMirror.getMode(options, "text/plain"); 5526 var modeObj = mfactory(options, spec); 5527 if (modeExtensions.hasOwnProperty(spec.name)) { 5528 var exts = modeExtensions[spec.name]; 5529 for (var prop in exts) { 5530 if (!exts.hasOwnProperty(prop)) continue; 5531 if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; 5532 modeObj[prop] = exts[prop]; 5533 } 5534 } 5535 modeObj.name = spec.name; 5536 if (spec.helperType) modeObj.helperType = spec.helperType; 5537 if (spec.modeProps) for (var prop in spec.modeProps) 5538 modeObj[prop] = spec.modeProps[prop]; 5539 5540 return modeObj; 5541 }; 5542 5543 // Minimal default mode. 5544 CodeMirror.defineMode("null", function() { 5545 return {token: function(stream) {stream.skipToEnd();}}; 5546 }); 5547 CodeMirror.defineMIME("text/plain", "null"); 5548 5549 // This can be used to attach properties to mode objects from 5550 // outside the actual mode definition. 5551 var modeExtensions = CodeMirror.modeExtensions = {}; 5552 CodeMirror.extendMode = function(mode, properties) { 5553 var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); 5554 copyObj(properties, exts); 5555 }; 5556 5557 // EXTENSIONS 5558 5559 CodeMirror.defineExtension = function(name, func) { 5560 CodeMirror.prototype[name] = func; 5561 }; 5562 CodeMirror.defineDocExtension = function(name, func) { 5563 Doc.prototype[name] = func; 5564 }; 5565 CodeMirror.defineOption = option; 5566 5567 var initHooks = []; 5568 CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; 5569 5570 var helpers = CodeMirror.helpers = {}; 5571 CodeMirror.registerHelper = function(type, name, value) { 5572 if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []}; 5573 helpers[type][name] = value; 5574 }; 5575 CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { 5576 CodeMirror.registerHelper(type, name, value); 5577 helpers[type]._global.push({pred: predicate, val: value}); 5578 }; 5579 5580 // MODE STATE HANDLING 5581 5582 // Utility functions for working with state. Exported because nested 5583 // modes need to do this for their inner modes. 5584 5585 var copyState = CodeMirror.copyState = function(mode, state) { 5586 if (state === true) return state; 5587 if (mode.copyState) return mode.copyState(state); 5588 var nstate = {}; 5589 for (var n in state) { 5590 var val = state[n]; 5591 if (val instanceof Array) val = val.concat([]); 5592 nstate[n] = val; 5593 } 5594 return nstate; 5595 }; 5596 5597 var startState = CodeMirror.startState = function(mode, a1, a2) { 5598 return mode.startState ? mode.startState(a1, a2) : true; 5599 }; 5600 5601 // Given a mode and a state (for that mode), find the inner mode and 5602 // state at the position that the state refers to. 5603 CodeMirror.innerMode = function(mode, state) { 5604 while (mode.innerMode) { 5605 var info = mode.innerMode(state); 5606 if (!info || info.mode == mode) break; 5607 state = info.state; 5608 mode = info.mode; 5609 } 5610 return info || {mode: mode, state: state}; 5611 }; 5612 5613 // STANDARD COMMANDS 5614 5615 // Commands are parameter-less actions that can be performed on an 5616 // editor, mostly used for keybindings. 5617 var commands = CodeMirror.commands = { 5618 selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);}, 5619 singleSelection: function(cm) { 5620 cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); 5621 }, 5622 killLine: function(cm) { 5623 deleteNearSelection(cm, function(range) { 5624 if (range.empty()) { 5625 var len = getLine(cm.doc, range.head.line).text.length; 5626 if (range.head.ch == len && range.head.line < cm.lastLine()) 5627 return {from: range.head, to: Pos(range.head.line + 1, 0)}; 5628 else 5629 return {from: range.head, to: Pos(range.head.line, len)}; 5630 } else { 5631 return {from: range.from(), to: range.to()}; 5632 } 5633 }); 5634 }, 5635 deleteLine: function(cm) { 5636 deleteNearSelection(cm, function(range) { 5637 return {from: Pos(range.from().line, 0), 5638 to: clipPos(cm.doc, Pos(range.to().line + 1, 0))}; 5639 }); 5640 }, 5641 delLineLeft: function(cm) { 5642 deleteNearSelection(cm, function(range) { 5643 return {from: Pos(range.from().line, 0), to: range.from()}; 5644 }); 5645 }, 5646 delWrappedLineLeft: function(cm) { 5647 deleteNearSelection(cm, function(range) { 5648 var top = cm.charCoords(range.head, "div").top + 5; 5649 var leftPos = cm.coordsChar({left: 0, top: top}, "div"); 5650 return {from: leftPos, to: range.from()}; 5651 }); 5652 }, 5653 delWrappedLineRight: function(cm) { 5654 deleteNearSelection(cm, function(range) { 5655 var top = cm.charCoords(range.head, "div").top + 5; 5656 var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); 5657 return {from: range.from(), to: rightPos }; 5658 }); 5659 }, 5660 undo: function(cm) {cm.undo();}, 5661 redo: function(cm) {cm.redo();}, 5662 undoSelection: function(cm) {cm.undoSelection();}, 5663 redoSelection: function(cm) {cm.redoSelection();}, 5664 goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, 5665 goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, 5666 goLineStart: function(cm) { 5667 cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); }, 5668 {origin: "+move", bias: 1}); 5669 }, 5670 goLineStartSmart: function(cm) { 5671 cm.extendSelectionsBy(function(range) { 5672 return lineStartSmart(cm, range.head); 5673 }, {origin: "+move", bias: 1}); 5674 }, 5675 goLineEnd: function(cm) { 5676 cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); }, 5677 {origin: "+move", bias: -1}); 5678 }, 5679 goLineRight: function(cm) { 5680 cm.extendSelectionsBy(function(range) { 5681 var top = cm.charCoords(range.head, "div").top + 5; 5682 return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); 5683 }, sel_move); 5684 }, 5685 goLineLeft: function(cm) { 5686 cm.extendSelectionsBy(function(range) { 5687 var top = cm.charCoords(range.head, "div").top + 5; 5688 return cm.coordsChar({left: 0, top: top}, "div"); 5689 }, sel_move); 5690 }, 5691 goLineLeftSmart: function(cm) { 5692 cm.extendSelectionsBy(function(range) { 5693 var top = cm.charCoords(range.head, "div").top + 5; 5694 var pos = cm.coordsChar({left: 0, top: top}, "div"); 5695 if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head); 5696 return pos; 5697 }, sel_move); 5698 }, 5699 goLineUp: function(cm) {cm.moveV(-1, "line");}, 5700 goLineDown: function(cm) {cm.moveV(1, "line");}, 5701 goPageUp: function(cm) {cm.moveV(-1, "page");}, 5702 goPageDown: function(cm) {cm.moveV(1, "page");}, 5703 goCharLeft: function(cm) {cm.moveH(-1, "char");}, 5704 goCharRight: function(cm) {cm.moveH(1, "char");}, 5705 goColumnLeft: function(cm) {cm.moveH(-1, "column");}, 5706 goColumnRight: function(cm) {cm.moveH(1, "column");}, 5707 goWordLeft: function(cm) {cm.moveH(-1, "word");}, 5708 goGroupRight: function(cm) {cm.moveH(1, "group");}, 5709 goGroupLeft: function(cm) {cm.moveH(-1, "group");}, 5710 goWordRight: function(cm) {cm.moveH(1, "word");}, 5711 delCharBefore: function(cm) {cm.deleteH(-1, "char");}, 5712 delCharAfter: function(cm) {cm.deleteH(1, "char");}, 5713 delWordBefore: function(cm) {cm.deleteH(-1, "word");}, 5714 delWordAfter: function(cm) {cm.deleteH(1, "word");}, 5715 delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, 5716 delGroupAfter: function(cm) {cm.deleteH(1, "group");}, 5717 indentAuto: function(cm) {cm.indentSelection("smart");}, 5718 indentMore: function(cm) {cm.indentSelection("add");}, 5719 indentLess: function(cm) {cm.indentSelection("subtract");}, 5720 insertTab: function(cm) {cm.replaceSelection("\t");}, 5721 insertSoftTab: function(cm) { 5722 var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; 5723 for (var i = 0; i < ranges.length; i++) { 5724 var pos = ranges[i].from(); 5725 var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); 5726 spaces.push(spaceStr(tabSize - col % tabSize)); 5727 } 5728 cm.replaceSelections(spaces); 5729 }, 5730 defaultTab: function(cm) { 5731 if (cm.somethingSelected()) cm.indentSelection("add"); 5732 else cm.execCommand("insertTab"); 5733 }, 5734 transposeChars: function(cm) { 5735 runInOp(cm, function() { 5736 var ranges = cm.listSelections(), newSel = []; 5737 for (var i = 0; i < ranges.length; i++) { 5738 var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; 5739 if (line) { 5740 if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1); 5741 if (cur.ch > 0) { 5742 cur = new Pos(cur.line, cur.ch + 1); 5743 cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), 5744 Pos(cur.line, cur.ch - 2), cur, "+transpose"); 5745 } else if (cur.line > cm.doc.first) { 5746 var prev = getLine(cm.doc, cur.line - 1).text; 5747 if (prev) 5748 cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + 5749 prev.charAt(prev.length - 1), 5750 Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose"); 5751 } 5752 } 5753 newSel.push(new Range(cur, cur)); 5754 } 5755 cm.setSelections(newSel); 5756 }); 5757 }, 5758 newlineAndIndent: function(cm) { 5759 runInOp(cm, function() { 5760 var len = cm.listSelections().length; 5761 for (var i = 0; i < len; i++) { 5762 var range = cm.listSelections()[i]; 5763 cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input"); 5764 cm.indentLine(range.from().line + 1, null, true); 5765 } 5766 ensureCursorVisible(cm); 5767 }); 5768 }, 5769 openLine: function(cm) {cm.replaceSelection("\n", "start")}, 5770 toggleOverwrite: function(cm) {cm.toggleOverwrite();} 5771 }; 5772 5773 5774 // STANDARD KEYMAPS 5775 5776 var keyMap = CodeMirror.keyMap = {}; 5777 5778 keyMap.basic = { 5779 "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", 5780 "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", 5781 "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", 5782 "Tab": "defaultTab", "Shift-Tab": "indentAuto", 5783 "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", 5784 "Esc": "singleSelection" 5785 }; 5786 // Note that the save and find-related commands aren't defined by 5787 // default. User code or addons can define them. Unknown commands 5788 // are simply ignored. 5789 keyMap.pcDefault = { 5790 "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", 5791 "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", 5792 "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", 5793 "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", 5794 "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", 5795 "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", 5796 "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", 5797 fallthrough: "basic" 5798 }; 5799 // Very basic readline/emacs-style bindings, which are standard on Mac. 5800 keyMap.emacsy = { 5801 "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", 5802 "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", 5803 "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", 5804 "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", 5805 "Ctrl-O": "openLine" 5806 }; 5807 keyMap.macDefault = { 5808 "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", 5809 "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", 5810 "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", 5811 "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", 5812 "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", 5813 "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", 5814 "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", 5815 fallthrough: ["basic", "emacsy"] 5816 }; 5817 keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; 5818 5819 // KEYMAP DISPATCH 5820 5821 function normalizeKeyName(name) { 5822 var parts = name.split(/-(?!$)/), name = parts[parts.length - 1]; 5823 var alt, ctrl, shift, cmd; 5824 for (var i = 0; i < parts.length - 1; i++) { 5825 var mod = parts[i]; 5826 if (/^(cmd|meta|m)$/i.test(mod)) cmd = true; 5827 else if (/^a(lt)?$/i.test(mod)) alt = true; 5828 else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true; 5829 else if (/^s(hift)$/i.test(mod)) shift = true; 5830 else throw new Error("Unrecognized modifier name: " + mod); 5831 } 5832 if (alt) name = "Alt-" + name; 5833 if (ctrl) name = "Ctrl-" + name; 5834 if (cmd) name = "Cmd-" + name; 5835 if (shift) name = "Shift-" + name; 5836 return name; 5837 } 5838 5839 // This is a kludge to keep keymaps mostly working as raw objects 5840 // (backwards compatibility) while at the same time support features 5841 // like normalization and multi-stroke key bindings. It compiles a 5842 // new normalized keymap, and then updates the old object to reflect 5843 // this. 5844 CodeMirror.normalizeKeyMap = function(keymap) { 5845 var copy = {}; 5846 for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) { 5847 var value = keymap[keyname]; 5848 if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue; 5849 if (value == "...") { delete keymap[keyname]; continue; } 5850 5851 var keys = map(keyname.split(" "), normalizeKeyName); 5852 for (var i = 0; i < keys.length; i++) { 5853 var val, name; 5854 if (i == keys.length - 1) { 5855 name = keys.join(" "); 5856 val = value; 5857 } else { 5858 name = keys.slice(0, i + 1).join(" "); 5859 val = "..."; 5860 } 5861 var prev = copy[name]; 5862 if (!prev) copy[name] = val; 5863 else if (prev != val) throw new Error("Inconsistent bindings for " + name); 5864 } 5865 delete keymap[keyname]; 5866 } 5867 for (var prop in copy) keymap[prop] = copy[prop]; 5868 return keymap; 5869 }; 5870 5871 var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) { 5872 map = getKeyMap(map); 5873 var found = map.call ? map.call(key, context) : map[key]; 5874 if (found === false) return "nothing"; 5875 if (found === "...") return "multi"; 5876 if (found != null && handle(found)) return "handled"; 5877 5878 if (map.fallthrough) { 5879 if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") 5880 return lookupKey(key, map.fallthrough, handle, context); 5881 for (var i = 0; i < map.fallthrough.length; i++) { 5882 var result = lookupKey(key, map.fallthrough[i], handle, context); 5883 if (result) return result; 5884 } 5885 } 5886 }; 5887 5888 // Modifier key presses don't count as 'real' key presses for the 5889 // purpose of keymap fallthrough. 5890 var isModifierKey = CodeMirror.isModifierKey = function(value) { 5891 var name = typeof value == "string" ? value : keyNames[value.keyCode]; 5892 return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; 5893 }; 5894 5895 // Look up the name of a key as indicated by an event object. 5896 var keyName = CodeMirror.keyName = function(event, noShift) { 5897 if (presto && event.keyCode == 34 && event["char"]) return false; 5898 var base = keyNames[event.keyCode], name = base; 5899 if (name == null || event.altGraphKey) return false; 5900 if (event.altKey && base != "Alt") name = "Alt-" + name; 5901 if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name; 5902 if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name; 5903 if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name; 5904 return name; 5905 }; 5906 5907 function getKeyMap(val) { 5908 return typeof val == "string" ? keyMap[val] : val; 5909 } 5910 5911 // FROMTEXTAREA 5912 5913 CodeMirror.fromTextArea = function(textarea, options) { 5914 options = options ? copyObj(options) : {}; 5915 options.value = textarea.value; 5916 if (!options.tabindex && textarea.tabIndex) 5917 options.tabindex = textarea.tabIndex; 5918 if (!options.placeholder && textarea.placeholder) 5919 options.placeholder = textarea.placeholder; 5920 // Set autofocus to true if this textarea is focused, or if it has 5921 // autofocus and no other element is focused. 5922 if (options.autofocus == null) { 5923 var hasFocus = activeElt(); 5924 options.autofocus = hasFocus == textarea || 5925 textarea.getAttribute("autofocus") != null && hasFocus == document.body; 5926 } 5927 5928 function save() {textarea.value = cm.getValue();} 5929 if (textarea.form) { 5930 on(textarea.form, "submit", save); 5931 // Deplorable hack to make the submit method do the right thing. 5932 if (!options.leaveSubmitMethodAlone) { 5933 var form = textarea.form, realSubmit = form.submit; 5934 try { 5935 var wrappedSubmit = form.submit = function() { 5936 save(); 5937 form.submit = realSubmit; 5938 form.submit(); 5939 form.submit = wrappedSubmit; 5940 }; 5941 } catch(e) {} 5942 } 5943 } 5944 5945 options.finishInit = function(cm) { 5946 cm.save = save; 5947 cm.getTextArea = function() { return textarea; }; 5948 cm.toTextArea = function() { 5949 cm.toTextArea = isNaN; // Prevent this from being ran twice 5950 save(); 5951 textarea.parentNode.removeChild(cm.getWrapperElement()); 5952 textarea.style.display = ""; 5953 if (textarea.form) { 5954 off(textarea.form, "submit", save); 5955 if (typeof textarea.form.submit == "function") 5956 textarea.form.submit = realSubmit; 5957 } 5958 }; 5959 }; 5960 5961 textarea.style.display = "none"; 5962 var cm = CodeMirror(function(node) { 5963 textarea.parentNode.insertBefore(node, textarea.nextSibling); 5964 }, options); 5965 return cm; 5966 }; 5967 5968 // STRING STREAM 5969 5970 // Fed to the mode parsers, provides helper functions to make 5971 // parsers more succinct. 5972 5973 var StringStream = CodeMirror.StringStream = function(string, tabSize) { 5974 this.pos = this.start = 0; 5975 this.string = string; 5976 this.tabSize = tabSize || 8; 5977 this.lastColumnPos = this.lastColumnValue = 0; 5978 this.lineStart = 0; 5979 }; 5980 5981 StringStream.prototype = { 5982 eol: function() {return this.pos >= this.string.length;}, 5983 sol: function() {return this.pos == this.lineStart;}, 5984 peek: function() {return this.string.charAt(this.pos) || undefined;}, 5985 next: function() { 5986 if (this.pos < this.string.length) 5987 return this.string.charAt(this.pos++); 5988 }, 5989 eat: function(match) { 5990 var ch = this.string.charAt(this.pos); 5991 if (typeof match == "string") var ok = ch == match; 5992 else var ok = ch && (match.test ? match.test(ch) : match(ch)); 5993 if (ok) {++this.pos; return ch;} 5994 }, 5995 eatWhile: function(match) { 5996 var start = this.pos; 5997 while (this.eat(match)){} 5998 return this.pos > start; 5999 }, 6000 eatSpace: function() { 6001 var start = this.pos; 6002 while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; 6003 return this.pos > start; 6004 }, 6005 skipToEnd: function() {this.pos = this.string.length;}, 6006 skipTo: function(ch) { 6007 var found = this.string.indexOf(ch, this.pos); 6008 if (found > -1) {this.pos = found; return true;} 6009 }, 6010 backUp: function(n) {this.pos -= n;}, 6011 column: function() { 6012 if (this.lastColumnPos < this.start) { 6013 this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); 6014 this.lastColumnPos = this.start; 6015 } 6016 return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); 6017 }, 6018 indentation: function() { 6019 return countColumn(this.string, null, this.tabSize) - 6020 (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); 6021 }, 6022 match: function(pattern, consume, caseInsensitive) { 6023 if (typeof pattern == "string") { 6024 var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; 6025 var substr = this.string.substr(this.pos, pattern.length); 6026 if (cased(substr) == cased(pattern)) { 6027 if (consume !== false) this.pos += pattern.length; 6028 return true; 6029 } 6030 } else { 6031 var match = this.string.slice(this.pos).match(pattern); 6032 if (match && match.index > 0) return null; 6033 if (match && consume !== false) this.pos += match[0].length; 6034 return match; 6035 } 6036 }, 6037 current: function(){return this.string.slice(this.start, this.pos);}, 6038 hideFirstChars: function(n, inner) { 6039 this.lineStart += n; 6040 try { return inner(); } 6041 finally { this.lineStart -= n; } 6042 } 6043 }; 6044 6045 // TEXTMARKERS 6046 6047 // Created with markText and setBookmark methods. A TextMarker is a 6048 // handle that can be used to clear or find a marked position in the 6049 // document. Line objects hold arrays (markedSpans) containing 6050 // {from, to, marker} object pointing to such marker objects, and 6051 // indicating that such a marker is present on that line. Multiple 6052 // lines may point to the same marker when it spans across lines. 6053 // The spans will have null for their from/to properties when the 6054 // marker continues beyond the start/end of the line. Markers have 6055 // links back to the lines they currently touch. 6056 6057 var nextMarkerId = 0; 6058 6059 var TextMarker = CodeMirror.TextMarker = function(doc, type) { 6060 this.lines = []; 6061 this.type = type; 6062 this.doc = doc; 6063 this.id = ++nextMarkerId; 6064 }; 6065 eventMixin(TextMarker); 6066 6067 // Clear the marker. 6068 TextMarker.prototype.clear = function() { 6069 if (this.explicitlyCleared) return; 6070 var cm = this.doc.cm, withOp = cm && !cm.curOp; 6071 if (withOp) startOperation(cm); 6072 if (hasHandler(this, "clear")) { 6073 var found = this.find(); 6074 if (found) signalLater(this, "clear", found.from, found.to); 6075 } 6076 var min = null, max = null; 6077 for (var i = 0; i < this.lines.length; ++i) { 6078 var line = this.lines[i]; 6079 var span = getMarkedSpanFor(line.markedSpans, this); 6080 if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text"); 6081 else if (cm) { 6082 if (span.to != null) max = lineNo(line); 6083 if (span.from != null) min = lineNo(line); 6084 } 6085 line.markedSpans = removeMarkedSpan(line.markedSpans, span); 6086 if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) 6087 updateLineHeight(line, textHeight(cm.display)); 6088 } 6089 if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) { 6090 var visual = visualLine(this.lines[i]), len = lineLength(visual); 6091 if (len > cm.display.maxLineLength) { 6092 cm.display.maxLine = visual; 6093 cm.display.maxLineLength = len; 6094 cm.display.maxLineChanged = true; 6095 } 6096 } 6097 6098 if (min != null && cm && this.collapsed) regChange(cm, min, max + 1); 6099 this.lines.length = 0; 6100 this.explicitlyCleared = true; 6101 if (this.atomic && this.doc.cantEdit) { 6102 this.doc.cantEdit = false; 6103 if (cm) reCheckSelection(cm.doc); 6104 } 6105 if (cm) signalLater(cm, "markerCleared", cm, this); 6106 if (withOp) endOperation(cm); 6107 if (this.parent) this.parent.clear(); 6108 }; 6109 6110 // Find the position of the marker in the document. Returns a {from, 6111 // to} object by default. Side can be passed to get a specific side 6112 // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the 6113 // Pos objects returned contain a line object, rather than a line 6114 // number (used to prevent looking up the same line twice). 6115 TextMarker.prototype.find = function(side, lineObj) { 6116 if (side == null && this.type == "bookmark") side = 1; 6117 var from, to; 6118 for (var i = 0; i < this.lines.length; ++i) { 6119 var line = this.lines[i]; 6120 var span = getMarkedSpanFor(line.markedSpans, this); 6121 if (span.from != null) { 6122 from = Pos(lineObj ? line : lineNo(line), span.from); 6123 if (side == -1) return from; 6124 } 6125 if (span.to != null) { 6126 to = Pos(lineObj ? line : lineNo(line), span.to); 6127 if (side == 1) return to; 6128 } 6129 } 6130 return from && {from: from, to: to}; 6131 }; 6132 6133 // Signals that the marker's widget changed, and surrounding layout 6134 // should be recomputed. 6135 TextMarker.prototype.changed = function() { 6136 var pos = this.find(-1, true), widget = this, cm = this.doc.cm; 6137 if (!pos || !cm) return; 6138 runInOp(cm, function() { 6139 var line = pos.line, lineN = lineNo(pos.line); 6140 var view = findViewForLine(cm, lineN); 6141 if (view) { 6142 clearLineMeasurementCacheFor(view); 6143 cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; 6144 } 6145 cm.curOp.updateMaxLine = true; 6146 if (!lineIsHidden(widget.doc, line) && widget.height != null) { 6147 var oldHeight = widget.height; 6148 widget.height = null; 6149 var dHeight = widgetHeight(widget) - oldHeight; 6150 if (dHeight) 6151 updateLineHeight(line, line.height + dHeight); 6152 } 6153 }); 6154 }; 6155 6156 TextMarker.prototype.attachLine = function(line) { 6157 if (!this.lines.length && this.doc.cm) { 6158 var op = this.doc.cm.curOp; 6159 if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) 6160 (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); 6161 } 6162 this.lines.push(line); 6163 }; 6164 TextMarker.prototype.detachLine = function(line) { 6165 this.lines.splice(indexOf(this.lines, line), 1); 6166 if (!this.lines.length && this.doc.cm) { 6167 var op = this.doc.cm.curOp; 6168 (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); 6169 } 6170 }; 6171 6172 // Collapsed markers have unique ids, in order to be able to order 6173 // them, which is needed for uniquely determining an outer marker 6174 // when they overlap (they may nest, but not partially overlap). 6175 var nextMarkerId = 0; 6176 6177 // Create a marker, wire it up to the right lines, and 6178 function markText(doc, from, to, options, type) { 6179 // Shared markers (across linked documents) are handled separately 6180 // (markTextShared will call out to this again, once per 6181 // document). 6182 if (options && options.shared) return markTextShared(doc, from, to, options, type); 6183 // Ensure we are in an operation. 6184 if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); 6185 6186 var marker = new TextMarker(doc, type), diff = cmp(from, to); 6187 if (options) copyObj(options, marker, false); 6188 // Don't connect empty markers unless clearWhenEmpty is false 6189 if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) 6190 return marker; 6191 if (marker.replacedWith) { 6192 // Showing up as a widget implies collapsed (widget replaces text) 6193 marker.collapsed = true; 6194 marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget"); 6195 if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true"); 6196 if (options.insertLeft) marker.widgetNode.insertLeft = true; 6197 } 6198 if (marker.collapsed) { 6199 if (conflictingCollapsedRange(doc, from.line, from, to, marker) || 6200 from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) 6201 throw new Error("Inserting collapsed marker partially overlapping an existing one"); 6202 sawCollapsedSpans = true; 6203 } 6204 6205 if (marker.addToHistory) 6206 addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); 6207 6208 var curLine = from.line, cm = doc.cm, updateMaxLine; 6209 doc.iter(curLine, to.line + 1, function(line) { 6210 if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) 6211 updateMaxLine = true; 6212 if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0); 6213 addMarkedSpan(line, new MarkedSpan(marker, 6214 curLine == from.line ? from.ch : null, 6215 curLine == to.line ? to.ch : null)); 6216 ++curLine; 6217 }); 6218 // lineIsHidden depends on the presence of the spans, so needs a second pass 6219 if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { 6220 if (lineIsHidden(doc, line)) updateLineHeight(line, 0); 6221 }); 6222 6223 if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); }); 6224 6225 if (marker.readOnly) { 6226 sawReadOnlySpans = true; 6227 if (doc.history.done.length || doc.history.undone.length) 6228 doc.clearHistory(); 6229 } 6230 if (marker.collapsed) { 6231 marker.id = ++nextMarkerId; 6232 marker.atomic = true; 6233 } 6234 if (cm) { 6235 // Sync editor state 6236 if (updateMaxLine) cm.curOp.updateMaxLine = true; 6237 if (marker.collapsed) 6238 regChange(cm, from.line, to.line + 1); 6239 else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) 6240 for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text"); 6241 if (marker.atomic) reCheckSelection(cm.doc); 6242 signalLater(cm, "markerAdded", cm, marker); 6243 } 6244 return marker; 6245 } 6246 6247 // SHARED TEXTMARKERS 6248 6249 // A shared marker spans multiple linked documents. It is 6250 // implemented as a meta-marker-object controlling multiple normal 6251 // markers. 6252 var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) { 6253 this.markers = markers; 6254 this.primary = primary; 6255 for (var i = 0; i < markers.length; ++i) 6256 markers[i].parent = this; 6257 }; 6258 eventMixin(SharedTextMarker); 6259 6260 SharedTextMarker.prototype.clear = function() { 6261 if (this.explicitlyCleared) return; 6262 this.explicitlyCleared = true; 6263 for (var i = 0; i < this.markers.length; ++i) 6264 this.markers[i].clear(); 6265 signalLater(this, "clear"); 6266 }; 6267 SharedTextMarker.prototype.find = function(side, lineObj) { 6268 return this.primary.find(side, lineObj); 6269 }; 6270 6271 function markTextShared(doc, from, to, options, type) { 6272 options = copyObj(options); 6273 options.shared = false; 6274 var markers = [markText(doc, from, to, options, type)], primary = markers[0]; 6275 var widget = options.widgetNode; 6276 linkedDocs(doc, function(doc) { 6277 if (widget) options.widgetNode = widget.cloneNode(true); 6278 markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); 6279 for (var i = 0; i < doc.linked.length; ++i) 6280 if (doc.linked[i].isParent) return; 6281 primary = lst(markers); 6282 }); 6283 return new SharedTextMarker(markers, primary); 6284 } 6285 6286 function findSharedMarkers(doc) { 6287 return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), 6288 function(m) { return m.parent; }); 6289 } 6290 6291 function copySharedMarkers(doc, markers) { 6292 for (var i = 0; i < markers.length; i++) { 6293 var marker = markers[i], pos = marker.find(); 6294 var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); 6295 if (cmp(mFrom, mTo)) { 6296 var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); 6297 marker.markers.push(subMark); 6298 subMark.parent = marker; 6299 } 6300 } 6301 } 6302 6303 function detachSharedMarkers(markers) { 6304 for (var i = 0; i < markers.length; i++) { 6305 var marker = markers[i], linked = [marker.primary.doc];; 6306 linkedDocs(marker.primary.doc, function(d) { linked.push(d); }); 6307 for (var j = 0; j < marker.markers.length; j++) { 6308 var subMarker = marker.markers[j]; 6309 if (indexOf(linked, subMarker.doc) == -1) { 6310 subMarker.parent = null; 6311 marker.markers.splice(j--, 1); 6312 } 6313 } 6314 } 6315 } 6316 6317 // TEXTMARKER SPANS 6318 6319 function MarkedSpan(marker, from, to) { 6320 this.marker = marker; 6321 this.from = from; this.to = to; 6322 } 6323 6324 // Search an array of spans for a span matching the given marker. 6325 function getMarkedSpanFor(spans, marker) { 6326 if (spans) for (var i = 0; i < spans.length; ++i) { 6327 var span = spans[i]; 6328 if (span.marker == marker) return span; 6329 } 6330 } 6331 // Remove a span from an array, returning undefined if no spans are 6332 // left (we don't store arrays for lines without spans). 6333 function removeMarkedSpan(spans, span) { 6334 for (var r, i = 0; i < spans.length; ++i) 6335 if (spans[i] != span) (r || (r = [])).push(spans[i]); 6336 return r; 6337 } 6338 // Add a span to a line. 6339 function addMarkedSpan(line, span) { 6340 line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; 6341 span.marker.attachLine(line); 6342 } 6343 6344 // Used for the algorithm that adjusts markers for a change in the 6345 // document. These functions cut an array of spans at a given 6346 // character position, returning an array of remaining chunks (or 6347 // undefined if nothing remains). 6348 function markedSpansBefore(old, startCh, isInsert) { 6349 if (old) for (var i = 0, nw; i < old.length; ++i) { 6350 var span = old[i], marker = span.marker; 6351 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); 6352 if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { 6353 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); 6354 (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); 6355 } 6356 } 6357 return nw; 6358 } 6359 function markedSpansAfter(old, endCh, isInsert) { 6360 if (old) for (var i = 0, nw; i < old.length; ++i) { 6361 var span = old[i], marker = span.marker; 6362 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); 6363 if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { 6364 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); 6365 (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, 6366 span.to == null ? null : span.to - endCh)); 6367 } 6368 } 6369 return nw; 6370 } 6371 6372 // Given a change object, compute the new set of marker spans that 6373 // cover the line in which the change took place. Removes spans 6374 // entirely within the change, reconnects spans belonging to the 6375 // same marker that appear on both sides of the change, and cuts off 6376 // spans partially within the change. Returns an array of span 6377 // arrays with one element for each line in (after) the change. 6378 function stretchSpansOverChange(doc, change) { 6379 if (change.full) return null; 6380 var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; 6381 var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; 6382 if (!oldFirst && !oldLast) return null; 6383 6384 var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; 6385 // Get the spans that 'stick out' on both sides 6386 var first = markedSpansBefore(oldFirst, startCh, isInsert); 6387 var last = markedSpansAfter(oldLast, endCh, isInsert); 6388 6389 // Next, merge those two ends 6390 var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); 6391 if (first) { 6392 // Fix up .to properties of first 6393 for (var i = 0; i < first.length; ++i) { 6394 var span = first[i]; 6395 if (span.to == null) { 6396 var found = getMarkedSpanFor(last, span.marker); 6397 if (!found) span.to = startCh; 6398 else if (sameLine) span.to = found.to == null ? null : found.to + offset; 6399 } 6400 } 6401 } 6402 if (last) { 6403 // Fix up .from in last (or move them into first in case of sameLine) 6404 for (var i = 0; i < last.length; ++i) { 6405 var span = last[i]; 6406 if (span.to != null) span.to += offset; 6407 if (span.from == null) { 6408 var found = getMarkedSpanFor(first, span.marker); 6409 if (!found) { 6410 span.from = offset; 6411 if (sameLine) (first || (first = [])).push(span); 6412 } 6413 } else { 6414 span.from += offset; 6415 if (sameLine) (first || (first = [])).push(span); 6416 } 6417 } 6418 } 6419 // Make sure we didn't create any zero-length spans 6420 if (first) first = clearEmptySpans(first); 6421 if (last && last != first) last = clearEmptySpans(last); 6422 6423 var newMarkers = [first]; 6424 if (!sameLine) { 6425 // Fill gap with whole-line-spans 6426 var gap = change.text.length - 2, gapMarkers; 6427 if (gap > 0 && first) 6428 for (var i = 0; i < first.length; ++i) 6429 if (first[i].to == null) 6430 (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null)); 6431 for (var i = 0; i < gap; ++i) 6432 newMarkers.push(gapMarkers); 6433 newMarkers.push(last); 6434 } 6435 return newMarkers; 6436 } 6437 6438 // Remove spans that are empty and don't have a clearWhenEmpty 6439 // option of false. 6440 function clearEmptySpans(spans) { 6441 for (var i = 0; i < spans.length; ++i) { 6442 var span = spans[i]; 6443 if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) 6444 spans.splice(i--, 1); 6445 } 6446 if (!spans.length) return null; 6447 return spans; 6448 } 6449 6450 // Used for un/re-doing changes from the history. Combines the 6451 // result of computing the existing spans with the set of spans that 6452 // existed in the history (so that deleting around a span and then 6453 // undoing brings back the span). 6454 function mergeOldSpans(doc, change) { 6455 var old = getOldSpans(doc, change); 6456 var stretched = stretchSpansOverChange(doc, change); 6457 if (!old) return stretched; 6458 if (!stretched) return old; 6459 6460 for (var i = 0; i < old.length; ++i) { 6461 var oldCur = old[i], stretchCur = stretched[i]; 6462 if (oldCur && stretchCur) { 6463 spans: for (var j = 0; j < stretchCur.length; ++j) { 6464 var span = stretchCur[j]; 6465 for (var k = 0; k < oldCur.length; ++k) 6466 if (oldCur[k].marker == span.marker) continue spans; 6467 oldCur.push(span); 6468 } 6469 } else if (stretchCur) { 6470 old[i] = stretchCur; 6471 } 6472 } 6473 return old; 6474 } 6475 6476 // Used to 'clip' out readOnly ranges when making a change. 6477 function removeReadOnlyRanges(doc, from, to) { 6478 var markers = null; 6479 doc.iter(from.line, to.line + 1, function(line) { 6480 if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { 6481 var mark = line.markedSpans[i].marker; 6482 if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) 6483 (markers || (markers = [])).push(mark); 6484 } 6485 }); 6486 if (!markers) return null; 6487 var parts = [{from: from, to: to}]; 6488 for (var i = 0; i < markers.length; ++i) { 6489 var mk = markers[i], m = mk.find(0); 6490 for (var j = 0; j < parts.length; ++j) { 6491 var p = parts[j]; 6492 if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue; 6493 var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); 6494 if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) 6495 newParts.push({from: p.from, to: m.from}); 6496 if (dto > 0 || !mk.inclusiveRight && !dto) 6497 newParts.push({from: m.to, to: p.to}); 6498 parts.splice.apply(parts, newParts); 6499 j += newParts.length - 1; 6500 } 6501 } 6502 return parts; 6503 } 6504 6505 // Connect or disconnect spans from a line. 6506 function detachMarkedSpans(line) { 6507 var spans = line.markedSpans; 6508 if (!spans) return; 6509 for (var i = 0; i < spans.length; ++i) 6510 spans[i].marker.detachLine(line); 6511 line.markedSpans = null; 6512 } 6513 function attachMarkedSpans(line, spans) { 6514 if (!spans) return; 6515 for (var i = 0; i < spans.length; ++i) 6516 spans[i].marker.attachLine(line); 6517 line.markedSpans = spans; 6518 } 6519 6520 // Helpers used when computing which overlapping collapsed span 6521 // counts as the larger one. 6522 function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; } 6523 function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; } 6524 6525 // Returns a number indicating which of two overlapping collapsed 6526 // spans is larger (and thus includes the other). Falls back to 6527 // comparing ids when the spans cover exactly the same range. 6528 function compareCollapsedMarkers(a, b) { 6529 var lenDiff = a.lines.length - b.lines.length; 6530 if (lenDiff != 0) return lenDiff; 6531 var aPos = a.find(), bPos = b.find(); 6532 var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); 6533 if (fromCmp) return -fromCmp; 6534 var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); 6535 if (toCmp) return toCmp; 6536 return b.id - a.id; 6537 } 6538 6539 // Find out whether a line ends or starts in a collapsed span. If 6540 // so, return the marker for that span. 6541 function collapsedSpanAtSide(line, start) { 6542 var sps = sawCollapsedSpans && line.markedSpans, found; 6543 if (sps) for (var sp, i = 0; i < sps.length; ++i) { 6544 sp = sps[i]; 6545 if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && 6546 (!found || compareCollapsedMarkers(found, sp.marker) < 0)) 6547 found = sp.marker; 6548 } 6549 return found; 6550 } 6551 function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); } 6552 function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); } 6553 6554 // Test whether there exists a collapsed span that partially 6555 // overlaps (covers the start or end, but not both) of a new span. 6556 // Such overlap is not allowed. 6557 function conflictingCollapsedRange(doc, lineNo, from, to, marker) { 6558 var line = getLine(doc, lineNo); 6559 var sps = sawCollapsedSpans && line.markedSpans; 6560 if (sps) for (var i = 0; i < sps.length; ++i) { 6561 var sp = sps[i]; 6562 if (!sp.marker.collapsed) continue; 6563 var found = sp.marker.find(0); 6564 var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); 6565 var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); 6566 if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue; 6567 if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || 6568 fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) 6569 return true; 6570 } 6571 } 6572 6573 // A visual line is a line as drawn on the screen. Folding, for 6574 // example, can cause multiple logical lines to appear on the same 6575 // visual line. This finds the start of the visual line that the 6576 // given line is part of (usually that is the line itself). 6577 function visualLine(line) { 6578 var merged; 6579 while (merged = collapsedSpanAtStart(line)) 6580 line = merged.find(-1, true).line; 6581 return line; 6582 } 6583 6584 // Returns an array of logical lines that continue the visual line 6585 // started by the argument, or undefined if there are no such lines. 6586 function visualLineContinued(line) { 6587 var merged, lines; 6588 while (merged = collapsedSpanAtEnd(line)) { 6589 line = merged.find(1, true).line; 6590 (lines || (lines = [])).push(line); 6591 } 6592 return lines; 6593 } 6594 6595 // Get the line number of the start of the visual line that the 6596 // given line number is part of. 6597 function visualLineNo(doc, lineN) { 6598 var line = getLine(doc, lineN), vis = visualLine(line); 6599 if (line == vis) return lineN; 6600 return lineNo(vis); 6601 } 6602 // Get the line number of the start of the next visual line after 6603 // the given line. 6604 function visualLineEndNo(doc, lineN) { 6605 if (lineN > doc.lastLine()) return lineN; 6606 var line = getLine(doc, lineN), merged; 6607 if (!lineIsHidden(doc, line)) return lineN; 6608 while (merged = collapsedSpanAtEnd(line)) 6609 line = merged.find(1, true).line; 6610 return lineNo(line) + 1; 6611 } 6612 6613 // Compute whether a line is hidden. Lines count as hidden when they 6614 // are part of a visual line that starts with another line, or when 6615 // they are entirely covered by collapsed, non-widget span. 6616 function lineIsHidden(doc, line) { 6617 var sps = sawCollapsedSpans && line.markedSpans; 6618 if (sps) for (var sp, i = 0; i < sps.length; ++i) { 6619 sp = sps[i]; 6620 if (!sp.marker.collapsed) continue; 6621 if (sp.from == null) return true; 6622 if (sp.marker.widgetNode) continue; 6623 if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) 6624 return true; 6625 } 6626 } 6627 function lineIsHiddenInner(doc, line, span) { 6628 if (span.to == null) { 6629 var end = span.marker.find(1, true); 6630 return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); 6631 } 6632 if (span.marker.inclusiveRight && span.to == line.text.length) 6633 return true; 6634 for (var sp, i = 0; i < line.markedSpans.length; ++i) { 6635 sp = line.markedSpans[i]; 6636 if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && 6637 (sp.to == null || sp.to != span.from) && 6638 (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && 6639 lineIsHiddenInner(doc, line, sp)) return true; 6640 } 6641 } 6642 6643 // LINE WIDGETS 6644 6645 // Line widgets are block elements displayed above or below a line. 6646 6647 var LineWidget = CodeMirror.LineWidget = function(doc, node, options) { 6648 if (options) for (var opt in options) if (options.hasOwnProperty(opt)) 6649 this[opt] = options[opt]; 6650 this.doc = doc; 6651 this.node = node; 6652 }; 6653 eventMixin(LineWidget); 6654 6655 function adjustScrollWhenAboveVisible(cm, line, diff) { 6656 if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) 6657 addToScrollPos(cm, null, diff); 6658 } 6659 6660 LineWidget.prototype.clear = function() { 6661 var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); 6662 if (no == null || !ws) return; 6663 for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); 6664 if (!ws.length) line.widgets = null; 6665 var height = widgetHeight(this); 6666 updateLineHeight(line, Math.max(0, line.height - height)); 6667 if (cm) runInOp(cm, function() { 6668 adjustScrollWhenAboveVisible(cm, line, -height); 6669 regLineChange(cm, no, "widget"); 6670 }); 6671 }; 6672 LineWidget.prototype.changed = function() { 6673 var oldH = this.height, cm = this.doc.cm, line = this.line; 6674 this.height = null; 6675 var diff = widgetHeight(this) - oldH; 6676 if (!diff) return; 6677 updateLineHeight(line, line.height + diff); 6678 if (cm) runInOp(cm, function() { 6679 cm.curOp.forceUpdate = true; 6680 adjustScrollWhenAboveVisible(cm, line, diff); 6681 }); 6682 }; 6683 6684 function widgetHeight(widget) { 6685 if (widget.height != null) return widget.height; 6686 var cm = widget.doc.cm; 6687 if (!cm) return 0; 6688 if (!contains(document.body, widget.node)) { 6689 var parentStyle = "position: relative;"; 6690 if (widget.coverGutter) 6691 parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; 6692 if (widget.noHScroll) 6693 parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; 6694 removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); 6695 } 6696 return widget.height = widget.node.parentNode.offsetHeight; 6697 } 6698 6699 function addLineWidget(doc, handle, node, options) { 6700 var widget = new LineWidget(doc, node, options); 6701 var cm = doc.cm; 6702 if (cm && widget.noHScroll) cm.display.alignWidgets = true; 6703 changeLine(doc, handle, "widget", function(line) { 6704 var widgets = line.widgets || (line.widgets = []); 6705 if (widget.insertAt == null) widgets.push(widget); 6706 else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); 6707 widget.line = line; 6708 if (cm && !lineIsHidden(doc, line)) { 6709 var aboveVisible = heightAtLine(line) < doc.scrollTop; 6710 updateLineHeight(line, line.height + widgetHeight(widget)); 6711 if (aboveVisible) addToScrollPos(cm, null, widget.height); 6712 cm.curOp.forceUpdate = true; 6713 } 6714 return true; 6715 }); 6716 return widget; 6717 } 6718 6719 // LINE DATA STRUCTURE 6720 6721 // Line objects. These hold state related to a line, including 6722 // highlighting info (the styles array). 6723 var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) { 6724 this.text = text; 6725 attachMarkedSpans(this, markedSpans); 6726 this.height = estimateHeight ? estimateHeight(this) : 1; 6727 }; 6728 eventMixin(Line); 6729 Line.prototype.lineNo = function() { return lineNo(this); }; 6730 6731 // Change the content (text, markers) of a line. Automatically 6732 // invalidates cached information and tries to re-estimate the 6733 // line's height. 6734 function updateLine(line, text, markedSpans, estimateHeight) { 6735 line.text = text; 6736 if (line.stateAfter) line.stateAfter = null; 6737 if (line.styles) line.styles = null; 6738 if (line.order != null) line.order = null; 6739 detachMarkedSpans(line); 6740 attachMarkedSpans(line, markedSpans); 6741 var estHeight = estimateHeight ? estimateHeight(line) : 1; 6742 if (estHeight != line.height) updateLineHeight(line, estHeight); 6743 } 6744 6745 // Detach a line from the document tree and its markers. 6746 function cleanUpLine(line) { 6747 line.parent = null; 6748 detachMarkedSpans(line); 6749 } 6750 6751 function extractLineClasses(type, output) { 6752 if (type) for (;;) { 6753 var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); 6754 if (!lineClass) break; 6755 type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); 6756 var prop = lineClass[1] ? "bgClass" : "textClass"; 6757 if (output[prop] == null) 6758 output[prop] = lineClass[2]; 6759 else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) 6760 output[prop] += " " + lineClass[2]; 6761 } 6762 return type; 6763 } 6764 6765 function callBlankLine(mode, state) { 6766 if (mode.blankLine) return mode.blankLine(state); 6767 if (!mode.innerMode) return; 6768 var inner = CodeMirror.innerMode(mode, state); 6769 if (inner.mode.blankLine) return inner.mode.blankLine(inner.state); 6770 } 6771 6772 function readToken(mode, stream, state, inner) { 6773 for (var i = 0; i < 10; i++) { 6774 if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode; 6775 var style = mode.token(stream, state); 6776 if (stream.pos > stream.start) return style; 6777 } 6778 throw new Error("Mode " + mode.name + " failed to advance stream."); 6779 } 6780 6781 // Utility for getTokenAt and getLineTokens 6782 function takeToken(cm, pos, precise, asArray) { 6783 function getObj(copy) { 6784 return {start: stream.start, end: stream.pos, 6785 string: stream.current(), 6786 type: style || null, 6787 state: copy ? copyState(doc.mode, state) : state}; 6788 } 6789 6790 var doc = cm.doc, mode = doc.mode, style; 6791 pos = clipPos(doc, pos); 6792 var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise); 6793 var stream = new StringStream(line.text, cm.options.tabSize), tokens; 6794 if (asArray) tokens = []; 6795 while ((asArray || stream.pos < pos.ch) && !stream.eol()) { 6796 stream.start = stream.pos; 6797 style = readToken(mode, stream, state); 6798 if (asArray) tokens.push(getObj(true)); 6799 } 6800 return asArray ? tokens : getObj(); 6801 } 6802 6803 // Run the given mode's parser over a line, calling f for each token. 6804 function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) { 6805 var flattenSpans = mode.flattenSpans; 6806 if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; 6807 var curStart = 0, curStyle = null; 6808 var stream = new StringStream(text, cm.options.tabSize), style; 6809 var inner = cm.options.addModeClass && [null]; 6810 if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses); 6811 while (!stream.eol()) { 6812 if (stream.pos > cm.options.maxHighlightLength) { 6813 flattenSpans = false; 6814 if (forceToEnd) processLine(cm, text, state, stream.pos); 6815 stream.pos = text.length; 6816 style = null; 6817 } else { 6818 style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses); 6819 } 6820 if (inner) { 6821 var mName = inner[0].name; 6822 if (mName) style = "m-" + (style ? mName + " " + style : mName); 6823 } 6824 if (!flattenSpans || curStyle != style) { 6825 while (curStart < stream.start) { 6826 curStart = Math.min(stream.start, curStart + 50000); 6827 f(curStart, curStyle); 6828 } 6829 curStyle = style; 6830 } 6831 stream.start = stream.pos; 6832 } 6833 while (curStart < stream.pos) { 6834 // Webkit seems to refuse to render text nodes longer than 57444 characters 6835 var pos = Math.min(stream.pos, curStart + 50000); 6836 f(pos, curStyle); 6837 curStart = pos; 6838 } 6839 } 6840 6841 // Compute a style array (an array starting with a mode generation 6842 // -- for invalidation -- followed by pairs of end positions and 6843 // style strings), which is used to highlight the tokens on the 6844 // line. 6845 function highlightLine(cm, line, state, forceToEnd) { 6846 // A styles array always starts with a number identifying the 6847 // mode/overlays that it is based on (for easy invalidation). 6848 var st = [cm.state.modeGen], lineClasses = {}; 6849 // Compute the base array of styles 6850 runMode(cm, line.text, cm.doc.mode, state, function(end, style) { 6851 st.push(end, style); 6852 }, lineClasses, forceToEnd); 6853 6854 // Run overlays, adjust style array. 6855 for (var o = 0; o < cm.state.overlays.length; ++o) { 6856 var overlay = cm.state.overlays[o], i = 1, at = 0; 6857 runMode(cm, line.text, overlay.mode, true, function(end, style) { 6858 var start = i; 6859 // Ensure there's a token end at the current position, and that i points at it 6860 while (at < end) { 6861 var i_end = st[i]; 6862 if (i_end > end) 6863 st.splice(i, 1, end, st[i+1], i_end); 6864 i += 2; 6865 at = Math.min(end, i_end); 6866 } 6867 if (!style) return; 6868 if (overlay.opaque) { 6869 st.splice(start, i - start, end, "cm-overlay " + style); 6870 i = start + 2; 6871 } else { 6872 for (; start < i; start += 2) { 6873 var cur = st[start+1]; 6874 st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style; 6875 } 6876 } 6877 }, lineClasses); 6878 } 6879 6880 return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}; 6881 } 6882 6883 function getLineStyles(cm, line, updateFrontier) { 6884 if (!line.styles || line.styles[0] != cm.state.modeGen) { 6885 var state = getStateBefore(cm, lineNo(line)); 6886 var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state); 6887 line.stateAfter = state; 6888 line.styles = result.styles; 6889 if (result.classes) line.styleClasses = result.classes; 6890 else if (line.styleClasses) line.styleClasses = null; 6891 if (updateFrontier === cm.doc.frontier) cm.doc.frontier++; 6892 } 6893 return line.styles; 6894 } 6895 6896 // Lightweight form of highlight -- proceed over this line and 6897 // update state, but don't save a style array. Used for lines that 6898 // aren't currently visible. 6899 function processLine(cm, text, state, startAt) { 6900 var mode = cm.doc.mode; 6901 var stream = new StringStream(text, cm.options.tabSize); 6902 stream.start = stream.pos = startAt || 0; 6903 if (text == "") callBlankLine(mode, state); 6904 while (!stream.eol()) { 6905 readToken(mode, stream, state); 6906 stream.start = stream.pos; 6907 } 6908 } 6909 6910 // Convert a style as returned by a mode (either null, or a string 6911 // containing one or more styles) to a CSS style. This is cached, 6912 // and also looks for line-wide styles. 6913 var styleToClassCache = {}, styleToClassCacheWithMode = {}; 6914 function interpretTokenStyle(style, options) { 6915 if (!style || /^\s*$/.test(style)) return null; 6916 var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; 6917 return cache[style] || 6918 (cache[style] = style.replace(/\S+/g, "cm-$&")); 6919 } 6920 6921 // Render the DOM representation of the text of a line. Also builds 6922 // up a 'line map', which points at the DOM nodes that represent 6923 // specific stretches of text, and is used by the measuring code. 6924 // The returned object contains the DOM node, this map, and 6925 // information about line-wide styles that were set by the mode. 6926 function buildLineContent(cm, lineView) { 6927 // The padding-right forces the element to have a 'border', which 6928 // is needed on Webkit to be able to get line-level bounding 6929 // rectangles for it (in measureChar). 6930 var content = elt("span", null, null, webkit ? "padding-right: .1px" : null); 6931 var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content, 6932 col: 0, pos: 0, cm: cm, 6933 splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}; 6934 lineView.measure = {}; 6935 6936 // Iterate over the logical lines that make up this visual line. 6937 for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { 6938 var line = i ? lineView.rest[i - 1] : lineView.line, order; 6939 builder.pos = 0; 6940 builder.addToken = buildToken; 6941 // Optionally wire in some hacks into the token-rendering 6942 // algorithm, to deal with browser quirks. 6943 if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) 6944 builder.addToken = buildTokenBadBidi(builder.addToken, order); 6945 builder.map = []; 6946 var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); 6947 insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); 6948 if (line.styleClasses) { 6949 if (line.styleClasses.bgClass) 6950 builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); 6951 if (line.styleClasses.textClass) 6952 builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); 6953 } 6954 6955 // Ensure at least a single node is present, for measuring. 6956 if (builder.map.length == 0) 6957 builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); 6958 6959 // Store the map and a cache object for the current logical line 6960 if (i == 0) { 6961 lineView.measure.map = builder.map; 6962 lineView.measure.cache = {}; 6963 } else { 6964 (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); 6965 (lineView.measure.caches || (lineView.measure.caches = [])).push({}); 6966 } 6967 } 6968 6969 // See issue #2901 6970 if (webkit) { 6971 var last = builder.content.lastChild 6972 if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) 6973 builder.content.className = "cm-tab-wrap-hack"; 6974 } 6975 6976 signal(cm, "renderLine", cm, lineView.line, builder.pre); 6977 if (builder.pre.className) 6978 builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); 6979 6980 return builder; 6981 } 6982 6983 function defaultSpecialCharPlaceholder(ch) { 6984 var token = elt("span", "\u2022", "cm-invalidchar"); 6985 token.title = "\\u" + ch.charCodeAt(0).toString(16); 6986 token.setAttribute("aria-label", token.title); 6987 return token; 6988 } 6989 6990 // Build up the DOM representation for a single token, and add it to 6991 // the line map. Takes care to render special characters separately. 6992 function buildToken(builder, text, style, startStyle, endStyle, title, css) { 6993 if (!text) return; 6994 var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text; 6995 var special = builder.cm.state.specialChars, mustWrap = false; 6996 if (!special.test(text)) { 6997 builder.col += text.length; 6998 var content = document.createTextNode(displayText); 6999 builder.map.push(builder.pos, builder.pos + text.length, content); 7000 if (ie && ie_version < 9) mustWrap = true; 7001 builder.pos += text.length; 7002 } else { 7003 var content = document.createDocumentFragment(), pos = 0; 7004 while (true) { 7005 special.lastIndex = pos; 7006 var m = special.exec(text); 7007 var skipped = m ? m.index - pos : text.length - pos; 7008 if (skipped) { 7009 var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); 7010 if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); 7011 else content.appendChild(txt); 7012 builder.map.push(builder.pos, builder.pos + skipped, txt); 7013 builder.col += skipped; 7014 builder.pos += skipped; 7015 } 7016 if (!m) break; 7017 pos += skipped + 1; 7018 if (m[0] == "\t") { 7019 var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; 7020 var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); 7021 txt.setAttribute("role", "presentation"); 7022 txt.setAttribute("cm-text", "\t"); 7023 builder.col += tabWidth; 7024 } else if (m[0] == "\r" || m[0] == "\n") { 7025 var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); 7026 txt.setAttribute("cm-text", m[0]); 7027 builder.col += 1; 7028 } else { 7029 var txt = builder.cm.options.specialCharPlaceholder(m[0]); 7030 txt.setAttribute("cm-text", m[0]); 7031 if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); 7032 else content.appendChild(txt); 7033 builder.col += 1; 7034 } 7035 builder.map.push(builder.pos, builder.pos + 1, txt); 7036 builder.pos++; 7037 } 7038 } 7039 if (style || startStyle || endStyle || mustWrap || css) { 7040 var fullStyle = style || ""; 7041 if (startStyle) fullStyle += startStyle; 7042 if (endStyle) fullStyle += endStyle; 7043 var token = elt("span", [content], fullStyle, css); 7044 if (title) token.title = title; 7045 return builder.content.appendChild(token); 7046 } 7047 builder.content.appendChild(content); 7048 } 7049 7050 function splitSpaces(old) { 7051 var out = " "; 7052 for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; 7053 out += " "; 7054 return out; 7055 } 7056 7057 // Work around nonsense dimensions being reported for stretches of 7058 // right-to-left text. 7059 function buildTokenBadBidi(inner, order) { 7060 return function(builder, text, style, startStyle, endStyle, title, css) { 7061 style = style ? style + " cm-force-border" : "cm-force-border"; 7062 var start = builder.pos, end = start + text.length; 7063 for (;;) { 7064 // Find the part that overlaps with the start of this text 7065 for (var i = 0; i < order.length; i++) { 7066 var part = order[i]; 7067 if (part.to > start && part.from <= start) break; 7068 } 7069 if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css); 7070 inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css); 7071 startStyle = null; 7072 text = text.slice(part.to - start); 7073 start = part.to; 7074 } 7075 }; 7076 } 7077 7078 function buildCollapsedSpan(builder, size, marker, ignoreWidget) { 7079 var widget = !ignoreWidget && marker.widgetNode; 7080 if (widget) builder.map.push(builder.pos, builder.pos + size, widget); 7081 if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { 7082 if (!widget) 7083 widget = builder.content.appendChild(document.createElement("span")); 7084 widget.setAttribute("cm-marker", marker.id); 7085 } 7086 if (widget) { 7087 builder.cm.display.input.setUneditable(widget); 7088 builder.content.appendChild(widget); 7089 } 7090 builder.pos += size; 7091 } 7092 7093 // Outputs a number of spans to make up a line, taking highlighting 7094 // and marked text into account. 7095 function insertLineContent(line, builder, styles) { 7096 var spans = line.markedSpans, allText = line.text, at = 0; 7097 if (!spans) { 7098 for (var i = 1; i < styles.length; i+=2) 7099 builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options)); 7100 return; 7101 } 7102 7103 var len = allText.length, pos = 0, i = 1, text = "", style, css; 7104 var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; 7105 for (;;) { 7106 if (nextChange == pos) { // Update current marker set 7107 spanStyle = spanEndStyle = spanStartStyle = title = css = ""; 7108 collapsed = null; nextChange = Infinity; 7109 var foundBookmarks = [], endStyles 7110 for (var j = 0; j < spans.length; ++j) { 7111 var sp = spans[j], m = sp.marker; 7112 if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { 7113 foundBookmarks.push(m); 7114 } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { 7115 if (sp.to != null && sp.to != pos && nextChange > sp.to) { 7116 nextChange = sp.to; 7117 spanEndStyle = ""; 7118 } 7119 if (m.className) spanStyle += " " + m.className; 7120 if (m.css) css = (css ? css + ";" : "") + m.css; 7121 if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; 7122 if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to) 7123 if (m.title && !title) title = m.title; 7124 if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) 7125 collapsed = sp; 7126 } else if (sp.from > pos && nextChange > sp.from) { 7127 nextChange = sp.from; 7128 } 7129 } 7130 if (endStyles) for (var j = 0; j < endStyles.length; j += 2) 7131 if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j] 7132 7133 if (!collapsed || collapsed.from == pos) for (var j = 0; j < foundBookmarks.length; ++j) 7134 buildCollapsedSpan(builder, 0, foundBookmarks[j]); 7135 if (collapsed && (collapsed.from || 0) == pos) { 7136 buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, 7137 collapsed.marker, collapsed.from == null); 7138 if (collapsed.to == null) return; 7139 if (collapsed.to == pos) collapsed = false; 7140 } 7141 } 7142 if (pos >= len) break; 7143 7144 var upto = Math.min(len, nextChange); 7145 while (true) { 7146 if (text) { 7147 var end = pos + text.length; 7148 if (!collapsed) { 7149 var tokenText = end > upto ? text.slice(0, upto - pos) : text; 7150 builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, 7151 spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css); 7152 } 7153 if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} 7154 pos = end; 7155 spanStartStyle = ""; 7156 } 7157 text = allText.slice(at, at = styles[i++]); 7158 style = interpretTokenStyle(styles[i++], builder.cm.options); 7159 } 7160 } 7161 } 7162 7163 // DOCUMENT DATA STRUCTURE 7164 7165 // By default, updates that start and end at the beginning of a line 7166 // are treated specially, in order to make the association of line 7167 // widgets and marker elements with the text behave more intuitive. 7168 function isWholeLineUpdate(doc, change) { 7169 return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && 7170 (!doc.cm || doc.cm.options.wholeLineUpdateBefore); 7171 } 7172 7173 // Perform a change on the document data structure. 7174 function updateDoc(doc, change, markedSpans, estimateHeight) { 7175 function spansFor(n) {return markedSpans ? markedSpans[n] : null;} 7176 function update(line, text, spans) { 7177 updateLine(line, text, spans, estimateHeight); 7178 signalLater(line, "change", line, change); 7179 } 7180 function linesFor(start, end) { 7181 for (var i = start, result = []; i < end; ++i) 7182 result.push(new Line(text[i], spansFor(i), estimateHeight)); 7183 return result; 7184 } 7185 7186 var from = change.from, to = change.to, text = change.text; 7187 var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); 7188 var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; 7189 7190 // Adjust the line structure 7191 if (change.full) { 7192 doc.insert(0, linesFor(0, text.length)); 7193 doc.remove(text.length, doc.size - text.length); 7194 } else if (isWholeLineUpdate(doc, change)) { 7195 // This is a whole-line replace. Treated specially to make 7196 // sure line objects move the way they are supposed to. 7197 var added = linesFor(0, text.length - 1); 7198 update(lastLine, lastLine.text, lastSpans); 7199 if (nlines) doc.remove(from.line, nlines); 7200 if (added.length) doc.insert(from.line, added); 7201 } else if (firstLine == lastLine) { 7202 if (text.length == 1) { 7203 update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); 7204 } else { 7205 var added = linesFor(1, text.length - 1); 7206 added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); 7207 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); 7208 doc.insert(from.line + 1, added); 7209 } 7210 } else if (text.length == 1) { 7211 update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); 7212 doc.remove(from.line + 1, nlines); 7213 } else { 7214 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); 7215 update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); 7216 var added = linesFor(1, text.length - 1); 7217 if (nlines > 1) doc.remove(from.line + 1, nlines - 1); 7218 doc.insert(from.line + 1, added); 7219 } 7220 7221 signalLater(doc, "change", doc, change); 7222 } 7223 7224 // The document is represented as a BTree consisting of leaves, with 7225 // chunk of lines in them, and branches, with up to ten leaves or 7226 // other branch nodes below them. The top node is always a branch 7227 // node, and is the document object itself (meaning it has 7228 // additional methods and properties). 7229 // 7230 // All nodes have parent links. The tree is used both to go from 7231 // line numbers to line objects, and to go from objects to numbers. 7232 // It also indexes by height, and is used to convert between height 7233 // and line object, and to find the total height of the document. 7234 // 7235 // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html 7236 7237 function LeafChunk(lines) { 7238 this.lines = lines; 7239 this.parent = null; 7240 for (var i = 0, height = 0; i < lines.length; ++i) { 7241 lines[i].parent = this; 7242 height += lines[i].height; 7243 } 7244 this.height = height; 7245 } 7246 7247 LeafChunk.prototype = { 7248 chunkSize: function() { return this.lines.length; }, 7249 // Remove the n lines at offset 'at'. 7250 removeInner: function(at, n) { 7251 for (var i = at, e = at + n; i < e; ++i) { 7252 var line = this.lines[i]; 7253 this.height -= line.height; 7254 cleanUpLine(line); 7255 signalLater(line, "delete"); 7256 } 7257 this.lines.splice(at, n); 7258 }, 7259 // Helper used to collapse a small branch into a single leaf. 7260 collapse: function(lines) { 7261 lines.push.apply(lines, this.lines); 7262 }, 7263 // Insert the given array of lines at offset 'at', count them as 7264 // having the given height. 7265 insertInner: function(at, lines, height) { 7266 this.height += height; 7267 this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); 7268 for (var i = 0; i < lines.length; ++i) lines[i].parent = this; 7269 }, 7270 // Used to iterate over a part of the tree. 7271 iterN: function(at, n, op) { 7272 for (var e = at + n; at < e; ++at) 7273 if (op(this.lines[at])) return true; 7274 } 7275 }; 7276 7277 function BranchChunk(children) { 7278 this.children = children; 7279 var size = 0, height = 0; 7280 for (var i = 0; i < children.length; ++i) { 7281 var ch = children[i]; 7282 size += ch.chunkSize(); height += ch.height; 7283 ch.parent = this; 7284 } 7285 this.size = size; 7286 this.height = height; 7287 this.parent = null; 7288 } 7289 7290 BranchChunk.prototype = { 7291 chunkSize: function() { return this.size; }, 7292 removeInner: function(at, n) { 7293 this.size -= n; 7294 for (var i = 0; i < this.children.length; ++i) { 7295 var child = this.children[i], sz = child.chunkSize(); 7296 if (at < sz) { 7297 var rm = Math.min(n, sz - at), oldHeight = child.height; 7298 child.removeInner(at, rm); 7299 this.height -= oldHeight - child.height; 7300 if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } 7301 if ((n -= rm) == 0) break; 7302 at = 0; 7303 } else at -= sz; 7304 } 7305 // If the result is smaller than 25 lines, ensure that it is a 7306 // single leaf node. 7307 if (this.size - n < 25 && 7308 (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { 7309 var lines = []; 7310 this.collapse(lines); 7311 this.children = [new LeafChunk(lines)]; 7312 this.children[0].parent = this; 7313 } 7314 }, 7315 collapse: function(lines) { 7316 for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines); 7317 }, 7318 insertInner: function(at, lines, height) { 7319 this.size += lines.length; 7320 this.height += height; 7321 for (var i = 0; i < this.children.length; ++i) { 7322 var child = this.children[i], sz = child.chunkSize(); 7323 if (at <= sz) { 7324 child.insertInner(at, lines, height); 7325 if (child.lines && child.lines.length > 50) { 7326 // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. 7327 // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. 7328 var remaining = child.lines.length % 25 + 25 7329 for (var pos = remaining; pos < child.lines.length;) { 7330 var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); 7331 child.height -= leaf.height; 7332 this.children.splice(++i, 0, leaf); 7333 leaf.parent = this; 7334 } 7335 child.lines = child.lines.slice(0, remaining); 7336 this.maybeSpill(); 7337 } 7338 break; 7339 } 7340 at -= sz; 7341 } 7342 }, 7343 // When a node has grown, check whether it should be split. 7344 maybeSpill: function() { 7345 if (this.children.length <= 10) return; 7346 var me = this; 7347 do { 7348 var spilled = me.children.splice(me.children.length - 5, 5); 7349 var sibling = new BranchChunk(spilled); 7350 if (!me.parent) { // Become the parent node 7351 var copy = new BranchChunk(me.children); 7352 copy.parent = me; 7353 me.children = [copy, sibling]; 7354 me = copy; 7355 } else { 7356 me.size -= sibling.size; 7357 me.height -= sibling.height; 7358 var myIndex = indexOf(me.parent.children, me); 7359 me.parent.children.splice(myIndex + 1, 0, sibling); 7360 } 7361 sibling.parent = me.parent; 7362 } while (me.children.length > 10); 7363 me.parent.maybeSpill(); 7364 }, 7365 iterN: function(at, n, op) { 7366 for (var i = 0; i < this.children.length; ++i) { 7367 var child = this.children[i], sz = child.chunkSize(); 7368 if (at < sz) { 7369 var used = Math.min(n, sz - at); 7370 if (child.iterN(at, used, op)) return true; 7371 if ((n -= used) == 0) break; 7372 at = 0; 7373 } else at -= sz; 7374 } 7375 } 7376 }; 7377 7378 var nextDocId = 0; 7379 var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) { 7380 if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep); 7381 if (firstLine == null) firstLine = 0; 7382 7383 BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); 7384 this.first = firstLine; 7385 this.scrollTop = this.scrollLeft = 0; 7386 this.cantEdit = false; 7387 this.cleanGeneration = 1; 7388 this.frontier = firstLine; 7389 var start = Pos(firstLine, 0); 7390 this.sel = simpleSelection(start); 7391 this.history = new History(null); 7392 this.id = ++nextDocId; 7393 this.modeOption = mode; 7394 this.lineSep = lineSep; 7395 this.extend = false; 7396 7397 if (typeof text == "string") text = this.splitLines(text); 7398 updateDoc(this, {from: start, to: start, text: text}); 7399 setSelection(this, simpleSelection(start), sel_dontScroll); 7400 }; 7401 7402 Doc.prototype = createObj(BranchChunk.prototype, { 7403 constructor: Doc, 7404 // Iterate over the document. Supports two forms -- with only one 7405 // argument, it calls that for each line in the document. With 7406 // three, it iterates over the range given by the first two (with 7407 // the second being non-inclusive). 7408 iter: function(from, to, op) { 7409 if (op) this.iterN(from - this.first, to - from, op); 7410 else this.iterN(this.first, this.first + this.size, from); 7411 }, 7412 7413 // Non-public interface for adding and removing lines. 7414 insert: function(at, lines) { 7415 var height = 0; 7416 for (var i = 0; i < lines.length; ++i) height += lines[i].height; 7417 this.insertInner(at - this.first, lines, height); 7418 }, 7419 remove: function(at, n) { this.removeInner(at - this.first, n); }, 7420 7421 // From here, the methods are part of the public interface. Most 7422 // are also available from CodeMirror (editor) instances. 7423 7424 getValue: function(lineSep) { 7425 var lines = getLines(this, this.first, this.first + this.size); 7426 if (lineSep === false) return lines; 7427 return lines.join(lineSep || this.lineSeparator()); 7428 }, 7429 setValue: docMethodOp(function(code) { 7430 var top = Pos(this.first, 0), last = this.first + this.size - 1; 7431 makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), 7432 text: this.splitLines(code), origin: "setValue", full: true}, true); 7433 setSelection(this, simpleSelection(top)); 7434 }), 7435 replaceRange: function(code, from, to, origin) { 7436 from = clipPos(this, from); 7437 to = to ? clipPos(this, to) : from; 7438 replaceRange(this, code, from, to, origin); 7439 }, 7440 getRange: function(from, to, lineSep) { 7441 var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); 7442 if (lineSep === false) return lines; 7443 return lines.join(lineSep || this.lineSeparator()); 7444 }, 7445 7446 getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, 7447 7448 getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);}, 7449 getLineNumber: function(line) {return lineNo(line);}, 7450 7451 getLineHandleVisualStart: function(line) { 7452 if (typeof line == "number") line = getLine(this, line); 7453 return visualLine(line); 7454 }, 7455 7456 lineCount: function() {return this.size;}, 7457 firstLine: function() {return this.first;}, 7458 lastLine: function() {return this.first + this.size - 1;}, 7459 7460 clipPos: function(pos) {return clipPos(this, pos);}, 7461 7462 getCursor: function(start) { 7463 var range = this.sel.primary(), pos; 7464 if (start == null || start == "head") pos = range.head; 7465 else if (start == "anchor") pos = range.anchor; 7466 else if (start == "end" || start == "to" || start === false) pos = range.to(); 7467 else pos = range.from(); 7468 return pos; 7469 }, 7470 listSelections: function() { return this.sel.ranges; }, 7471 somethingSelected: function() {return this.sel.somethingSelected();}, 7472 7473 setCursor: docMethodOp(function(line, ch, options) { 7474 setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); 7475 }), 7476 setSelection: docMethodOp(function(anchor, head, options) { 7477 setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); 7478 }), 7479 extendSelection: docMethodOp(function(head, other, options) { 7480 extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); 7481 }), 7482 extendSelections: docMethodOp(function(heads, options) { 7483 extendSelections(this, clipPosArray(this, heads), options); 7484 }), 7485 extendSelectionsBy: docMethodOp(function(f, options) { 7486 var heads = map(this.sel.ranges, f); 7487 extendSelections(this, clipPosArray(this, heads), options); 7488 }), 7489 setSelections: docMethodOp(function(ranges, primary, options) { 7490 if (!ranges.length) return; 7491 for (var i = 0, out = []; i < ranges.length; i++) 7492 out[i] = new Range(clipPos(this, ranges[i].anchor), 7493 clipPos(this, ranges[i].head)); 7494 if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex); 7495 setSelection(this, normalizeSelection(out, primary), options); 7496 }), 7497 addSelection: docMethodOp(function(anchor, head, options) { 7498 var ranges = this.sel.ranges.slice(0); 7499 ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); 7500 setSelection(this, normalizeSelection(ranges, ranges.length - 1), options); 7501 }), 7502 7503 getSelection: function(lineSep) { 7504 var ranges = this.sel.ranges, lines; 7505 for (var i = 0; i < ranges.length; i++) { 7506 var sel = getBetween(this, ranges[i].from(), ranges[i].to()); 7507 lines = lines ? lines.concat(sel) : sel; 7508 } 7509 if (lineSep === false) return lines; 7510 else return lines.join(lineSep || this.lineSeparator()); 7511 }, 7512 getSelections: function(lineSep) { 7513 var parts = [], ranges = this.sel.ranges; 7514 for (var i = 0; i < ranges.length; i++) { 7515 var sel = getBetween(this, ranges[i].from(), ranges[i].to()); 7516 if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator()); 7517 parts[i] = sel; 7518 } 7519 return parts; 7520 }, 7521 replaceSelection: function(code, collapse, origin) { 7522 var dup = []; 7523 for (var i = 0; i < this.sel.ranges.length; i++) 7524 dup[i] = code; 7525 this.replaceSelections(dup, collapse, origin || "+input"); 7526 }, 7527 replaceSelections: docMethodOp(function(code, collapse, origin) { 7528 var changes = [], sel = this.sel; 7529 for (var i = 0; i < sel.ranges.length; i++) { 7530 var range = sel.ranges[i]; 7531 changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin}; 7532 } 7533 var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); 7534 for (var i = changes.length - 1; i >= 0; i--) 7535 makeChange(this, changes[i]); 7536 if (newSel) setSelectionReplaceHistory(this, newSel); 7537 else if (this.cm) ensureCursorVisible(this.cm); 7538 }), 7539 undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), 7540 redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), 7541 undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), 7542 redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), 7543 7544 setExtending: function(val) {this.extend = val;}, 7545 getExtending: function() {return this.extend;}, 7546 7547 historySize: function() { 7548 var hist = this.history, done = 0, undone = 0; 7549 for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done; 7550 for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone; 7551 return {undo: done, redo: undone}; 7552 }, 7553 clearHistory: function() {this.history = new History(this.history.maxGeneration);}, 7554 7555 markClean: function() { 7556 this.cleanGeneration = this.changeGeneration(true); 7557 }, 7558 changeGeneration: function(forceSplit) { 7559 if (forceSplit) 7560 this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; 7561 return this.history.generation; 7562 }, 7563 isClean: function (gen) { 7564 return this.history.generation == (gen || this.cleanGeneration); 7565 }, 7566 7567 getHistory: function() { 7568 return {done: copyHistoryArray(this.history.done), 7569 undone: copyHistoryArray(this.history.undone)}; 7570 }, 7571 setHistory: function(histData) { 7572 var hist = this.history = new History(this.history.maxGeneration); 7573 hist.done = copyHistoryArray(histData.done.slice(0), null, true); 7574 hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); 7575 }, 7576 7577 addLineClass: docMethodOp(function(handle, where, cls) { 7578 return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { 7579 var prop = where == "text" ? "textClass" 7580 : where == "background" ? "bgClass" 7581 : where == "gutter" ? "gutterClass" : "wrapClass"; 7582 if (!line[prop]) line[prop] = cls; 7583 else if (classTest(cls).test(line[prop])) return false; 7584 else line[prop] += " " + cls; 7585 return true; 7586 }); 7587 }), 7588 removeLineClass: docMethodOp(function(handle, where, cls) { 7589 return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { 7590 var prop = where == "text" ? "textClass" 7591 : where == "background" ? "bgClass" 7592 : where == "gutter" ? "gutterClass" : "wrapClass"; 7593 var cur = line[prop]; 7594 if (!cur) return false; 7595 else if (cls == null) line[prop] = null; 7596 else { 7597 var found = cur.match(classTest(cls)); 7598 if (!found) return false; 7599 var end = found.index + found[0].length; 7600 line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; 7601 } 7602 return true; 7603 }); 7604 }), 7605 7606 addLineWidget: docMethodOp(function(handle, node, options) { 7607 return addLineWidget(this, handle, node, options); 7608 }), 7609 removeLineWidget: function(widget) { widget.clear(); }, 7610 7611 markText: function(from, to, options) { 7612 return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range"); 7613 }, 7614 setBookmark: function(pos, options) { 7615 var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), 7616 insertLeft: options && options.insertLeft, 7617 clearWhenEmpty: false, shared: options && options.shared, 7618 handleMouseEvents: options && options.handleMouseEvents}; 7619 pos = clipPos(this, pos); 7620 return markText(this, pos, pos, realOpts, "bookmark"); 7621 }, 7622 findMarksAt: function(pos) { 7623 pos = clipPos(this, pos); 7624 var markers = [], spans = getLine(this, pos.line).markedSpans; 7625 if (spans) for (var i = 0; i < spans.length; ++i) { 7626 var span = spans[i]; 7627 if ((span.from == null || span.from <= pos.ch) && 7628 (span.to == null || span.to >= pos.ch)) 7629 markers.push(span.marker.parent || span.marker); 7630 } 7631 return markers; 7632 }, 7633 findMarks: function(from, to, filter) { 7634 from = clipPos(this, from); to = clipPos(this, to); 7635 var found = [], lineNo = from.line; 7636 this.iter(from.line, to.line + 1, function(line) { 7637 var spans = line.markedSpans; 7638 if (spans) for (var i = 0; i < spans.length; i++) { 7639 var span = spans[i]; 7640 if (!(span.to != null && lineNo == from.line && from.ch >= span.to || 7641 span.from == null && lineNo != from.line || 7642 span.from != null && lineNo == to.line && span.from >= to.ch) && 7643 (!filter || filter(span.marker))) 7644 found.push(span.marker.parent || span.marker); 7645 } 7646 ++lineNo; 7647 }); 7648 return found; 7649 }, 7650 getAllMarks: function() { 7651 var markers = []; 7652 this.iter(function(line) { 7653 var sps = line.markedSpans; 7654 if (sps) for (var i = 0; i < sps.length; ++i) 7655 if (sps[i].from != null) markers.push(sps[i].marker); 7656 }); 7657 return markers; 7658 }, 7659 7660 posFromIndex: function(off) { 7661 var ch, lineNo = this.first, sepSize = this.lineSeparator().length; 7662 this.iter(function(line) { 7663 var sz = line.text.length + sepSize; 7664 if (sz > off) { ch = off; return true; } 7665 off -= sz; 7666 ++lineNo; 7667 }); 7668 return clipPos(this, Pos(lineNo, ch)); 7669 }, 7670 indexFromPos: function (coords) { 7671 coords = clipPos(this, coords); 7672 var index = coords.ch; 7673 if (coords.line < this.first || coords.ch < 0) return 0; 7674 var sepSize = this.lineSeparator().length; 7675 this.iter(this.first, coords.line, function (line) { 7676 index += line.text.length + sepSize; 7677 }); 7678 return index; 7679 }, 7680 7681 copy: function(copyHistory) { 7682 var doc = new Doc(getLines(this, this.first, this.first + this.size), 7683 this.modeOption, this.first, this.lineSep); 7684 doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; 7685 doc.sel = this.sel; 7686 doc.extend = false; 7687 if (copyHistory) { 7688 doc.history.undoDepth = this.history.undoDepth; 7689 doc.setHistory(this.getHistory()); 7690 } 7691 return doc; 7692 }, 7693 7694 linkedDoc: function(options) { 7695 if (!options) options = {}; 7696 var from = this.first, to = this.first + this.size; 7697 if (options.from != null && options.from > from) from = options.from; 7698 if (options.to != null && options.to < to) to = options.to; 7699 var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep); 7700 if (options.sharedHist) copy.history = this.history; 7701 (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); 7702 copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; 7703 copySharedMarkers(copy, findSharedMarkers(this)); 7704 return copy; 7705 }, 7706 unlinkDoc: function(other) { 7707 if (other instanceof CodeMirror) other = other.doc; 7708 if (this.linked) for (var i = 0; i < this.linked.length; ++i) { 7709 var link = this.linked[i]; 7710 if (link.doc != other) continue; 7711 this.linked.splice(i, 1); 7712 other.unlinkDoc(this); 7713 detachSharedMarkers(findSharedMarkers(this)); 7714 break; 7715 } 7716 // If the histories were shared, split them again 7717 if (other.history == this.history) { 7718 var splitIds = [other.id]; 7719 linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); 7720 other.history = new History(null); 7721 other.history.done = copyHistoryArray(this.history.done, splitIds); 7722 other.history.undone = copyHistoryArray(this.history.undone, splitIds); 7723 } 7724 }, 7725 iterLinkedDocs: function(f) {linkedDocs(this, f);}, 7726 7727 getMode: function() {return this.mode;}, 7728 getEditor: function() {return this.cm;}, 7729 7730 splitLines: function(str) { 7731 if (this.lineSep) return str.split(this.lineSep); 7732 return splitLinesAuto(str); 7733 }, 7734 lineSeparator: function() { return this.lineSep || "\n"; } 7735 }); 7736 7737 // Public alias. 7738 Doc.prototype.eachLine = Doc.prototype.iter; 7739 7740 // Set up methods on CodeMirror's prototype to redirect to the editor's document. 7741 var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); 7742 for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) 7743 CodeMirror.prototype[prop] = (function(method) { 7744 return function() {return method.apply(this.doc, arguments);}; 7745 })(Doc.prototype[prop]); 7746 7747 eventMixin(Doc); 7748 7749 // Call f for all linked documents. 7750 function linkedDocs(doc, f, sharedHistOnly) { 7751 function propagate(doc, skip, sharedHist) { 7752 if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { 7753 var rel = doc.linked[i]; 7754 if (rel.doc == skip) continue; 7755 var shared = sharedHist && rel.sharedHist; 7756 if (sharedHistOnly && !shared) continue; 7757 f(rel.doc, shared); 7758 propagate(rel.doc, doc, shared); 7759 } 7760 } 7761 propagate(doc, null, true); 7762 } 7763 7764 // Attach a document to an editor. 7765 function attachDoc(cm, doc) { 7766 if (doc.cm) throw new Error("This document is already in use."); 7767 cm.doc = doc; 7768 doc.cm = cm; 7769 estimateLineHeights(cm); 7770 loadMode(cm); 7771 if (!cm.options.lineWrapping) findMaxLine(cm); 7772 cm.options.mode = doc.modeOption; 7773 regChange(cm); 7774 } 7775 7776 // LINE UTILITIES 7777 7778 // Find the line object corresponding to the given line number. 7779 function getLine(doc, n) { 7780 n -= doc.first; 7781 if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document."); 7782 for (var chunk = doc; !chunk.lines;) { 7783 for (var i = 0;; ++i) { 7784 var child = chunk.children[i], sz = child.chunkSize(); 7785 if (n < sz) { chunk = child; break; } 7786 n -= sz; 7787 } 7788 } 7789 return chunk.lines[n]; 7790 } 7791 7792 // Get the part of a document between two positions, as an array of 7793 // strings. 7794 function getBetween(doc, start, end) { 7795 var out = [], n = start.line; 7796 doc.iter(start.line, end.line + 1, function(line) { 7797 var text = line.text; 7798 if (n == end.line) text = text.slice(0, end.ch); 7799 if (n == start.line) text = text.slice(start.ch); 7800 out.push(text); 7801 ++n; 7802 }); 7803 return out; 7804 } 7805 // Get the lines between from and to, as array of strings. 7806 function getLines(doc, from, to) { 7807 var out = []; 7808 doc.iter(from, to, function(line) { out.push(line.text); }); 7809 return out; 7810 } 7811 7812 // Update the height of a line, propagating the height change 7813 // upwards to parent nodes. 7814 function updateLineHeight(line, height) { 7815 var diff = height - line.height; 7816 if (diff) for (var n = line; n; n = n.parent) n.height += diff; 7817 } 7818 7819 // Given a line object, find its line number by walking up through 7820 // its parent links. 7821 function lineNo(line) { 7822 if (line.parent == null) return null; 7823 var cur = line.parent, no = indexOf(cur.lines, line); 7824 for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { 7825 for (var i = 0;; ++i) { 7826 if (chunk.children[i] == cur) break; 7827 no += chunk.children[i].chunkSize(); 7828 } 7829 } 7830 return no + cur.first; 7831 } 7832 7833 // Find the line at the given vertical position, using the height 7834 // information in the document tree. 7835 function lineAtHeight(chunk, h) { 7836 var n = chunk.first; 7837 outer: do { 7838 for (var i = 0; i < chunk.children.length; ++i) { 7839 var child = chunk.children[i], ch = child.height; 7840 if (h < ch) { chunk = child; continue outer; } 7841 h -= ch; 7842 n += child.chunkSize(); 7843 } 7844 return n; 7845 } while (!chunk.lines); 7846 for (var i = 0; i < chunk.lines.length; ++i) { 7847 var line = chunk.lines[i], lh = line.height; 7848 if (h < lh) break; 7849 h -= lh; 7850 } 7851 return n + i; 7852 } 7853 7854 7855 // Find the height above the given line. 7856 function heightAtLine(lineObj) { 7857 lineObj = visualLine(lineObj); 7858 7859 var h = 0, chunk = lineObj.parent; 7860 for (var i = 0; i < chunk.lines.length; ++i) { 7861 var line = chunk.lines[i]; 7862 if (line == lineObj) break; 7863 else h += line.height; 7864 } 7865 for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { 7866 for (var i = 0; i < p.children.length; ++i) { 7867 var cur = p.children[i]; 7868 if (cur == chunk) break; 7869 else h += cur.height; 7870 } 7871 } 7872 return h; 7873 } 7874 7875 // Get the bidi ordering for the given line (and cache it). Returns 7876 // false for lines that are fully left-to-right, and an array of 7877 // BidiSpan objects otherwise. 7878 function getOrder(line) { 7879 var order = line.order; 7880 if (order == null) order = line.order = bidiOrdering(line.text); 7881 return order; 7882 } 7883 7884 // HISTORY 7885 7886 function History(startGen) { 7887 // Arrays of change events and selections. Doing something adds an 7888 // event to done and clears undo. Undoing moves events from done 7889 // to undone, redoing moves them in the other direction. 7890 this.done = []; this.undone = []; 7891 this.undoDepth = Infinity; 7892 // Used to track when changes can be merged into a single undo 7893 // event 7894 this.lastModTime = this.lastSelTime = 0; 7895 this.lastOp = this.lastSelOp = null; 7896 this.lastOrigin = this.lastSelOrigin = null; 7897 // Used by the isClean() method 7898 this.generation = this.maxGeneration = startGen || 1; 7899 } 7900 7901 // Create a history change event from an updateDoc-style change 7902 // object. 7903 function historyChangeFromChange(doc, change) { 7904 var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; 7905 attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); 7906 linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); 7907 return histChange; 7908 } 7909 7910 // Pop all selection events off the end of a history array. Stop at 7911 // a change event. 7912 function clearSelectionEvents(array) { 7913 while (array.length) { 7914 var last = lst(array); 7915 if (last.ranges) array.pop(); 7916 else break; 7917 } 7918 } 7919 7920 // Find the top change event in the history. Pop off selection 7921 // events that are in the way. 7922 function lastChangeEvent(hist, force) { 7923 if (force) { 7924 clearSelectionEvents(hist.done); 7925 return lst(hist.done); 7926 } else if (hist.done.length && !lst(hist.done).ranges) { 7927 return lst(hist.done); 7928 } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { 7929 hist.done.pop(); 7930 return lst(hist.done); 7931 } 7932 } 7933 7934 // Register a change in the history. Merges changes that are within 7935 // a single operation, ore are close together with an origin that 7936 // allows merging (starting with "+") into a single event. 7937 function addChangeToHistory(doc, change, selAfter, opId) { 7938 var hist = doc.history; 7939 hist.undone.length = 0; 7940 var time = +new Date, cur; 7941 7942 if ((hist.lastOp == opId || 7943 hist.lastOrigin == change.origin && change.origin && 7944 ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || 7945 change.origin.charAt(0) == "*")) && 7946 (cur = lastChangeEvent(hist, hist.lastOp == opId))) { 7947 // Merge this change into the last event 7948 var last = lst(cur.changes); 7949 if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { 7950 // Optimized case for simple insertion -- don't want to add 7951 // new changesets for every character typed 7952 last.to = changeEnd(change); 7953 } else { 7954 // Add new sub-event 7955 cur.changes.push(historyChangeFromChange(doc, change)); 7956 } 7957 } else { 7958 // Can not be merged, start a new event. 7959 var before = lst(hist.done); 7960 if (!before || !before.ranges) 7961 pushSelectionToHistory(doc.sel, hist.done); 7962 cur = {changes: [historyChangeFromChange(doc, change)], 7963 generation: hist.generation}; 7964 hist.done.push(cur); 7965 while (hist.done.length > hist.undoDepth) { 7966 hist.done.shift(); 7967 if (!hist.done[0].ranges) hist.done.shift(); 7968 } 7969 } 7970 hist.done.push(selAfter); 7971 hist.generation = ++hist.maxGeneration; 7972 hist.lastModTime = hist.lastSelTime = time; 7973 hist.lastOp = hist.lastSelOp = opId; 7974 hist.lastOrigin = hist.lastSelOrigin = change.origin; 7975 7976 if (!last) signal(doc, "historyAdded"); 7977 } 7978 7979 function selectionEventCanBeMerged(doc, origin, prev, sel) { 7980 var ch = origin.charAt(0); 7981 return ch == "*" || 7982 ch == "+" && 7983 prev.ranges.length == sel.ranges.length && 7984 prev.somethingSelected() == sel.somethingSelected() && 7985 new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); 7986 } 7987 7988 // Called whenever the selection changes, sets the new selection as 7989 // the pending selection in the history, and pushes the old pending 7990 // selection into the 'done' array when it was significantly 7991 // different (in number of selected ranges, emptiness, or time). 7992 function addSelectionToHistory(doc, sel, opId, options) { 7993 var hist = doc.history, origin = options && options.origin; 7994 7995 // A new event is started when the previous origin does not match 7996 // the current, or the origins don't allow matching. Origins 7997 // starting with * are always merged, those starting with + are 7998 // merged when similar and close together in time. 7999 if (opId == hist.lastSelOp || 8000 (origin && hist.lastSelOrigin == origin && 8001 (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || 8002 selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) 8003 hist.done[hist.done.length - 1] = sel; 8004 else 8005 pushSelectionToHistory(sel, hist.done); 8006 8007 hist.lastSelTime = +new Date; 8008 hist.lastSelOrigin = origin; 8009 hist.lastSelOp = opId; 8010 if (options && options.clearRedo !== false) 8011 clearSelectionEvents(hist.undone); 8012 } 8013 8014 function pushSelectionToHistory(sel, dest) { 8015 var top = lst(dest); 8016 if (!(top && top.ranges && top.equals(sel))) 8017 dest.push(sel); 8018 } 8019 8020 // Used to store marked span information in the history. 8021 function attachLocalSpans(doc, change, from, to) { 8022 var existing = change["spans_" + doc.id], n = 0; 8023 doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) { 8024 if (line.markedSpans) 8025 (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; 8026 ++n; 8027 }); 8028 } 8029 8030 // When un/re-doing restores text containing marked spans, those 8031 // that have been explicitly cleared should not be restored. 8032 function removeClearedSpans(spans) { 8033 if (!spans) return null; 8034 for (var i = 0, out; i < spans.length; ++i) { 8035 if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } 8036 else if (out) out.push(spans[i]); 8037 } 8038 return !out ? spans : out.length ? out : null; 8039 } 8040 8041 // Retrieve and filter the old marked spans stored in a change event. 8042 function getOldSpans(doc, change) { 8043 var found = change["spans_" + doc.id]; 8044 if (!found) return null; 8045 for (var i = 0, nw = []; i < change.text.length; ++i) 8046 nw.push(removeClearedSpans(found[i])); 8047 return nw; 8048 } 8049 8050 // Used both to provide a JSON-safe object in .getHistory, and, when 8051 // detaching a document, to split the history in two 8052 function copyHistoryArray(events, newGroup, instantiateSel) { 8053 for (var i = 0, copy = []; i < events.length; ++i) { 8054 var event = events[i]; 8055 if (event.ranges) { 8056 copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); 8057 continue; 8058 } 8059 var changes = event.changes, newChanges = []; 8060 copy.push({changes: newChanges}); 8061 for (var j = 0; j < changes.length; ++j) { 8062 var change = changes[j], m; 8063 newChanges.push({from: change.from, to: change.to, text: change.text}); 8064 if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { 8065 if (indexOf(newGroup, Number(m[1])) > -1) { 8066 lst(newChanges)[prop] = change[prop]; 8067 delete change[prop]; 8068 } 8069 } 8070 } 8071 } 8072 return copy; 8073 } 8074 8075 // Rebasing/resetting history to deal with externally-sourced changes 8076 8077 function rebaseHistSelSingle(pos, from, to, diff) { 8078 if (to < pos.line) { 8079 pos.line += diff; 8080 } else if (from < pos.line) { 8081 pos.line = from; 8082 pos.ch = 0; 8083 } 8084 } 8085 8086 // Tries to rebase an array of history events given a change in the 8087 // document. If the change touches the same lines as the event, the 8088 // event, and everything 'behind' it, is discarded. If the change is 8089 // before the event, the event's positions are updated. Uses a 8090 // copy-on-write scheme for the positions, to avoid having to 8091 // reallocate them all on every rebase, but also avoid problems with 8092 // shared position objects being unsafely updated. 8093 function rebaseHistArray(array, from, to, diff) { 8094 for (var i = 0; i < array.length; ++i) { 8095 var sub = array[i], ok = true; 8096 if (sub.ranges) { 8097 if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } 8098 for (var j = 0; j < sub.ranges.length; j++) { 8099 rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); 8100 rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); 8101 } 8102 continue; 8103 } 8104 for (var j = 0; j < sub.changes.length; ++j) { 8105 var cur = sub.changes[j]; 8106 if (to < cur.from.line) { 8107 cur.from = Pos(cur.from.line + diff, cur.from.ch); 8108 cur.to = Pos(cur.to.line + diff, cur.to.ch); 8109 } else if (from <= cur.to.line) { 8110 ok = false; 8111 break; 8112 } 8113 } 8114 if (!ok) { 8115 array.splice(0, i + 1); 8116 i = 0; 8117 } 8118 } 8119 } 8120 8121 function rebaseHist(hist, change) { 8122 var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; 8123 rebaseHistArray(hist.done, from, to, diff); 8124 rebaseHistArray(hist.undone, from, to, diff); 8125 } 8126 8127 // EVENT UTILITIES 8128 8129 // Due to the fact that we still support jurassic IE versions, some 8130 // compatibility wrappers are needed. 8131 8132 var e_preventDefault = CodeMirror.e_preventDefault = function(e) { 8133 if (e.preventDefault) e.preventDefault(); 8134 else e.returnValue = false; 8135 }; 8136 var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) { 8137 if (e.stopPropagation) e.stopPropagation(); 8138 else e.cancelBubble = true; 8139 }; 8140 function e_defaultPrevented(e) { 8141 return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; 8142 } 8143 var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);}; 8144 8145 function e_target(e) {return e.target || e.srcElement;} 8146 function e_button(e) { 8147 var b = e.which; 8148 if (b == null) { 8149 if (e.button & 1) b = 1; 8150 else if (e.button & 2) b = 3; 8151 else if (e.button & 4) b = 2; 8152 } 8153 if (mac && e.ctrlKey && b == 1) b = 3; 8154 return b; 8155 } 8156 8157 // EVENT HANDLING 8158 8159 // Lightweight event framework. on/off also work on DOM nodes, 8160 // registering native DOM handlers. 8161 8162 var on = CodeMirror.on = function(emitter, type, f) { 8163 if (emitter.addEventListener) 8164 emitter.addEventListener(type, f, false); 8165 else if (emitter.attachEvent) 8166 emitter.attachEvent("on" + type, f); 8167 else { 8168 var map = emitter._handlers || (emitter._handlers = {}); 8169 var arr = map[type] || (map[type] = []); 8170 arr.push(f); 8171 } 8172 }; 8173 8174 var noHandlers = [] 8175 function getHandlers(emitter, type, copy) { 8176 var arr = emitter._handlers && emitter._handlers[type] 8177 if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers 8178 else return arr || noHandlers 8179 } 8180 8181 var off = CodeMirror.off = function(emitter, type, f) { 8182 if (emitter.removeEventListener) 8183 emitter.removeEventListener(type, f, false); 8184 else if (emitter.detachEvent) 8185 emitter.detachEvent("on" + type, f); 8186 else { 8187 var handlers = getHandlers(emitter, type, false) 8188 for (var i = 0; i < handlers.length; ++i) 8189 if (handlers[i] == f) { handlers.splice(i, 1); break; } 8190 } 8191 }; 8192 8193 var signal = CodeMirror.signal = function(emitter, type /*, values...*/) { 8194 var handlers = getHandlers(emitter, type, true) 8195 if (!handlers.length) return; 8196 var args = Array.prototype.slice.call(arguments, 2); 8197 for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args); 8198 }; 8199 8200 var orphanDelayedCallbacks = null; 8201 8202 // Often, we want to signal events at a point where we are in the 8203 // middle of some work, but don't want the handler to start calling 8204 // other methods on the editor, which might be in an inconsistent 8205 // state or simply not expect any other events to happen. 8206 // signalLater looks whether there are any handlers, and schedules 8207 // them to be executed when the last operation ends, or, if no 8208 // operation is active, when a timeout fires. 8209 function signalLater(emitter, type /*, values...*/) { 8210 var arr = getHandlers(emitter, type, false) 8211 if (!arr.length) return; 8212 var args = Array.prototype.slice.call(arguments, 2), list; 8213 if (operationGroup) { 8214 list = operationGroup.delayedCallbacks; 8215 } else if (orphanDelayedCallbacks) { 8216 list = orphanDelayedCallbacks; 8217 } else { 8218 list = orphanDelayedCallbacks = []; 8219 setTimeout(fireOrphanDelayed, 0); 8220 } 8221 function bnd(f) {return function(){f.apply(null, args);};}; 8222 for (var i = 0; i < arr.length; ++i) 8223 list.push(bnd(arr[i])); 8224 } 8225 8226 function fireOrphanDelayed() { 8227 var delayed = orphanDelayedCallbacks; 8228 orphanDelayedCallbacks = null; 8229 for (var i = 0; i < delayed.length; ++i) delayed[i](); 8230 } 8231 8232 // The DOM events that CodeMirror handles can be overridden by 8233 // registering a (non-DOM) handler on the editor for the event name, 8234 // and preventDefault-ing the event in that handler. 8235 function signalDOMEvent(cm, e, override) { 8236 if (typeof e == "string") 8237 e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; 8238 signal(cm, override || e.type, cm, e); 8239 return e_defaultPrevented(e) || e.codemirrorIgnore; 8240 } 8241 8242 function signalCursorActivity(cm) { 8243 var arr = cm._handlers && cm._handlers.cursorActivity; 8244 if (!arr) return; 8245 var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); 8246 for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1) 8247 set.push(arr[i]); 8248 } 8249 8250 function hasHandler(emitter, type) { 8251 return getHandlers(emitter, type).length > 0 8252 } 8253 8254 // Add on and off methods to a constructor's prototype, to make 8255 // registering events on such objects more convenient. 8256 function eventMixin(ctor) { 8257 ctor.prototype.on = function(type, f) {on(this, type, f);}; 8258 ctor.prototype.off = function(type, f) {off(this, type, f);}; 8259 } 8260 8261 // MISC UTILITIES 8262 8263 // Number of pixels added to scroller and sizer to hide scrollbar 8264 var scrollerGap = 30; 8265 8266 // Returned or thrown by various protocols to signal 'I'm not 8267 // handling this'. 8268 var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; 8269 8270 // Reused option objects for setSelection & friends 8271 var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; 8272 8273 function Delayed() {this.id = null;} 8274 Delayed.prototype.set = function(ms, f) { 8275 clearTimeout(this.id); 8276 this.id = setTimeout(f, ms); 8277 }; 8278 8279 // Counts the column offset in a string, taking tabs into account. 8280 // Used mostly to find indentation. 8281 var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) { 8282 if (end == null) { 8283 end = string.search(/[^\s\u00a0]/); 8284 if (end == -1) end = string.length; 8285 } 8286 for (var i = startIndex || 0, n = startValue || 0;;) { 8287 var nextTab = string.indexOf("\t", i); 8288 if (nextTab < 0 || nextTab >= end) 8289 return n + (end - i); 8290 n += nextTab - i; 8291 n += tabSize - (n % tabSize); 8292 i = nextTab + 1; 8293 } 8294 }; 8295 8296 // The inverse of countColumn -- find the offset that corresponds to 8297 // a particular column. 8298 var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) { 8299 for (var pos = 0, col = 0;;) { 8300 var nextTab = string.indexOf("\t", pos); 8301 if (nextTab == -1) nextTab = string.length; 8302 var skipped = nextTab - pos; 8303 if (nextTab == string.length || col + skipped >= goal) 8304 return pos + Math.min(skipped, goal - col); 8305 col += nextTab - pos; 8306 col += tabSize - (col % tabSize); 8307 pos = nextTab + 1; 8308 if (col >= goal) return pos; 8309 } 8310 } 8311 8312 var spaceStrs = [""]; 8313 function spaceStr(n) { 8314 while (spaceStrs.length <= n) 8315 spaceStrs.push(lst(spaceStrs) + " "); 8316 return spaceStrs[n]; 8317 } 8318 8319 function lst(arr) { return arr[arr.length-1]; } 8320 8321 var selectInput = function(node) { node.select(); }; 8322 if (ios) // Mobile Safari apparently has a bug where select() is broken. 8323 selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; 8324 else if (ie) // Suppress mysterious IE10 errors 8325 selectInput = function(node) { try { node.select(); } catch(_e) {} }; 8326 8327 function indexOf(array, elt) { 8328 for (var i = 0; i < array.length; ++i) 8329 if (array[i] == elt) return i; 8330 return -1; 8331 } 8332 function map(array, f) { 8333 var out = []; 8334 for (var i = 0; i < array.length; i++) out[i] = f(array[i], i); 8335 return out; 8336 } 8337 8338 function nothing() {} 8339 8340 function createObj(base, props) { 8341 var inst; 8342 if (Object.create) { 8343 inst = Object.create(base); 8344 } else { 8345 nothing.prototype = base; 8346 inst = new nothing(); 8347 } 8348 if (props) copyObj(props, inst); 8349 return inst; 8350 }; 8351 8352 function copyObj(obj, target, overwrite) { 8353 if (!target) target = {}; 8354 for (var prop in obj) 8355 if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) 8356 target[prop] = obj[prop]; 8357 return target; 8358 } 8359 8360 function bind(f) { 8361 var args = Array.prototype.slice.call(arguments, 1); 8362 return function(){return f.apply(null, args);}; 8363 } 8364 8365 var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; 8366 var isWordCharBasic = CodeMirror.isWordChar = function(ch) { 8367 return /\w/.test(ch) || ch > "\x80" && 8368 (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); 8369 }; 8370 function isWordChar(ch, helper) { 8371 if (!helper) return isWordCharBasic(ch); 8372 if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true; 8373 return helper.test(ch); 8374 } 8375 8376 function isEmpty(obj) { 8377 for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; 8378 return true; 8379 } 8380 8381 // Extending unicode characters. A series of a non-extending char + 8382 // any number of extending chars is treated as a single unit as far 8383 // as editing and measuring is concerned. This is not fully correct, 8384 // since some scripts/fonts/browsers also treat other configurations 8385 // of code points as a group. 8386 var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; 8387 function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); } 8388 8389 // DOM UTILITIES 8390 8391 function elt(tag, content, className, style) { 8392 var e = document.createElement(tag); 8393 if (className) e.className = className; 8394 if (style) e.style.cssText = style; 8395 if (typeof content == "string") e.appendChild(document.createTextNode(content)); 8396 else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); 8397 return e; 8398 } 8399 8400 var range; 8401 if (document.createRange) range = function(node, start, end, endNode) { 8402 var r = document.createRange(); 8403 r.setEnd(endNode || node, end); 8404 r.setStart(node, start); 8405 return r; 8406 }; 8407 else range = function(node, start, end) { 8408 var r = document.body.createTextRange(); 8409 try { r.moveToElementText(node.parentNode); } 8410 catch(e) { return r; } 8411 r.collapse(true); 8412 r.moveEnd("character", end); 8413 r.moveStart("character", start); 8414 return r; 8415 }; 8416 8417 function removeChildren(e) { 8418 for (var count = e.childNodes.length; count > 0; --count) 8419 e.removeChild(e.firstChild); 8420 return e; 8421 } 8422 8423 function removeChildrenAndAdd(parent, e) { 8424 return removeChildren(parent).appendChild(e); 8425 } 8426 8427 var contains = CodeMirror.contains = function(parent, child) { 8428 if (child.nodeType == 3) // Android browser always returns false when child is a textnode 8429 child = child.parentNode; 8430 if (parent.contains) 8431 return parent.contains(child); 8432 do { 8433 if (child.nodeType == 11) child = child.host; 8434 if (child == parent) return true; 8435 } while (child = child.parentNode); 8436 }; 8437 8438 function activeElt() { 8439 var activeElement = document.activeElement; 8440 while (activeElement && activeElement.root && activeElement.root.activeElement) 8441 activeElement = activeElement.root.activeElement; 8442 return activeElement; 8443 } 8444 // Older versions of IE throws unspecified error when touching 8445 // document.activeElement in some cases (during loading, in iframe) 8446 if (ie && ie_version < 11) activeElt = function() { 8447 try { return document.activeElement; } 8448 catch(e) { return document.body; } 8449 }; 8450 8451 function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); } 8452 var rmClass = CodeMirror.rmClass = function(node, cls) { 8453 var current = node.className; 8454 var match = classTest(cls).exec(current); 8455 if (match) { 8456 var after = current.slice(match.index + match[0].length); 8457 node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); 8458 } 8459 }; 8460 var addClass = CodeMirror.addClass = function(node, cls) { 8461 var current = node.className; 8462 if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls; 8463 }; 8464 function joinClasses(a, b) { 8465 var as = a.split(" "); 8466 for (var i = 0; i < as.length; i++) 8467 if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i]; 8468 return b; 8469 } 8470 8471 // WINDOW-WIDE EVENTS 8472 8473 // These must be handled carefully, because naively registering a 8474 // handler for each editor will cause the editors to never be 8475 // garbage collected. 8476 8477 function forEachCodeMirror(f) { 8478 if (!document.body.getElementsByClassName) return; 8479 var byClass = document.body.getElementsByClassName("CodeMirror"); 8480 for (var i = 0; i < byClass.length; i++) { 8481 var cm = byClass[i].CodeMirror; 8482 if (cm) f(cm); 8483 } 8484 } 8485 8486 var globalsRegistered = false; 8487 function ensureGlobalHandlers() { 8488 if (globalsRegistered) return; 8489 registerGlobalHandlers(); 8490 globalsRegistered = true; 8491 } 8492 function registerGlobalHandlers() { 8493 // When the window resizes, we need to refresh active editors. 8494 var resizeTimer; 8495 on(window, "resize", function() { 8496 if (resizeTimer == null) resizeTimer = setTimeout(function() { 8497 resizeTimer = null; 8498 forEachCodeMirror(onResize); 8499 }, 100); 8500 }); 8501 // When the window loses focus, we want to show the editor as blurred 8502 on(window, "blur", function() { 8503 forEachCodeMirror(onBlur); 8504 }); 8505 } 8506 8507 // FEATURE DETECTION 8508 8509 // Detect drag-and-drop 8510 var dragAndDrop = function() { 8511 // There is *some* kind of drag-and-drop support in IE6-8, but I 8512 // couldn't get it to work yet. 8513 if (ie && ie_version < 9) return false; 8514 var div = elt('div'); 8515 return "draggable" in div || "dragDrop" in div; 8516 }(); 8517 8518 var zwspSupported; 8519 function zeroWidthElement(measure) { 8520 if (zwspSupported == null) { 8521 var test = elt("span", "\u200b"); 8522 removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); 8523 if (measure.firstChild.offsetHeight != 0) 8524 zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); 8525 } 8526 var node = zwspSupported ? elt("span", "\u200b") : 8527 elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); 8528 node.setAttribute("cm-text", ""); 8529 return node; 8530 } 8531 8532 // Feature-detect IE's crummy client rect reporting for bidi text 8533 var badBidiRects; 8534 function hasBadBidiRects(measure) { 8535 if (badBidiRects != null) return badBidiRects; 8536 var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); 8537 var r0 = range(txt, 0, 1).getBoundingClientRect(); 8538 if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780) 8539 var r1 = range(txt, 1, 2).getBoundingClientRect(); 8540 return badBidiRects = (r1.right - r0.right < 3); 8541 } 8542 8543 // See if "".split is the broken IE version, if so, provide an 8544 // alternative way to split lines. 8545 var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { 8546 var pos = 0, result = [], l = string.length; 8547 while (pos <= l) { 8548 var nl = string.indexOf("\n", pos); 8549 if (nl == -1) nl = string.length; 8550 var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); 8551 var rt = line.indexOf("\r"); 8552 if (rt != -1) { 8553 result.push(line.slice(0, rt)); 8554 pos += rt + 1; 8555 } else { 8556 result.push(line); 8557 pos = nl + 1; 8558 } 8559 } 8560 return result; 8561 } : function(string){return string.split(/\r\n?|\n/);}; 8562 8563 var hasSelection = window.getSelection ? function(te) { 8564 try { return te.selectionStart != te.selectionEnd; } 8565 catch(e) { return false; } 8566 } : function(te) { 8567 try {var range = te.ownerDocument.selection.createRange();} 8568 catch(e) {} 8569 if (!range || range.parentElement() != te) return false; 8570 return range.compareEndPoints("StartToEnd", range) != 0; 8571 }; 8572 8573 var hasCopyEvent = (function() { 8574 var e = elt("div"); 8575 if ("oncopy" in e) return true; 8576 e.setAttribute("oncopy", "return;"); 8577 return typeof e.oncopy == "function"; 8578 })(); 8579 8580 var badZoomedRects = null; 8581 function hasBadZoomedRects(measure) { 8582 if (badZoomedRects != null) return badZoomedRects; 8583 var node = removeChildrenAndAdd(measure, elt("span", "x")); 8584 var normal = node.getBoundingClientRect(); 8585 var fromRange = range(node, 0, 1).getBoundingClientRect(); 8586 return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; 8587 } 8588 8589 // KEY NAMES 8590 8591 var keyNames = CodeMirror.keyNames = { 8592 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 8593 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 8594 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 8595 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 8596 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", 8597 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 8598 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", 8599 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" 8600 }; 8601 (function() { 8602 // Number keys 8603 for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i); 8604 // Alphabetic keys 8605 for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); 8606 // Function keys 8607 for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; 8608 })(); 8609 8610 // BIDI HELPERS 8611 8612 function iterateBidiSections(order, from, to, f) { 8613 if (!order) return f(from, to, "ltr"); 8614 var found = false; 8615 for (var i = 0; i < order.length; ++i) { 8616 var part = order[i]; 8617 if (part.from < to && part.to > from || from == to && part.to == from) { 8618 f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); 8619 found = true; 8620 } 8621 } 8622 if (!found) f(from, to, "ltr"); 8623 } 8624 8625 function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } 8626 function bidiRight(part) { return part.level % 2 ? part.from : part.to; } 8627 8628 function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } 8629 function lineRight(line) { 8630 var order = getOrder(line); 8631 if (!order) return line.text.length; 8632 return bidiRight(lst(order)); 8633 } 8634 8635 function lineStart(cm, lineN) { 8636 var line = getLine(cm.doc, lineN); 8637 var visual = visualLine(line); 8638 if (visual != line) lineN = lineNo(visual); 8639 var order = getOrder(visual); 8640 var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); 8641 return Pos(lineN, ch); 8642 } 8643 function lineEnd(cm, lineN) { 8644 var merged, line = getLine(cm.doc, lineN); 8645 while (merged = collapsedSpanAtEnd(line)) { 8646 line = merged.find(1, true).line; 8647 lineN = null; 8648 } 8649 var order = getOrder(line); 8650 var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); 8651 return Pos(lineN == null ? lineNo(line) : lineN, ch); 8652 } 8653 function lineStartSmart(cm, pos) { 8654 var start = lineStart(cm, pos.line); 8655 var line = getLine(cm.doc, start.line); 8656 var order = getOrder(line); 8657 if (!order || order[0].level == 0) { 8658 var firstNonWS = Math.max(0, line.text.search(/\S/)); 8659 var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; 8660 return Pos(start.line, inWS ? 0 : firstNonWS); 8661 } 8662 return start; 8663 } 8664 8665 function compareBidiLevel(order, a, b) { 8666 var linedir = order[0].level; 8667 if (a == linedir) return true; 8668 if (b == linedir) return false; 8669 return a < b; 8670 } 8671 var bidiOther; 8672 function getBidiPartAt(order, pos) { 8673 bidiOther = null; 8674 for (var i = 0, found; i < order.length; ++i) { 8675 var cur = order[i]; 8676 if (cur.from < pos && cur.to > pos) return i; 8677 if ((cur.from == pos || cur.to == pos)) { 8678 if (found == null) { 8679 found = i; 8680 } else if (compareBidiLevel(order, cur.level, order[found].level)) { 8681 if (cur.from != cur.to) bidiOther = found; 8682 return i; 8683 } else { 8684 if (cur.from != cur.to) bidiOther = i; 8685 return found; 8686 } 8687 } 8688 } 8689 return found; 8690 } 8691 8692 function moveInLine(line, pos, dir, byUnit) { 8693 if (!byUnit) return pos + dir; 8694 do pos += dir; 8695 while (pos > 0 && isExtendingChar(line.text.charAt(pos))); 8696 return pos; 8697 } 8698 8699 // This is needed in order to move 'visually' through bi-directional 8700 // text -- i.e., pressing left should make the cursor go left, even 8701 // when in RTL text. The tricky part is the 'jumps', where RTL and 8702 // LTR text touch each other. This often requires the cursor offset 8703 // to move more than one unit, in order to visually move one unit. 8704 function moveVisually(line, start, dir, byUnit) { 8705 var bidi = getOrder(line); 8706 if (!bidi) return moveLogically(line, start, dir, byUnit); 8707 var pos = getBidiPartAt(bidi, start), part = bidi[pos]; 8708 var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); 8709 8710 for (;;) { 8711 if (target > part.from && target < part.to) return target; 8712 if (target == part.from || target == part.to) { 8713 if (getBidiPartAt(bidi, target) == pos) return target; 8714 part = bidi[pos += dir]; 8715 return (dir > 0) == part.level % 2 ? part.to : part.from; 8716 } else { 8717 part = bidi[pos += dir]; 8718 if (!part) return null; 8719 if ((dir > 0) == part.level % 2) 8720 target = moveInLine(line, part.to, -1, byUnit); 8721 else 8722 target = moveInLine(line, part.from, 1, byUnit); 8723 } 8724 } 8725 } 8726 8727 function moveLogically(line, start, dir, byUnit) { 8728 var target = start + dir; 8729 if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir; 8730 return target < 0 || target > line.text.length ? null : target; 8731 } 8732 8733 // Bidirectional ordering algorithm 8734 // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm 8735 // that this (partially) implements. 8736 8737 // One-char codes used for character types: 8738 // L (L): Left-to-Right 8739 // R (R): Right-to-Left 8740 // r (AL): Right-to-Left Arabic 8741 // 1 (EN): European Number 8742 // + (ES): European Number Separator 8743 // % (ET): European Number Terminator 8744 // n (AN): Arabic Number 8745 // , (CS): Common Number Separator 8746 // m (NSM): Non-Spacing Mark 8747 // b (BN): Boundary Neutral 8748 // s (B): Paragraph Separator 8749 // t (S): Segment Separator 8750 // w (WS): Whitespace 8751 // N (ON): Other Neutrals 8752 8753 // Returns null if characters are ordered as they appear 8754 // (left-to-right), or an array of sections ({from, to, level} 8755 // objects) in the order in which they occur visually. 8756 var bidiOrdering = (function() { 8757 // Character types for codepoints 0 to 0xff 8758 var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; 8759 // Character types for codepoints 0x600 to 0x6ff 8760 var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm"; 8761 function charType(code) { 8762 if (code <= 0xf7) return lowTypes.charAt(code); 8763 else if (0x590 <= code && code <= 0x5f4) return "R"; 8764 else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600); 8765 else if (0x6ee <= code && code <= 0x8ac) return "r"; 8766 else if (0x2000 <= code && code <= 0x200b) return "w"; 8767 else if (code == 0x200c) return "b"; 8768 else return "L"; 8769 } 8770 8771 var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; 8772 var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; 8773 // Browsers seem to always treat the boundaries of block elements as being L. 8774 var outerType = "L"; 8775 8776 function BidiSpan(level, from, to) { 8777 this.level = level; 8778 this.from = from; this.to = to; 8779 } 8780 8781 return function(str) { 8782 if (!bidiRE.test(str)) return false; 8783 var len = str.length, types = []; 8784 for (var i = 0, type; i < len; ++i) 8785 types.push(type = charType(str.charCodeAt(i))); 8786 8787 // W1. Examine each non-spacing mark (NSM) in the level run, and 8788 // change the type of the NSM to the type of the previous 8789 // character. If the NSM is at the start of the level run, it will 8790 // get the type of sor. 8791 for (var i = 0, prev = outerType; i < len; ++i) { 8792 var type = types[i]; 8793 if (type == "m") types[i] = prev; 8794 else prev = type; 8795 } 8796 8797 // W2. Search backwards from each instance of a European number 8798 // until the first strong type (R, L, AL, or sor) is found. If an 8799 // AL is found, change the type of the European number to Arabic 8800 // number. 8801 // W3. Change all ALs to R. 8802 for (var i = 0, cur = outerType; i < len; ++i) { 8803 var type = types[i]; 8804 if (type == "1" && cur == "r") types[i] = "n"; 8805 else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } 8806 } 8807 8808 // W4. A single European separator between two European numbers 8809 // changes to a European number. A single common separator between 8810 // two numbers of the same type changes to that type. 8811 for (var i = 1, prev = types[0]; i < len - 1; ++i) { 8812 var type = types[i]; 8813 if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; 8814 else if (type == "," && prev == types[i+1] && 8815 (prev == "1" || prev == "n")) types[i] = prev; 8816 prev = type; 8817 } 8818 8819 // W5. A sequence of European terminators adjacent to European 8820 // numbers changes to all European numbers. 8821 // W6. Otherwise, separators and terminators change to Other 8822 // Neutral. 8823 for (var i = 0; i < len; ++i) { 8824 var type = types[i]; 8825 if (type == ",") types[i] = "N"; 8826 else if (type == "%") { 8827 for (var end = i + 1; end < len && types[end] == "%"; ++end) {} 8828 var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; 8829 for (var j = i; j < end; ++j) types[j] = replace; 8830 i = end - 1; 8831 } 8832 } 8833 8834 // W7. Search backwards from each instance of a European number 8835 // until the first strong type (R, L, or sor) is found. If an L is 8836 // found, then change the type of the European number to L. 8837 for (var i = 0, cur = outerType; i < len; ++i) { 8838 var type = types[i]; 8839 if (cur == "L" && type == "1") types[i] = "L"; 8840 else if (isStrong.test(type)) cur = type; 8841 } 8842 8843 // N1. A sequence of neutrals takes the direction of the 8844 // surrounding strong text if the text on both sides has the same 8845 // direction. European and Arabic numbers act as if they were R in 8846 // terms of their influence on neutrals. Start-of-level-run (sor) 8847 // and end-of-level-run (eor) are used at level run boundaries. 8848 // N2. Any remaining neutrals take the embedding direction. 8849 for (var i = 0; i < len; ++i) { 8850 if (isNeutral.test(types[i])) { 8851 for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} 8852 var before = (i ? types[i-1] : outerType) == "L"; 8853 var after = (end < len ? types[end] : outerType) == "L"; 8854 var replace = before || after ? "L" : "R"; 8855 for (var j = i; j < end; ++j) types[j] = replace; 8856 i = end - 1; 8857 } 8858 } 8859 8860 // Here we depart from the documented algorithm, in order to avoid 8861 // building up an actual levels array. Since there are only three 8862 // levels (0, 1, 2) in an implementation that doesn't take 8863 // explicit embedding into account, we can build up the order on 8864 // the fly, without following the level-based algorithm. 8865 var order = [], m; 8866 for (var i = 0; i < len;) { 8867 if (countsAsLeft.test(types[i])) { 8868 var start = i; 8869 for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} 8870 order.push(new BidiSpan(0, start, i)); 8871 } else { 8872 var pos = i, at = order.length; 8873 for (++i; i < len && types[i] != "L"; ++i) {} 8874 for (var j = pos; j < i;) { 8875 if (countsAsNum.test(types[j])) { 8876 if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j)); 8877 var nstart = j; 8878 for (++j; j < i && countsAsNum.test(types[j]); ++j) {} 8879 order.splice(at, 0, new BidiSpan(2, nstart, j)); 8880 pos = j; 8881 } else ++j; 8882 } 8883 if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i)); 8884 } 8885 } 8886 if (order[0].level == 1 && (m = str.match(/^\s+/))) { 8887 order[0].from = m[0].length; 8888 order.unshift(new BidiSpan(0, 0, m[0].length)); 8889 } 8890 if (lst(order).level == 1 && (m = str.match(/\s+$/))) { 8891 lst(order).to -= m[0].length; 8892 order.push(new BidiSpan(0, len - m[0].length, len)); 8893 } 8894 if (order[0].level == 2) 8895 order.unshift(new BidiSpan(1, order[0].to, order[0].to)); 8896 if (order[0].level != lst(order).level) 8897 order.push(new BidiSpan(order[0].level, len, len)); 8898 8899 return order; 8900 }; 8901 })(); 8902 8903 // THE END 8904 8905 CodeMirror.version = "5.15.3"; 8906 8907 return CodeMirror; 8908 });