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;
168 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;
531 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) { 596 if (view[i].gutter) 597 view[i].gutter.style.left = left; 598 if (view[i].gutterBackground) 599 view[i].gutterBackground.style.left = left; 600 } 601 var align = view[i].alignable; 602 if (align) for (var j = 0; j < align.length; j++) 603 align[j].style.left = left; 604 } 605 if (cm.options.fixedGutter) 606 display.gutters.style.left = (comp + gutterW) + "px"; 607 } 608 609 // Used to ensure that the line number gutter is still the right 610 // size for the current document size. Returns true when an update 611 // is needed. 612 function maybeUpdateLineNumberWidth(cm) { 613 if (!cm.options.lineNumbers) return false; 614 var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; 615 if (last.length != display.lineNumChars) { 616 var test = display.measure.appendChild(elt("div", [elt("div", last)], 617 "CodeMirror-linenumber CodeMirror-gutter-elt")); 618 var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; 619 display.lineGutter.style.width = ""; 620 display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; 621 display.lineNumWidth = display.lineNumInnerWidth + padding; 622 display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; 623 display.lineGutter.style.width = display.lineNumWidth + "px"; 624 updateGutterSpace(cm); 625 return true; 626 } 627 return false;
628 } 629 630 function lineNumberFor(options, i) { 631 return String(options.lineNumberFormatter(i + options.firstLineNumber)); 632 } 633 634 // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, 635 // but using getBoundingClientRect to get a sub-pixel-accurate 636 // result. 637 function compensateForHScroll(display) { 638 return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; 639 } 640 641 // DISPLAY DRAWING 642 643 function DisplayUpdate(cm, viewport, force) { 644 var display = cm.display; 645 646 this.viewport = viewport; 647 // Store some values that we'll need later (but don't want to force a relayout for) 648 this.visible = visibleLines(display, cm.doc, viewport); 649 this.editorIsHidden = !display.wrapper.offsetWidth; 650 this.wrapperHeight = display.wrapper.clientHeight; 651 this.wrapperWidth = display.wrapper.clientWidth; 652 this.oldDisplayWidth = displayWidth(cm); 653 this.force = force; 654 this.dims = getDimensions(cm); 655 this.events = []; 656 } 657 658 DisplayUpdate.prototype.signal = function(emitter, type) { 659 if (hasHandler(emitter, type)) 660 this.events.push(arguments); 661 }; 662 DisplayUpdate.prototype.finish = function() { 663 for (var i = 0; i < this.events.length; i++) 664 signal.apply(null, this.events[i]); 665 }; 666 667 function maybeClipScrollbars(cm) { 668 var display = cm.display; 669 if (!display.scrollbarsClipped && display.scroller.offsetWidth) { 670 display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; 671 display.heightForcer.style.height = scrollGap(cm) + "px"; 672 display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; 673 display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; 674 display.scrollbarsClipped = true; 675 } 676 } 677 678 // Does the actual updating of the line display. Bails out 679 // (returning false) when there is nothing to be done and forced is 680 // false. 681 function updateDisplayIfNeeded(cm, update) { 682 var display = cm.display, doc = cm.doc; 683 684 if (update.editorIsHidden) { 685 resetView(cm); 686 return false; 687 } 688 689 // Bail out if the visible area is already rendered and nothing changed. 690 if (!update.force && 691 update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && 692 (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && 693 display.renderedView == display.view && countDirtyView(cm) == 0) 694 return false; 695 696 if (maybeUpdateLineNumberWidth(cm)) { 697 resetView(cm); 698 update.dims = getDimensions(cm); 699 } 700 701 // Compute a suitable new viewport (from & to) 702 var end = doc.first + doc.size; 703 var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); 704 var to = Math.min(end, update.visible.to + cm.options.viewportMargin); 705 if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom); 706 if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo); 707 if (sawCollapsedSpans) { 708 from = visualLineNo(cm.doc, from);
709 to = visualLineEndNo(cm.doc, to); 710 } 711 712 var different = from != display.viewFrom || to != display.viewTo || 713 display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; 714 adjustView(cm, from, to); 715 716 display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); 717 // Position the mover div to align with the current scroll position 718 cm.display.mover.style.top = display.viewOffset + "px"; 719 720 var toUpdate = countDirtyView(cm); 721 if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && 722 (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) 723 return false; 724 725 // For big changes, we hide the enclosing element during the 726 // update, since that speeds up the operations on most browsers. 727 var focused = activeElt(); 728 if (toUpdate > 4) display.lineDiv.style.display = "none"; 729 patchDisplay(cm, display.updateLineNumbers, update.dims); 730 if (toUpdate > 4) display.lineDiv.style.display = ""; 731 display.renderedView = display.view; 732 // There might have been a widget with a focused element that got 733 // hidden or updated, if so re-focus it. 734 if (focused && activeElt() != focused && focused.offsetHeight) focused.focus(); 735 736 // Prevent selection and cursors from interfering with the scroll 737 // width and height. 738 removeChildren(display.cursorDiv); 739 removeChildren(display.selectionDiv); 740 display.gutters.style.height = display.sizer.style.minHeight = 0; 741 742 if (different) { 743 display.lastWrapHeight = update.wrapperHeight; 744 display.lastWrapWidth = update.wrapperWidth; 745 startWorker(cm, 400); 746 } 747 748 display.updateLineNumbers = null; 749 750 return true; 751 } 752 753 function postUpdateDisplay(cm, update) { 754 var viewport = update.viewport; 755 756 for (var first = true;; first = false) { 757 if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { 758 // Clip forced viewport to actual scrollable area. 759 if (viewport && viewport.top != null) 760 viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; 761 // Updated line heights might result in the drawn area not 762 // actually covering the viewport. Keep looping until it does. 763 update.visible = visibleLines(cm.display, cm.doc, viewport); 764 if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) 765 break; 766 } 767 if (!updateDisplayIfNeeded(cm, update)) break; 768 updateHeightsInViewport(cm); 769 var barMeasure = measureForScrollbars(cm); 770 updateSelection(cm); 771 updateScrollbars(cm, barMeasure); 772 setDocumentHeight(cm, barMeasure); 773 } 774 775 update.signal(cm, "update", cm); 776 if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { 777 update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); 778 cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; 779 } 780 } 781 782 function updateDisplaySimple(cm, viewport) { 783 var update = new DisplayUpdate(cm, viewport); 784 if (updateDisplayIfNeeded(cm, update)) { 785 updateHeightsInViewport(cm); 786 postUpdateDisplay(cm, update); 787 var barMeasure = measureForScrollbars(cm); 788 updateSelection(cm); 789 updateScrollbars(cm, barMeasure); 790 setDocumentHeight(cm, barMeasure); 791 update.finish(); 792 } 793 } 794 795 function setDocumentHeight(cm, measure) { 796 cm.display.sizer.style.minHeight = measure.docHeight + "px"; 797 cm.display.heightForcer.style.top = measure.docHeight + "px"; 798 cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"; 799 } 800 801 // Read the actual heights of the rendered lines, and update their 802 // stored heights to match. 803 function updateHeightsInViewport(cm) { 804 var display = cm.display; 805 var prevBottom = display.lineDiv.offsetTop; 806 for (var i = 0; i < display.view.length; i++) { 807 var cur = display.view[i], height; 808 if (cur.hidden) continue; 809 if (ie && ie_version < 8) { 810 var bot = cur.node.offsetTop + cur.node.offsetHeight; 811 height = bot - prevBottom; 812 prevBottom = bot; 813 } else { 814 var box = cur.node.getBoundingClientRect(); 815 height = box.bottom - box.top; 816 }
817 var diff = cur.line.height - height; 818 if (height < 2) height = textHeight(display); 819 if (diff > .001 || diff < -.001) { 820 updateLineHeight(cur.line, height); 821 updateWidgetHeight(cur.line); 822 if (cur.rest) for (var j = 0; j < cur.rest.length; j++) 823 updateWidgetHeight(cur.rest[j]); 824 } 825 } 826 } 827 828 // Read and store the height of line widgets associated with the 829 // given line. 830 function updateWidgetHeight(line) { 831 if (line.widgets) for (var i = 0; i < line.widgets.length; ++i) 832 line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight; 833 } 834 835 // Do a bulk-read of the DOM positions and sizes needed to draw the 836 // view, so that we don't interleave reading and writing to the DOM. 837 function getDimensions(cm) { 838 var d = cm.display, left = {}, width = {}; 839 var gutterLeft = d.gutters.clientLeft; 840 for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { 841 left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; 842 width[cm.options.gutters[i]] = n.clientWidth; 843 } 844 return {fixedPos: compensateForHScroll(d), 845 gutterTotalWidth: d.gutters.offsetWidth, 846 gutterLeft: left, 847 gutterWidth: width, 848 wrapperWidth: d.wrapper.clientWidth}; 849 } 850 851 // Sync the actual display DOM structure with display.view, removing 852 // nodes for lines that are no longer in view, and creating the ones 853 // that are not there yet, and updating the ones that are out of 854 // date. 855 function patchDisplay(cm, updateNumbersFrom, dims) { 856 var display = cm.display, lineNumbers = cm.options.lineNumbers; 857 var container = display.lineDiv, cur = container.firstChild; 858 859 function rm(node) { 860 var next = node.nextSibling; 861 // Works around a throw-scroll bug in OS X Webkit 862 if (webkit && mac && cm.display.currentWheelTarget == node) 863 node.style.display = "none"; 864 else 865 node.parentNode.removeChild(node); 866 return next; 867 } 868 869 var view = display.view, lineN = display.viewFrom; 870 // Loop over the elements in the view, syncing cur (the DOM nodes 871 // in display.lineDiv) with the view as we go. 872 for (var i = 0; i < view.length; i++) { 873 var lineView = view[i]; 874 if (lineView.hidden) { 875 } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet 876 var node = buildLineElement(cm, lineView, lineN, dims); 877 container.insertBefore(node, cur); 878 } else { // Already drawn 879 while (cur != lineView.node) cur = rm(cur); 880 var updateNumber = lineNumbers && updateNumbersFrom != null && 881 updateNumbersFrom <= lineN && lineView.lineNumber; 882 if (lineView.changes) { 883 if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false; 884 updateLineForChanges(cm, lineView, lineN, dims); 885 } 886 if (updateNumber) { 887 removeChildren(lineView.lineNumber); 888 lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); 889 } 890 cur = lineView.node.nextSibling; 891 } 892 lineN += lineView.size; 893 } 894 while (cur) cur = rm(cur); 895 } 896 897 // When an aspect of a line changes, a string is added to 898 // lineView.changes. This updates the relevant part of the line's 899 // DOM structure. 900 function updateLineForChanges(cm, lineView, lineN, dims) { 901 for (var j = 0; j < lineView.changes.length; j++) { 902 var type = lineView.changes[j]; 903 if (type == "text") updateLineText(cm, lineView); 904 else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims); 905 else if (type == "class") updateLineClasses(lineView); 906 else if (type == "widget") updateLineWidgets(cm, lineView, dims); 907 } 908 lineView.changes = null; 909 } 910 911 // Lines with gutter elements, widgets or a background class need to 912 // be wrapped, and have the extra elements added to the wrapper div 913 function ensureLineWrapped(lineView) { 914 if (lineView.node == lineView.text) { 915 lineView.node = elt("div", null, null, "position: relative"); 916 if (lineView.text.parentNode) 917 lineView.text.parentNode.replaceChild(lineView.node, lineView.text); 918 lineView.node.appendChild(lineView.text); 919 if (ie && ie_version < 8) lineView.node.style.zIndex = 2; 920 } 921 return lineView.node; 922 } 923
924 function updateLineBackground(lineView) { 925 var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; 926 if (cls) cls += " CodeMirror-linebackground"; 927 if (lineView.background) { 928 if (cls) lineView.background.className = cls; 929 else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } 930 } else if (cls) { 931 var wrap = ensureLineWrapped(lineView); 932 lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); 933 } 934 } 935 936 // Wrapper around buildLineContent which will reuse the structure 937 // in display.externalMeasured when possible. 938 function getLineContent(cm, lineView) { 939 var ext = cm.display.externalMeasured; 940 if (ext && ext.line == lineView.line) { 941 cm.display.externalMeasured = null; 942 lineView.measure = ext.measure; 943 return ext.built; 944 } 945 return buildLineContent(cm, lineView); 946 } 947 948 // Redraw the line's text. Interacts with the background and text 949 // classes because the mode may output tokens that influence these 950 // classes. 951 function updateLineText(cm, lineView) { 952 var cls = lineView.text.className; 953 var built = getLineContent(cm, lineView); 954 if (lineView.text == lineView.node) lineView.node = built.pre; 955 lineView.text.parentNode.replaceChild(built.pre, lineView.text); 956 lineView.text = built.pre; 957 if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { 958 lineView.bgClass = built.bgClass; 959 lineView.textClass = built.textClass; 960 updateLineClasses(lineView); 961 } else if (cls) { 962 lineView.text.className = cls; 963 } 964 } 965 966 function updateLineClasses(lineView) { 967 updateLineBackground(lineView); 968 if (lineView.line.wrapClass) 969 ensureLineWrapped(lineView).className = lineView.line.wrapClass; 970 else if (lineView.node != lineView.text) 971 lineView.node.className = ""; 972 var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; 973 lineView.text.className = textClass || ""; 974 } 975 976 function updateLineGutter(cm, lineView, lineN, dims) { 977 if (lineView.gutter) { 978 lineView.node.removeChild(lineView.gutter); 979 lineView.gutter = null; 980 } 981 if (lineView.gutterBackground) { 982 lineView.node.removeChild(lineView.gutterBackground); 983 lineView.gutterBackground = null; 984 } 985 if (lineView.line.gutterClass) { 986 var wrap = ensureLineWrapped(lineView); 987 lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, 988 "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + 989 "px; width: " + dims.gutterTotalWidth + "px"); 990 wrap.insertBefore(lineView.gutterBackground, lineView.text); 991 } 992 var markers = lineView.line.gutterMarkers; 993 if (cm.options.lineNumbers || markers) { 994 var wrap = ensureLineWrapped(lineView); 995 var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + 996 (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"); 997 cm.display.input.setUneditable(gutterWrap); 998 wrap.insertBefore(gutterWrap, lineView.text); 999 if (lineView.line.gutterClass) 1000 gutterWrap.className += " " + lineView.line.gutterClass; 1001 if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) 1002 lineView.lineNumber = gutterWrap.appendChild( 1003 elt("div", lineNumberFor(cm.options, lineN), 1004 "CodeMirror-linenumber CodeMirror-gutter-elt", 1005 "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " 1006 + cm.display.lineNumInnerWidth + "px")); 1007 if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) { 1008 var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; 1009 if (found) 1010 gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + 1011 dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); 1012 } 1013 } 1014 } 1015 1016 function updateLineWidgets(cm, lineView, dims) { 1017 if (lineView.alignable) lineView.alignable = null; 1018 for (var node = lineView.node.firstChild, next; node; node = next) { 1019 var next = node.nextSibling; 1020 if (node.className == "CodeMirror-linewidget") 1021 lineView.node.removeChild(node); 1022 } 1023 insertLineWidgets(cm, lineView, dims); 1024 } 1025 1026 // Build a line's DOM representation from scratch 1027 function buildLineElement(cm, lineView, lineN, dims) { 1028 var built = getLineContent(cm, lineView); 1029 lineView.text = lineView.node = built.pre; 1030 if (built.bgClass) lineView.bgClass = built.bgClass; 1031 if (built.textClass) lineView.textClass = built.textClass; 1032 1033 updateLineClasses(lineView); 1034 updateLineGutter(cm, lineView, lineN, dims); 1035 insertLineWidgets(cm, lineView, dims); 1036 return lineView.node; 1037 } 1038 1039 // A lineView may contain multiple logical lines (when merged by
1040 // collapsed spans). The widgets for all of them need to be drawn. 1041 function insertLineWidgets(cm, lineView, dims) { 1042 insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); 1043 if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) 1044 insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); 1045 } 1046 1047 function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { 1048 if (!line.widgets) return; 1049 var wrap = ensureLineWrapped(lineView); 1050 for (var i = 0, ws = line.widgets; i < ws.length; ++i) { 1051 var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); 1052 if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true"); 1053 positionLineWidget(widget, node, lineView, dims); 1054 cm.display.input.setUneditable(node); 1055 if (allowAbove && widget.above) 1056 wrap.insertBefore(node, lineView.gutter || lineView.text); 1057 else 1058 wrap.appendChild(node); 1059 signalLater(widget, "redraw"); 1060 } 1061 } 1062 1063 function positionLineWidget(widget, node, lineView, dims) { 1064 if (widget.noHScroll) { 1065 (lineView.alignable || (lineView.alignable = [])).push(node); 1066 var width = dims.wrapperWidth; 1067 node.style.left = dims.fixedPos + "px"; 1068 if (!widget.coverGutter) { 1069 width -= dims.gutterTotalWidth; 1070 node.style.paddingLeft = dims.gutterTotalWidth + "px"; 1071 } 1072 node.style.width = width + "px"; 1073 } 1074 if (widget.coverGutter) { 1075 node.style.zIndex = 5; 1076 node.style.position = "relative"; 1077 if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; 1078 } 1079 } 1080 1081 // POSITION OBJECT 1082 1083 // A Pos instance represents a position within the text. 1084 var Pos = CodeMirror.Pos = function(line, ch) { 1085 if (!(this instanceof Pos)) return new Pos(line, ch); 1086 this.line = line; this.ch = ch; 1087 }; 1088 1089 // Compare two positions, return 0 if they are the same, a negative 1090 // number when a is less, and a positive number otherwise. 1091 var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; }; 1092 1093 function copyPos(x) {return Pos(x.line, x.ch);} 1094 function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; } 1095 function minPos(a, b) { return cmp(a, b) < 0 ? a : b; } 1096 1097 // INPUT HANDLING 1098 1099 function ensureFocus(cm) { 1100 if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } 1101 } 1102 1103 // This will be set to a {lineWise: bool, text: [string]} object, so 1104 // that, when pasting, we know what kind of selections the copied 1105 // text was made out of. 1106 var lastCopied = null; 1107 1108 function applyTextInput(cm, inserted, deleted, sel, origin) { 1109 var doc = cm.doc; 1110 cm.display.shift = false; 1111 if (!sel) sel = doc.sel; 1112 1113 var paste = cm.state.pasteIncoming || origin == "paste"; 1114 var textLines = doc.splitLines(inserted), multiPaste = null 1115 // When pasing N lines into N selections, insert one line per selection 1116 if (paste && sel.ranges.length > 1) { 1117 if (lastCopied && lastCopied.text.join("\n") == inserted) { 1118 if (sel.ranges.length % lastCopied.text.length == 0) { 1119 multiPaste = []; 1120 for (var i = 0; i < lastCopied.text.length; i++) 1121 multiPaste.push(doc.splitLines(lastCopied.text[i])); 1122 } 1123 } else if (textLines.length == sel.ranges.length) { 1124 multiPaste = map(textLines, function(l) { return [l]; }); 1125 } 1126 } 1127 1128 // Normal behavior is to insert the new text into every selection 1129 for (var i = sel.ranges.length - 1; i >= 0; i--) { 1130 var range = sel.ranges[i]; 1131 var from = range.from(), to = range.to(); 1132 if (range.empty()) { 1133 if (deleted && deleted > 0) // Handle deletion 1134 from = Pos(from.line, from.ch - deleted); 1135 else if (cm.state.overwrite && !paste) // Handle overwrite 1136 to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); 1137 else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) 1138 from = to = Pos(from.line, 0) 1139 } 1140 var updateInput = cm.curOp.updateInput; 1141 var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines, 1142 origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; 1143 makeChange(cm.doc, changeEvent); 1144 signalLater(cm, "inputRead", cm, changeEvent); 1145 } 1146 if (inserted && !paste) 1147 triggerElectric(cm, inserted); 1148 1149 ensureCursorVisible(cm); 1150 cm.curOp.updateInput = updateInput; 1151 cm.curOp.typing = true; 1152 cm.state.pasteIncoming = cm.state.cutIncoming = false;
1153 } 1154 1155 function handlePaste(e, cm) { 1156 var pasted = e.clipboardData && e.clipboardData.getData("Text"); 1157 if (pasted) { 1158 e.preventDefault(); 1159 if (!cm.isReadOnly() && !cm.options.disableInput) 1160 runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); }); 1161 return true; 1162 } 1163 } 1164 1165 function triggerElectric(cm, inserted) { 1166 // When an 'electric' character is inserted, immediately trigger a reindent 1167 if (!cm.options.electricChars || !cm.options.smartIndent) return; 1168 var sel = cm.doc.sel; 1169 1170 for (var i = sel.ranges.length - 1; i >= 0; i--) { 1171 var range = sel.ranges[i]; 1172 if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue; 1173 var mode = cm.getModeAt(range.head); 1174 var indented = false; 1175 if (mode.electricChars) { 1176 for (var j = 0; j < mode.electricChars.length; j++) 1177 if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { 1178 indented = indentLine(cm, range.head.line, "smart"); 1179 break; 1180 } 1181 } else if (mode.electricInput) { 1182 if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) 1183 indented = indentLine(cm, range.head.line, "smart"); 1184 } 1185 if (indented) signalLater(cm, "electricInput", cm, range.head.line); 1186 } 1187 } 1188 1189 function copyableRanges(cm) { 1190 var text = [], ranges = []; 1191 for (var i = 0; i < cm.doc.sel.ranges.length; i++) { 1192 var line = cm.doc.sel.ranges[i].head.line; 1193 var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; 1194 ranges.push(lineRange); 1195 text.push(cm.getRange(lineRange.anchor, lineRange.head)); 1196 } 1197 return {text: text, ranges: ranges}; 1198 } 1199 1200 function disableBrowserMagic(field, spellcheck) { 1201 field.setAttribute("autocorrect", "off"); 1202 field.setAttribute("autocapitalize", "off"); 1203 field.setAttribute("spellcheck", !!spellcheck); 1204 } 1205 1206 // TEXTAREA INPUT STYLE 1207 1208 function TextareaInput(cm) { 1209 this.cm = cm; 1210 // See input.poll and input.reset 1211 this.prevInput = ""; 1212 1213 // Flag that indicates whether we expect input to appear real soon 1214 // now (after some event like 'keypress' or 'input') and are 1215 // polling intensively. 1216 this.pollingFast = false; 1217 // Self-resetting timeout for the poller 1218 this.polling = new Delayed(); 1219 // Tracks when input.reset has punted to just putting a short 1220 // string into the textarea instead of the full selection. 1221 this.inaccurateSelection = false; 1222 // Used to work around IE issue with selection being forgotten when focus moves away from textarea 1223 this.hasSelection = false; 1224 this.composing = null; 1225 }; 1226 1227 function hiddenTextarea() { 1228 var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"); 1229 var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); 1230 // The textarea is kept positioned near the cursor to prevent the 1231 // fact that it'll be scrolled into view on input from scrolling 1232 // our fake cursor out of view. On webkit, when wrap=off, paste is 1233 // very slow. So make the area wide instead. 1234 if (webkit) te.style.width = "1000px"; 1235 else te.setAttribute("wrap", "off"); 1236 // If border: 0; -- iOS fails to open keyboard (issue #1287) 1237 if (ios) te.style.border = "1px solid black"; 1238 disableBrowserMagic(te); 1239 return div; 1240 } 1241 1242 TextareaInput.prototype = copyObj({ 1243 init: function(display) { 1244 var input = this, cm = this.cm; 1245 1246 // Wraps and hides input textarea 1247 var div = this.wrapper = hiddenTextarea(); 1248 // The semihidden textarea that is focused when the editor is 1249 // focused, and receives input. 1250 var te = this.textarea = div.firstChild; 1251 display.wrapper.insertBefore(div, display.wrapper.firstChild); 1252 1253 // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) 1254 if (ios) te.style.width = "0px"; 1255 1256 on(te, "input", function() { 1257 if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null; 1258 input.poll(); 1259 }); 1260 1261 on(te, "paste", function(e) { 1262 if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return 1263 1264 cm.state.pasteIncoming = true; 1265 input.fastPoll(); 1266 }); 1267 1268 function prepareCopyCut(e) { 1269 if (signalDOMEvent(cm, e)) return 1270 if (cm.somethingSelected()) { 1271 lastCopied = {lineWise: false, text: cm.getSelections()}; 1272 if (input.inaccurateSelection) { 1273 input.prevInput = ""; 1274 input.inaccurateSelection = false;
1275 te.value = lastCopied.text.join("\n"); 1276 selectInput(te); 1277 } 1278 } else if (!cm.options.lineWiseCopyCut) { 1279 return; 1280 } else { 1281 var ranges = copyableRanges(cm); 1282 lastCopied = {lineWise: true, text: ranges.text}; 1283 if (e.type == "cut") { 1284 cm.setSelections(ranges.ranges, null, sel_dontScroll); 1285 } else { 1286 input.prevInput = ""; 1287 te.value = ranges.text.join("\n"); 1288 selectInput(te); 1289 } 1290 } 1291 if (e.type == "cut") cm.state.cutIncoming = true; 1292 } 1293 on(te, "cut", prepareCopyCut); 1294 on(te, "copy", prepareCopyCut); 1295 1296 on(display.scroller, "paste", function(e) { 1297 if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return; 1298 cm.state.pasteIncoming = true; 1299 input.focus(); 1300 }); 1301 1302 // Prevent normal selection in the editor (we handle our own) 1303 on(display.lineSpace, "selectstart", function(e) { 1304 if (!eventInWidget(display, e)) e_preventDefault(e); 1305 }); 1306 1307 on(te, "compositionstart", function() { 1308 var start = cm.getCursor("from"); 1309 if (input.composing) input.composing.range.clear() 1310 input.composing = { 1311 start: start, 1312 range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) 1313 }; 1314 }); 1315 on(te, "compositionend", function() { 1316 if (input.composing) { 1317 input.poll(); 1318 input.composing.range.clear(); 1319 input.composing = null; 1320 } 1321 }); 1322 }, 1323 1324 prepareSelection: function() { 1325 // Redraw the selection and/or cursor 1326 var cm = this.cm, display = cm.display, doc = cm.doc; 1327 var result = prepareSelection(cm); 1328 1329 // Move the hidden textarea near the cursor to prevent scrolling artifacts 1330 if (cm.options.moveInputWithCursor) { 1331 var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); 1332 var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); 1333 result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, 1334 headPos.top + lineOff.top - wrapOff.top)); 1335 result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, 1336 headPos.left + lineOff.left - wrapOff.left)); 1337 } 1338 1339 return result; 1340 }, 1341 1342 showSelection: function(drawn) { 1343 var cm = this.cm, display = cm.display; 1344 removeChildrenAndAdd(display.cursorDiv, drawn.cursors); 1345 removeChildrenAndAdd(display.selectionDiv, drawn.selection); 1346 if (drawn.teTop != null) { 1347 this.wrapper.style.top = drawn.teTop + "px"; 1348 this.wrapper.style.left = drawn.teLeft + "px"; 1349 } 1350 }, 1351 1352 // Reset the input to correspond to the selection (or to be empty, 1353 // when not typing and nothing is selected) 1354 reset: function(typing) { 1355 if (this.contextMenuPending) return; 1356 var minimal, selected, cm = this.cm, doc = cm.doc; 1357 if (cm.somethingSelected()) { 1358 this.prevInput = ""; 1359 var range = doc.sel.primary(); 1360 minimal = hasCopyEvent && 1361 (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000); 1362 var content = minimal ? "-" : selected || cm.getSelection(); 1363 this.textarea.value = content; 1364 if (cm.state.focused) selectInput(this.textarea); 1365 if (ie && ie_version >= 9) this.hasSelection = content; 1366 } else if (!typing) { 1367 this.prevInput = this.textarea.value = ""; 1368 if (ie && ie_version >= 9) this.hasSelection = null; 1369 } 1370 this.inaccurateSelection = minimal; 1371 }, 1372 1373 getField: function() { return this.textarea; }, 1374 1375 supportsTouch: function() { return false; }, 1376 1377 focus: function() { 1378 if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { 1379 try { this.textarea.focus(); } 1380 catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM 1381 } 1382 }, 1383 1384 blur: function() { this.textarea.blur(); }, 1385 1386 resetPosition: function() { 1387 this.wrapper.style.top = this.wrapper.style.left = 0; 1388 }, 1389 1390 receivedFocus: function() { this.slowPoll(); }, 1391 1392 // Poll for input changes, using the normal rate of polling. This 1393 // runs as long as the editor is focused. 1394 slowPoll: function() { 1395 var input = this; 1396 if (input.pollingFast) return; 1397 input.polling.set(this.cm.options.pollInterval, function() { 1398 input.poll(); 1399 if (input.cm.state.focused) input.slowPoll(); 1400 }); 1401 }, 1402 1403 // When an event has just come in that is likely to add or change 1404 // something in the input textarea, we poll faster, to ensure that 1405 // the change appears on the screen quickly. 1406 fastPoll: function() { 1407 var missed = false, input = this; 1408 input.pollingFast = true; 1409 function p() { 1410 var changed = input.poll(); 1411 if (!changed && !missed) {missed = true; input.polling.set(60, p);} 1412 else {input.pollingFast = false; input.slowPoll();} 1413 } 1414 input.polling.set(20, p); 1415 }, 1416 1417 // Read input from the textarea, and update the document to match. 1418 // When something is selected, it is present in the textarea, and 1419 // selected (unless it is huge, in which case a placeholder is 1420 // used). When nothing is selected, the cursor sits after previously 1421 // seen text (can be empty), which is stored in prevInput (we must 1422 // not reset the textarea when typing, because that breaks IME). 1423 poll: function() { 1424 var cm = this.cm, input = this.textarea, prevInput = this.prevInput; 1425 // Since this is called a *lot*, try to bail out as cheaply as 1426 // possible when it is clear that nothing happened. hasSelection 1427 // will be the case when there is a lot of text in the textarea,
1428 // in which case reading its value would be expensive. 1429 if (this.contextMenuPending || !cm.state.focused || 1430 (hasSelection(input) && !prevInput && !this.composing) || 1431 cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) 1432 return false; 1433 1434 var text = input.value; 1435 // If nothing changed, bail. 1436 if (text == prevInput && !cm.somethingSelected()) return false; 1437 // Work around nonsensical selection resetting in IE9/10, and 1438 // inexplicable appearance of private area unicode characters on 1439 // some key combos in Mac (#2689). 1440 if (ie && ie_version >= 9 && this.hasSelection === text || 1441 mac && /[\uf700-\uf7ff]/.test(text)) { 1442 cm.display.input.reset(); 1443 return false; 1444 } 1445 1446 if (cm.doc.sel == cm.display.selForContextMenu) { 1447 var first = text.charCodeAt(0); 1448 if (first == 0x200b && !prevInput) prevInput = "\u200b"; 1449 if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); } 1450 } 1451 // Find the part of the input that is actually new 1452 var same = 0, l = Math.min(prevInput.length, text.length); 1453 while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; 1454 1455 var self = this; 1456 runInOp(cm, function() { 1457 applyTextInput(cm, text.slice(same), prevInput.length - same, 1458 null, self.composing ? "*compose" : null); 1459 1460 // Don't leave long text in the textarea, since it makes further polling slow 1461 if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = ""; 1462 else self.prevInput = text; 1463 1464 if (self.composing) { 1465 self.composing.range.clear(); 1466 self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"), 1467 {className: "CodeMirror-composing"}); 1468 } 1469 }); 1470 return true; 1471 }, 1472 1473 ensurePolled: function() { 1474 if (this.pollingFast && this.poll()) this.pollingFast = false; 1475 }, 1476 1477 onKeyPress: function() { 1478 if (ie && ie_version >= 9) this.hasSelection = null; 1479 this.fastPoll(); 1480 }, 1481 1482 onContextMenu: function(e) { 1483 var input = this, cm = input.cm, display = cm.display, te = input.textarea; 1484 var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; 1485 if (!pos || presto) return; // Opera is difficult. 1486 1487 // Reset the current text selection only if the click is done outside of the selection 1488 // and 'resetSelectionOnContextMenu' option is true. 1489 var reset = cm.options.resetSelectionOnContextMenu; 1490 if (reset && cm.doc.sel.contains(pos) == -1) 1491 operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); 1492 1493 var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText; 1494 input.wrapper.style.cssText = "position: absolute" 1495 var wrapperBox = input.wrapper.getBoundingClientRect() 1496 te.style.cssText = "position: absolute; width: 30px; height: 30px; top: " + (e.clientY - wrapperBox.top - 5) + 1497 "px; left: " + (e.clientX - wrapperBox.left - 5) + "px; z-index: 1000; background: " + 1498 (ie ? "rgba(255, 255, 255, .05)" : "transparent") + 1499 "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; 1500 if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712) 1501 display.input.focus(); 1502 if (webkit) window.scrollTo(null, oldScrollY); 1503 display.input.reset(); 1504 // Adds "Select all" to context menu in FF 1505 if (!cm.somethingSelected()) te.value = input.prevInput = " "; 1506 input.contextMenuPending = true; 1507 display.selForContextMenu = cm.doc.sel; 1508 clearTimeout(display.detectingSelectAll); 1509 1510 // Select-all will be greyed out if there's nothing to select, so 1511 // this adds a zero-width space so that we can later check whether 1512 // it got selected. 1513 function prepareSelectAllHack() { 1514 if (te.selectionStart != null) { 1515 var selected = cm.somethingSelected(); 1516 var extval = "\u200b" + (selected ? te.value : ""); 1517 te.value = "\u21da"; // Used to catch context-menu undo 1518 te.value = extval; 1519 input.prevInput = selected ? "" : "\u200b"; 1520 te.selectionStart = 1; te.selectionEnd = extval.length; 1521 // Re-set this, in case some other handler touched the 1522 // selection in the meantime. 1523 display.selForContextMenu = cm.doc.sel; 1524 } 1525 } 1526 function rehide() { 1527 input.contextMenuPending = false;
1528 input.wrapper.style.cssText = oldWrapperCSS 1529 te.style.cssText = oldCSS; 1530 if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); 1531 1532 // Try to detect the user choosing select-all 1533 if (te.selectionStart != null) { 1534 if (!ie || (ie && ie_version < 9)) prepareSelectAllHack(); 1535 var i = 0, poll = function() { 1536 if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && 1537 te.selectionEnd > 0 && input.prevInput == "\u200b") 1538 operation(cm, commands.selectAll)(cm); 1539 else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500); 1540 else display.input.reset(); 1541 }; 1542 display.detectingSelectAll = setTimeout(poll, 200); 1543 } 1544 } 1545 1546 if (ie && ie_version >= 9) prepareSelectAllHack(); 1547 if (captureRightClick) { 1548 e_stop(e); 1549 var mouseup = function() { 1550 off(window, "mouseup", mouseup); 1551 setTimeout(rehide, 20); 1552 }; 1553 on(window, "mouseup", mouseup); 1554 } else { 1555 setTimeout(rehide, 50); 1556 } 1557 }, 1558 1559 readOnlyChanged: function(val) { 1560 if (!val) this.reset(); 1561 }, 1562 1563 setUneditable: nothing, 1564 1565 needsContentAttribute: false 1566 }, TextareaInput.prototype); 1567 1568 // CONTENTEDITABLE INPUT STYLE 1569 1570 function ContentEditableInput(cm) { 1571 this.cm = cm; 1572 this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; 1573 this.polling = new Delayed(); 1574 this.gracePeriod = false; 1575 } 1576 1577 ContentEditableInput.prototype = copyObj({ 1578 init: function(display) { 1579 var input = this, cm = input.cm; 1580 var div = input.div = display.lineDiv; 1581 disableBrowserMagic(div, cm.options.spellcheck); 1582 1583 on(div, "paste", function(e) { 1584 if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return 1585 // IE doesn't fire input events, so we schedule a read for the pasted content in this way 1586 if (ie_version <= 11) setTimeout(operation(cm, function() { 1587 if (!input.pollContent()) regChange(cm); 1588 }), 20) 1589 }) 1590 1591 on(div, "compositionstart", function(e) { 1592 var data = e.data; 1593 input.composing = {sel: cm.doc.sel, data: data, startData: data}; 1594 if (!data) return; 1595 var prim = cm.doc.sel.primary(); 1596 var line = cm.getLine(prim.head.line); 1597 var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length)); 1598 if (found > -1 && found <= prim.head.ch) 1599 input.composing.sel = simpleSelection(Pos(prim.head.line, found), 1600 Pos(prim.head.line, found + data.length)); 1601 }); 1602 on(div, "compositionupdate", function(e) { 1603 input.composing.data = e.data; 1604 }); 1605 on(div, "compositionend", function(e) { 1606 var ours = input.composing; 1607 if (!ours) return; 1608 if (e.data != ours.startData && !/\u200b/.test(e.data)) 1609 ours.data = e.data; 1610 // Need a small delay to prevent other code (input event, 1611 // selection polling) from doing damage when fired right after 1612 // compositionend. 1613 setTimeout(function() { 1614 if (!ours.handled) 1615 input.applyComposition(ours); 1616 if (input.composing == ours) 1617 input.composing = null; 1618 }, 50); 1619 }); 1620 1621 on(div, "touchstart", function() { 1622 input.forceCompositionEnd(); 1623 }); 1624 1625 on(div, "input", function() { 1626 if (input.composing) return; 1627 if (cm.isReadOnly() || !input.pollContent()) 1628 runInOp(input.cm, function() {regChange(cm);}); 1629 }); 1630 1631 function onCopyCut(e) { 1632 if (signalDOMEvent(cm, e)) return 1633 if (cm.somethingSelected()) { 1634 lastCopied = {lineWise: false, text: cm.getSelections()}; 1635 if (e.type == "cut") cm.replaceSelection("", null, "cut"); 1636 } else if (!cm.options.lineWiseCopyCut) { 1637 return; 1638 } else { 1639 var ranges = copyableRanges(cm); 1640 lastCopied = {lineWise: true, text: ranges.text}; 1641 if (e.type == "cut") { 1642 cm.operation(function() { 1643 cm.setSelections(ranges.ranges, 0, sel_dontScroll); 1644 cm.replaceSelection("", null, "cut"); 1645 }); 1646 } 1647 } 1648 if (e.clipboardData) { 1649 e.clipboardData.clearData();
1650 var content = lastCopied.text.join("\n") 1651 // iOS exposes the clipboard API, but seems to discard content inserted into it 1652 e.clipboardData.setData("Text", content); 1653 if (e.clipboardData.getData("Text") == content) { 1654 e.preventDefault(); 1655 return 1656 } 1657 } 1658 // Old-fashioned briefly-focus-a-textarea hack 1659 var kludge = hiddenTextarea(), te = kludge.firstChild; 1660 cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); 1661 te.value = lastCopied.text.join("\n"); 1662 var hadFocus = document.activeElement; 1663 selectInput(te); 1664 setTimeout(function() { 1665 cm.display.lineSpace.removeChild(kludge); 1666 hadFocus.focus(); 1667 if (hadFocus == div) input.showPrimarySelection() 1668 }, 50); 1669 } 1670 on(div, "copy", onCopyCut); 1671 on(div, "cut", onCopyCut); 1672 }, 1673 1674 prepareSelection: function() { 1675 var result = prepareSelection(this.cm, false); 1676 result.focus = this.cm.state.focused; 1677 return result; 1678 }, 1679 1680 showSelection: function(info, takeFocus) { 1681 if (!info || !this.cm.display.view.length) return; 1682 if (info.focus || takeFocus) this.showPrimarySelection(); 1683 this.showMultipleSelections(info); 1684 }, 1685 1686 showPrimarySelection: function() { 1687 var sel = window.getSelection(), prim = this.cm.doc.sel.primary(); 1688 var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset); 1689 var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset); 1690 if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && 1691 cmp(minPos(curAnchor, curFocus), prim.from()) == 0 && 1692 cmp(maxPos(curAnchor, curFocus), prim.to()) == 0) 1693 return; 1694 1695 var start = posToDOM(this.cm, prim.from()); 1696 var end = posToDOM(this.cm, prim.to()); 1697 if (!start && !end) return; 1698 1699 var view = this.cm.display.view; 1700 var old = sel.rangeCount && sel.getRangeAt(0); 1701 if (!start) { 1702 start = {node: view[0].measure.map[2], offset: 0}; 1703 } else if (!end) { // FIXME dangerously hacky 1704 var measure = view[view.length - 1].measure; 1705 var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; 1706 end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}; 1707 } 1708 1709 try { var rng = range(start.node, start.offset, end.offset, end.node); } 1710 catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible 1711 if (rng) { 1712 if (!gecko && this.cm.state.focused) { 1713 sel.collapse(start.node, start.offset); 1714 if (!rng.collapsed) sel.addRange(rng); 1715 } else { 1716 sel.removeAllRanges(); 1717 sel.addRange(rng); 1718 } 1719 if (old && sel.anchorNode == null) sel.addRange(old); 1720 else if (gecko) this.startGracePeriod(); 1721 } 1722 this.rememberSelection(); 1723 }, 1724 1725 startGracePeriod: function() { 1726 var input = this; 1727 clearTimeout(this.gracePeriod); 1728 this.gracePeriod = setTimeout(function() { 1729 input.gracePeriod = false; 1730 if (input.selectionChanged()) 1731 input.cm.operation(function() { input.cm.curOp.selectionChanged = true; }); 1732 }, 20); 1733 }, 1734 1735 showMultipleSelections: function(info) { 1736 removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); 1737 removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); 1738 }, 1739 1740 rememberSelection: function() { 1741 var sel = window.getSelection(); 1742 this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; 1743 this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; 1744 }, 1745 1746 selectionInEditor: function() { 1747 var sel = window.getSelection(); 1748 if (!sel.rangeCount) return false; 1749 var node = sel.getRangeAt(0).commonAncestorContainer; 1750 return contains(this.div, node); 1751 }, 1752 1753 focus: function() { 1754 if (this.cm.options.readOnly != "nocursor") this.div.focus(); 1755 }, 1756 blur: function() { this.div.blur(); }, 1757 getField: function() { return this.div; }, 1758 1759 supportsTouch: function() { return true; }, 1760 1761 receivedFocus: function() { 1762 var input = this; 1763 if (this.selectionInEditor()) 1764 this.pollSelection(); 1765 else 1766 runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; }); 1767 1768 function poll() { 1769 if (input.cm.state.focused) { 1770 input.pollSelection(); 1771 input.polling.set(input.cm.options.pollInterval, poll); 1772 } 1773 } 1774 this.polling.set(this.cm.options.pollInterval, poll); 1775 }, 1776 1777 selectionChanged: function() { 1778 var sel = window.getSelection(); 1779 return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || 1780 sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; 1781 }, 1782 1783 pollSelection: function() { 1784 if (!this.composing && !this.gracePeriod && this.selectionChanged()) { 1785 var sel = window.getSelection(), cm = this.cm; 1786 this.rememberSelection(); 1787 var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); 1788 var head = domToPos(cm, sel.focusNode, sel.focusOffset); 1789 if (anchor && head) runInOp(cm, function() { 1790 setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); 1791 if (anchor.bad || head.bad) cm.curOp.selectionChanged = true; 1792 }); 1793 } 1794 }, 1795 1796 pollContent: function() { 1797 var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); 1798 var from = sel.from(), to = sel.to();
1799 if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false; 1800 1801 var fromIndex; 1802 if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { 1803 var fromLine = lineNo(display.view[0].line); 1804 var fromNode = display.view[0].node; 1805 } else { 1806 var fromLine = lineNo(display.view[fromIndex].line); 1807 var fromNode = display.view[fromIndex - 1].node.nextSibling; 1808 } 1809 var toIndex = findViewIndex(cm, to.line); 1810 if (toIndex == display.view.length - 1) { 1811 var toLine = display.viewTo - 1; 1812 var toNode = display.lineDiv.lastChild; 1813 } else { 1814 var toLine = lineNo(display.view[toIndex + 1].line) - 1; 1815 var toNode = display.view[toIndex + 1].node.previousSibling; 1816 } 1817 1818 var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); 1819 var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); 1820 while (newText.length > 1 && oldText.length > 1) { 1821 if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } 1822 else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } 1823 else break; 1824 } 1825 1826 var cutFront = 0, cutEnd = 0; 1827 var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
1828 while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) 1829 ++cutFront; 1830 var newBot = lst(newText), oldBot = lst(oldText); 1831 var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), 1832 oldBot.length - (oldText.length == 1 ? cutFront : 0)); 1833 while (cutEnd < maxCutEnd && 1834 newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) 1835 ++cutEnd; 1836 1837 newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd); 1838 newText[0] = newText[0].slice(cutFront); 1839 1840 var chFrom = Pos(fromLine, cutFront); 1841 var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); 1842 if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { 1843 replaceRange(cm.doc, newText, chFrom, chTo, "+input"); 1844 return true; 1845 } 1846 }, 1847 1848 ensurePolled: function() { 1849 this.forceCompositionEnd(); 1850 }, 1851 reset: function() { 1852 this.forceCompositionEnd(); 1853 }, 1854 forceCompositionEnd: function() { 1855 if (!this.composing || this.composing.handled) return; 1856 this.applyComposition(this.composing); 1857 this.composing.handled = true; 1858 this.div.blur(); 1859 this.div.focus(); 1860 }, 1861 applyComposition: function(composing) { 1862 if (this.cm.isReadOnly()) 1863 operation(this.cm, regChange)(this.cm) 1864 else if (composing.data && composing.data != composing.startData) 1865 operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel); 1866 }, 1867 1868 setUneditable: function(node) { 1869 node.contentEditable = "false" 1870 }, 1871 1872 onKeyPress: function(e) { 1873 e.preventDefault(); 1874 if (!this.cm.isReadOnly()) 1875 operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); 1876 }, 1877 1878 readOnlyChanged: function(val) { 1879 this.div.contentEditable = String(val != "nocursor") 1880 }, 1881 1882 onContextMenu: nothing, 1883 resetPosition: nothing, 1884 1885 needsContentAttribute: true 1886 }, ContentEditableInput.prototype); 1887 1888 function posToDOM(cm, pos) { 1889 var view = findViewForLine(cm, pos.line); 1890 if (!view || view.hidden) return null; 1891 var line = getLine(cm.doc, pos.line); 1892 var info = mapFromLineView(view, line, pos.line); 1893 1894 var order = getOrder(line), side = "left"; 1895 if (order) { 1896 var partPos = getBidiPartAt(order, pos.ch); 1897 side = partPos % 2 ? "right" : "left"; 1898 } 1899 var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); 1900 result.offset = result.collapse == "right" ? result.end : result.start; 1901 return result; 1902 } 1903 1904 function badPos(pos, bad) { if (bad) pos.bad = true; return pos; } 1905 1906 function domToPos(cm, node, offset) { 1907 var lineNode; 1908 if (node == cm.display.lineDiv) { 1909 lineNode = cm.display.lineDiv.childNodes[offset]; 1910 if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); 1911 node = null; offset = 0; 1912 } else { 1913 for (lineNode = node;; lineNode = lineNode.parentNode) { 1914 if (!lineNode || lineNode == cm.display.lineDiv) return null; 1915 if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break; 1916 } 1917 } 1918 for (var i = 0; i < cm.display.view.length; i++) { 1919 var lineView = cm.display.view[i]; 1920 if (lineView.node == lineNode) 1921 return locateNodeInLineView(lineView, node, offset); 1922 } 1923 } 1924 1925 function locateNodeInLineView(lineView, node, offset) { 1926 var wrapper = lineView.text.firstChild, bad = false; 1927 if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true); 1928 if (node == wrapper) { 1929 bad = true; 1930 node = wrapper.childNodes[offset]; 1931 offset = 0; 1932 if (!node) { 1933 var line = lineView.rest ? lst(lineView.rest) : lineView.line; 1934 return badPos(Pos(lineNo(line), line.text.length), bad); 1935 } 1936 } 1937 1938 var textNode = node.nodeType == 3 ? node : null, topNode = node; 1939 if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { 1940 textNode = node.firstChild; 1941 if (offset) offset = textNode.nodeValue.length; 1942 } 1943 while (topNode.parentNode != wrapper) topNode = topNode.parentNode; 1944 var measure = lineView.measure, maps = measure.maps; 1945 1946 function find(textNode, topNode, offset) {
1947 for (var i = -1; i < (maps ? maps.length : 0); i++) { 1948 var map = i < 0 ? measure.map : maps[i]; 1949 for (var j = 0; j < map.length; j += 3) { 1950 var curNode = map[j + 2]; 1951 if (curNode == textNode || curNode == topNode) { 1952 var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); 1953 var ch = map[j] + offset; 1954 if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)]; 1955 return Pos(line, ch); 1956 } 1957 } 1958 } 1959 } 1960 var found = find(textNode, topNode, offset); 1961 if (found) return badPos(found, bad); 1962 1963 // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems 1964 for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { 1965 found = find(after, after.firstChild, 0); 1966 if (found) 1967 return badPos(Pos(found.line, found.ch - dist), bad); 1968 else 1969 dist += after.textContent.length; 1970 } 1971 for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) { 1972 found = find(before, before.firstChild, -1); 1973 if (found) 1974 return badPos(Pos(found.line, found.ch + dist), bad); 1975 else 1976 dist += before.textContent.length; 1977 } 1978 } 1979 1980 function domTextBetween(cm, from, to, fromLine, toLine) { 1981 var text = "", closing = false, lineSep = cm.doc.lineSeparator(); 1982 function recognizeMarker(id) { return function(marker) { return marker.id == id; }; } 1983 function walk(node) { 1984 if (node.nodeType == 1) { 1985 var cmText = node.getAttribute("cm-text"); 1986 if (cmText != null) { 1987 if (cmText == "") cmText = node.textContent.replace(/\u200b/g, ""); 1988 text += cmText; 1989 return; 1990 } 1991 var markerID = node.getAttribute("cm-marker"), range; 1992 if (markerID) { 1993 var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); 1994 if (found.length && (range = found[0].find())) 1995 text += getBetween(cm.doc, range.from, range.to).join(lineSep); 1996 return; 1997 } 1998 if (node.getAttribute("contenteditable") == "false") return; 1999 for (var i = 0; i < node.childNodes.length; i++) 2000 walk(node.childNodes[i]); 2001 if (/^(pre|div|p)$/i.test(node.nodeName)) 2002 closing = true; 2003 } else if (node.nodeType == 3) { 2004 var val = node.nodeValue; 2005 if (!val) return; 2006 if (closing) { 2007 text += lineSep; 2008 closing = false; 2009 } 2010 text += val; 2011 } 2012 } 2013 for (;;) { 2014 walk(from); 2015 if (from == to) break; 2016 from = from.nextSibling; 2017 } 2018 return text; 2019 } 2020 2021 CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; 2022 2023 // SELECTION / CURSOR 2024 2025 // Selection objects are immutable. A new one is created every time 2026 // the selection changes. A selection is one or more non-overlapping 2027 // (and non-touching) ranges, sorted, and an integer that indicates 2028 // which one is the primary selection (the one that's scrolled into 2029 // view, that getCursor returns, etc). 2030 function Selection(ranges, primIndex) { 2031 this.ranges = ranges; 2032 this.primIndex = primIndex; 2033 } 2034 2035 Selection.prototype = { 2036 primary: function() { return this.ranges[this.primIndex]; }, 2037 equals: function(other) { 2038 if (other == this) return true; 2039 if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false; 2040 for (var i = 0; i < this.ranges.length; i++) { 2041 var here = this.ranges[i], there = other.ranges[i]; 2042 if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false; 2043 } 2044 return true; 2045 }, 2046 deepCopy: function() { 2047 for (var out = [], i = 0; i < this.ranges.length; i++) 2048 out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); 2049 return new Selection(out, this.primIndex); 2050 }, 2051 somethingSelected: function() { 2052 for (var i = 0; i < this.ranges.length; i++) 2053 if (!this.ranges[i].empty()) return true; 2054 return false;
2055 }, 2056 contains: function(pos, end) { 2057 if (!end) end = pos; 2058 for (var i = 0; i < this.ranges.length; i++) { 2059 var range = this.ranges[i]; 2060 if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) 2061 return i; 2062 } 2063 return -1; 2064 } 2065 }; 2066 2067 function Range(anchor, head) { 2068 this.anchor = anchor; this.head = head; 2069 } 2070 2071 Range.prototype = { 2072 from: function() { return minPos(this.anchor, this.head); }, 2073 to: function() { return maxPos(this.anchor, this.head); }, 2074 empty: function() { 2075 return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; 2076 } 2077 }; 2078 2079 // Take an unsorted, potentially overlapping set of ranges, and 2080 // build a selection out of it. 'Consumes' ranges array (modifying 2081 // it). 2082 function normalizeSelection(ranges, primIndex) { 2083 var prim = ranges[primIndex]; 2084 ranges.sort(function(a, b) { return cmp(a.from(), b.from()); }); 2085 primIndex = indexOf(ranges, prim); 2086 for (var i = 1; i < ranges.length; i++) { 2087 var cur = ranges[i], prev = ranges[i - 1]; 2088 if (cmp(prev.to(), cur.from()) >= 0) { 2089 var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); 2090 var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; 2091 if (i <= primIndex) --primIndex; 2092 ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); 2093 } 2094 } 2095 return new Selection(ranges, primIndex); 2096 } 2097 2098 function simpleSelection(anchor, head) { 2099 return new Selection([new Range(anchor, head || anchor)], 0); 2100 } 2101 2102 // Most of the external API clips given positions to make sure they 2103 // actually exist within the document. 2104 function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} 2105 function clipPos(doc, pos) { 2106 if (pos.line < doc.first) return Pos(doc.first, 0); 2107 var last = doc.first + doc.size - 1; 2108 if (pos.line > last) return Pos(last, getLine(doc, last).text.length); 2109 return clipToLen(pos, getLine(doc, pos.line).text.length); 2110 } 2111 function clipToLen(pos, linelen) { 2112 var ch = pos.ch; 2113 if (ch == null || ch > linelen) return Pos(pos.line, linelen); 2114 else if (ch < 0) return Pos(pos.line, 0); 2115 else return pos; 2116 } 2117 function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} 2118 function clipPosArray(doc, array) { 2119 for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]); 2120 return out; 2121 } 2122 2123 // SELECTION UPDATES 2124 2125 // The 'scroll' parameter given to many of these indicated whether 2126 // the new cursor position should be scrolled into view after 2127 // modifying the selection. 2128 2129 // If shift is held or the extend flag is set, extends a range to 2130 // include a given position (and optionally a second position). 2131 // Otherwise, simply returns the range between the given positions. 2132 // Used for cursor motion and such. 2133 function extendRange(doc, range, head, other) { 2134 if (doc.cm && doc.cm.display.shift || doc.extend) { 2135 var anchor = range.anchor; 2136 if (other) { 2137 var posBefore = cmp(head, anchor) < 0; 2138 if (posBefore != (cmp(other, anchor) < 0)) { 2139 anchor = head; 2140 head = other; 2141 } else if (posBefore != (cmp(head, other) < 0)) { 2142 head = other; 2143 } 2144 } 2145 return new Range(anchor, head); 2146 } else { 2147 return new Range(other || head, head); 2148 } 2149 } 2150 2151 // Extend the primary selection range, discard the rest. 2152 function extendSelection(doc, head, other, options) { 2153 setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options); 2154 } 2155 2156 // Extend all selections (pos is an array of selections with length 2157 // equal the number of selections) 2158 function extendSelections(doc, heads, options) { 2159 for (var out = [], i = 0; i < doc.sel.ranges.length; i++) 2160 out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null); 2161 var newSel = normalizeSelection(out, doc.sel.primIndex); 2162 setSelection(doc, newSel, options); 2163 } 2164 2165 // Updates a single range in the selection. 2166 function replaceOneSelection(doc, i, range, options) { 2167 var ranges = doc.sel.ranges.slice(0); 2168 ranges[i] = range; 2169 setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); 2170 } 2171 2172 // Reset the selection to a single range. 2173 function setSimpleSelection(doc, anchor, head, options) { 2174 setSelection(doc, simpleSelection(anchor, head), options); 2175 } 2176 2177 // Give beforeSelectionChange handlers a change to influence a 2178 // selection update. 2179 function filterSelectionChange(doc, sel, options) { 2180 var obj = { 2181 ranges: sel.ranges, 2182 update: function(ranges) { 2183 this.ranges = []; 2184 for (var i = 0; i < ranges.length; i++) 2185 this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), 2186 clipPos(doc, ranges[i].head)); 2187 }, 2188 origin: options && options.origin 2189 }; 2190 signal(doc, "beforeSelectionChange", doc, obj); 2191 if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); 2192 if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1); 2193 else return sel; 2194 } 2195 2196 function setSelectionReplaceHistory(doc, sel, options) { 2197 var done = doc.history.done, last = lst(done); 2198 if (last && last.ranges) { 2199 done[done.length - 1] = sel; 2200 setSelectionNoUndo(doc, sel, options); 2201 } else { 2202 setSelection(doc, sel, options); 2203 } 2204 } 2205 2206 // Set a new selection. 2207 function setSelection(doc, sel, options) { 2208 setSelectionNoUndo(doc, sel, options); 2209 addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); 2210 } 2211 2212 function setSelectionNoUndo(doc, sel, options) { 2213 if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) 2214 sel = filterSelectionChange(doc, sel, options); 2215 2216 var bias = options && options.bias || 2217 (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); 2218 setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); 2219 2220 if (!(options && options.scroll === false) && doc.cm) 2221 ensureCursorVisible(doc.cm); 2222 } 2223 2224 function setSelectionInner(doc, sel) { 2225 if (sel.equals(doc.sel)) return; 2226 2227 doc.sel = sel; 2228 2229 if (doc.cm) { 2230 doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; 2231 signalCursorActivity(doc.cm); 2232 } 2233 signalLater(doc, "cursorActivity", doc); 2234 } 2235 2236 // Verify that the selection does not partially select any atomic 2237 // marked ranges. 2238 function reCheckSelection(doc) { 2239 setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll); 2240 } 2241 2242 // Return a selection that does not partially select any atomic 2243 // ranges. 2244 function skipAtomicInSelection(doc, sel, bias, mayClear) { 2245 var out; 2246 for (var i = 0; i < sel.ranges.length; i++) { 2247 var range = sel.ranges[i]; 2248 var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]; 2249 var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear); 2250 var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear); 2251 if (out || newAnchor != range.anchor || newHead != range.head) { 2252 if (!out) out = sel.ranges.slice(0, i); 2253 out[i] = new Range(newAnchor, newHead); 2254 } 2255 } 2256 return out ? normalizeSelection(out, sel.primIndex) : sel; 2257 } 2258 2259 function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { 2260 var line = getLine(doc, pos.line); 2261 if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { 2262 var sp = line.markedSpans[i], m = sp.marker; 2263 if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && 2264 (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) { 2265 if (mayClear) { 2266 signal(m, "beforeCursorEnter"); 2267 if (m.explicitlyCleared) { 2268 if (!line.markedSpans) break; 2269 else {--i; continue;} 2270 } 2271 } 2272 if (!m.atomic) continue; 2273 2274 if (oldPos) { 2275 var near = m.find(dir < 0 ? 1 : -1), diff; 2276 if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft) 2277 near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); 2278 if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) 2279 return skipAtomicInner(doc, near, pos, dir, mayClear); 2280 } 2281 2282 var far = m.find(dir < 0 ? -1 : 1); 2283 if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight) 2284 far = movePos(doc, far, dir, far.line == pos.line ? line : null); 2285 return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null; 2286 } 2287 } 2288 return pos; 2289 } 2290 2291 // Ensure a given position is not inside an atomic range. 2292 function skipAtomic(doc, pos, oldPos, bias, mayClear) { 2293 var dir = bias || 1; 2294 var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || 2295 (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || 2296 skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || 2297 (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)); 2298 if (!found) { 2299 doc.cantEdit = true; 2300 return Pos(doc.first, 0); 2301 } 2302 return found; 2303 } 2304 2305 function movePos(doc, pos, dir, line) { 2306 if (dir < 0 && pos.ch == 0) { 2307 if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1)); 2308 else return null; 2309 } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { 2310 if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0); 2311 else return null; 2312 } else { 2313 return new Pos(pos.line, pos.ch + dir); 2314 } 2315 } 2316 2317 // SELECTION DRAWING 2318 2319 function updateSelection(cm) { 2320 cm.display.input.showSelection(cm.display.input.prepareSelection()); 2321 } 2322 2323 function prepareSelection(cm, primary) { 2324 var doc = cm.doc, result = {}; 2325 var curFragment = result.cursors = document.createDocumentFragment(); 2326 var selFragment = result.selection = document.createDocumentFragment(); 2327 2328 for (var i = 0; i < doc.sel.ranges.length; i++) { 2329 if (primary === false && i == doc.sel.primIndex) continue; 2330 var range = doc.sel.ranges[i]; 2331 if (range.from().line >
2331= cm.display.viewTo || range.to().line < cm.display.viewFrom) continue; 2332 var collapsed = range.empty(); 2333 if (collapsed || cm.options.showCursorWhenSelecting) 2334 drawSelectionCursor(cm, range.head, curFragment); 2335 if (!collapsed) 2336 drawSelectionRange(cm, range, selFragment); 2337 } 2338 return result; 2339 } 2340 2341 // Draws a cursor for the given range 2342 function drawSelectionCursor(cm, head, output) { 2343 var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); 2344 2345 var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); 2346 cursor.style.left = pos.left + "px"; 2347 cursor.style.top = pos.top + "px"; 2348 cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; 2349 2350 if (pos.other) { 2351 // Secondary cursor, shown when on a 'jump' in bi-directional text 2352 var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); 2353 otherCursor.style.display = ""; 2354 otherCursor.style.left = pos.other.left + "px"; 2355 otherCursor.style.top = pos.other.top + "px"; 2356 otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; 2357 } 2358 } 2359 2360 // Draws the given range as a highlighted selection 2361 function drawSelectionRange(cm, range, output) { 2362 var display = cm.display, doc = cm.doc; 2363 var fragment = document.createDocumentFragment(); 2364 var padding = paddingH(cm.display), leftSide = padding.left; 2365 var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; 2366 2367 function add(left, top, width, bottom) { 2368 if (top < 0) top = 0; 2369 top = Math.round(top); 2370 bottom = Math.round(bottom); 2371 fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + 2372 "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) + 2373 "px; height: " + (bottom - top) + "px")); 2374 } 2375 2376 function drawForLine(line, fromArg, toArg) { 2377 var lineObj = getLine(doc, line); 2378 var lineLen = lineObj.text.length; 2379 var start, end; 2380 function coords(ch, bias) { 2381 return charCoords(cm, Pos(line, ch), "div", lineObj, bias); 2382 } 2383 2384 iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { 2385 var leftPos = coords(from, "left"), rightPos, left, right; 2386 if (from == to) { 2387 rightPos = leftPos; 2388 left = right = leftPos.left; 2389 } else { 2390 rightPos = coords(to - 1, "right"); 2391 if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } 2392 left = leftPos.left; 2393 right = rightPos.right; 2394 } 2395 if (fromArg == null && from == 0) left = leftSide; 2396 if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part 2397 add(left, leftPos.top, null, leftPos.bottom); 2398 left = leftSide; 2399 if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); 2400 } 2401 if (toArg == null && to == lineLen) right = rightSide; 2402 if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) 2403 start = leftPos; 2404 if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) 2405 end = rightPos; 2406 if (left < leftSide + 1) left = leftSide; 2407 add(left, rightPos.top, right - left, rightPos.bottom); 2408 }); 2409 return {start: start, end: end}; 2410 } 2411 2412 var sFrom = range.from(), sTo = range.to(); 2413 if (sFrom.line == sTo.line) { 2414 drawForLine(sFrom.line, sFrom.ch, sTo.ch); 2415 } else { 2416 var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); 2417 var singleVLine = visualLine(fromLine) == visualLine(toLine); 2418 var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; 2419 var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; 2420 if (singleVLine) { 2421 if (leftEnd.top < rightStart.top - 2) { 2422 add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); 2423 add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); 2424 } else { 2425 add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); 2426 } 2427 } 2428 if (leftEnd.bottom < rightStart.top) 2429 add(leftSide, leftEnd.bottom, null, rightStart.top); 2430 } 2431 2432 output.appendChild(fragment); 2433 } 2434 2435 // Cursor-blinking 2436 function restartBlink(cm) { 2437 if (!cm.state.focused) return; 2438 var display = cm.display; 2439 clearInterval(display.blinker); 2440 var on = true; 2441 display.cursorDiv.style.visibility = ""; 2442 if (cm.options.cursorBlinkRate > 0) 2443 display.blinker = setInterval(function() { 2444 display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; 2445 }, cm.options.cursorBlinkRate); 2446 else if (cm.options.cursorBlinkRate < 0) 2447 display.cursorDiv.style.visibility = "hidden"; 2448 } 2449 2450 // HIGHLIGHT WORKER 2451 2452 function startWorker(cm, time) { 2453 if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) 2454 cm.state.highlight.set(time, bind(highlightWorker, cm)); 2455 } 2456 2457 function highlightWorker(cm) { 2458 var doc = cm.doc; 2459 if (doc.frontier < doc.first) doc.frontier = doc.first; 2460 if (doc.frontier >
2460= cm.display.viewTo) return; 2461 var end = +new Date + cm.options.workTime; 2462 var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); 2463 var changedLines = []; 2464 2465 doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) { 2466 if (doc.frontier >= cm.display.viewFrom) { // Visible 2467 var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength; 2468 var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true); 2469 line.styles = highlighted.styles; 2470 var oldCls = line.styleClasses, newCls = highlighted.classes; 2471 if (newCls) line.styleClasses = newCls; 2472 else if (oldCls) line.styleClasses = null; 2473 var ischange = !oldStyles || oldStyles.length != line.styles.length || 2474 oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); 2475 for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; 2476 if (ischange) changedLines.push(doc.frontier); 2477 line.stateAfter = tooLong ? state : copyState(doc.mode, state); 2478 } else { 2479 if (line.text.length <= cm.options.maxHighlightLength) 2480 processLine(cm, line.text, state); 2481 line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; 2482 } 2483 ++doc.frontier; 2484 if (+new Date >
2484 end) { 2485 startWorker(cm, cm.options.workDelay); 2486 return true; 2487 } 2488 }); 2489 if (changedLines.length) runInOp(cm, function() { 2490 for (var i = 0; i < changedLines.length; i++) 2491 regLineChange(cm, changedLines[i], "text"); 2492 }); 2493 } 2494 2495 // Finds the line to start with when starting a parse. Tries to 2496 // find a line with a stateAfter, so that it can start with a 2497 // valid state. If that fails, it returns the line with the 2498 // smallest indentation, which tends to need the least context to 2499 // parse correctly. 2500 function findStartLine(cm, n, precise) { 2501 var minindent, minline, doc = cm.doc; 2502 var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); 2503 for (var search = n; search > lim; --search) { 2504 if (search <= doc.first) return doc.first; 2505 var line = getLine(doc, search - 1); 2506 if (line.stateAfter && (!precise || search <= doc.frontier)) return search; 2507 var indented = countColumn(line.text, null, cm.options.tabSize); 2508 if (minline == null || minindent > indented) { 2509 minline = search - 1; 2510 minindent = indented; 2511 } 2512 } 2513 return minline; 2514 } 2515 2516 function getStateBefore(cm, n, precise) { 2517 var doc = cm.doc, display = cm.display; 2518 if (!doc.mode.startState) return true; 2519 var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter; 2520 if (!state) state = startState(doc.mode); 2521 else state = copyState(doc.mode, state); 2522 doc.iter(pos, n, function(line) { 2523 processLine(cm, line.text, state); 2524 var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo; 2525 line.stateAfter = save ? copyState(doc.mode, state) : null; 2526 ++pos; 2527 }); 2528 if (precise) doc.frontier = pos; 2529 return state; 2530 } 2531 2532 // POSITION MEASUREMENT 2533 2534 function paddingTop(display) {return display.lineSpace.offsetTop;} 2535 function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} 2536 function paddingH(display) { 2537 if (display.cachedPaddingH) return display.cachedPaddingH; 2538 var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); 2539 var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; 2540 var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; 2541 if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data; 2542 return data; 2543 } 2544 2545 function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; } 2546 function displayWidth(cm) { 2547 return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; 2548 } 2549 function displayHeight(cm) { 2550 return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; 2551 } 2552 2553 // Ensure the lineView.wrapping.heights array is populated. This is 2554 // an array of bottom offsets for the lines that make up a drawn 2555 // line. When lineWrapping is on, there might be more than one 2556 // height. 2557 function ensureLineHeights(cm, lineView, rect) { 2558 var wrapping = cm.options.lineWrapping; 2559 var curWidth = wrapping && displayWidth(cm); 2560 if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { 2561 var heights = lineView.measure.heights = []; 2562 if (wrapping) { 2563 lineView.measure.width = curWidth; 2564 var rects = lineView.text.firstChild.getClientRects(); 2565 for (var i = 0; i < rects.length - 1; i++) { 2566 var cur = rects[i], next = rects[i + 1]; 2567 if (Math.abs(cur.bottom - next.bottom) > 2) 2568 heights.push((cur.bottom + next.top) / 2 - rect.top); 2569 } 2570 } 2571 heights.push(rect.bottom - rect.top); 2572 } 2573 } 2574 2575 // Find a line map (mapping character offsets to text nodes) and a 2576 // measurement cache for the given line number. (A line view might 2577 // contain multiple lines when collapsed ranges are present.) 2578 function mapFromLineView(lineView, line, lineN) { 2579 if (lineView.line == line) 2580 return {map: lineView.measure.map, cache: lineView.measure.cache}; 2581 for (var i = 0; i < lineView.rest.length; i++) 2582 if (lineView.rest[i] == line) 2583 return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]}; 2584 for (var i = 0; i < lineView.rest.length; i++) 2585 if (lineNo(lineView.rest[i]) > lineN) 2586 return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true}; 2587 } 2588 2589 // Render a line into the hidden node display.externalMeasured. Used 2590 // when measurement is needed for a line that's not in the viewport.
2591 function updateExternalMeasurement(cm, line) { 2592 line = visualLine(line); 2593 var lineN = lineNo(line); 2594 var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); 2595 view.lineN = lineN; 2596 var built = view.built = buildLineContent(cm, view); 2597 view.text = built.pre; 2598 removeChildrenAndAdd(cm.display.lineMeasure, built.pre); 2599 return view; 2600 } 2601 2602 // Get a {top, bottom, left, right} box (in line-local coordinates) 2603 // for a given character. 2604 function measureChar(cm, line, ch, bias) { 2605 return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); 2606 } 2607 2608 // Find a line view that corresponds to the given line number. 2609 function findViewForLine(cm, lineN) { 2610 if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) 2611 return cm.display.view[findViewIndex(cm, lineN)]; 2612 var ext = cm.display.externalMeasured; 2613 if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) 2614 return ext; 2615 } 2616 2617 // Measurement can be split in two steps, the set-up work that 2618 // applies to the whole line, and the measurement of the actual 2619 // character. Functions like coordsChar, that need to do a lot of 2620 // measurements in a row, can thus ensure that the set-up work is 2621 // only done once. 2622 function prepareMeasureForLine(cm, line) { 2623 var lineN = lineNo(line); 2624 var view = findViewForLine(cm, lineN); 2625 if (view && !view.text) { 2626 view = null; 2627 } else if (view && view.changes) { 2628 updateLineForChanges(cm, view, lineN, getDimensions(cm)); 2629 cm.curOp.forceUpdate = true; 2630 } 2631 if (!view) 2632 view = updateExternalMeasurement(cm, line); 2633 2634 var info = mapFromLineView(view, line, lineN); 2635 return { 2636 line: line, view: view, rect: null, 2637 map: info.map, cache: info.cache, before: info.before, 2638 hasHeights: false 2639 }; 2640 } 2641 2642 // Given a prepared measurement object, measures the position of an 2643 // actual character (or fetches it from the cache). 2644 function measureCharPrepared(cm, prepared, ch, bias, varHeight) { 2645 if (prepared.before) ch = -1; 2646 var key = ch + (bias || ""), found; 2647 if (prepared.cache.hasOwnProperty(key)) { 2648 found = prepared.cache[key]; 2649 } else { 2650 if (!prepared.rect) 2651 prepared.rect = prepared.view.text.getBoundingClientRect(); 2652 if (!prepared.hasHeights) { 2653 ensureLineHeights(cm, prepared.view, prepared.rect); 2654 prepared.hasHeights = true; 2655 } 2656 found = measureCharInner(cm, prepared, ch, bias); 2657 if (!found.bogus) prepared.cache[key] = found; 2658 } 2659 return {left: found.left, right: found.right, 2660 top: varHeight ? found.rtop : found.top, 2661 bottom: varHeight ? found.rbottom : found.bottom}; 2662 } 2663 2664 var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; 2665 2666 function nodeAndOffsetInLineMap(map, ch, bias) { 2667 var node, start, end, collapse; 2668 // First, search the line map for the text node corresponding to, 2669 // or closest to, the target character. 2670 for (var i = 0; i < map.length; i += 3) { 2671 var mStart = map[i], mEnd = map[i + 1]; 2672 if (ch < mStart) { 2673 start = 0; end = 1; 2674 collapse = "left"; 2675 } else if (ch < mEnd) { 2676 start = ch - mStart; 2677 end = start + 1; 2678 } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { 2679 end = mEnd - mStart; 2680 start = end - 1; 2681 if (ch >= mEnd) collapse = "right"; 2682 } 2683 if (start != null) { 2684 node = map[i + 2]; 2685 if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) 2686 collapse = bias; 2687 if (bias == "left" && start == 0) 2688 while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { 2689 node = map[(i -= 3) + 2]; 2690 collapse = "left"; 2691 } 2692 if (bias == "right" && start == mEnd - mStart) 2693 while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { 2694 node = map[(i += 3) + 2]; 2695 collapse = "right"; 2696 } 2697 break; 2698 } 2699 } 2700 return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}; 2701 } 2702 2703 function getUsefulRect(rects, bias) { 2704 var rect = nullRect 2705 if (bias == "left") for (var i = 0; i < rects.length; i++) { 2706 if ((rect = rects[i]).left != rect.right) break 2707 } else for (var i = rects.length - 1; i >= 0; i--) { 2708 if ((rect = rects[i]).left != rect.right) break 2709 } 2710 return rect 2711 } 2712 2713 function measureCharInner(cm, prepared, ch, bias) { 2714 var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); 2715 var node = place.node, start = place.start, end = place.end, collapse = place.collapse; 2716 2717 var rect; 2718 if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. 2719 for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned 2720 while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
2721 while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end; 2722 if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) 2723 rect = node.parentNode.getBoundingClientRect(); 2724 else 2725 rect = getUsefulRect(range(node, start, end).getClientRects(), bias) 2726 if (rect.left || rect.right || start == 0) break; 2727 end = start; 2728 start = start - 1; 2729 collapse = "right"; 2730 } 2731 if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect); 2732 } else { // If it is a widget, simply get the box for the whole widget. 2733 if (start > 0) collapse = bias = "right"; 2734 var rects; 2735 if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) 2736 rect = rects[bias == "right" ? rects.length - 1 : 0]; 2737 else 2738 rect = node.getBoundingClientRect(); 2739 } 2740 if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { 2741 var rSpan = node.parentNode.getClientRects()[0]; 2742 if (rSpan) 2743 rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; 2744 else 2745 rect = nullRect; 2746 } 2747 2748 var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; 2749 var mid = (rtop + rbot) / 2; 2750 var heights = prepared.view.measure.heights; 2751 for (var i = 0; i < heights.length - 1; i++) 2752 if (mid < heights[i]) break; 2753 var top = i ? heights[i - 1] : 0, bot = heights[i]; 2754 var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, 2755 right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, 2756 top: top, bottom: bot}; 2757 if (!rect.left && !rect.right) result.bogus = true; 2758 if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } 2759 2760 return result; 2761 } 2762 2763 // Work around problem with bounding client rects on ranges being 2764 // returned incorrectly when zoomed on IE10 and below. 2765 function maybeUpdateRectForZooming(measure, rect) { 2766 if (!window.screen || screen.logicalXDPI == null || 2767 screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) 2768 return rect; 2769 var scaleX = screen.logicalXDPI / screen.deviceXDPI; 2770 var scaleY = screen.logicalYDPI / screen.deviceYDPI; 2771 return {left: rect.left * scaleX, right: rect.right * scaleX, 2772 top: rect.top * scaleY, bottom: rect.bottom * scaleY}; 2773 } 2774 2775 function clearLineMeasurementCacheFor(lineView) { 2776 if (lineView.measure) { 2777 lineView.measure.cache = {}; 2778 lineView.measure.heights = null; 2779 if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) 2780 lineView.measure.caches[i] = {}; 2781 } 2782 } 2783 2784 function clearLineMeasurementCache(cm) { 2785 cm.display.externalMeasure = null; 2786 removeChildren(cm.display.lineMeasure); 2787 for (var i = 0; i < cm.display.view.length; i++) 2788 clearLineMeasurementCacheFor(cm.display.view[i]); 2789 } 2790 2791 function clearCaches(cm) { 2792 clearLineMeasurementCache(cm); 2793 cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; 2794 if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; 2795 cm.display.lineNumChars = null; 2796 } 2797 2798 function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } 2799 function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } 2800 2801 // Converts a {top, bottom, left, right} box from line-local 2802 // coordinates into another coordinate system. Context may be one of 2803 // "line", "div" (display.lineDiv), "local"/null (editor), "window", 2804 // or "page". 2805 function intoCoordSystem(cm, lineObj, rect, context) { 2806 if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { 2807 var size = widgetHeight(lineObj.widgets[i]); 2808 rect.top += size; rect.bottom += size; 2809 } 2810 if (context == "line") return rect; 2811 if (!context) context = "local"; 2812 var yOff = heightAtLine(lineObj); 2813 if (context == "local") yOff += paddingTop(cm.display);
2814 else yOff -= cm.display.viewOffset; 2815 if (context == "page" || context == "window") { 2816 var lOff = cm.display.lineSpace.getBoundingClientRect(); 2817 yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); 2818 var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); 2819 rect.left += xOff; rect.right += xOff; 2820 } 2821 rect.top += yOff; rect.bottom += yOff; 2822 return rect; 2823 } 2824 2825 // Coverts a box from "div" coords to another coordinate system. 2826 // Context may be "window", "page", "div", or "local"/null. 2827 function fromCoordSystem(cm, coords, context) { 2828 if (context == "div") return coords; 2829 var left = coords.left, top = coords.top; 2830 // First move into "page" coordinate system 2831 if (context == "page") { 2832 left -= pageScrollX(); 2833 top -= pageScrollY(); 2834 } else if (context == "local" || !context) { 2835 var localBox = cm.display.sizer.getBoundingClientRect(); 2836 left += localBox.left; 2837 top += localBox.top; 2838 } 2839 2840 var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); 2841 return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; 2842 } 2843 2844 function charCoords(cm, pos, context, lineObj, bias) { 2845 if (!lineObj) lineObj = getLine(cm.doc, pos.line); 2846 return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); 2847 } 2848 2849 // Returns a box for a given cursor position, which may have an 2850 // 'other' property containing the position of the secondary cursor 2851 // on a bidi boundary. 2852 function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { 2853 lineObj = lineObj || getLine(cm.doc, pos.line); 2854 if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj); 2855 function get(ch, right) { 2856 var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); 2857 if (right) m.left = m.right; else m.right = m.left; 2858 return intoCoordSystem(cm, lineObj, m, context); 2859 } 2860 function getBidi(ch, partPos) { 2861 var part = order[partPos], right = part.level % 2; 2862 if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { 2863 part = order[--partPos]; 2864 ch = bidiRight(part) - (part.level % 2 ? 0 : 1); 2865 right = true; 2866 } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { 2867 part = order[++partPos]; 2868 ch = bidiLeft(part) - part.level % 2; 2869 right = false; 2870 } 2871 if (right && ch == part.to && ch > part.from) return get(ch - 1); 2872 return get(ch, right); 2873 } 2874 var order = getOrder(lineObj), ch = pos.ch; 2875 if (!order) return get(ch); 2876 var partPos = getBidiPartAt(order, ch); 2877 var val = getBidi(ch, partPos); 2878 if (bidiOther != null) val.other = getBidi(ch, bidiOther); 2879 return val; 2880 } 2881 2882 // Used to cheaply estimate the coordinates for a position. Used for 2883 // intermediate scroll updates. 2884 function estimateCoords(cm, pos) { 2885 var left = 0, pos = clipPos(cm.doc, pos); 2886 if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch; 2887 var lineObj = getLine(cm.doc, pos.line); 2888 var top = heightAtLine(lineObj) + paddingTop(cm.display); 2889 return {left: left, right: left, top: top, bottom: top + lineObj.height}; 2890 } 2891 2892 // Positions returned by coordsChar contain some extra information. 2893 // xRel is the relative x position of the input coordinates compared 2894 // to the found position (so xRel > 0 means the coordinates are to 2895 // the right of the character position, for example). When outside 2896 // is true, that means the coordinates lie outside the line's 2897 // vertical range. 2898 function PosWithInfo(line, ch, outside, xRel) { 2899 var pos = Pos(line, ch); 2900 pos.xRel = xRel; 2901 if (outside) pos.outside = true; 2902 return pos; 2903 } 2904 2905 // Compute the character position closest to the given coordinates. 2906 // Input must be lineSpace-local ("div" coordinate system). 2907 function coordsChar(cm, x, y) { 2908 var doc = cm.doc; 2909 y += cm.display.viewOffset; 2910 if (y < 0) return PosWithInfo(doc.first, 0, true, -1); 2911 var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; 2912 if (lineN > last) 2913 return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
2914 if (x < 0) x = 0; 2915 2916 var lineObj = getLine(doc, lineN); 2917 for (;;) { 2918 var found = coordsCharInner(cm, lineObj, lineN, x, y); 2919 var merged = collapsedSpanAtEnd(lineObj); 2920 var mergedPos = merged && merged.find(0, true); 2921 if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) 2922 lineN = lineNo(lineObj = mergedPos.to.line); 2923 else 2924 return found; 2925 } 2926 } 2927 2928 function coordsCharInner(cm, lineObj, lineNo, x, y) { 2929 var innerOff = y - heightAtLine(lineObj); 2930 var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; 2931 var preparedMeasure = prepareMeasureForLine(cm, lineObj); 2932 2933 function getX(ch) { 2934 var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure); 2935 wrongLine = true; 2936 if (innerOff > sp.bottom) return sp.left - adjust; 2937 else if (innerOff < sp.top) return sp.left + adjust; 2938 else wrongLine = false; 2939 return sp.left; 2940 } 2941 2942 var bidi = getOrder(lineObj), dist = lineObj.text.length; 2943 var from = lineLeft(lineObj), to = lineRight(lineObj); 2944 var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; 2945 2946 if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); 2947 // Do a binary search between these bounds. 2948 for (;;) { 2949 if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { 2950 var ch = x < fromX || x - fromX <= toX - x ? from : to; 2951 var outside = ch == from ? fromOutside : toOutside 2952 var xDiff = x - (ch == from ? fromX : toX); 2953 // This is a kludge to handle the case where the coordinates 2954 // are after a line-wrapped line. We should replace it with a 2955 // more general handling of cursor positions around line 2956 // breaks. (Issue #4078) 2957 if (toOutside && !bidi && !/\s/.test(lineObj.text.charAt(ch)) && xDiff > 0 && 2958 ch < lineObj.text.length && preparedMeasure.view.measure.heights.length > 1) { 2959 var charSize = measureCharPrepared(cm, preparedMeasure, ch, "right"); 2960 if (innerOff <= charSize.bottom && innerOff >= charSize.top && Math.abs(x - charSize.right) < xDiff) { 2961 outside = false 2962 ch++ 2963 xDiff = x - charSize.right 2964 } 2965 } 2966 while (isExtendingChar(lineObj.text.charAt(ch))) ++ch; 2967 var pos = PosWithInfo(lineNo, ch, outside, xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0); 2968 return pos; 2969 } 2970 var step = Math.ceil(dist / 2), middle = from + step; 2971 if (bidi) { 2972 middle = from; 2973 for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); 2974 } 2975 var middleX = getX(middle); 2976 if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} 2977 else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} 2978 } 2979 } 2980 2981 var measureText; 2982 // Compute the default text height. 2983 function textHeight(display) { 2984 if (display.cachedTextHeight != null) return display.cachedTextHeight; 2985 if (measureText == null) { 2986 measureText = elt("pre"); 2987 // Measure a bunch of lines, for browsers that compute 2988 // fractional heights. 2989 for (var i = 0; i < 49; ++i) { 2990 measureText.appendChild(document.createTextNode("x")); 2991 measureText.appendChild(elt("br")); 2992 } 2993 measureText.appendChild(document.createTextNode("x")); 2994 } 2995 removeChildrenAndAdd(display.measure, measureText); 2996 var height = measureText.offsetHeight / 50; 2997 if (height > 3) display.cachedTextHeight = height; 2998 removeChildren(display.measure); 2999 return height || 1; 3000 } 3001 3002 // Compute the default character width. 3003 function charWidth(display) { 3004 if (display.cachedCharWidth != null) return display.cachedCharWidth; 3005 var anchor = elt("span", "xxxxxxxxxx"); 3006 var pre = elt("pre", [anchor]); 3007 removeChildrenAndAdd(display.measure, pre); 3008 var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; 3009 if (width > 2) display.cachedCharWidth = width; 3010 return width || 10; 3011 } 3012 3013 // OPERATIONS 3014 3015 // Operations are used to wrap a series of changes to the editor
3016 // state in such a way that each change won't have to update the 3017 // cursor and display (which would be awkward, slow, and 3018 // error-prone). Instead, display updates are batched and then all 3019 // combined and executed at once. 3020 3021 var operationGroup = null; 3022 3023 var nextOpId = 0; 3024 // Start a new operation. 3025 function startOperation(cm) { 3026 cm.curOp = { 3027 cm: cm, 3028 viewChanged: false, // Flag that indicates that lines might need to be redrawn 3029 startHeight: cm.doc.height, // Used to detect need to update scrollbar 3030 forceUpdate: false, // Used to force a redraw 3031 updateInput: null, // Whether to reset the input textarea 3032 typing: false, // Whether this reset should be careful to leave existing text (for compositing) 3033 changeObjs: null, // Accumulated changes, for firing change events 3034 cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on 3035 cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already 3036 selectionChanged: false, // Whether the selection needs to be redrawn 3037 updateMaxLine: false, // Set when the widest line needs to be determined anew 3038 scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet 3039 scrollToPos: null, // Used to scroll to a specific position 3040 focus: false, 3041 id: ++nextOpId // Unique ID 3042 }; 3043 if (operationGroup) { 3044 operationGroup.ops.push(cm.curOp); 3045 } else { 3046 cm.curOp.ownsGroup = operationGroup = { 3047 ops: [cm.curOp], 3048 delayedCallbacks: [] 3049 }; 3050 } 3051 } 3052 3053 function fireCallbacksForOps(group) { 3054 // Calls delayed callbacks and cursorActivity handlers until no 3055 // new ones appear 3056 var callbacks = group.delayedCallbacks, i = 0; 3057 do { 3058 for (; i < callbacks.length; i++) 3059 callbacks[i].call(null); 3060 for (var j = 0; j < group.ops.length; j++) { 3061 var op = group.ops[j]; 3062 if (op.cursorActivityHandlers) 3063 while (op.cursorActivityCalled < op.cursorActivityHandlers.length) 3064 op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); 3065 } 3066 } while (i < callbacks.length); 3067 } 3068 3069 // Finish an operation, updating the display and signalling delayed events 3070 function endOperation(cm) { 3071 var op = cm.curOp, group = op.ownsGroup; 3072 if (!group) return; 3073 3074 try { fireCallbacksForOps(group); } 3075 finally { 3076 operationGroup = null; 3077 for (var i = 0; i < group.ops.length; i++) 3078 group.ops[i].cm.curOp = null; 3079 endOperations(group); 3080 } 3081 } 3082 3083 // The DOM updates done when an operation finishes are batched so 3084 // that the minimum number of relayouts are required. 3085 function endOperations(group) { 3086 var ops = group.ops; 3087 for (var i = 0; i < ops.length; i++) // Read DOM 3088 endOperation_R1(ops[i]); 3089 for (var i = 0; i < ops.length; i++) // Write DOM (maybe) 3090 endOperation_W1(ops[i]); 3091 for (var i = 0; i < ops.length; i++) // Read DOM 3092 endOperation_R2(ops[i]); 3093 for (var i = 0; i < ops.length; i++) // Write DOM (maybe) 3094 endOperation_W2(ops[i]); 3095 for (var i = 0; i < ops.length; i++) // Read DOM 3096 endOperation_finish(ops[i]); 3097 } 3098 3099 function endOperation_R1(op) { 3100 var cm = op.cm, display = cm.display; 3101 maybeClipScrollbars(cm); 3102 if (op.updateMaxLine) findMaxLine(cm); 3103 3104 op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || 3105 op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || 3106 op.scrollToPos.to.line >= display.viewTo) || 3107 display.maxLineChanged && cm.options.lineWrapping; 3108 op.update = op.mustUpdate && 3109 new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); 3110 } 3111 3112 function endOperation_W1(op) { 3113 op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); 3114 } 3115 3116 function endOperation_R2(op) { 3117 var cm = op.cm, display = cm.display; 3118 if (op.updatedDisplay) updateHeightsInViewport(cm); 3119 3120 op.barMeasure = measureForScrollbars(cm); 3121 3122 // If the max line changed since it was last measured, measure it, 3123 // and ensure the document's width matches it. 3124 // updateDisplay_W2 will use these properties to do the actual resizing 3125 if (display.maxLineChanged && !cm.options.lineWrapping) { 3126 op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; 3127 cm.display.sizerWidth = op.adjustWidthTo; 3128 op.barMeasure.scrollWidth = 3129 Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); 3130 op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); 3131 } 3132 3133 if (op.updatedDisplay || op.selectionChanged)
3134 op.preparedSelection = display.input.prepareSelection(op.focus); 3135 } 3136 3137 function endOperation_W2(op) { 3138 var cm = op.cm; 3139 3140 if (op.adjustWidthTo != null) { 3141 cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; 3142 if (op.maxScrollLeft < cm.doc.scrollLeft) 3143 setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); 3144 cm.display.maxLineChanged = false; 3145 } 3146 3147 var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus()) 3148 if (op.preparedSelection) 3149 cm.display.input.showSelection(op.preparedSelection, takeFocus); 3150 if (op.updatedDisplay || op.startHeight != cm.doc.height) 3151 updateScrollbars(cm, op.barMeasure); 3152 if (op.updatedDisplay) 3153 setDocumentHeight(cm, op.barMeasure); 3154 3155 if (op.selectionChanged) restartBlink(cm); 3156 3157 if (cm.state.focused && op.updateInput) 3158 cm.display.input.reset(op.typing); 3159 if (takeFocus) ensureFocus(op.cm); 3160 } 3161 3162 function endOperation_finish(op) { 3163 var cm = op.cm, display = cm.display, doc = cm.doc; 3164 3165 if (op.updatedDisplay) postUpdateDisplay(cm, op.update); 3166 3167 // Abort mouse wheel delta measurement, when scrolling explicitly 3168 if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) 3169 display.wheelStartX = display.wheelStartY = null; 3170 3171 // Propagate the scroll position to the actual DOM scroller 3172 if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) { 3173 doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)); 3174 display.scrollbars.setScrollTop(doc.scrollTop); 3175 display.scroller.scrollTop = doc.scrollTop; 3176 } 3177 if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) { 3178 doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft)); 3179 display.scrollbars.setScrollLeft(doc.scrollLeft); 3180 display.scroller.scrollLeft = doc.scrollLeft; 3181 alignHorizontally(cm); 3182 } 3183 // If we need to scroll a specific position into view, do so. 3184 if (op.scrollToPos) { 3185 var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), 3186 clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); 3187 if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords); 3188 } 3189 3190 // Fire events for markers that are hidden/unidden by editing or 3191 // undoing 3192 var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; 3193 if (hidden) for (var i = 0; i < hidden.length; ++i) 3194 if (!hidden[i].lines.length) signal(hidden[i], "hide"); 3195 if (unhidden) for (var i = 0; i < unhidden.length; ++i) 3196 if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); 3197 3198 if (display.wrapper.offsetHeight) 3199 doc.scrollTop = cm.display.scroller.scrollTop; 3200 3201 // Fire change events, and delayed event handlers 3202 if (op.changeObjs) 3203 signal(cm, "changes", cm, op.changeObjs); 3204 if (op.update) 3205 op.update.finish(); 3206 } 3207 3208 // Run the given function in an operation 3209 function runInOp(cm, f) { 3210 if (cm.curOp) return f(); 3211 startOperation(cm); 3212 try { return f(); } 3213 finally { endOperation(cm); } 3214 } 3215 // Wraps a function in an operation. Returns the wrapped function. 3216 function operation(cm, f) { 3217 return function() { 3218 if (cm.curOp) return f.apply(cm, arguments); 3219 startOperation(cm); 3220 try { return f.apply(cm, arguments); } 3221 finally { endOperation(cm); } 3222 }; 3223 } 3224 // Used to add methods to editor and doc instances, wrapping them in 3225 // operations. 3226 function methodOp(f) { 3227 return function() { 3228 if (this.curOp) return f.apply(this, arguments); 3229 startOperation(this); 3230 try { return f.apply(this, arguments); } 3231 finally { endOperation(this); } 3232 }; 3233 } 3234 function docMethodOp(f) { 3235 return function() { 3236 var cm = this.cm; 3237 if (!cm || cm.curOp) return f.apply(this, arguments); 3238 startOperation(cm);
3239 try { return f.apply(this, arguments); } 3240 finally { endOperation(cm); } 3241 }; 3242 } 3243 3244 // VIEW TRACKING 3245 3246 // These objects are used to represent the visible (currently drawn) 3247 // part of the document. A LineView may correspond to multiple 3248 // logical lines, if those are connected by collapsed ranges. 3249 function LineView(doc, line, lineN) { 3250 // The starting line 3251 this.line = line; 3252 // Continuing lines, if any 3253 this.rest = visualLineContinued(line); 3254 // Number of logical lines in this visual line 3255 this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; 3256 this.node = this.text = null; 3257 this.hidden = lineIsHidden(doc, line); 3258 } 3259 3260 // Create a range of LineView objects for the given lines. 3261 function buildViewArray(cm, from, to) { 3262 var array = [], nextPos; 3263 for (var pos = from; pos < to; pos = nextPos) { 3264 var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); 3265 nextPos = pos + view.size; 3266 array.push(view); 3267 } 3268 return array; 3269 } 3270 3271 // Updates the display.view data structure for a given change to the 3272 // document. From and to are in pre-change coordinates. Lendiff is 3273 // the amount of lines added or subtracted by the change. This is 3274 // used for changes that span multiple lines, or change the way 3275 // lines are divided into visual lines. regLineChange (below) 3276 // registers single-line changes. 3277 function regChange(cm, from, to, lendiff) { 3278 if (from == null) from = cm.doc.first; 3279 if (to == null) to = cm.doc.first + cm.doc.size; 3280 if (!lendiff) lendiff = 0; 3281 3282 var display = cm.display; 3283 if (lendiff && to < display.viewTo && 3284 (display.updateLineNumbers == null || display.updateLineNumbers > from)) 3285 display.updateLineNumbers = from; 3286 3287 cm.curOp.viewChanged = true; 3288 3289 if (from >= display.viewTo) { // Change after 3290 if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) 3291 resetView(cm); 3292 } else if (to <= display.viewFrom) { // Change before 3293 if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { 3294 resetView(cm); 3295 } else { 3296 display.viewFrom += lendiff; 3297 display.viewTo += lendiff; 3298 } 3299 } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap 3300 resetView(cm); 3301 } else if (from <= display.viewFrom) { // Top overlap 3302 var cut = viewCuttingPoint(cm, to, to + lendiff, 1); 3303 if (cut) { 3304 display.view = display.view.slice(cut.index); 3305 display.viewFrom = cut.lineN; 3306 display.viewTo += lendiff; 3307 } else { 3308 resetView(cm); 3309 } 3310 } else if (to >= display.viewTo) { // Bottom overlap 3311 var cut = viewCuttingPoint(cm, from, from, -1); 3312 if (cut) { 3313 display.view = display.view.slice(0, cut.index); 3314 display.viewTo = cut.lineN; 3315 } else { 3316 resetView(cm); 3317 } 3318 } else { // Gap in the middle 3319 var cutTop = viewCuttingPoint(cm, from, from, -1); 3320 var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); 3321 if (cutTop && cutBot) { 3322 display.view = display.view.slice(0, cutTop.index) 3323 .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) 3324 .concat(display.view.slice(cutBot.index)); 3325 display.viewTo += lendiff; 3326 } else { 3327 resetView(cm); 3328 } 3329 } 3330 3331 var ext = display.externalMeasured; 3332 if (ext) { 3333 if (to < ext.lineN) 3334 ext.lineN += lendiff; 3335 else if (from < ext.lineN + ext.size) 3336 display.externalMeasured = null; 3337 } 3338 } 3339 3340 // Register a change to a single line. Type must be one of "text", 3341 // "gutter", "class", "widget" 3342 function regLineChange(cm, line, type) { 3343 cm.curOp.viewChanged = true; 3344 var display = cm.display, ext = cm.display.externalMeasured; 3345 if (ext && line >= ext.lineN && line < ext.lineN + ext.size) 3346 display.externalMeasured = null; 3347 3348 if (line < display.viewFrom || line >= display.viewTo) return; 3349 var lineView = display.view[findViewIndex(cm, line)]; 3350 if (lineView.node == null) return; 3351 var arr = lineView.changes || (lineView.changes = []); 3352 if (indexOf(arr, type) == -1) arr.push(type); 3353 } 3354 3355 // Clear the view. 3356 function resetView(cm) { 3357 cm.display.viewFrom = cm.display.viewTo = cm.doc.first; 3358 cm.display.view = []; 3359 cm.display.viewOffset = 0; 3360 } 3361 3362 // Find the view element corresponding to a given line. Return null 3363 // when the line isn't visible. 3364 function findViewIndex(cm, n) { 3365 if (n >
3365= cm.display.viewTo) return null; 3366 n -= cm.display.viewFrom; 3367 if (n < 0) return null; 3368 var view = cm.display.view; 3369 for (var i = 0; i < view.length; i++) { 3370 n -= view[i].size; 3371 if (n < 0) return i; 3372 } 3373 } 3374 3375 function viewCuttingPoint(cm, oldN, newN, dir) { 3376 var index = findViewIndex(cm, oldN), diff, view = cm.display.view; 3377 if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) 3378 return {index: index, lineN: newN}; 3379 for (var i = 0, n = cm.display.viewFrom; i < index; i++) 3380 n += view[i].size; 3381 if (n != oldN) { 3382 if (dir > 0) { 3383 if (index == view.length - 1) return null; 3384 diff = (n + view[index].size) - oldN; 3385 index++; 3386 } else { 3387 diff = n - oldN; 3388 } 3389 oldN += diff; newN += diff; 3390 } 3391 while (visualLineNo(cm.doc, newN) != newN) { 3392 if (index == (dir < 0 ? 0 : view.length - 1)) return null; 3393 newN += dir * view[index - (dir < 0 ? 1 : 0)].size; 3394 index += dir; 3395 } 3396 return {index: index, lineN: newN}; 3397 } 3398 3399 // Force the view to cover a given range, adding empty view element 3400 // or clipping off existing ones as needed. 3401 function adjustView(cm, from, to) { 3402 var display = cm.display, view = display.view; 3403 if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { 3404 display.view = buildViewArray(cm, from, to); 3405 display.viewFrom = from; 3406 } else { 3407 if (display.viewFrom > from) 3408 display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); 3409 else if (display.viewFrom < from) 3410 display.view = display.view.slice(findViewIndex(cm, from)); 3411 display.viewFrom = from; 3412 if (display.viewTo < to) 3413 display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); 3414 else if (display.viewTo > to) 3415 display.view = display.view.slice(0, findViewIndex(cm, to)); 3416 } 3417 display.viewTo = to; 3418 } 3419 3420 // Count the number of lines in the view whose DOM representation is 3421 // out of date (or nonexistent). 3422 function countDirtyView(cm) { 3423 var view = cm.display.view, dirty = 0; 3424 for (var i = 0; i < view.length; i++) { 3425 var lineView = view[i]; 3426 if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty; 3427 } 3428 return dirty; 3429 } 3430 3431 // EVENT HANDLERS 3432 3433 // Attach the necessary event handlers when initializing the editor 3434 function registerEventHandlers(cm) { 3435 var d = cm.display; 3436 on(d.scroller, "mousedown", operation(cm, onMouseDown)); 3437 // Older IE's will not fire a second mousedown for a double click 3438 if (ie && ie_version < 11) 3439 on(d.scroller, "dblclick", operation(cm, function(e) { 3440 if (signalDOMEvent(cm, e)) return; 3441 var pos = posFromMouse(cm, e); 3442 if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; 3443 e_preventDefault(e); 3444 var word = cm.findWordAt(pos); 3445 extendSelection(cm.doc, word.anchor, word.head); 3446 })); 3447 else 3448 on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); }); 3449 // Some browsers fire contextmenu *after* opening the menu, at 3450 // which point we can't mess with it anymore. Context menu is 3451 // handled in onMouseDown for these browsers. 3452 if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); 3453 3454 // Used to suppress mouse event handling when a touch happens 3455 var touchFinished, prevTouch = {end: 0}; 3456 function finishTouch() { 3457 if (d.activeTouch) { 3458 touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000); 3459 prevTouch = d.activeTouch; 3460 prevTouch.end = +new Date; 3461 } 3462 }; 3463 function isMouseLikeTouchEvent(e) { 3464 if (e.touches.length != 1) return false; 3465 var touch = e.touches[0]; 3466 return touch.radiusX <= 1 && touch.radiusY <= 1; 3467 } 3468 function farAway(touch, other) { 3469 if (other.left == null) return true; 3470 var dx = other.left - touch.left, dy = other.top - touch.top; 3471 return dx * dx + dy * dy > 20 * 20; 3472 } 3473 on(d.scroller, "touchstart", function(e) { 3474 if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) { 3475 clearTimeout(touchFinished); 3476 var now = +new Date; 3477 d.activeTouch = {start: now, moved: false, 3478 prev: now - prevTouch.end <= 300 ? prevTouch : null}; 3479 if (e.touches.length == 1) { 3480 d.activeTouch.left = e.touches[0].pageX; 3481 d.activeTouch.top = e.touches[0].pageY; 3482 } 3483 } 3484 }); 3485 on(d.scroller, "touchmove", function() { 3486 if (d.activeTouch) d.activeTouch.moved = true; 3487 }); 3488 on(d.scroller, "touchend", function(e) { 3489 var touch = d.activeTouch; 3490 if (touch && !eventInWidget(d, e) && touch.left != null && 3491 !touch.moved && new Date - touch.start < 300) { 3492 var pos = cm.coordsChar(d.activeTouch, "page"), range; 3493 if (!touch.prev || farAway(touch, touch.prev)) // Single tap 3494 range = new Range(pos, pos); 3495 else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap 3496 range = cm.findWordAt(pos);
3497 else // Triple tap 3498 range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); 3499 cm.setSelection(range.anchor, range.head); 3500 cm.focus(); 3501 e_preventDefault(e); 3502 } 3503 finishTouch(); 3504 }); 3505 on(d.scroller, "touchcancel", finishTouch); 3506 3507 // Sync scrolling between fake scrollbars and real scrollable 3508 // area, ensure viewport is updated when scrolling. 3509 on(d.scroller, "scroll", function() { 3510 if (d.scroller.clientHeight) { 3511 setScrollTop(cm, d.scroller.scrollTop); 3512 setScrollLeft(cm, d.scroller.scrollLeft, true); 3513 signal(cm, "scroll", cm); 3514 } 3515 }); 3516 3517 // Listen to wheel events in order to try and update the viewport on time. 3518 on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); 3519 on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); 3520 3521 // Prevent wrapper from ever scrolling 3522 on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); 3523 3524 d.dragFunctions = { 3525 enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);}, 3526 over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, 3527 start: function(e){onDragStart(cm, e);}, 3528 drop: operation(cm, onDrop), 3529 leave: function(e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }} 3530 }; 3531 3532 var inp = d.input.getField(); 3533 on(inp, "keyup", function(e) { onKeyUp.call(cm, e); }); 3534 on(inp, "keydown", operation(cm, onKeyDown)); 3535 on(inp, "keypress", operation(cm, onKeyPress)); 3536 on(inp, "focus", function (e) { onFocus(cm, e); }); 3537 on(inp, "blur", function (e) { onBlur(cm, e); }); 3538 } 3539 3540 function dragDropChanged(cm, value, old) { 3541 var wasOn = old && old != CodeMirror.Init; 3542 if (!value != !wasOn) { 3543 var funcs = cm.display.dragFunctions; 3544 var toggle = value ? on : off; 3545 toggle(cm.display.scroller, "dragstart", funcs.start); 3546 toggle(cm.display.scroller, "dragenter", funcs.enter); 3547 toggle(cm.display.scroller, "dragover", funcs.over); 3548 toggle(cm.display.scroller, "dragleave", funcs.leave); 3549 toggle(cm.display.scroller, "drop", funcs.drop); 3550 } 3551 } 3552 3553 // Called when the window resizes 3554 function onResize(cm) { 3555 var d = cm.display; 3556 if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) 3557 return; 3558 // Might be a text scaling operation, clear size caches. 3559 d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; 3560 d.scrollbarsClipped = false; 3561 cm.setSize(); 3562 } 3563 3564 // MOUSE EVENTS 3565 3566 // Return true when the given mouse event happened in a widget 3567 function eventInWidget(display, e) { 3568 for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { 3569 if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || 3570 (n.parentNode == display.sizer && n != display.mover)) 3571 return true; 3572 } 3573 } 3574 3575 // Given a mouse event, find the corresponding position. If liberal 3576 // is false, it checks whether a gutter or scrollbar was clicked, 3577 // and returns null if it was. forRect is used by rectangular 3578 // selections, and tries to estimate a character position even for 3579 // coordinates beyond the right of the text. 3580 function posFromMouse(cm, e, liberal, forRect) { 3581 var display = cm.display; 3582 if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null; 3583 3584 var x, y, space = display.lineSpace.getBoundingClientRect(); 3585 // Fails unpredictably on IE[67] when mouse is dragged around quickly. 3586 try { x = e.clientX - space.left; y = e.clientY - space.top; } 3587 catch (e) { return null; } 3588 var coords = coordsChar(cm, x, y), line; 3589 if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { 3590 var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; 3591 coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); 3592 } 3593 return coords; 3594 } 3595 3596 // A mouse down can be a single click, double click, triple click, 3597 // start of selection drag, start of text drag, new cursor 3598 // (ctrl-click), rectangle drag (alt-drag), or xwin 3599 // middle-click-paste. Or it might be a click on something we should 3600 // not interfere with, such as a scrollbar or widget. 3601 function onMouseDown(e) { 3602 var cm = this, display = cm.display; 3603 if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) return; 3604 display.shift = e.shiftKey; 3605 3606 if (eventInWidget(display, e)) { 3607 if (!webkit) { 3608 // Briefly turn off draggability, to allow widgets to do 3609 // normal dragging things. 3610 display.scroller.draggable = false;
3611 setTimeout(function(){display.scroller.draggable = true;}, 100); 3612 } 3613 return; 3614 } 3615 if (clickInGutter(cm, e)) return; 3616 var start = posFromMouse(cm, e); 3617 window.focus(); 3618 3619 switch (e_button(e)) { 3620 case 1: 3621 // #3261: make sure, that we're not starting a second selection 3622 if (cm.state.selectingText) 3623 cm.state.selectingText(e); 3624 else if (start) 3625 leftButtonDown(cm, e, start); 3626 else if (e_target(e) == display.scroller) 3627 e_preventDefault(e); 3628 break; 3629 case 2: 3630 if (webkit) cm.state.lastMiddleDown = +new Date; 3631 if (start) extendSelection(cm.doc, start); 3632 setTimeout(function() {display.input.focus();}, 20); 3633 e_preventDefault(e); 3634 break; 3635 case 3: 3636 if (captureRightClick) onContextMenu(cm, e); 3637 else delayBlurEvent(cm); 3638 break; 3639 } 3640 } 3641 3642 var lastClick, lastDoubleClick; 3643 function leftButtonDown(cm, e, start) { 3644 if (ie) setTimeout(bind(ensureFocus, cm), 0); 3645 else cm.curOp.focus = activeElt(); 3646 3647 var now = +new Date, type; 3648 if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { 3649 type = "triple"; 3650 } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { 3651 type = "double"; 3652 lastDoubleClick = {time: now, pos: start}; 3653 } else { 3654 type = "single"; 3655 lastClick = {time: now, pos: start}; 3656 } 3657 3658 var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained; 3659 if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && 3660 type == "single" && (contained = sel.contains(start)) > -1 && 3661 (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) && 3662 (cmp(contained.to(), start) > 0 || start.xRel < 0)) 3663 leftButtonStartDrag(cm, e, start, modifier); 3664 else 3665 leftButtonSelect(cm, e, start, type, modifier); 3666 } 3667 3668 // Start a text drag. When it ends, see if any dragging actually 3669 // happen, and treat as a click if it didn't. 3670 function leftButtonStartDrag(cm, e, start, modifier) { 3671 var display = cm.display, startTime = +new Date; 3672 var dragEnd = operation(cm, function(e2) { 3673 if (webkit) display.scroller.draggable = false; 3674 cm.state.draggingText = false; 3675 off(document, "mouseup", dragEnd); 3676 off(display.scroller, "drop", dragEnd); 3677 if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { 3678 e_preventDefault(e2); 3679 if (!modifier && +new Date - 200 < startTime) 3680 extendSelection(cm.doc, start); 3681 // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) 3682 if (webkit || ie && ie_version == 9) 3683 setTimeout(function() {document.body.focus(); display.input.focus();}, 20); 3684 else 3685 display.input.focus(); 3686 } 3687 }); 3688 // Let the drag handler handle this. 3689 if (webkit) display.scroller.draggable = true; 3690 cm.state.draggingText = dragEnd; 3691 dragEnd.copy = mac ? e.altKey : e.ctrlKey 3692 // IE's approach to draggable 3693 if (display.scroller.dragDrop) display.scroller.dragDrop(); 3694 on(document, "mouseup", dragEnd); 3695 on(display.scroller, "drop", dragEnd); 3696 } 3697 3698 // Normal selection, as opposed to text dragging. 3699 function leftButtonSelect(cm, e, start, type, addNew) { 3700 var display = cm.display, doc = cm.doc; 3701 e_preventDefault(e); 3702 3703 var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; 3704 if (addNew && !e.shiftKey) { 3705 ourIndex = doc.sel.contains(start); 3706 if (ourIndex > -1) 3707 ourRange = ranges[ourIndex]; 3708 else 3709 ourRange = new Range(start, start); 3710 } else { 3711 ourRange = doc.sel.primary(); 3712 ourIndex = doc.sel.primIndex; 3713 } 3714 3715 if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) { 3716 type = "rect"; 3717 if (!addNew) ourRange = new Range(start, start); 3718 start = posFromMouse(cm, e, true, true); 3719 ourIndex = -1; 3720 } else if (type == "double") { 3721 var word = cm.findWordAt(start); 3722 if (cm.display.shift || doc.extend)
3723 ourRange = extendRange(doc, ourRange, word.anchor, word.head); 3724 else 3725 ourRange = word; 3726 } else if (type == "triple") { 3727 var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))); 3728 if (cm.display.shift || doc.extend) 3729 ourRange = extendRange(doc, ourRange, line.anchor, line.head); 3730 else 3731 ourRange = line; 3732 } else { 3733 ourRange = extendRange(doc, ourRange, start); 3734 } 3735 3736 if (!addNew) { 3737 ourIndex = 0; 3738 setSelection(doc, new Selection([ourRange], 0), sel_mouse); 3739 startSel = doc.sel; 3740 } else if (ourIndex == -1) { 3741 ourIndex = ranges.length; 3742 setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), 3743 {scroll: false, origin: "*mouse"}); 3744 } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) { 3745 setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), 3746 {scroll: false, origin: "*mouse"}); 3747 startSel = doc.sel; 3748 } else { 3749 replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); 3750 } 3751 3752 var lastPos = start; 3753 function extendTo(pos) { 3754 if (cmp(lastPos, pos) == 0) return; 3755 lastPos = pos; 3756 3757 if (type == "rect") { 3758 var ranges = [], tabSize = cm.options.tabSize; 3759 var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); 3760 var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); 3761 var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); 3762 for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); 3763 line <= end; line++) { 3764 var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); 3765 if (left == right) 3766 ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); 3767 else if (text.length > leftPos) 3768 ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); 3769 } 3770 if (!ranges.length) ranges.push(new Range(start, start));
3771 setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), 3772 {origin: "*mouse", scroll: false}); 3773 cm.scrollIntoView(pos); 3774 } else { 3775 var oldRange = ourRange; 3776 var anchor = oldRange.anchor, head = pos; 3777 if (type != "single") { 3778 if (type == "double") 3779 var range = cm.findWordAt(pos); 3780 else 3781 var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))); 3782 if (cmp(range.anchor, anchor) > 0) { 3783 head = range.head; 3784 anchor = minPos(oldRange.from(), range.anchor); 3785 } else { 3786 head = range.anchor; 3787 anchor = maxPos(oldRange.to(), range.head); 3788 } 3789 } 3790 var ranges = startSel.ranges.slice(0); 3791 ranges[ourIndex] = new Range(clipPos(doc, anchor), head); 3792 setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse); 3793 } 3794 } 3795 3796 var editorSize = display.wrapper.getBoundingClientRect(); 3797 // Used to ensure timeout re-tries don't fire when another extend 3798 // happened in the meantime (clearTimeout isn't reliable -- at 3799 // least on Chrome, the timeouts still happen even when cleared, 3800 // if the clear happens after their scheduled firing time). 3801 var counter = 0; 3802 3803 function extend(e) { 3804 var curCount = ++counter; 3805 var cur = posFromMouse(cm, e, true, type == "rect"); 3806 if (!cur) return; 3807 if (cmp(cur, lastPos) != 0) { 3808 cm.curOp.focus = activeElt(); 3809 extendTo(cur); 3810 var visible = visibleLines(display, doc); 3811 if (cur.line >= visible.to || cur.line < visible.from) 3812 setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); 3813 } else { 3814 var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; 3815 if (outside) setTimeout(operation(cm, function() { 3816 if (counter != curCount) return; 3817 display.scroller.scrollTop += outside; 3818 extend(e); 3819 }), 50); 3820 } 3821 } 3822 3823 function done(e) { 3824 cm.state.selectingText = false; 3825 counter = Infinity; 3826 e_preventDefault(e); 3827 display.input.focus(); 3828 off(document, "mousemove", move); 3829 off(document, "mouseup", up); 3830 doc.history.lastSelOrigin = null; 3831 } 3832 3833 var move = operation(cm, function(e) { 3834 if (!e_button(e)) done(e); 3835 else extend(e); 3836 }); 3837 var up = operation(cm, done); 3838 cm.state.selectingText = up; 3839 on(document, "mousemove", move); 3840 on(document, "mouseup", up); 3841 } 3842 3843 // Determines whether an event happened in the gutter, and fires the 3844 // handlers for the corresponding event. 3845 function gutterEvent(cm, e, type, prevent) { 3846 try { var mX = e.clientX, mY = e.clientY; } 3847 catch(e) { return false; } 3848 if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false; 3849 if (prevent) e_preventDefault(e); 3850 3851 var display = cm.display; 3852 var lineBox = display.lineDiv.getBoundingClientRect(); 3853 3854 if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e); 3855 mY -= lineBox.top - display.viewOffset; 3856 3857 for (var i = 0; i < cm.options.gutters.length; ++i) { 3858 var g = display.gutters.childNodes[i]; 3859 if (g && g.getBoundingClientRect().right >= mX) { 3860 var line = lineAtHeight(cm.doc, mY); 3861 var gutter = cm.options.gutters[i]; 3862 signal(cm, type, cm, line, gutter, e); 3863 return e_defaultPrevented(e); 3864 } 3865 } 3866 } 3867 3868 function clickInGutter(cm, e) { 3869 return gutterEvent(cm, e, "gutterClick", true); 3870 } 3871 3872 // Kludge to work around strange IE behavior where it'll sometimes 3873 // re-fire a series of drag-related events right after the drop (#1551) 3874 var lastDrop = 0; 3875 3876 function onDrop(e) { 3877 var cm = this; 3878 clearDragCursor(cm); 3879 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) 3880 return; 3881 e_preventDefault(e); 3882 if (ie) lastDrop = +new Date; 3883 var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; 3884 if (!pos || cm.isReadOnly()) return; 3885 // Might be a file drop, in which case we simply extract the text 3886 // and insert it. 3887 if (files && files.length && window.FileReader && window.File) { 3888 var n = files.length, text = Array(n), read = 0; 3889 var loadFile = function(file, i) { 3890 if (cm.options.allowDropFileTypes && 3891 indexOf(cm.options.allowDropFileTypes, file.type) == -1) 3892 return; 3893 3894 var reader = new FileReader; 3895 reader.onload = operation(cm, function() { 3896 var content = reader.result; 3897 if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = ""; 3898 text[i] = content; 3899 if (++read == n) { 3900 pos = clipPos(cm.doc, pos); 3901 var change = {from: pos, to: pos, 3902 text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), 3903 origin: "paste"}; 3904 makeChange(cm.doc, change); 3905 setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); 3906 } 3907 }); 3908 reader.readAsText(file); 3909 }; 3910 for (var i = 0; i < n; ++i) loadFile(files[i], i); 3911 } else { // Normal drop 3912 // Don't do a replace if the drop happened inside of the selected text. 3913 if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { 3914 cm.state.draggingText(e); 3915 // Ensure the editor is re-focused 3916 setTimeout(function() {cm.display.input.focus();}, 20); 3917 return; 3918 }
3919 try { 3920 var text = e.dataTransfer.getData("Text"); 3921 if (text) { 3922 if (cm.state.draggingText && !cm.state.draggingText.copy) 3923 var selected = cm.listSelections(); 3924 setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); 3925 if (selected) for (var i = 0; i < selected.length; ++i) 3926 replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag"); 3927 cm.replaceSelection(text, "around", "paste"); 3928 cm.display.input.focus(); 3929 } 3930 } 3931 catch(e){} 3932 } 3933 } 3934 3935 function onDragStart(cm, e) { 3936 if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } 3937 if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; 3938 3939 e.dataTransfer.setData("Text", cm.getSelection()); 3940 e.dataTransfer.effectAllowed = "copyMove" 3941 3942 // Use dummy image instead of default browsers image. 3943 // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. 3944 if (e.dataTransfer.setDragImage && !safari) { 3945 var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); 3946 img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; 3947 if (presto) { 3948 img.width = img.height = 1; 3949 cm.display.wrapper.appendChild(img); 3950 // Force a relayout, or Opera won't use our image for some obscure reason 3951 img._top = img.offsetTop; 3952 } 3953 e.dataTransfer.setDragImage(img, 0, 0); 3954 if (presto) img.parentNode.removeChild(img); 3955 } 3956 } 3957 3958 function onDragOver(cm, e) { 3959 var pos = posFromMouse(cm, e); 3960 if (!pos) return; 3961 var frag = document.createDocumentFragment(); 3962 drawSelectionCursor(cm, pos, frag); 3963 if (!cm.display.dragCursor) { 3964 cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); 3965 cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); 3966 } 3967 removeChildrenAndAdd(cm.display.dragCursor, frag); 3968 } 3969 3970 function clearDragCursor(cm) { 3971 if (cm.display.dragCursor) { 3972 cm.display.lineSpace.removeChild(cm.display.dragCursor); 3973 cm.display.dragCursor = null; 3974 } 3975 } 3976 3977 // SCROLL EVENTS 3978 3979 // Sync the scrollable area and scrollbars, ensure the viewport 3980 // covers the visible area. 3981 function setScrollTop(cm, val) { 3982 if (Math.abs(cm.doc.scrollTop - val) < 2) return; 3983 cm.doc.scrollTop = val; 3984 if (!gecko) updateDisplaySimple(cm, {top: val}); 3985 if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; 3986 cm.display.scrollbars.setScrollTop(val); 3987 if (gecko) updateDisplaySimple(cm); 3988 startWorker(cm, 100); 3989 } 3990 // Sync scroller and scrollbar, ensure the gutter elements are 3991 // aligned. 3992 function setScrollLeft(cm, val, isScroller) { 3993 if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; 3994 val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); 3995 cm.doc.scrollLeft = val; 3996 alignHorizontally(cm); 3997 if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; 3998 cm.display.scrollbars.setScrollLeft(val); 3999 } 4000 4001 // Since the delta values reported on mouse wheel events are 4002 // unstandardized between browsers and even browser versions, and 4003 // generally horribly unpredictable, this code starts by measuring 4004 // the scroll effect that the first few mouse wheel events have, 4005 // and, from that, detects the way it can convert deltas to pixel 4006 // offsets afterwards. 4007 // 4008 // The reason we want to know the amount a wheel event will scroll 4009 // is that it gives us a chance to update the display before the 4010 // actual scrolling happens, reducing flickering. 4011 4012 var wheelSamples = 0, wheelPixelsPerUnit = null; 4013 // Fill in a browser-detected starting value on browsers where we 4014 // know one. These don't have to be accurate -- the result of them 4015 // being wrong would just be a slight flicker on the first wheel 4016 // scroll (if it is large enough). 4017 if (ie) wheelPixelsPerUnit = -.53; 4018 else if (gecko) wheelPixelsPerUnit = 15; 4019 else if (chrome) wheelPixelsPerUnit = -.7; 4020 else if (safari) wheelPixelsPerUnit = -1/3; 4021 4022 var wheelEventDelta = function(e) { 4023 var dx = e.wheelDeltaX, dy = e.wheelDeltaY; 4024 if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; 4025 if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; 4026 else if (dy == null) dy = e.wheelDelta; 4027 return {x: dx, y: dy}; 4028 }; 4029 CodeMirror.wheelEventPixels = function(e) { 4030 var delta = wheelEventDelta(e); 4031 delta.x *= wheelPixelsPerUnit; 4032 delta.y *= wheelPixelsPerUnit; 4033 return delta; 4034 }; 4035 4036 function onScrollWheel(cm, e) { 4037 var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; 4038 4039 var display = cm.display, scroll = display.scroller; 4040 // Quit if there's nothing to scroll here 4041 var canScrollX = scroll.scrollWidth > scroll.clientWidth; 4042 var canScrollY = scroll.scrollHeight > scroll.clientHeight;
4043 if (!(dx && canScrollX || dy && canScrollY)) return; 4044 4045 // Webkit browsers on OS X abort momentum scrolls when the target 4046 // of the scroll event is removed from the scrollable element. 4047 // This hack (see related code in patchDisplay) makes sure the 4048 // element is kept around. 4049 if (dy && mac && webkit) { 4050 outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { 4051 for (var i = 0; i < view.length; i++) { 4052 if (view[i].node == cur) { 4053 cm.display.currentWheelTarget = cur; 4054 break outer; 4055 } 4056 } 4057 } 4058 } 4059 4060 // On some browsers, horizontal scrolling will cause redraws to 4061 // happen before the gutter has been realigned, causing it to 4062 // wriggle around in a most unseemly way. When we have an 4063 // estimated pixels/delta value, we just handle horizontal 4064 // scrolling entirely here. It'll be slightly off from native, but 4065 // better than glitching out. 4066 if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { 4067 if (dy && canScrollY) 4068 setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); 4069 setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); 4070 // Only prevent default scrolling if vertical scrolling is 4071 // actually possible. Otherwise, it causes vertical scroll 4072 // jitter on OSX trackpads when deltaX is small and deltaY 4073 // is large (issue #3579) 4074 if (!dy || (dy && canScrollY)) 4075 e_preventDefault(e); 4076 display.wheelStartX = null; // Abort measurement, if in progress 4077 return; 4078 } 4079 4080 // 'Project' the visible viewport to cover the area that is being 4081 // scrolled into view (if we know enough to estimate it). 4082 if (dy && wheelPixelsPerUnit != null) { 4083 var pixels = dy * wheelPixelsPerUnit; 4084 var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; 4085 if (pixels < 0) top = Math.max(0, top + pixels - 50); 4086 else bot = Math.min(cm.doc.height, bot + pixels + 50); 4087 updateDisplaySimple(cm, {top: top, bottom: bot}); 4088 } 4089 4090 if (wheelSamples < 20) { 4091 if (display.wheelStartX == null) { 4092 display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; 4093 display.wheelDX = dx; display.wheelDY = dy; 4094 setTimeout(function() { 4095 if (display.wheelStartX == null) return; 4096 var movedX = scroll.scrollLeft - display.wheelStartX; 4097 var movedY = scroll.scrollTop - display.wheelStartY; 4098 var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || 4099 (movedX && display.wheelDX && movedX / display.wheelDX); 4100 display.wheelStartX = display.wheelStartY = null; 4101 if (!sample) return; 4102 wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); 4103 ++wheelSamples; 4104 }, 200); 4105 } else { 4106 display.wheelDX += dx; display.wheelDY += dy; 4107 } 4108 } 4109 } 4110 4111 // KEY EVENTS 4112 4113 // Run a handler that was bound to a key. 4114 function doHandleBinding(cm, bound, dropShift) { 4115 if (typeof bound == "string") { 4116 bound = commands[bound]; 4117 if (!bound) return false; 4118 } 4119 // Ensure previous input has been read, so that the handler sees a 4120 // consistent view of the document 4121 cm.display.input.ensurePolled(); 4122 var prevShift = cm.display.shift, done = false; 4123 try { 4124 if (cm.isReadOnly()) cm.state.suppressEdits = true; 4125 if (dropShift) cm.display.shift = false; 4126 done = bound(cm) != Pass; 4127 } finally { 4128 cm.display.shift = prevShift; 4129 cm.state.suppressEdits = false; 4130 } 4131 return done; 4132 } 4133 4134 function lookupKeyForEditor(cm, name, handle) { 4135 for (var i = 0; i < cm.state.keyMaps.length; i++) { 4136 var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); 4137 if (result) return result; 4138 } 4139 return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) 4140 || lookupKey(name, cm.options.keyMap, handle, cm); 4141 } 4142 4143 var stopSeq = new Delayed; 4144 function dispatchKey(cm, name, e, handle) { 4145 var seq = cm.state.keySeq; 4146 if (seq) { 4147 if (isModifierKey(name)) return "handled"; 4148 stopSeq.set(50, function() { 4149 if (cm.state.keySeq == seq) { 4150 cm.state.keySeq = null; 4151 cm.display.input.reset(); 4152 } 4153 }); 4154 name = seq + " " + name; 4155 } 4156 var result = lookupKeyForEditor(cm, name, handle); 4157 4158 if (result == "multi") 4159 cm.state.keySeq = name; 4160 if (result == "handled") 4161 signalLater(cm, "keyHandled", cm, name, e); 4162 4163 if (result == "handled" || result == "multi") { 4164 e_preventDefault(e); 4165 restartBlink(cm); 4166 } 4167 4168 if (seq && !result && /\'$/.test(name)) { 4169 e_preventDefault(e); 4170 return true; 4171 } 4172 return !!result; 4173 } 4174 4175 // Handle a key from the keydown event. 4176 function handleKeyBinding(cm, e) { 4177 var name = keyName(e, true); 4178 if (!name) return false;
4179 4180 if (e.shiftKey && !cm.state.keySeq) { 4181 // First try to resolve full name (including 'Shift-'). Failing 4182 // that, see if there is a cursor-motion command (starting with 4183 // 'go') bound to the keyname without 'Shift-'. 4184 return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);}) 4185 || dispatchKey(cm, name, e, function(b) { 4186 if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) 4187 return doHandleBinding(cm, b); 4188 }); 4189 } else { 4190 return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); }); 4191 } 4192 } 4193 4194 // Handle a key from the keypress event 4195 function handleCharBinding(cm, e, ch) { 4196 return dispatchKey(cm, "'" + ch + "'", e, 4197 function(b) { return doHandleBinding(cm, b, true); }); 4198 } 4199 4200 var lastStoppedKey = null; 4201 function onKeyDown(e) { 4202 var cm = this; 4203 cm.curOp.focus = activeElt(); 4204 if (signalDOMEvent(cm, e)) return; 4205 // IE does strange things with escape. 4206 if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false; 4207 var code = e.keyCode; 4208 cm.display.shift = code == 16 || e.shiftKey; 4209 var handled = handleKeyBinding(cm, e); 4210 if (presto) { 4211 lastStoppedKey = handled ? code : null; 4212 // Opera has no cut event... we try to at least catch the key combo 4213 if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) 4214 cm.replaceSelection("", null, "cut"); 4215 } 4216 4217 // Turn mouse into crosshair when Alt is held on Mac. 4218 if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) 4219 showCrossHair(cm); 4220 } 4221 4222 function showCrossHair(cm) { 4223 var lineDiv = cm.display.lineDiv; 4224 addClass(lineDiv, "CodeMirror-crosshair"); 4225 4226 function up(e) { 4227 if (e.keyCode == 18 || !e.altKey) { 4228 rmClass(lineDiv, "CodeMirror-crosshair"); 4229 off(document, "keyup", up); 4230 off(document, "mouseover", up); 4231 } 4232 } 4233 on(document, "keyup", up); 4234 on(document, "mouseover", up); 4235 } 4236 4237 function onKeyUp(e) { 4238 if (e.keyCode == 16) this.doc.sel.shift = false; 4239 signalDOMEvent(this, e); 4240 } 4241 4242 function onKeyPress(e) { 4243 var cm = this; 4244 if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return; 4245 var keyCode = e.keyCode, charCode = e.charCode; 4246 if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} 4247 if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return; 4248 var ch = String.fromCharCode(charCode == null ? keyCode : charCode); 4249 if (handleCharBinding(cm, e, ch)) return; 4250 cm.display.input.onKeyPress(e); 4251 } 4252 4253 // FOCUS/BLUR EVENTS 4254 4255 function delayBlurEvent(cm) { 4256 cm.state.delayingBlurEvent = true; 4257 setTimeout(function() { 4258 if (cm.state.delayingBlurEvent) { 4259 cm.state.delayingBlurEvent = false; 4260 onBlur(cm); 4261 } 4262 }, 100); 4263 } 4264 4265 function onFocus(cm, e) { 4266 if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false; 4267 4268 if (cm.options.readOnly == "nocursor") return; 4269 if (!cm.state.focused) { 4270 signal(cm, "focus", cm, e); 4271 cm.state.focused = true; 4272 addClass(cm.display.wrapper, "CodeMirror-focused"); 4273 // This test prevents this from firing when a context 4274 // menu is closed (since the input reset would kill the 4275 // select-all detection hack) 4276 if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { 4277 cm.display.input.reset(); 4278 if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730 4279 } 4280 cm.display.input.receivedFocus(); 4281 } 4282 restartBlink(cm); 4283 } 4284 function onBlur(cm, e) { 4285 if (cm.state.delayingBlurEvent) return; 4286 4287 if (cm.state.focused) { 4288 signal(cm, "blur", cm, e); 4289 cm.state.focused = false; 4290 rmClass(cm.display.wrapper, "CodeMirror-focused"); 4291 } 4292 clearInterval(cm.display.blinker); 4293 setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150); 4294 } 4295 4296 // CONTEXT MENU HANDLING 4297 4298 // To make the context menu work, we need to briefly unhide the 4299 // textarea (making it as unobtrusive as possible) to let the 4300 // right-click take effect on it. 4301 function onContextMenu(cm, e) { 4302 if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return; 4303 if (signalDOMEvent(cm, e, "contextmenu")) return; 4304 cm.display.input.onContextMenu(e); 4305 } 4306 4307 function contextMenuInGutter(cm, e) { 4308 if (!hasHandler(cm, "gutterContextMenu")) return false;
4309 return gutterEvent(cm, e, "gutterContextMenu", false); 4310 } 4311 4312 // UPDATING 4313 4314 // Compute the position of the end of a change (its 'to' property 4315 // refers to the pre-change end). 4316 var changeEnd = CodeMirror.changeEnd = function(change) { 4317 if (!change.text) return change.to; 4318 return Pos(change.from.line + change.text.length - 1, 4319 lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); 4320 }; 4321 4322 // Adjust a position to refer to the post-change position of the 4323 // same text, or the end of the change if the change covers it. 4324 function adjustForChange(pos, change) { 4325 if (cmp(pos, change.from) < 0) return pos; 4326 if (cmp(pos, change.to) <= 0) return changeEnd(change); 4327 4328 var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; 4329 if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch; 4330 return Pos(line, ch); 4331 } 4332 4333 function computeSelAfterChange(doc, change) { 4334 var out = []; 4335 for (var i = 0; i < doc.sel.ranges.length; i++) { 4336 var range = doc.sel.ranges[i]; 4337 out.push(new Range(adjustForChange(range.anchor, change), 4338 adjustForChange(range.head, change))); 4339 } 4340 return normalizeSelection(out, doc.sel.primIndex); 4341 } 4342 4343 function offsetPos(pos, old, nw) { 4344 if (pos.line == old.line) 4345 return Pos(nw.line, pos.ch - old.ch + nw.ch); 4346 else 4347 return Pos(nw.line + (pos.line - old.line), pos.ch); 4348 } 4349 4350 // Used by replaceSelections to allow moving the selection to the 4351 // start or around the replaced test. Hint may be "start" or "around". 4352 function computeReplacedSel(doc, changes, hint) { 4353 var out = []; 4354 var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; 4355 for (var i = 0; i < changes.length; i++) { 4356 var change = changes[i]; 4357 var from = offsetPos(change.from, oldPrev, newPrev); 4358 var to = offsetPos(changeEnd(change), oldPrev, newPrev); 4359 oldPrev = change.to; 4360 newPrev = to; 4361 if (hint == "around") { 4362 var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; 4363 out[i] = new Range(inv ? to : from, inv ? from : to); 4364 } else { 4365 out[i] = new Range(from, from); 4366 } 4367 } 4368 return new Selection(out, doc.sel.primIndex); 4369 } 4370 4371 // Allow "beforeChange" event handlers to influence a change 4372 function filterChange(doc, change, update) { 4373 var obj = { 4374 canceled: false, 4375 from: change.from, 4376 to: change.to, 4377 text: change.text, 4378 origin: change.origin, 4379 cancel: function() { this.canceled = true; } 4380 }; 4381 if (update) obj.update = function(from, to, text, origin) { 4382 if (from) this.from = clipPos(doc, from); 4383 if (to) this.to = clipPos(doc, to); 4384 if (text) this.text = text; 4385 if (origin !== undefined) this.origin = origin; 4386 }; 4387 signal(doc, "beforeChange", doc, obj); 4388 if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); 4389 4390 if (obj.canceled) return null; 4391 return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; 4392 } 4393 4394 // Apply a change to a document, and add it to the document's 4395 // history, and propagating it to all linked documents. 4396 function makeChange(doc, change, ignoreReadOnly) { 4397 if (doc.cm) { 4398 if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); 4399 if (doc.cm.state.suppressEdits) return; 4400 } 4401 4402 if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { 4403 change = filterChange(doc, change, true); 4404 if (!change) return; 4405 } 4406 4407 // Possibly split or suppress the update based on the presence 4408 // of read-only spans in its range. 4409 var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); 4410 if (split) { 4411 for (var i = split.length - 1; i >= 0; --i) 4412 makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}); 4413 } else { 4414 makeChangeInner(doc, change); 4415 } 4416 } 4417 4418 function makeChangeInner(doc, change) { 4419 if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return; 4420 var selAfter = computeSelAfterChange(doc, change); 4421 addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); 4422 4423 makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); 4424 var rebased = []; 4425 4426 linkedDocs(doc, function(doc, sharedHist) { 4427 if (!sharedHist && indexOf(rebased, doc.history) == -1) { 4428 rebaseHist(doc.history, change); 4429 rebased.push(doc.history); 4430 } 4431 makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); 4432 }); 4433 } 4434 4435 // Revert a change stored in a document's history. 4436 function makeChangeFromHistory(doc, type, allowSelectionOnly) { 4437 if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) return; 4438 4439 var hist = doc.history, event, selAfter = doc.sel; 4440 var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; 4441 4442 // Verify that there is a useable event (so that ctrl-z won't 4443 // needlessly clear selection events) 4444 for (var i = 0; i < source.length; i++) { 4445 event = source[i]; 4446 if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) 4447 break; 4448 } 4449 if (i == source.length) return; 4450 hist.lastOrigin = hist.lastSelOrigin = null; 4451 4452 for (;;) { 4453 event = source.pop(); 4454 if (event.ranges) { 4455 pushSelectionToHistory(event, dest); 4456 if (allowSelectionOnly && !event.equals(doc.sel)) { 4457 setSelection(doc, event, {clearRedo: false}); 4458 return; 4459 } 4460 selAfter = event; 4461 } 4462 else break; 4463 } 4464 4465 // Build up a reverse change object to add to the opposite history 4466 // stack (redo when undoing, and vice versa). 4467 var antiChanges = []; 4468 pushSelectionToHistory(selAfter, dest); 4469 dest.push({changes: antiChanges, generation: hist.generation}); 4470 hist.generation = event.generation || ++hist.maxGeneration; 4471 4472 var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); 4473 4474 for (var i = event.changes.length - 1; i >= 0; --i) { 4475 var change = event.changes[i]; 4476 change.origin = type; 4477 if (filter && !filterChange(doc, change, false)) { 4478 source.length = 0; 4479 return; 4480 } 4481 4482 antiChanges.push(historyChangeFromChange(doc, change)); 4483 4484 var after = i ? computeSelAfterChange(doc, change) : lst(source); 4485 makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); 4486 if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); 4487 var rebased = []; 4488 4489 // Propagate to the linked documents 4490 linkedDocs(doc, function(doc, sharedHist) { 4491 if (!sharedHist && indexOf(rebased, doc.history) == -1) { 4492 rebaseHist(doc.history, change); 4493 rebased.push(doc.history); 4494 } 4495 makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); 4496 }); 4497 } 4498 } 4499 4500 // Sub-views need their line numbers shifted when text is added 4501 // above or below them in the parent document. 4502 function shiftDoc(doc, distance) { 4503 if (distance == 0) return; 4504 doc.first += distance; 4505 doc.sel = new Selection(map(doc.sel.ranges, function(range) { 4506 return new Range(Pos(range.anchor.line + distance, range.anchor.ch), 4507 Pos(range.head.line + distance, range.head.ch)); 4508 }), doc.sel.primIndex); 4509 if (doc.cm) { 4510 regChange(doc.cm, doc.first, doc.first - distance, distance); 4511 for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) 4512 regLineChange(doc.cm, l, "gutter"); 4513 } 4514 } 4515 4516 // More lower-level change function, handling only a single document 4517 // (not linked ones). 4518 function makeChangeSingleDoc(doc, change, selAfter, spans) { 4519 if (doc.cm && !doc.cm.curOp) 4520 return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); 4521 4522 if (change.to.line < doc.first) { 4523 shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); 4524 return; 4525 } 4526 if (change.from.line >
4526 doc.lastLine()) return; 4527 4528 // Clip the change to the size of this doc 4529 if (change.from.line < doc.first) { 4530 var shift = change.text.length - 1 - (doc.first - change.from.line); 4531 shiftDoc(doc, shift); 4532 change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), 4533 text: [lst(change.text)], origin: change.origin}; 4534 } 4535 var last = doc.lastLine(); 4536 if (change.to.line > last) { 4537 change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), 4538 text: [change.text[0]], origin: change.origin}; 4539 } 4540 4541 change.removed = getBetween(doc, change.from, change.to); 4542 4543 if (!selAfter) selAfter = computeSelAfterChange(doc, change); 4544 if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans); 4545 else updateDoc(doc, change, spans); 4546 setSelectionNoUndo(doc, selAfter, sel_dontScroll); 4547 } 4548 4549 // Handle the interaction of a change to a document with the editor 4550 // that this document is part of. 4551 function makeChangeSingleDocInEditor(cm, change, spans) { 4552 var doc = cm.doc, display = cm.display, from = change.from, to = change.to; 4553 4554 var recomputeMaxLength = false, checkWidthStart = from.line; 4555 if (!cm.options.lineWrapping) { 4556 checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); 4557 doc.iter(checkWidthStart, to.line + 1, function(line) { 4558 if (line == display.maxLine) { 4559 recomputeMaxLength = true; 4560 return true; 4561 } 4562 }); 4563 } 4564 4565 if (doc.sel.contains(change.from, change.to) > -1) 4566 signalCursorActivity(cm); 4567 4568 updateDoc(doc, change, spans, estimateHeight(cm)); 4569 4570 if (!cm.options.lineWrapping) { 4571 doc.iter(checkWidthStart, from.line + change.text.length, function(line) { 4572 var len = lineLength(line); 4573 if (len > display.maxLineLength) { 4574 display.maxLine = line; 4575 display.maxLineLength = len; 4576 display.maxLineChanged = true; 4577 recomputeMaxLength = false; 4578 } 4579 }); 4580 if (recomputeMaxLength) cm.curOp.updateMaxLine = true; 4581 } 4582 4583 // Adjust frontier, schedule worker 4584 doc.frontier = Math.min(doc.frontier, from.line); 4585 startWorker(cm, 400); 4586 4587 var lendiff = change.text.length - (to.line - from.line) - 1; 4588 // Remember that these lines changed, for updating the display 4589 if (change.full) 4590 regChange(cm); 4591 else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) 4592 regLineChange(cm, from.line, "text"); 4593 else 4594 regChange(cm, from.line, to.line + 1, lendiff); 4595 4596 var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); 4597 if (changeHandler || changesHandler) { 4598 var obj = { 4599 from: from, to: to, 4600 text: change.text, 4601 removed: change.removed, 4602 origin: change.origin 4603 }; 4604 if (changeHandler) signalLater(cm, "change", cm, obj); 4605 if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); 4606 } 4607 cm.display.selForContextMenu = null; 4608 } 4609 4610 function replaceRange(doc, code, from, to, origin) { 4611 if (!to) to = from; 4612 if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } 4613 if (typeof code == "string") code = doc.splitLines(code); 4614 makeChange(doc, {from: from, to: to, text: code, origin: origin}); 4615 } 4616 4617 // SCROLLING THINGS INTO VIEW 4618 4619 // If an editor sits on the top or bottom of the window, partially 4620 // scrolled out of view, this ensures that the cursor is visible. 4621 function maybeScrollWindow(cm, coords) { 4622 if (signalDOMEvent(cm, "scrollCursorIntoView")) return; 4623 4624 var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; 4625 if (coords.top + box.top < 0) doScroll = true; 4626 else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; 4627 if (doScroll != null && !phantom) { 4628 var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " + 4629 (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " + 4630 (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " + 4631 coords.left + "px; width: 2px;"); 4632 cm.display.lineSpace.appendChild(scrollNode); 4633 scrollNode.scrollIntoView(doScroll); 4634 cm.display.lineSpace.removeChild(scrollNode); 4635 } 4636 } 4637 4638 // Scroll a given position into view (immediately), verifying that 4639 // it actually became visible (as line heights are accurately 4640 // measured, the position of something may 'drift' during drawing). 4641 function scrollPosIntoView(cm, pos, end, margin) { 4642 if (margin == null) margin = 0; 4643 for (var limit = 0; limit < 5; limit++) { 4644 var changed = false, coords = cursorCoords(cm, pos); 4645 var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); 4646 var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), 4647 Math.min(coords.top, endCoords.top) - margin, 4648 Math.max(coords.left, endCoords.left), 4649 Math.max(coords.bottom, endCoords.bottom) + margin); 4650 var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; 4651 if (scrollPos.scrollTop != null) { 4652 setScrollTop(cm, scrollPos.scrollTop); 4653 if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; 4654 } 4655 if (scrollPos.scrollLeft != null) { 4656 setScrollLeft(cm, scrollPos.scrollLeft); 4657 if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; 4658 } 4659 if (!changed) break; 4660 } 4661 return coords; 4662 } 4663 4664 // Scroll a given set of coordinates into view (immediately). 4665 function scrollIntoView(cm, x1, y1, x2, y2) { 4666 var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); 4667 if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); 4668 if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); 4669 } 4670 4671 // Calculate a new scroll position needed to scroll the given 4672 // rectangle into view. Returns an object with scrollTop and 4673 // scrollLeft properties. When these are undefined, the
4674 // vertical/horizontal position does not need to be adjusted. 4675 function calculateScrollPos(cm, x1, y1, x2, y2) { 4676 var display = cm.display, snapMargin = textHeight(cm.display); 4677 if (y1 < 0) y1 = 0; 4678 var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; 4679 var screen = displayHeight(cm), result = {}; 4680 if (y2 - y1 > screen) y2 = y1 + screen; 4681 var docBottom = cm.doc.height + paddingVert(display); 4682 var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; 4683 if (y1 < screentop) { 4684 result.scrollTop = atTop ? 0 : y1; 4685 } else if (y2 > screentop + screen) { 4686 var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); 4687 if (newTop != screentop) result.scrollTop = newTop; 4688 } 4689 4690 var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; 4691 var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); 4692 var tooWide = x2 - x1 > screenw; 4693 if (tooWide) x2 = x1 + screenw; 4694 if (x1 < 10) 4695 result.scrollLeft = 0; 4696 else if (x1 < screenleft) 4697 result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)); 4698 else if (x2 > screenw + screenleft - 3) 4699 result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw; 4700 return result; 4701 } 4702 4703 // Store a relative adjustment to the scroll position in the current 4704 // operation (to be applied when the operation finishes). 4705 function addToScrollPos(cm, left, top) { 4706 if (left != null || top != null) resolveScrollToPos(cm); 4707 if (left != null) 4708 cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left; 4709 if (top != null) 4710 cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; 4711 } 4712 4713 // Make sure that at the end of the operation the current cursor is 4714 // shown. 4715 function ensureCursorVisible(cm) { 4716 resolveScrollToPos(cm); 4717 var cur = cm.getCursor(), from = cur, to = cur; 4718 if (!cm.options.lineWrapping) { 4719 from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; 4720 to = Pos(cur.line, cur.ch + 1); 4721 } 4722 cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}; 4723 } 4724 4725 // When an operation has its scrollToPos property set, and another 4726 // scroll action is applied before the end of the operation, this 4727 // 'simulates' scrolling that position into view in a cheap way, so 4728 // that the effect of intermediate scroll commands is not ignored. 4729 function resolveScrollToPos(cm) { 4730 var range = cm.curOp.scrollToPos; 4731 if (range) { 4732 cm.curOp.scrollToPos = null; 4733 var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); 4734 var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), 4735 Math.min(from.top, to.top) - range.margin, 4736 Math.max(from.right, to.right), 4737 Math.max(from.bottom, to.bottom) + range.margin); 4738 cm.scrollTo(sPos.scrollLeft, sPos.scrollTop); 4739 } 4740 } 4741 4742 // API UTILITIES 4743 4744 // Indent the given line. The how parameter can be "smart", 4745 // "add"/null, "subtract", or "prev". When aggressive is false 4746 // (typically set to true for forced single-line indents), empty 4747 // lines are not indented, and places where the mode returns Pass 4748 // are left alone. 4749 function indentLine(cm, n, how, aggressive) { 4750 var doc = cm.doc, state; 4751 if (how == null) how = "add"; 4752 if (how == "smart") { 4753 // Fall back to "prev" when the mode doesn't have an indentation 4754 // method. 4755 if (!doc.mode.indent) how = "prev"; 4756 else state = getStateBefore(cm, n); 4757 } 4758 4759 var tabSize = cm.options.tabSize; 4760 var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); 4761 if (line.stateAfter) line.stateAfter = null; 4762 var curSpaceString = line.text.match(/^\s*/)[0], indentation; 4763 if (!aggressive && !/\S/.test(line.text)) { 4764 indentation = 0; 4765 how = "not"; 4766 } else if (how == "smart") { 4767 indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); 4768 if (indentation == Pass || indentation > 150) { 4769 if (!aggressive) return; 4770 how = "prev"; 4771 } 4772 } 4773 if (how == "prev") { 4774 if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); 4775 else indentation = 0; 4776 } else if (how == "add") { 4777 indentation = curSpace + cm.options.indentUnit; 4778 } else if (how == "subtract") { 4779 indentation = curSpace - cm.options.indentUnit; 4780 } else if (typeof how == "number") { 4781 indentation = curSpace + how; 4782 } 4783 indentation = Math.max(0, indentation); 4784
4785 var indentString = "", pos = 0; 4786 if (cm.options.indentWithTabs) 4787 for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} 4788 if (pos < indentation) indentString += spaceStr(indentation - pos); 4789 4790 if (indentString != curSpaceString) { 4791 replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); 4792 line.stateAfter = null; 4793 return true; 4794 } else { 4795 // Ensure that, if the cursor was in the whitespace at the start 4796 // of the line, it is moved to the end of that space. 4797 for (var i = 0; i < doc.sel.ranges.length; i++) { 4798 var range = doc.sel.ranges[i]; 4799 if (range.head.line == n && range.head.ch < curSpaceString.length) { 4800 var pos = Pos(n, curSpaceString.length); 4801 replaceOneSelection(doc, i, new Range(pos, pos)); 4802 break; 4803 } 4804 } 4805 } 4806 } 4807 4808 // Utility for applying a change to a line by handle or number, 4809 // returning the number and optionally registering the line as 4810 // changed. 4811 function changeLine(doc, handle, changeType, op) { 4812 var no = handle, line = handle; 4813 if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); 4814 else no = lineNo(handle); 4815 if (no == null) return null; 4816 if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType); 4817 return line; 4818 } 4819 4820 // Helper for deleting text near the selection(s), used to implement 4821 // backspace, delete, and similar functionality. 4822 function deleteNearSelection(cm, compute) { 4823 var ranges = cm.doc.sel.ranges, kill = []; 4824 // Build up a set of ranges to kill first, merging overlapping 4825 // ranges. 4826 for (var i = 0; i < ranges.length; i++) { 4827 var toKill = compute(ranges[i]); 4828 while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { 4829 var replaced = kill.pop(); 4830 if (cmp(replaced.from, toKill.from) < 0) { 4831 toKill.from = replaced.from; 4832 break; 4833 } 4834 } 4835 kill.push(toKill); 4836 } 4837 // Next, remove those actual ranges. 4838 runInOp(cm, function() { 4839 for (var i = kill.length - 1; i >= 0; i--) 4840 replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); 4841 ensureCursorVisible(cm); 4842 }); 4843 } 4844 4845 // Used for horizontal relative motion. Dir is -1 or 1 (left or 4846 // right), unit can be "char", "column" (like char, but doesn't 4847 // cross line boundaries), "word" (across next word), or "group" (to 4848 // the start of next group of word or non-word-non-whitespace 4849 // chars). The visually param controls whether, in right-to-left 4850 // text, direction 1 means to move towards the next index in the 4851 // string, or towards the character to the right of the current 4852 // position. The resulting position will have a hitSide=true 4853 // property if it reached the end of the document. 4854 function findPosH(doc, pos, dir, unit, visually) { 4855 var line = pos.line, ch = pos.ch, origDir = dir; 4856 var lineObj = getLine(doc, line); 4857 function findNextLine() { 4858 var l = line + dir; 4859 if (l < doc.first || l >= doc.first + doc.size) return false 4860 line = l; 4861 return lineObj = getLine(doc, l); 4862 } 4863 function moveOnce(boundToLine) { 4864 var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); 4865 if (next == null) { 4866 if (!boundToLine && findNextLine()) { 4867 if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); 4868 else ch = dir < 0 ? lineObj.text.length : 0; 4869 } else return false 4870 } else ch = next; 4871 return true; 4872 } 4873 4874 if (unit == "char") { 4875 moveOnce() 4876 } else if (unit == "column") { 4877 moveOnce(true) 4878 } else if (unit == "word" || unit == "group") { 4879 var sawType = null, group = unit == "group"; 4880 var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); 4881 for (var first = true;; first = false) { 4882 if (dir < 0 && !moveOnce(!first)) break; 4883 var cur = lineObj.text.charAt(ch) || "\n"; 4884 var type = isWordChar(cur, helper) ? "w" 4885 : group && cur == "\n" ? "n" 4886 : !group || /\s/.test(cur) ? null 4887 : "p"; 4888 if (group && !first && !type) type = "s"; 4889 if (sawType && sawType != type) { 4890 if (dir < 0) {dir = 1; moveOnce();} 4891 break; 4892 } 4893 4894 if (type) sawType = type; 4895 if (dir > 0 && !moveOnce(!first)) break; 4896 } 4897 } 4898 var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true); 4899 if (!cmp(pos, result)) result.hitSide = true; 4900 return result; 4901 } 4902 4903 // For relative vertical movement. Dir may be -1 or 1. Unit can be 4904 // "page" or "line". The resulting position will have a hitSide=true 4905 // property if it reached the end of the document. 4906 function findPosV(cm, pos, dir, unit) { 4907 var doc = cm.doc, x = pos.left, y; 4908 if (unit == "page") { 4909 var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); 4910 var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3); 4911 y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; 4912 } else if (unit == "line") { 4913 y = dir > 0 ? pos.bottom + 3 : pos.top - 3; 4914 } 4915 for (;;) { 4916 var target = coordsChar(cm, x, y); 4917 if (!target.outside) break; 4918 if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } 4919 y += dir * 5; 4920 } 4921 return target; 4922 } 4923 4924 // EDITOR METHODS 4925 4926 // The publicly visible API. Note that methodOp(f) means 4927 // 'wrap f in an operation, performed on its `this` parameter'. 4928 4929 // This is not the complete set of editor methods. Most of the 4930 // methods defined on the Doc type are also injected into 4931 // CodeMirror.prototype, for backwards compatibility and 4932 // convenience. 4933 4934 CodeMirror.prototype = { 4935 constructor: CodeMirror, 4936 focus: function(){window.focus(); this.display.input.focus();}, 4937 4938 setOption: function(option, value) { 4939 var options = this.options, old = options[option]; 4940 if (options[option] == value && option != "mode") return; 4941 options[option] = value; 4942 if (optionHandlers.hasOwnProperty(option)) 4943 operation(this, optionHandlers[option])(this, value, old); 4944 }, 4945 4946 getOption: function(option) {return this.options[option];}, 4947 getDoc: function() {return this.doc;}, 4948 4949 addKeyMap: function(map, bottom) { 4950 this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)); 4951 }, 4952 removeKeyMap: function(map) { 4953 var maps = this.state.keyMaps; 4954 for (var i = 0; i < maps.length; ++i) 4955 if (maps[i] == map || maps[i].name == map) { 4956 maps.splice(i, 1); 4957 return true; 4958 } 4959 }, 4960 4961 addOverlay: methodOp(function(spec, options) { 4962 var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); 4963 if (mode.startState) throw new Error("Overlays may not be stateful."); 4964 insertSorted(this.state.overlays, 4965 {mode: mode, modeSpec: spec, opaque: options && options.opaque, 4966 priority: (options && options.priority) || 0}, 4967 function(overlay) { return overlay.priority }) 4968 this.state.modeGen++; 4969 regChange(this); 4970 }), 4971 removeOverlay: methodOp(function(spec) { 4972 var overlays = this.state.overlays; 4973 for (var i = 0; i < overlays.length; ++i) { 4974 var cur = overlays[i].modeSpec;
4975 if (cur == spec || typeof spec == "string" && cur.name == spec) { 4976 overlays.splice(i, 1); 4977 this.state.modeGen++; 4978 regChange(this); 4979 return; 4980 } 4981 } 4982 }), 4983 4984 indentLine: methodOp(function(n, dir, aggressive) { 4985 if (typeof dir != "string" && typeof dir != "number") { 4986 if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; 4987 else dir = dir ? "add" : "subtract"; 4988 } 4989 if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); 4990 }), 4991 indentSelection: methodOp(function(how) { 4992 var ranges = this.doc.sel.ranges, end = -1; 4993 for (var i = 0; i < ranges.length; i++) { 4994 var range = ranges[i]; 4995 if (!range.empty()) { 4996 var from = range.from(), to = range.to(); 4997 var start = Math.max(end, from.line); 4998 end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; 4999 for (var j = start; j < end; ++j) 5000 indentLine(this, j, how); 5001 var newRanges = this.doc.sel.ranges; 5002 if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) 5003 replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); 5004 } else if (range.head.line > end) { 5005 indentLine(this, range.head.line, how, true); 5006 end = range.head.line; 5007 if (i == this.doc.sel.primIndex) ensureCursorVisible(this); 5008 } 5009 } 5010 }), 5011 5012 // Fetch the parser token for a given character. Useful for hacks 5013 // that want to inspect the mode state (say, for completion). 5014 getTokenAt: function(pos, precise) { 5015 return takeToken(this, pos, precise); 5016 }, 5017 5018 getLineTokens: function(line, precise) { 5019 return takeToken(this, Pos(line), precise, true); 5020 }, 5021 5022 getTokenTypeAt: function(pos) { 5023 pos = clipPos(this.doc, pos); 5024 var styles = getLineStyles(this, getLine(this.doc, pos.line)); 5025 var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; 5026 var type; 5027 if (ch == 0) type = styles[2]; 5028 else for (;;) { 5029 var mid = (before + after) >> 1; 5030 if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; 5031 else if (styles[mid * 2 + 1] < ch) before = mid + 1; 5032 else { type = styles[mid * 2 + 2]; break; } 5033 } 5034 var cut = type ? type.indexOf("cm-overlay ") : -1; 5035 return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); 5036 }, 5037 5038 getModeAt: function(pos) { 5039 var mode = this.doc.mode; 5040 if (!mode.innerMode) return mode; 5041 return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; 5042 }, 5043 5044 getHelper: function(pos, type) { 5045 return this.getHelpers(pos, type)[0]; 5046 }, 5047 5048 getHelpers: function(pos, type) { 5049 var found = []; 5050 if (!helpers.hasOwnProperty(type)) return found; 5051 var help = helpers[type], mode = this.getModeAt(pos); 5052 if (typeof mode[type] == "string") { 5053 if (help[mode[type]]) found.push(help[mode[type]]); 5054 } else if (mode[type]) { 5055 for (var i = 0; i < mode[type].length; i++) { 5056 var val = help[mode[type][i]]; 5057 if (val) found.push(val); 5058 } 5059 } else if (mode.helperType && help[mode.helperType]) { 5060 found.push(help[mode.helperType]); 5061 } else if (help[mode.name]) { 5062 found.push(help[mode.name]); 5063 } 5064 for (var i = 0; i < help._global.length; i++) { 5065 var cur = help._global[i]; 5066 if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) 5067 found.push(cur.val); 5068 } 5069 return found; 5070 }, 5071 5072 getStateAfter: function(line, precise) { 5073 var doc = this.doc; 5074 line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); 5075 return getStateBefore(this, line + 1, precise); 5076 }, 5077 5078 cursorCoords: function(start, mode) { 5079 var pos, range = this.doc.sel.primary(); 5080 if (start == null) pos = range.head; 5081 else if (typeof start == "object") pos = clipPos(this.doc, start); 5082 else pos = start ? range.from() : range.to(); 5083 return cursorCoords(this, pos, mode || "page"); 5084 }, 5085 5086 charCoords: function(pos, mode) { 5087 return charCoords(this, clipPos(this.doc, pos), mode || "page"); 5088 }, 5089 5090 coordsChar: function(coords, mode) { 5091 coords = fromCoordSystem(this, coords, mode || "page"); 5092 return coordsChar(this, coords.left, coords.top); 5093 }, 5094 5095 lineAtHeight: function(height, mode) { 5096 height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; 5097 return lineAtHeight(this.doc, height + this.display.viewOffset); 5098 }, 5099 heightAtLine: function(line, mode) { 5100 var end = false, lineObj; 5101 if (typeof line == "number") { 5102 var last = this.doc.first + this.doc.size - 1; 5103 if (line < this.doc.first) line = this.doc.first; 5104 else if (line > last) { line = last; end = true; } 5105 lineObj = getLine(this.doc, line); 5106 } else { 5107 lineObj = line; 5108 } 5109 return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top + 5110 (end ? this.doc.height - heightAtLine(lineObj) : 0); 5111 }, 5112 5113 defaultTextHeight: function() { return textHeight(this.display); }, 5114 defaultCharWidth: function() { return charWidth(this.display); }, 5115 5116 setGutterMarker: methodOp(function(line, gutterID, value) { 5117 return changeLine(this.doc, line, "gutter", function(line) { 5118 var markers = line.gutterMarkers || (line.gutterMarkers = {}); 5119 markers[gutterID] = value; 5120 if (!value && isEmpty(markers)) line.gutterMarkers = null; 5121 return true; 5122 }); 5123 }), 5124 5125 clearGutter: methodOp(function(gutterID) { 5126 var cm = this, doc = cm.doc, i = doc.first; 5127 doc.iter(function(line) { 5128 if (line.gutterMarkers && line.gutterMarkers[gutterID]) { 5129 line.gutterMarkers[gutterID] = null; 5130 regLineChange(cm, i, "gutter"); 5131 if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; 5132 } 5133 ++i; 5134 }); 5135 }), 5136 5137 lineInfo: function(line) { 5138 if (typeof line == "number") { 5139 if (!isLine(this.doc, line)) return null; 5140 var n = line; 5141 line = getLine(this.doc, line); 5142 if (!line) return null; 5143 } else { 5144 var n = lineNo(line); 5145 if (n == null) return null; 5146 } 5147 return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, 5148 textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, 5149 widgets: line.widgets}; 5150 }, 5151 5152 getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};}, 5153 5154 addWidget: function(pos, node, scroll, vert, horiz) { 5155 var display = this.display; 5156 pos = cursorCoords(this, clipPos(this.doc, pos)); 5157 var top = pos.bottom, left = pos.left; 5158 node.style.position = "absolute"; 5159 node.setAttribute("cm-ignore-events", "true"); 5160 this.display.input.setUneditable(node); 5161 display.sizer.appendChild(node); 5162 if (vert == "over") { 5163 top = pos.top; 5164 } else if (vert == "above" || vert == "near") { 5165 var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), 5166 hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); 5167 // Default to positioning above (if specified and possible); otherwise default to positioning below 5168 if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) 5169 top = pos.top - node.offsetHeight; 5170 else if (pos.bottom + node.offsetHeight <= vspace) 5171 top = pos.bottom; 5172 if (left + node.offsetWidth > hspace) 5173 left = hspace - node.offsetWidth; 5174 } 5175 node.style.top = top + "px"; 5176 node.style.left = node.style.right = ""; 5177 if (horiz == "right") { 5178 left = display.sizer.clientWidth - node.offsetWidth; 5179 node.style.right = "0px"; 5180 } else { 5181 if (horiz == "left") left = 0; 5182 else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; 5183 node.style.left = left + "px"; 5184 } 5185 if (scroll) 5186 scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight); 5187 }, 5188 5189 triggerOnKeyDown: methodOp(onKeyDown), 5190 triggerOnKeyPress: methodOp(onKeyPress), 5191 triggerOnKeyUp: onKeyUp, 5192 5193 execCommand: function(cmd) { 5194 if (commands.hasOwnProperty(cmd))
5195 return commands[cmd].call(null, this); 5196 }, 5197 5198 triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), 5199 5200 findPosH: function(from, amount, unit, visually) { 5201 var dir = 1; 5202 if (amount < 0) { dir = -1; amount = -amount; } 5203 for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { 5204 cur = findPosH(this.doc, cur, dir, unit, visually); 5205 if (cur.hitSide) break; 5206 } 5207 return cur; 5208 }, 5209 5210 moveH: methodOp(function(dir, unit) { 5211 var cm = this; 5212 cm.extendSelectionsBy(function(range) { 5213 if (cm.display.shift || cm.doc.extend || range.empty()) 5214 return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually); 5215 else 5216 return dir < 0 ? range.from() : range.to(); 5217 }, sel_move); 5218 }), 5219 5220 deleteH: methodOp(function(dir, unit) { 5221 var sel = this.doc.sel, doc = this.doc; 5222 if (sel.somethingSelected()) 5223 doc.replaceSelection("", null, "+delete"); 5224 else 5225 deleteNearSelection(this, function(range) { 5226 var other = findPosH(doc, range.head, dir, unit, false); 5227 return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}; 5228 }); 5229 }), 5230 5231 findPosV: function(from, amount, unit, goalColumn) { 5232 var dir = 1, x = goalColumn; 5233 if (amount < 0) { dir = -1; amount = -amount; } 5234 for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { 5235 var coords = cursorCoords(this, cur, "div"); 5236 if (x == null) x = coords.left; 5237 else coords.left = x; 5238 cur = findPosV(this, coords, dir, unit); 5239 if (cur.hitSide) break; 5240 } 5241 return cur; 5242 }, 5243 5244 moveV: methodOp(function(dir, unit) { 5245 var cm = this, doc = this.doc, goals = []; 5246 var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected(); 5247 doc.extendSelectionsBy(function(range) { 5248 if (collapse) 5249 return dir < 0 ? range.from() : range.to(); 5250 var headPos = cursorCoords(cm, range.head, "div"); 5251 if (range.goalColumn != null) headPos.left = range.goalColumn; 5252 goals.push(headPos.left); 5253 var pos = findPosV(cm, headPos, dir, unit); 5254 if (unit == "page" && range == doc.sel.primary()) 5255 addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top); 5256 return pos; 5257 }, sel_move); 5258 if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++) 5259 doc.sel.ranges[i].goalColumn = goals[i]; 5260 }), 5261 5262 // Find the word at the given position (as returned by coordsChar). 5263 findWordAt: function(pos) { 5264 var doc = this.doc, line = getLine(doc, pos.line).text; 5265 var start = pos.ch, end = pos.ch; 5266 if (line) { 5267 var helper = this.getHelper(pos, "wordChars"); 5268 if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; 5269 var startChar = line.charAt(start); 5270 var check = isWordChar(startChar, helper) 5271 ? function(ch) { return isWordChar(ch, helper); } 5272 : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} 5273 : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; 5274 while (start > 0 && check(line.charAt(start - 1))) --start; 5275 while (end < line.length && check(line.charAt(end))) ++end; 5276 } 5277 return new Range(Pos(pos.line, start), Pos(pos.line, end)); 5278 }, 5279 5280 toggleOverwrite: function(value) { 5281 if (value != null && value == this.state.overwrite) return; 5282 if (this.state.overwrite = !this.state.overwrite) 5283 addClass(this.display.cursorDiv, "CodeMirror-overwrite"); 5284 else 5285 rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); 5286 5287 signal(this, "overwriteToggle", this, this.state.overwrite); 5288 }, 5289 hasFocus: function() { return this.display.input.getField() == activeElt(); }, 5290 isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit); }, 5291 5292 scrollTo: methodOp(function(x, y) { 5293 if (x != null || y != null) resolveScrollToPos(this); 5294 if (x != null) this.curOp.scrollLeft = x; 5295 if (y != null) this.curOp.scrollTop = y; 5296 }), 5297 getScrollInfo: function() { 5298 var scroller = this.display.scroller; 5299 return {left: scroller.scrollLeft, top: scroller.scrollTop, 5300 height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, 5301 width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, 5302 clientHeight: displayHeight(this), clientWidth: displayWidth(this)}; 5303 }, 5304 5305 scrollIntoView: methodOp(function(range, margin) { 5306 if (range == null) { 5307 range = {from: this.doc.sel.primary().head, to: null}; 5308 if (margin == null) margin = this.options.cursorScrollMargin; 5309 } else if (typeof range == "number") { 5310 range = {from: Pos(range, 0), to: null}; 5311 } else if (range.from == null) { 5312 range = {from: range, to: null}; 5313 } 5314 if (!range.to) range.to = range.from; 5315 range.margin = margin || 0; 5316 5317 if (range.from.line != null) { 5318 resolveScrollToPos(this); 5319 this.curOp.scrollToPos = range; 5320 } else { 5321 var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left), 5322 Math.min(range.from.top, range.to.top) - range.margin, 5323 Math.max(range.from.right, range.to.right), 5324 Math.max(range.from.bottom, range.to.bottom) + range.margin); 5325 this.scrollTo(sPos.scrollLeft, sPos.scrollTop); 5326 } 5327 }), 5328 5329 setSize: methodOp(function(width, height) { 5330 var cm = this; 5331 function interpret(val) { 5332 return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; 5333 }
5334 if (width != null) cm.display.wrapper.style.width = interpret(width); 5335 if (height != null) cm.display.wrapper.style.height = interpret(height); 5336 if (cm.options.lineWrapping) clearLineMeasurementCache(this); 5337 var lineNo = cm.display.viewFrom; 5338 cm.doc.iter(lineNo, cm.display.viewTo, function(line) { 5339 if (line.widgets) for (var i = 0; i < line.widgets.length; i++) 5340 if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; } 5341 ++lineNo; 5342 }); 5343 cm.curOp.forceUpdate = true; 5344 signal(cm, "refresh", this); 5345 }), 5346 5347 operation: function(f){return runInOp(this, f);}, 5348 5349 refresh: methodOp(function() { 5350 var oldHeight = this.display.cachedTextHeight; 5351 regChange(this); 5352 this.curOp.forceUpdate = true; 5353 clearCaches(this); 5354 this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop); 5355 updateGutterSpace(this); 5356 if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) 5357 estimateLineHeights(this); 5358 signal(this, "refresh", this); 5359 }), 5360 5361 swapDoc: methodOp(function(doc) { 5362 var old = this.doc; 5363 old.cm = null; 5364 attachDoc(this, doc); 5365 clearCaches(this); 5366 this.display.input.reset(); 5367 this.scrollTo(doc.scrollLeft, doc.scrollTop); 5368 this.curOp.forceScroll = true; 5369 signalLater(this, "swapDoc", this, old); 5370 return old; 5371 }), 5372 5373 getInputField: function(){return this.display.input.getField();}, 5374 getWrapperElement: function(){return this.display.wrapper;}, 5375 getScrollerElement: function(){return this.display.scroller;}, 5376 getGutterElement: function(){return this.display.gutters;} 5377 }; 5378 eventMixin(CodeMirror); 5379 5380 // OPTION DEFAULTS 5381 5382 // The default configuration options. 5383 var defaults = CodeMirror.defaults = {}; 5384 // Functions to run when options are changed. 5385 var optionHandlers = CodeMirror.optionHandlers = {}; 5386 5387 function option(name, deflt, handle, notOnInit) { 5388 CodeMirror.defaults[name] = deflt; 5389 if (handle) optionHandlers[name] = 5390 notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; 5391 } 5392 5393 // Passed to option handlers when there is no old value. 5394 var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; 5395 5396 // These two are, on init, called from the constructor because they 5397 // have to be initialized before the editor can start at all. 5398 option("value", "", function(cm, val) { 5399 cm.setValue(val); 5400 }, true); 5401 option("mode", null, function(cm, val) { 5402 cm.doc.modeOption = val; 5403 loadMode(cm); 5404 }, true); 5405 5406 option("indentUnit", 2, loadMode, true); 5407 option("indentWithTabs", false); 5408 option("smartIndent", true); 5409 option("tabSize", 4, function(cm) { 5410 resetModeState(cm); 5411 clearCaches(cm); 5412 regChange(cm); 5413 }, true); 5414 option("lineSeparator", null, function(cm, val) { 5415 cm.doc.lineSep = val; 5416 if (!val) return; 5417 var newBreaks = [], lineNo = cm.doc.first; 5418 cm.doc.iter(function(line) { 5419 for (var pos = 0;;) { 5420 var found = line.text.indexOf(val, pos); 5421 if (found == -1) break; 5422 pos = found + val.length; 5423 newBreaks.push(Pos(lineNo, found)); 5424 } 5425 lineNo++; 5426 }); 5427 for (var i = newBreaks.length - 1; i >= 0; i--) 5428 replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) 5429 }); 5430 option("specialChars", /[\u0000-\u001f\u007f\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) { 5431 cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); 5432 if (old != CodeMirror.Init) cm.refresh(); 5433 }); 5434 option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true); 5435 option("electricChars", true); 5436 option("inputStyle", mobile ? "contenteditable" : "textarea", function() { 5437 throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME 5438 }, true); 5439 option("spellcheck", false, function(cm, val) { 5440 cm.getInputField().spellcheck = val 5441 }, true); 5442 option("rtlMoveVisually", !windows); 5443 option("wholeLineUpdateBefore", true); 5444 5445 option("theme", "default", function(cm) {
5446 themeChanged(cm); 5447 guttersChanged(cm); 5448 }, true); 5449 option("keyMap", "default", function(cm, val, old) { 5450 var next = getKeyMap(val); 5451 var prev = old != CodeMirror.Init && getKeyMap(old); 5452 if (prev && prev.detach) prev.detach(cm, next); 5453 if (next.attach) next.attach(cm, prev || null); 5454 }); 5455 option("extraKeys", null); 5456 5457 option("lineWrapping", false, wrappingChanged, true); 5458 option("gutters", [], function(cm) { 5459 setGuttersForLineNumbers(cm.options); 5460 guttersChanged(cm); 5461 }, true); 5462 option("fixedGutter", true, function(cm, val) { 5463 cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; 5464 cm.refresh(); 5465 }, true); 5466 option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true); 5467 option("scrollbarStyle", "native", function(cm) { 5468 initScrollbars(cm); 5469 updateScrollbars(cm); 5470 cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); 5471 cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); 5472 }, true); 5473 option("lineNumbers", false, function(cm) { 5474 setGuttersForLineNumbers(cm.options); 5475 guttersChanged(cm); 5476 }, true); 5477 option("firstLineNumber", 1, guttersChanged, true); 5478 option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true); 5479 option("showCursorWhenSelecting", false, updateSelection, true); 5480 5481 option("resetSelectionOnContextMenu", true); 5482 option("lineWiseCopyCut", true); 5483 5484 option("readOnly", false, function(cm, val) { 5485 if (val == "nocursor") { 5486 onBlur(cm); 5487 cm.display.input.blur(); 5488 cm.display.disabled = true; 5489 } else { 5490 cm.display.disabled = false; 5491 } 5492 cm.display.input.readOnlyChanged(val) 5493 }); 5494 option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true); 5495 option("dragDrop", true, dragDropChanged); 5496 option("allowDropFileTypes", null); 5497 5498 option("cursorBlinkRate", 530); 5499 option("cursorScrollMargin", 0); 5500 option("cursorHeight", 1, updateSelection, true); 5501 option("singleCursorHeightPerLine", true, updateSelection, true); 5502 option("workTime", 100); 5503 option("workDelay", 100); 5504 option("flattenSpans", true, resetModeState, true); 5505 option("addModeClass", false, resetModeState, true); 5506 option("pollInterval", 100); 5507 option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;}); 5508 option("historyEventDelay", 1250); 5509 option("viewportMargin", 10, function(cm){cm.refresh();}, true); 5510 option("maxHighlightLength", 10000, resetModeState, true); 5511 option("moveInputWithCursor", true, function(cm, val) { 5512 if (!val) cm.display.input.resetPosition(); 5513 }); 5514 5515 option("tabindex", null, function(cm, val) { 5516 cm.display.input.getField().tabIndex = val || ""; 5517 }); 5518 option("autofocus", null); 5519 5520 // MODE DEFINITION AND QUERYING 5521 5522 // Known modes, by name and by MIME 5523 var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; 5524 5525 // Extra arguments are stored as the mode's dependencies, which is 5526 // used by (legacy) mechanisms like loadmode.js to automatically 5527 // load a mode. (Preferred mechanism is the require/define calls.) 5528 CodeMirror.defineMode = function(name, mode) { 5529 if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; 5530 if (arguments.length > 2) 5531 mode.dependencies = Array.prototype.slice.call(arguments, 2); 5532 modes[name] = mode; 5533 }; 5534 5535 CodeMirror.defineMIME = function(mime, spec) { 5536 mimeModes[mime] = spec; 5537 }; 5538 5539 // Given a MIME type, a {name, ...options} config object, or a name 5540 // string, return a mode config object. 5541 CodeMirror.resolveMode = function(spec) { 5542 if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { 5543 spec = mimeModes[spec]; 5544 } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { 5545 var found = mimeModes[spec.name]; 5546 if (typeof found == "string") found = {name: found}; 5547 spec = createObj(found, spec); 5548 spec.name = found.name; 5549 } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { 5550 return CodeMirror.resolveMode("application/xml"); 5551 } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { 5552 return CodeMirror.resolveMode("application/json"); 5553 } 5554 if (typeof spec == "string") return {name: spec}; 5555 else return spec || {name: "null"}; 5556 }; 5557 5558 // Given a mode spec (anything that resolveMode accepts), find and 5559 // initialize an actual mode object. 5560 CodeMirror.getMode = function(options, spec) { 5561 var spec = CodeMirror.resolveMode(spec); 5562 var mfactory = modes[spec.name]; 5563 if (!mfactory) return CodeMirror.getMode(options, "text/plain"); 5564 var modeObj = mfactory(options, spec); 5565 if (modeExtensions.hasOwnProperty(spec.name)) { 5566 var exts = modeExtensions[spec.name]; 5567 for (var prop in exts) { 5568 if (!exts.hasOwnProperty(prop)) continue; 5569 if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; 5570 modeObj[prop] = exts[prop]; 5571 } 5572 } 5573 modeObj.name = spec.name; 5574 if (spec.helperType) modeObj.helperType = spec.helperType; 5575 if (spec.modeProps) for (var prop in spec.modeProps) 5576 modeObj[prop] = spec.modeProps[prop]; 5577 5578 return modeObj; 5579 }; 5580 5581 // Minimal default mode. 5582 CodeMirror.defineMode("null", function() { 5583 return {token: function(stream) {stream.skipToEnd();}}; 5584 }); 5585 CodeMirror.defineMIME("text/plain", "null"); 5586 5587 // This can be used to attach properties to mode objects from 5588 // outside the actual mode definition. 5589 var modeExtensions = CodeMirror.modeExtensions = {}; 5590 CodeMirror.extendMode = function(mode, properties) { 5591 var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); 5592 copyObj(properties, exts); 5593 }; 5594 5595 // EXTENSIONS 5596
5597 CodeMirror.defineExtension = function(name, func) { 5598 CodeMirror.prototype[name] = func; 5599 }; 5600 CodeMirror.defineDocExtension = function(name, func) { 5601 Doc.prototype[name] = func; 5602 }; 5603 CodeMirror.defineOption = option; 5604 5605 var initHooks = []; 5606 CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; 5607 5608 var helpers = CodeMirror.helpers = {}; 5609 CodeMirror.registerHelper = function(type, name, value) { 5610 if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []}; 5611 helpers[type][name] = value; 5612 }; 5613 CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { 5614 CodeMirror.registerHelper(type, name, value); 5615 helpers[type]._global.push({pred: predicate, val: value}); 5616 }; 5617 5618 // MODE STATE HANDLING 5619 5620 // Utility functions for working with state. Exported because nested 5621 // modes need to do this for their inner modes. 5622 5623 var copyState = CodeMirror.copyState = function(mode, state) { 5624 if (state === true) return state; 5625 if (mode.copyState) return mode.copyState(state); 5626 var nstate = {}; 5627 for (var n in state) { 5628 var val = state[n]; 5629 if (val instanceof Array) val = val.concat([]); 5630 nstate[n] = val; 5631 } 5632 return nstate; 5633 }; 5634 5635 var startState = CodeMirror.startState = function(mode, a1, a2) { 5636 return mode.startState ? mode.startState(a1, a2) : true; 5637 }; 5638 5639 // Given a mode and a state (for that mode), find the inner mode and 5640 // state at the position that the state refers to. 5641 CodeMirror.innerMode = function(mode, state) { 5642 while (mode.innerMode) { 5643 var info = mode.innerMode(state); 5644 if (!info || info.mode == mode) break; 5645 state = info.state; 5646 mode = info.mode; 5647 } 5648 return info || {mode: mode, state: state}; 5649 }; 5650 5651 // STANDARD COMMANDS 5652 5653 // Commands are parameter-less actions that can be performed on an 5654 // editor, mostly used for keybindings. 5655 var commands = CodeMirror.commands = { 5656 selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);}, 5657 singleSelection: function(cm) { 5658 cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); 5659 }, 5660 killLine: function(cm) { 5661 deleteNearSelection(cm, function(range) { 5662 if (range.empty()) { 5663 var len = getLine(cm.doc, range.head.line).text.length; 5664 if (range.head.ch == len && range.head.line < cm.lastLine()) 5665 return {from: range.head, to: Pos(range.head.line + 1, 0)}; 5666 else 5667 return {from: range.head, to: Pos(range.head.line, len)}; 5668 } else { 5669 return {from: range.from(), to: range.to()}; 5670 } 5671 }); 5672 }, 5673 deleteLine: function(cm) { 5674 deleteNearSelection(cm, function(range) { 5675 return {from: Pos(range.from().line, 0), 5676 to: clipPos(cm.doc, Pos(range.to().line + 1, 0))}; 5677 }); 5678 }, 5679 delLineLeft: function(cm) { 5680 deleteNearSelection(cm, function(range) { 5681 return {from: Pos(range.from().line, 0), to: range.from()}; 5682 }); 5683 }, 5684 delWrappedLineLeft: function(cm) { 5685 deleteNearSelection(cm, function(range) { 5686 var top = cm.charCoords(range.head, "div").top + 5; 5687 var leftPos = cm.coordsChar({left: 0, top: top}, "div"); 5688 return {from: leftPos, to: range.from()}; 5689 }); 5690 }, 5691 delWrappedLineRight: function(cm) { 5692 deleteNearSelection(cm, function(range) { 5693 var top = cm.charCoords(range.head, "div").top + 5; 5694 var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); 5695 return {from: range.from(), to: rightPos }; 5696 }); 5697 }, 5698 undo: function(cm) {cm.undo();}, 5699 redo: function(cm) {cm.redo();}, 5700 undoSelection: function(cm) {cm.undoSelection();}, 5701 redoSelection: function(cm) {cm.redoSelection();}, 5702 goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, 5703 goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, 5704 goLineStart: function(cm) { 5705 cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); }, 5706 {origin: "+move", bias: 1}); 5707 }, 5708 goLineStartSmart: function(cm) { 5709 cm.extendSelectionsBy(function(range) { 5710 return lineStartSmart(cm, range.head); 5711 }, {origin: "+move", bias: 1}); 5712 }, 5713 goLineEnd: function(cm) { 5714 cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); }, 5715 {origin: "+move", bias: -1}); 5716 }, 5717 goLineRight: function(cm) { 5718 cm.extendSelectionsBy(function(range) { 5719 var top = cm.charCoords(range.head, "div").top + 5; 5720 return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); 5721 }, sel_move); 5722 }, 5723 goLineLeft: function(cm) { 5724 cm.extendSelectionsBy(function(range) { 5725 var top = cm.charCoords(range.head, "div").top + 5; 5726 return cm.coordsChar({left: 0, top: top}, "div"); 5727 }, sel_move); 5728 }, 5729 goLineLeftSmart: function(cm) { 5730 cm.extendSelectionsBy(function(range) { 5731 var top = cm.charCoords(range.head, "div").top + 5; 5732 var pos = cm.coordsChar({left: 0, top: top}, "div"); 5733 if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head); 5734 return pos; 5735 }, sel_move); 5736 }, 5737 goLineUp: function(cm) {cm.moveV(-1, "line");}, 5738 goLineDown: function(cm) {cm.moveV(1, "line");}, 5739 goPageUp: function(cm) {cm.moveV(-1, "page");}, 5740 goPageDown: function(cm) {cm.moveV(1, "page");}, 5741 goCharLeft: function(cm) {cm.moveH(-1, "char");}, 5742 goCharRight: function(cm) {cm.moveH(1, "char");}, 5743 goColumnLeft: function(cm) {cm.moveH(-1, "column");}, 5744 goColumnRight: function(cm) {cm.moveH(1, "column");}, 5745 goWordLeft: function(cm) {cm.moveH(-1, "word");}, 5746 goGroupRight: function(cm) {cm.moveH(1, "group");}, 5747 goGroupLeft: function(cm) {cm.moveH(-1, "group");}, 5748 goWordRight: function(cm) {cm.moveH(1, "word");}, 5749 delCharBefore: function(cm) {cm.deleteH(-1, "char");}, 5750 delCharAfter: function(cm) {cm.deleteH(1, "char");}, 5751 delWordBefore: function(cm) {cm.deleteH(-1, "word");}, 5752 delWordAfter: function(cm) {cm.deleteH(1, "word");}, 5753 delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, 5754 delGroupAfter: function(cm) {cm.deleteH(1, "group");}, 5755 indentAuto: function(cm) {cm.indentSelection("smart");}, 5756 indentMore: function(cm) {cm.indentSelection("add");}, 5757 indentLess: function(cm) {cm.indentSelection("subtract");}, 5758 insertTab: function(cm) {cm.replaceSelection("\t");}, 5759 insertSoftTab: function(cm) { 5760 var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; 5761 for (var i = 0; i < ranges.length; i++) { 5762 var pos = ranges[i].from(); 5763 var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
5764 spaces.push(spaceStr(tabSize - col % tabSize)); 5765 } 5766 cm.replaceSelections(spaces); 5767 }, 5768 defaultTab: function(cm) { 5769 if (cm.somethingSelected()) cm.indentSelection("add"); 5770 else cm.execCommand("insertTab"); 5771 }, 5772 transposeChars: function(cm) { 5773 runInOp(cm, function() { 5774 var ranges = cm.listSelections(), newSel = []; 5775 for (var i = 0; i < ranges.length; i++) { 5776 var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; 5777 if (line) { 5778 if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1); 5779 if (cur.ch > 0) { 5780 cur = new Pos(cur.line, cur.ch + 1); 5781 cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), 5782 Pos(cur.line, cur.ch - 2), cur, "+transpose"); 5783 } else if (cur.line > cm.doc.first) { 5784 var prev = getLine(cm.doc, cur.line - 1).text; 5785 if (prev) 5786 cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + 5787 prev.charAt(prev.length - 1), 5788 Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose"); 5789 } 5790 } 5791 newSel.push(new Range(cur, cur)); 5792 } 5793 cm.setSelections(newSel); 5794 }); 5795 }, 5796 newlineAndIndent: function(cm) { 5797 runInOp(cm, function() { 5798 var len = cm.listSelections().length; 5799 for (var i = 0; i < len; i++) { 5800 var range = cm.listSelections()[i]; 5801 cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input"); 5802 cm.indentLine(range.from().line + 1, null, true); 5803 } 5804 ensureCursorVisible(cm); 5805 }); 5806 }, 5807 openLine: function(cm) {cm.replaceSelection("\n", "start")}, 5808 toggleOverwrite: function(cm) {cm.toggleOverwrite();} 5809 }; 5810 5811 5812 // STANDARD KEYMAPS 5813 5814 var keyMap = CodeMirror.keyMap = {}; 5815 5816 keyMap.basic = { 5817 "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", 5818 "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", 5819 "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", 5820 "Tab": "defaultTab", "Shift-Tab": "indentAuto", 5821 "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", 5822 "Esc": "singleSelection" 5823 }; 5824 // Note that the save and find-related commands aren't defined by 5825 // default. User code or addons can define them. Unknown commands 5826 // are simply ignored. 5827 keyMap.pcDefault = { 5828 "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", 5829 "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", 5830 "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", 5831 "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", 5832 "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", 5833 "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", 5834 "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", 5835 fallthrough: "basic" 5836 }; 5837 // Very basic readline/emacs-style bindings, which are standard on Mac. 5838 keyMap.emacsy = { 5839 "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", 5840 "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", 5841 "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", 5842 "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", 5843 "Ctrl-O": "openLine" 5844 }; 5845 keyMap.macDefault = { 5846 "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", 5847 "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", 5848 "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", 5849 "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", 5850 "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", 5851 "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", 5852 "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", 5853 fallthrough: ["basic", "emacsy"] 5854 }; 5855 keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; 5856 5857 // KEYMAP DISPATCH 5858 5859 function normalizeKeyName(name) { 5860 var parts = name.split(/-(?!$)/), name = parts[parts.length - 1]; 5861 var alt, ctrl, shift, cmd; 5862 for (var i = 0; i < parts.length - 1; i++) { 5863 var mod = parts[i]; 5864 if (/^(cmd|meta|m)$/i.test(mod)) cmd = true; 5865 else if (/^a(lt)?$/i.test(mod)) alt = true; 5866 else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true; 5867 else if (/^s(hift)$/i.test(mod)) shift = true; 5868 else throw new Error("Unrecognized modifier name: " + mod); 5869 } 5870 if (alt) name = "Alt-" + name; 5871 if (ctrl) name = "Ctrl-" + name; 5872 if (cmd) name = "Cmd-" + name; 5873 if (shift) name = "Shift-" + name; 5874 return name; 5875 } 5876 5877 // This is a kludge to keep keymaps mostly working as raw objects 5878 // (backwards compatibility) while at the same time support features 5879 // like normalization and multi-stroke key bindings. It compiles a 5880 // new normalized keymap, and then updates the old object to reflect 5881 // this. 5882 CodeMirror.normalizeKeyMap = function(keymap) { 5883 var copy = {}; 5884 for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) { 5885 var value = keymap[keyname]; 5886 if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue; 5887 if (value == "...") { delete keymap[keyname]; continue; } 5888 5889 var keys = map(keyname.split(" "), normalizeKeyName); 5890 for (var i = 0; i < keys.length; i++) { 5891 var val, name; 5892 if (i == keys.length - 1) { 5893 name = keys.join(" "); 5894 val = value; 5895 } else { 5896 name = keys.slice(0, i + 1).join(" "); 5897 val = "..."; 5898 } 5899 var prev = copy[name]; 5900 if (!prev) copy[name] = val; 5901 else if (prev != val) throw new Error("Inconsistent bindings for " + name); 5902 } 5903 delete keymap[keyname]; 5904 } 5905 for (var prop in copy) keymap[prop] = copy[prop]; 5906 return keymap; 5907 }; 5908 5909 var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) { 5910 map = getKeyMap(map); 5911 var found = map.call ? map.call(key, context) : map[key]; 5912 if (found === false) return "nothing"; 5913 if (found === "...") return "multi"; 5914 if (found != null && handle(found)) return "handled"; 5915 5916 if (map.fallthrough) { 5917 if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") 5918 return lookupKey(key, map.fallthrough, handle, context); 5919 for (var i = 0; i < map.fallthrough.length; i++) { 5920 var result = lookupKey(key, map.fallthrough[i], handle, context); 5921 if (result) return result; 5922 } 5923 } 5924 }; 5925 5926 // Modifier key presses don't count as 'real' key presses for the 5927 // purpose of keymap fallthrough. 5928 var isModifierKey = CodeMirror.isModifierKey = function(value) { 5929 var name = typeof value == "string" ? value : keyNames[value.keyCode]; 5930 return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; 5931 }; 5932 5933 // Look up the name of a key as indicated by an event object. 5934 var keyName = CodeMirror.keyName = function(event, noShift) { 5935 if (presto && event.keyCode == 34 && event["char"]) return false;
5936 var base = keyNames[event.keyCode], name = base; 5937 if (name == null || event.altGraphKey) return false; 5938 if (event.altKey && base != "Alt") name = "Alt-" + name; 5939 if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name; 5940 if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name; 5941 if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name; 5942 return name; 5943 }; 5944 5945 function getKeyMap(val) { 5946 return typeof val == "string" ? keyMap[val] : val; 5947 } 5948 5949 // FROMTEXTAREA 5950 5951 CodeMirror.fromTextArea = function(textarea, options) { 5952 options = options ? copyObj(options) : {}; 5953 options.value = textarea.value; 5954 if (!options.tabindex && textarea.tabIndex) 5955 options.tabindex = textarea.tabIndex; 5956 if (!options.placeholder && textarea.placeholder) 5957 options.placeholder = textarea.placeholder; 5958 // Set autofocus to true if this textarea is focused, or if it has 5959 // autofocus and no other element is focused. 5960 if (options.autofocus == null) { 5961 var hasFocus = activeElt(); 5962 options.autofocus = hasFocus == textarea || 5963 textarea.getAttribute("autofocus") != null && hasFocus == document.body; 5964 } 5965 5966 function save() {textarea.value = cm.getValue();} 5967 if (textarea.form) { 5968 on(textarea.form, "submit", save); 5969 // Deplorable hack to make the submit method do the right thing. 5970 if (!options.leaveSubmitMethodAlone) { 5971 var form = textarea.form, realSubmit = form.submit; 5972 try { 5973 var wrappedSubmit = form.submit = function() { 5974 save(); 5975 form.submit = realSubmit; 5976 form.submit(); 5977 form.submit = wrappedSubmit; 5978 }; 5979 } catch(e) {} 5980 } 5981 } 5982 5983 options.finishInit = function(cm) { 5984 cm.save = save; 5985 cm.getTextArea = function() { return textarea; }; 5986 cm.toTextArea = function() { 5987 cm.toTextArea = isNaN; // Prevent this from being ran twice 5988 save(); 5989 textarea.parentNode.removeChild(cm.getWrapperElement()); 5990 textarea.style.display = ""; 5991 if (textarea.form) { 5992 off(textarea.form, "submit", save); 5993 if (typeof textarea.form.submit == "function") 5994 textarea.form.submit = realSubmit; 5995 } 5996 }; 5997 }; 5998 5999 textarea.style.display = "none"; 6000 var cm = CodeMirror(function(node) { 6001 textarea.parentNode.insertBefore(node, textarea.nextSibling); 6002 }, options); 6003 return cm; 6004 }; 6005 6006 // STRING STREAM 6007 6008 // Fed to the mode parsers, provides helper functions to make 6009 // parsers more succinct. 6010 6011 var StringStream = CodeMirror.StringStream = function(string, tabSize) { 6012 this.pos = this.start = 0; 6013 this.string = string; 6014 this.tabSize = tabSize || 8; 6015 this.lastColumnPos = this.lastColumnValue = 0; 6016 this.lineStart = 0; 6017 }; 6018 6019 StringStream.prototype = { 6020 eol: function() {return this.pos >= this.string.length;}, 6021 sol: function() {return this.pos == this.lineStart;}, 6022 peek: function() {return this.string.charAt(this.pos) || undefined;}, 6023 next: function() { 6024 if (this.pos < this.string.length) 6025 return this.string.charAt(this.pos++); 6026 }, 6027 eat: function(match) { 6028 var ch = this.string.charAt(this.pos); 6029 if (typeof match == "string") var ok = ch == match; 6030 else var ok = ch && (match.test ? match.test(ch) : match(ch)); 6031 if (ok) {++this.pos; return ch;} 6032 }, 6033 eatWhile: function(match) { 6034 var start = this.pos; 6035 while (this.eat(match)){} 6036 return this.pos > start; 6037 }, 6038 eatSpace: function() { 6039 var start = this.pos; 6040 while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; 6041 return this.pos > start; 6042 }, 6043 skipToEnd: function() {this.pos = this.string.length;}, 6044 skipTo: function(ch) { 6045 var found = this.string.indexOf(ch, this.pos); 6046 if (found > -1) {this.pos = found; return true;} 6047 }, 6048 backUp: function(n) {this.pos -= n;}, 6049 column: function() { 6050 if (this.lastColumnPos < this.start) { 6051 this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); 6052 this.lastColumnPos = this.start; 6053 } 6054 return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); 6055 }, 6056 indentation: function() { 6057 return countColumn(this.string, null, this.tabSize) - 6058 (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); 6059 }, 6060 match: function(pattern, consume, caseInsensitive) { 6061 if (typeof pattern == "string") { 6062 var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; 6063 var substr = this.string.substr(this.pos, pattern.length); 6064 if (cased(substr) == cased(pattern)) { 6065 if (consume !== false) this.pos += pattern.length; 6066 return true; 6067 } 6068 } else { 6069 var match = this.string.slice(this.pos).match(pattern); 6070 if (match && match.index > 0) return null; 6071 if (match && consume !== false) this.pos += match[0].length; 6072 return match; 6073 } 6074 }, 6075 current: function(){return this.string.slice(this.start, this.pos);}, 6076 hideFirstChars: function(n, inner) { 6077 this.lineStart += n;
6078 try { return inner(); } 6079 finally { this.lineStart -= n; } 6080 } 6081 }; 6082 6083 // TEXTMARKERS 6084 6085 // Created with markText and setBookmark methods. A TextMarker is a 6086 // handle that can be used to clear or find a marked position in the 6087 // document. Line objects hold arrays (markedSpans) containing 6088 // {from, to, marker} object pointing to such marker objects, and 6089 // indicating that such a marker is present on that line. Multiple 6090 // lines may point to the same marker when it spans across lines. 6091 // The spans will have null for their from/to properties when the 6092 // marker continues beyond the start/end of the line. Markers have 6093 // links back to the lines they currently touch. 6094 6095 var nextMarkerId = 0; 6096 6097 var TextMarker = CodeMirror.TextMarker = function(doc, type) { 6098 this.lines = []; 6099 this.type = type; 6100 this.doc = doc; 6101 this.id = ++nextMarkerId; 6102 }; 6103 eventMixin(TextMarker); 6104 6105 // Clear the marker. 6106 TextMarker.prototype.clear = function() { 6107 if (this.explicitlyCleared) return; 6108 var cm = this.doc.cm, withOp = cm && !cm.curOp; 6109 if (withOp) startOperation(cm); 6110 if (hasHandler(this, "clear")) { 6111 var found = this.find(); 6112 if (found) signalLater(this, "clear", found.from, found.to); 6113 } 6114 var min = null, max = null; 6115 for (var i = 0; i < this.lines.length; ++i) { 6116 var line = this.lines[i]; 6117 var span = getMarkedSpanFor(line.markedSpans, this); 6118 if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text"); 6119 else if (cm) { 6120 if (span.to != null) max = lineNo(line); 6121 if (span.from != null) min = lineNo(line); 6122 } 6123 line.markedSpans = removeMarkedSpan(line.markedSpans, span); 6124 if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) 6125 updateLineHeight(line, textHeight(cm.display)); 6126 } 6127 if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) { 6128 var visual = visualLine(this.lines[i]), len = lineLength(visual); 6129 if (len > cm.display.maxLineLength) { 6130 cm.display.maxLine = visual; 6131 cm.display.maxLineLength = len; 6132 cm.display.maxLineChanged = true; 6133 } 6134 } 6135 6136 if (min != null && cm && this.collapsed) regChange(cm, min, max + 1); 6137 this.lines.length = 0; 6138 this.explicitlyCleared = true; 6139 if (this.atomic && this.doc.cantEdit) { 6140 this.doc.cantEdit = false; 6141 if (cm) reCheckSelection(cm.doc); 6142 } 6143 if (cm) signalLater(cm, "markerCleared", cm, this); 6144 if (withOp) endOperation(cm); 6145 if (this.parent) this.parent.clear(); 6146 }; 6147 6148 // Find the position of the marker in the document. Returns a {from, 6149 // to} object by default. Side can be passed to get a specific side 6150 // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the 6151 // Pos objects returned contain a line object, rather than a line 6152 // number (used to prevent looking up the same line twice). 6153 TextMarker.prototype.find = function(side, lineObj) { 6154 if (side == null && this.type == "bookmark") side = 1; 6155 var from, to; 6156 for (var i = 0; i < this.lines.length; ++i) { 6157 var line = this.lines[i]; 6158 var span = getMarkedSpanFor(line.markedSpans, this); 6159 if (span.from != null) { 6160 from = Pos(lineObj ? line : lineNo(line), span.from); 6161 if (side == -1) return from; 6162 } 6163 if (span.to != null) { 6164 to = Pos(lineObj ? line : lineNo(line), span.to); 6165 if (side == 1) return to; 6166 } 6167 } 6168 return from && {from: from, to: to}; 6169 }; 6170 6171 // Signals that the marker's widget changed, and surrounding layout 6172 // should be recomputed. 6173 TextMarker.prototype.changed = function() { 6174 var pos = this.find(-1, true), widget = this, cm = this.doc.cm; 6175 if (!pos || !cm) return; 6176 runInOp(cm, function() { 6177 var line = pos.line, lineN = lineNo(pos.line); 6178 var view = findViewForLine(cm, lineN); 6179 if (view) { 6180 clearLineMeasurementCacheFor(view); 6181 cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; 6182 } 6183 cm.curOp.updateMaxLine = true; 6184 if (!lineIsHidden(widget.doc, line) && widget.height != null) { 6185 var oldHeight = widget.height; 6186 widget.height = null; 6187 var dHeight = widgetHeight(widget) - oldHeight; 6188 if (dHeight) 6189 updateLineHeight(line, line.height + dHeight); 6190 } 6191 }); 6192 }; 6193 6194 TextMarker.prototype.attachLine = function(line) { 6195 if (!this.lines.length && this.doc.cm) { 6196 var op = this.doc.cm.curOp; 6197 if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) 6198 (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); 6199 } 6200 this.lines.push(line); 6201 }; 6202 TextMarker.prototype.detachLine = function(line) { 6203 this.lines.splice(indexOf(this.lines, line), 1); 6204 if (!this.lines.length && this.doc.cm) { 6205 var op = this.doc.cm.curOp; 6206 (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); 6207 } 6208 }; 6209 6210 // Collapsed markers have unique ids, in order to be able to order 6211 // them, which is needed for uniquely determining an outer marker 6212 // when they overlap (they may nest, but not partially overlap). 6213 var nextMarkerId = 0; 6214 6215 // Create a marker, wire it up to the right lines, and 6216 function markText(doc, from, to, options, type) { 6217 // Shared markers (across linked documents) are handled separately 6218 // (markTextShared will call out to this again, once per 6219 // document). 6220 if (options && options.shared) return markTextShared(doc, from, to, options, type); 6221 // Ensure we are in an operation. 6222 if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); 6223 6224 var marker = new TextMarker(doc, type), diff = cmp(from, to); 6225 if (options) copyObj(options, marker, false); 6226 // Don't connect empty markers unless clearWhenEmpty is false 6227 if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) 6228 return marker; 6229 if (marker.replacedWith) { 6230 // Showing up as a widget implies collapsed (widget replaces text) 6231 marker.collapsed = true; 6232 marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget"); 6233 if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true"); 6234 if (options.insertLeft) marker.widgetNode.insertLeft = true; 6235 } 6236 if (marker.collapsed) { 6237 if (conflictingCollapsedRange(doc, from.line, from, to, marker) || 6238 from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) 6239 throw new Error("Inserting collapsed marker partially overlapping an existing one"); 6240 sawCollapsedSpans = true; 6241 } 6242 6243 if (marker.addToHistory) 6244 addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); 6245 6246 var curLine = from.line, cm = doc.cm, updateMaxLine; 6247 doc.iter(curLine, to.line + 1, function(line) { 6248 if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.dis
6248play.maxLine) 6249 updateMaxLine = true; 6250 if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0); 6251 addMarkedSpan(line, new MarkedSpan(marker, 6252 curLine == from.line ? from.ch : null, 6253 curLine == to.line ? to.ch : null)); 6254 ++curLine; 6255 }); 6256 // lineIsHidden depends on the presence of the spans, so needs a second pass 6257 if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { 6258 if (lineIsHidden(doc, line)) updateLineHeight(line, 0); 6259 }); 6260 6261 if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); }); 6262 6263 if (marker.readOnly) { 6264 sawReadOnlySpans = true; 6265 if (doc.history.done.length || doc.history.undone.length) 6266 doc.clearHistory(); 6267 } 6268 if (marker.collapsed) { 6269 marker.id = ++nextMarkerId; 6270 marker.atomic = true; 6271 } 6272 if (cm) { 6273 // Sync editor state 6274 if (updateMaxLine) cm.curOp.updateMaxLine = true; 6275 if (marker.collapsed) 6276 regChange(cm, from.line, to.line + 1); 6277 else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) 6278 for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text"); 6279 if (marker.atomic) reCheckSelection(cm.doc); 6280 signalLater(cm, "markerAdded", cm, marker); 6281 } 6282 return marker; 6283 } 6284 6285 // SHARED TEXTMARKERS 6286 6287 // A shared marker spans multiple linked documents. It is 6288 // implemented as a meta-marker-object controlling multiple normal 6289 // markers. 6290 var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) { 6291 this.markers = markers; 6292 this.primary = primary; 6293 for (var i = 0; i < markers.length; ++i) 6294 markers[i].parent = this; 6295 }; 6296 eventMixin(SharedTextMarker); 6297 6298 SharedTextMarker.prototype.clear = function() { 6299 if (this.explicitlyCleared) return; 6300 this.explicitlyCleared = true; 6301 for (var i = 0; i < this.markers.length; ++i) 6302 this.markers[i].clear(); 6303 signalLater(this, "clear"); 6304 }; 6305 SharedTextMarker.prototype.find = function(side, lineObj) { 6306 return this.primary.find(side, lineObj); 6307 }; 6308 6309 function markTextShared(doc, from, to, options, type) { 6310 options = copyObj(options); 6311 options.shared = false; 6312 var markers = [markText(doc, from, to, options, type)], primary = markers[0]; 6313 var widget = options.widgetNode; 6314 linkedDocs(doc, function(doc) { 6315 if (widget) options.widgetNode = widget.cloneNode(true); 6316 markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); 6317 for (var i = 0; i < doc.linked.length; ++i) 6318 if (doc.linked[i].isParent) return; 6319 primary = lst(markers); 6320 }); 6321 return new SharedTextMarker(markers, primary); 6322 } 6323 6324 function findSharedMarkers(doc) { 6325 return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), 6326 function(m) { return m.parent; }); 6327 } 6328 6329 function copySharedMarkers(doc, markers) { 6330 for (var i = 0; i < markers.length; i++) { 6331 var marker = markers[i], pos = marker.find(); 6332 var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); 6333 if (cmp(mFrom, mTo)) { 6334 var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); 6335 marker.markers.push(subMark); 6336 subMark.parent = marker; 6337 } 6338 } 6339 } 6340 6341 function detachSharedMarkers(markers) { 6342 for (var i = 0; i < markers.length; i++) { 6343 var marker = markers[i], linked = [marker.primary.doc];; 6344 linkedDocs(marker.primary.doc, function(d) { linked.push(d); }); 6345 for (var j = 0; j < marker.markers.length; j++) { 6346 var subMarker = marker.markers[j]; 6347 if (indexOf(linked, subMarker.doc) == -1) { 6348 subMarker.parent = null; 6349 marker.markers.splice(j--, 1); 6350 } 6351 } 6352 } 6353 } 6354 6355 // TEXTMARKER SPANS 6356 6357 function MarkedSpan(marker, from, to) { 6358 this.marker = marker; 6359 this.from = from; this.to = to; 6360 } 6361 6362 // Search an array of spans for a span matching the given marker. 6363 function getMarkedSpanFor(spans, marker) { 6364 if (spans) for (var i = 0; i < spans.length; ++i) { 6365 var span = spans[i]; 6366 if (span.marker == marker) return span; 6367 } 6368 } 6369 // Remove a span from an array, returning undefined if no spans are 6370 // left (we don't store arrays for lines without spans). 6371 function removeMarkedSpan(spans, span) { 6372 for (var r, i = 0; i < spans.length; ++i) 6373 if (spans[i] != span) (r || (r = [])).push(spans[i]); 6374 return r; 6375 } 6376 // Add a span to a line. 6377 function addMarkedSpan(line, span) { 6378 line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; 6379 span.marker.attachLine(line); 6380 } 6381
6382 // Used for the algorithm that adjusts markers for a change in the 6383 // document. These functions cut an array of spans at a given 6384 // character position, returning an array of remaining chunks (or 6385 // undefined if nothing remains). 6386 function markedSpansBefore(old, startCh, isInsert) { 6387 if (old) for (var i = 0, nw; i < old.length; ++i) { 6388 var span = old[i], marker = span.marker; 6389 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); 6390 if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { 6391 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); 6392 (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); 6393 } 6394 } 6395 return nw; 6396 } 6397 function markedSpansAfter(old, endCh, isInsert) { 6398 if (old) for (var i = 0, nw; i < old.length; ++i) { 6399 var span = old[i], marker = span.marker; 6400 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); 6401 if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { 6402 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); 6403 (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, 6404 span.to == null ? null : span.to - endCh)); 6405 } 6406 } 6407 return nw; 6408 } 6409 6410 // Given a change object, compute the new set of marker spans that 6411 // cover the line in which the change took place. Removes spans 6412 // entirely within the change, reconnects spans belonging to the 6413 // same marker that appear on both sides of the change, and cuts off 6414 // spans partially within the change. Returns an array of span 6415 // arrays with one element for each line in (after) the change. 6416 function stretchSpansOverChange(doc, change) { 6417 if (change.full) return null; 6418 var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; 6419 var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; 6420 if (!oldFirst && !oldLast) return null; 6421 6422 var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; 6423 // Get the spans that 'stick out' on both sides 6424 var first = markedSpansBefore(oldFirst, startCh, isInsert); 6425 var last = markedSpansAfter(oldLast, endCh, isInsert); 6426 6427 // Next, merge those two ends 6428 var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); 6429 if (first) { 6430 // Fix up .to properties of first 6431 for (var i = 0; i < first.length; ++i) { 6432 var span = first[i]; 6433 if (span.to == null) { 6434 var found = getMarkedSpanFor(last, span.marker); 6435 if (!found) span.to = startCh; 6436 else if (sameLine) span.to = found.to == null ? null : found.to + offset; 6437 } 6438 } 6439 } 6440 if (last) { 6441 // Fix up .from in last (or move them into first in case of sameLine) 6442 for (var i = 0; i < last.length; ++i) { 6443 var span = last[i]; 6444 if (span.to != null) span.to += offset; 6445 if (span.from == null) { 6446 var found = getMarkedSpanFor(first, span.marker); 6447 if (!found) { 6448 span.from = offset; 6449 if (sameLine) (first || (first = [])).push(span); 6450 } 6451 } else { 6452 span.from += offset; 6453 if (sameLine) (first || (first = [])).push(span); 6454 } 6455 } 6456 } 6457 // Make sure we didn't create any zero-length spans 6458 if (first) first = clearEmptySpans(first); 6459 if (last && last != first) last = clearEmptySpans(last); 6460 6461 var newMarkers = [first]; 6462 if (!sameLine) { 6463 // Fill gap with whole-line-spans 6464 var gap = change.text.length - 2, gapMarkers; 6465 if (gap > 0 && first) 6466 for (var i = 0; i < first.length; ++i) 6467 if (first[i].to == null) 6468 (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null)); 6469 for (var i = 0; i < gap; ++i) 6470 newMarkers.push(gapMarkers); 6471 newMarkers.push(last); 6472 } 6473 return newMarkers; 6474 } 6475 6476 // Remove spans that are empty and don't have a clearWhenEmpty 6477 // option of false.
6478 function clearEmptySpans(spans) { 6479 for (var i = 0; i < spans.length; ++i) { 6480 var span = spans[i]; 6481 if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) 6482 spans.splice(i--, 1); 6483 } 6484 if (!spans.length) return null; 6485 return spans; 6486 } 6487 6488 // Used for un/re-doing changes from the history. Combines the 6489 // result of computing the existing spans with the set of spans that 6490 // existed in the history (so that deleting around a span and then 6491 // undoing brings back the span). 6492 function mergeOldSpans(doc, change) { 6493 var old = getOldSpans(doc, change); 6494 var stretched = stretchSpansOverChange(doc, change); 6495 if (!old) return stretched; 6496 if (!stretched) return old; 6497 6498 for (var i = 0; i < old.length; ++i) { 6499 var oldCur = old[i], stretchCur = stretched[i]; 6500 if (oldCur && stretchCur) { 6501 spans: for (var j = 0; j < stretchCur.length; ++j) { 6502 var span = stretchCur[j]; 6503 for (var k = 0; k < oldCur.length; ++k) 6504 if (oldCur[k].marker == span.marker) continue spans; 6505 oldCur.push(span); 6506 } 6507 } else if (stretchCur) { 6508 old[i] = stretchCur; 6509 } 6510 } 6511 return old; 6512 } 6513 6514 // Used to 'clip' out readOnly ranges when making a change. 6515 function removeReadOnlyRanges(doc, from, to) { 6516 var markers = null; 6517 doc.iter(from.line, to.line + 1, function(line) { 6518 if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { 6519 var mark = line.markedSpans[i].marker; 6520 if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) 6521 (markers || (markers = [])).push(mark); 6522 } 6523 }); 6524 if (!markers) return null; 6525 var parts = [{from: from, to: to}]; 6526 for (var i = 0; i < markers.length; ++i) { 6527 var mk = markers[i], m = mk.find(0); 6528 for (var j = 0; j < parts.length; ++j) { 6529 var p = parts[j]; 6530 if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue; 6531 var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); 6532 if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) 6533 newParts.push({from: p.from, to: m.from}); 6534 if (dto > 0 || !mk.inclusiveRight && !dto) 6535 newParts.push({from: m.to, to: p.to}); 6536 parts.splice.apply(parts, newParts); 6537 j += newParts.length - 1; 6538 } 6539 } 6540 return parts; 6541 } 6542 6543 // Connect or disconnect spans from a line. 6544 function detachMarkedSpans(line) { 6545 var spans = line.markedSpans; 6546 if (!spans) return; 6547 for (var i = 0; i < spans.length; ++i) 6548 spans[i].marker.detachLine(line); 6549 line.markedSpans = null; 6550 } 6551 function attachMarkedSpans(line, spans) { 6552 if (!spans) return; 6553 for (var i = 0; i < spans.length; ++i) 6554 spans[i].marker.attachLine(line); 6555 line.markedSpans = spans; 6556 } 6557 6558 // Helpers used when computing which overlapping collapsed span 6559 // counts as the larger one. 6560 function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; } 6561 function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; } 6562 6563 // Returns a number indicating which of two overlapping collapsed 6564 // spans is larger (and thus includes the other). Falls back to 6565 // comparing ids when the spans cover exactly the same range. 6566 function compareCollapsedMarkers(a, b) { 6567 var lenDiff = a.lines.length - b.lines.length; 6568 if (lenDiff != 0) return lenDiff; 6569 var aPos = a.find(), bPos = b.find(); 6570 var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); 6571 if (fromCmp) return -fromCmp; 6572 var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); 6573 if (toCmp) return toCmp; 6574 return b.id - a.id; 6575 } 6576 6577 // Find out whether a line ends or starts in a collapsed span. If 6578 // so, return the marker for that span. 6579 function collapsedSpanAtSide(line, start) { 6580 var sps = sawCollapsedSpans && line.markedSpans, found; 6581 if (sps) for (var sp, i = 0; i < sps.length; ++i) { 6582 sp = sps[i]; 6583 if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && 6584 (!found || compareCollapsedMarkers(found, sp.marker) < 0)) 6585 found = sp.marker; 6586 } 6587 return found; 6588 } 6589 function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); } 6590 function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); } 6591
6592 // Test whether there exists a collapsed span that partially 6593 // overlaps (covers the start or end, but not both) of a new span. 6594 // Such overlap is not allowed. 6595 function conflictingCollapsedRange(doc, lineNo, from, to, marker) { 6596 var line = getLine(doc, lineNo); 6597 var sps = sawCollapsedSpans && line.markedSpans; 6598 if (sps) for (var i = 0; i < sps.length; ++i) { 6599 var sp = sps[i]; 6600 if (!sp.marker.collapsed) continue; 6601 var found = sp.marker.find(0); 6602 var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); 6603 var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); 6604 if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue; 6605 if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || 6606 fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) 6607 return true; 6608 } 6609 } 6610 6611 // A visual line is a line as drawn on the screen. Folding, for 6612 // example, can cause multiple logical lines to appear on the same 6613 // visual line. This finds the start of the visual line that the 6614 // given line is part of (usually that is the line itself). 6615 function visualLine(line) { 6616 var merged; 6617 while (merged = collapsedSpanAtStart(line)) 6618 line = merged.find(-1, true).line; 6619 return line; 6620 } 6621 6622 // Returns an array of logical lines that continue the visual line 6623 // started by the argument, or undefined if there are no such lines. 6624 function visualLineContinued(line) { 6625 var merged, lines; 6626 while (merged = collapsedSpanAtEnd(line)) { 6627 line = merged.find(1, true).line; 6628 (lines || (lines = [])).push(line); 6629 } 6630 return lines; 6631 } 6632 6633 // Get the line number of the start of the visual line that the 6634 // given line number is part of. 6635 function visualLineNo(doc, lineN) { 6636 var line = getLine(doc, lineN), vis = visualLine(line); 6637 if (line == vis) return lineN; 6638 return lineNo(vis); 6639 } 6640 // Get the line number of the start of the next visual line after 6641 // the given line. 6642 function visualLineEndNo(doc, lineN) { 6643 if (lineN > doc.lastLine()) return lineN; 6644 var line = getLine(doc, lineN), merged; 6645 if (!lineIsHidden(doc, line)) return lineN; 6646 while (merged = collapsedSpanAtEnd(line)) 6647 line = merged.find(1, true).line; 6648 return lineNo(line) + 1; 6649 } 6650 6651 // Compute whether a line is hidden. Lines count as hidden when they 6652 // are part of a visual line that starts with another line, or when 6653 // they are entirely covered by collapsed, non-widget span. 6654 function lineIsHidden(doc, line) { 6655 var sps = sawCollapsedSpans && line.markedSpans; 6656 if (sps) for (var sp, i = 0; i < sps.length; ++i) { 6657 sp = sps[i]; 6658 if (!sp.marker.collapsed) continue; 6659 if (sp.from == null) return true; 6660 if (sp.marker.widgetNode) continue; 6661 if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) 6662 return true; 6663 } 6664 } 6665 function lineIsHiddenInner(doc, line, span) { 6666 if (span.to == null) { 6667 var end = span.marker.find(1, true); 6668 return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); 6669 } 6670 if (span.marker.inclusiveRight && span.to == line.text.length) 6671 return true; 6672 for (var sp, i = 0; i < line.markedSpans.length; ++i) { 6673 sp = line.markedSpans[i]; 6674 if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && 6675 (sp.to == null || sp.to != span.from) && 6676 (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && 6677 lineIsHiddenInner(doc, line, sp)) return true; 6678 } 6679 } 6680 6681 // LINE WIDGETS 6682 6683 // Line widgets are block elements displayed above or below a line. 6684 6685 var LineWidget = CodeMirror.LineWidget = function(doc, node, options) { 6686 if (options) for (var opt in options) if (options.hasOwnProperty(opt)) 6687 this[opt] = options[opt]; 6688 this.doc = doc; 6689 this.node = node; 6690 }; 6691 eventMixin(LineWidget); 6692 6693 function adjustScrollWhenAboveVisible(cm, line, diff) { 6694 if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) 6695 addToScrollPos(cm, null, diff); 6696 } 6697 6698 LineWidget.prototype.clear = function() { 6699 var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); 6700 if (no == null || !ws) return; 6701 for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); 6702 if (!ws.length) line.widgets = null; 6703 var height = widgetHeight(this); 6704 updateLineHeight(line, Math.max(0, line.height - height)); 6705 if (cm) runInOp(cm, function() { 6706 adjustScrollWhenAboveVisible(cm, line, -height); 6707 regLineChange(cm, no, "widget"); 6708 }); 6709 }; 6710 LineWidget.prototype.changed = function() { 6711 var oldH = this.height, cm = this.doc.cm, line = this.line; 6712 this.height = null; 6713 var diff = widgetHeight(this) - oldH; 6714 if (!diff) return; 6715 updateLineHeight(line, line.height + diff); 6716 if (cm) runInOp(cm, function() { 6717 cm.curOp.forceUpdate = true; 6718 adjustScrollWhenAboveVisible(cm, line, diff); 6719 }); 6720 }; 6721 6722 function widgetHeight(widget) { 6723 if (widget.height != null) return widget.height; 6724 var cm = widget.doc.cm; 6725 if (!cm) return 0; 6726 if (!contains(document.body, widget.node)) { 6727 var parentStyle = "position: relative;"; 6728 if (widget.coverGutter) 6729 parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; 6730 if (widget.noHScroll) 6731 parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; 6732 removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); 6733 } 6734 return widget.height = widget.node.parentNode.offsetHeight; 6735 } 6736 6737 function addLineWidget(doc, handle, node, options) { 6738 var widget = new LineWidget(doc, node, options); 6739 var cm = doc.cm;
6740 if (cm && widget.noHScroll) cm.display.alignWidgets = true; 6741 changeLine(doc, handle, "widget", function(line) { 6742 var widgets = line.widgets || (line.widgets = []); 6743 if (widget.insertAt == null) widgets.push(widget); 6744 else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); 6745 widget.line = line; 6746 if (cm && !lineIsHidden(doc, line)) { 6747 var aboveVisible = heightAtLine(line) < doc.scrollTop; 6748 updateLineHeight(line, line.height + widgetHeight(widget)); 6749 if (aboveVisible) addToScrollPos(cm, null, widget.height); 6750 cm.curOp.forceUpdate = true; 6751 } 6752 return true; 6753 }); 6754 return widget; 6755 } 6756 6757 // LINE DATA STRUCTURE 6758 6759 // Line objects. These hold state related to a line, including 6760 // highlighting info (the styles array). 6761 var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) { 6762 this.text = text; 6763 attachMarkedSpans(this, markedSpans); 6764 this.height = estimateHeight ? estimateHeight(this) : 1; 6765 }; 6766 eventMixin(Line); 6767 Line.prototype.lineNo = function() { return lineNo(this); }; 6768 6769 // Change the content (text, markers) of a line. Automatically 6770 // invalidates cached information and tries to re-estimate the 6771 // line's height. 6772 function updateLine(line, text, markedSpans, estimateHeight) { 6773 line.text = text; 6774 if (line.stateAfter) line.stateAfter = null; 6775 if (line.styles) line.styles = null; 6776 if (line.order != null) line.order = null; 6777 detachMarkedSpans(line); 6778 attachMarkedSpans(line, markedSpans); 6779 var estHeight = estimateHeight ? estimateHeight(line) : 1; 6780 if (estHeight != line.height) updateLineHeight(line, estHeight); 6781 } 6782 6783 // Detach a line from the document tree and its markers. 6784 function cleanUpLine(line) { 6785 line.parent = null; 6786 detachMarkedSpans(line); 6787 } 6788 6789 function extractLineClasses(type, output) { 6790 if (type) for (;;) { 6791 var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); 6792 if (!lineClass) break; 6793 type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); 6794 var prop = lineClass[1] ? "bgClass" : "textClass"; 6795 if (output[prop] == null) 6796 output[prop] = lineClass[2]; 6797 else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) 6798 output[prop] += " " + lineClass[2]; 6799 } 6800 return type; 6801 } 6802 6803 function callBlankLine(mode, state) { 6804 if (mode.blankLine) return mode.blankLine(state); 6805 if (!mode.innerMode) return; 6806 var inner = CodeMirror.innerMode(mode, state); 6807 if (inner.mode.blankLine) return inner.mode.blankLine(inner.state); 6808 } 6809 6810 function readToken(mode, stream, state, inner) { 6811 for (var i = 0; i < 10; i++) { 6812 if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode; 6813 var style = mode.token(stream, state); 6814 if (stream.pos > stream.start) return style; 6815 } 6816 throw new Error("Mode " + mode.name + " failed to advance stream."); 6817 } 6818 6819 // Utility for getTokenAt and getLineTokens 6820 function takeToken(cm, pos, precise, asArray) { 6821 function getObj(copy) { 6822 return {start: stream.start, end: stream.pos, 6823 string: stream.current(), 6824 type: style || null, 6825 state: copy ? copyState(doc.mode, state) : state}; 6826 } 6827 6828 var doc = cm.doc, mode = doc.mode, style; 6829 pos = clipPos(doc, pos); 6830 var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise); 6831 var stream = new StringStream(line.text, cm.options.tabSize), tokens; 6832 if (asArray) tokens = []; 6833 while ((asArray || stream.pos < pos.ch) && !stream.eol()) { 6834 stream.start = stream.pos; 6835 style = readToken(mode, stream, state); 6836 if (asArray) tokens.push(getObj(true)); 6837 } 6838 return asArray ? tokens : getObj(); 6839 } 6840 6841 // Run the given mode's parser over a line, calling f for each token. 6842 function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) { 6843 var flattenSpans = mode.flattenSpans; 6844 if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; 6845 var curStart = 0, curStyle = null; 6846 var stream = new StringStream(text, cm.options.tabSize), style; 6847 var inner = cm.options.addModeClass && [null]; 6848 if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses); 6849 while (!stream.eol()) { 6850 if (stream.pos > cm.options.maxHighlightLength) { 6851 flattenSpans = false;
6852 if (forceToEnd) processLine(cm, text, state, stream.pos); 6853 stream.pos = text.length; 6854 style = null; 6855 } else { 6856 style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses); 6857 } 6858 if (inner) { 6859 var mName = inner[0].name; 6860 if (mName) style = "m-" + (style ? mName + " " + style : mName); 6861 } 6862 if (!flattenSpans || curStyle != style) { 6863 while (curStart < stream.start) { 6864 curStart = Math.min(stream.start, curStart + 5000); 6865 f(curStart, curStyle); 6866 } 6867 curStyle = style; 6868 } 6869 stream.start = stream.pos; 6870 } 6871 while (curStart < stream.pos) { 6872 // Webkit seems to refuse to render text nodes longer than 57444 6873 // characters, and returns inaccurate measurements in nodes 6874 // starting around 5000 chars. 6875 var pos = Math.min(stream.pos, curStart + 5000); 6876 f(pos, curStyle); 6877 curStart = pos; 6878 } 6879 } 6880 6881 // Compute a style array (an array starting with a mode generation 6882 // -- for invalidation -- followed by pairs of end positions and 6883 // style strings), which is used to highlight the tokens on the 6884 // line. 6885 function highlightLine(cm, line, state, forceToEnd) { 6886 // A styles array always starts with a number identifying the 6887 // mode/overlays that it is based on (for easy invalidation). 6888 var st = [cm.state.modeGen], lineClasses = {}; 6889 // Compute the base array of styles 6890 runMode(cm, line.text, cm.doc.mode, state, function(end, style) { 6891 st.push(end, style); 6892 }, lineClasses, forceToEnd); 6893
6894 // Run overlays, adjust style array. 6895 for (var o = 0; o < cm.state.overlays.length; ++o) { 6896 var overlay = cm.state.overlays[o], i = 1, at = 0; 6897 runMode(cm, line.text, overlay.mode, true, function(end, style) { 6898 var start = i; 6899 // Ensure there's a token end at the current position, and that i points at it 6900 while (at < end) { 6901 var i_end = st[i]; 6902 if (i_end > end) 6903 st.splice(i, 1, end, st[i+1], i_end); 6904 i += 2; 6905 at = Math.min(end, i_end); 6906 } 6907 if (!style) return; 6908 if (overlay.opaque) { 6909 st.splice(start, i - start, end, "cm-overlay " + style); 6910 i = start + 2; 6911 } else { 6912 for (; start < i; start += 2) { 6913 var cur = st[start+1]; 6914 st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style; 6915 } 6916 } 6917 }, lineClasses); 6918 } 6919 6920 return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}; 6921 } 6922 6923 function getLineStyles(cm, line, updateFrontier) { 6924 if (!line.styles || line.styles[0] != cm.state.modeGen) { 6925 var state = getStateBefore(cm, lineNo(line)); 6926 var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state); 6927 line.stateAfter = state; 6928 line.styles = result.styles; 6929 if (result.classes) line.styleClasses = result.classes; 6930 else if (line.styleClasses) line.styleClasses = null; 6931 if (updateFrontier === cm.doc.frontier) cm.doc.frontier++; 6932 } 6933 return line.styles; 6934 } 6935 6936 // Lightweight form of highlight -- proceed over this line and 6937 // update state, but don't save a style array. Used for lines that 6938 // aren't currently visible. 6939 function processLine(cm, text, state, startAt) { 6940 var mode = cm.doc.mode; 6941 var stream = new StringStream(text, cm.options.tabSize); 6942 stream.start = stream.pos = startAt || 0; 6943 if (text == "") callBlankLine(mode, state); 6944 while (!stream.eol()) { 6945 readToken(mode, stream, state); 6946 stream.start = stream.pos; 6947 } 6948 } 6949 6950 // Convert a style as returned by a mode (either null, or a string 6951 // containing one or more styles) to a CSS style. This is cached, 6952 // and also looks for line-wide styles. 6953 var styleToClassCache = {}, styleToClassCacheWithMode = {}; 6954 function interpretTokenStyle(style, options) { 6955 if (!style || /^\s*$/.test(style)) return null; 6956 var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; 6957 return cache[style] || 6958 (cache[style] = style.replace(/\S+/g, "cm-$&")); 6959 } 6960 6961 // Render the DOM representation of the text of a line. Also builds 6962 // up a 'line map', which points at the DOM nodes that represent 6963 // specific stretches of text, and is used by the measuring code. 6964 // The returned object contains the DOM node, this map, and 6965 // information about line-wide styles that were set by the mode. 6966 function buildLineContent(cm, lineView) { 6967 // The padding-right forces the element to have a 'border', which 6968 // is needed on Webkit to be able to get line-level bounding 6969 // rectangles for it (in measureChar). 6970 var content = elt("span", null, null, webkit ? "padding-right: .1px" : null); 6971 var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content, 6972 col: 0, pos: 0, cm: cm, 6973 trailingSpace: false, 6974 splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}; 6975 lineView.measure = {}; 6976 6977 // Iterate over the logical lines that make up this visual line. 6978 for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { 6979 var line = i ? lineView.rest[i - 1] : lineView.line, order; 6980 builder.pos = 0; 6981 builder.addToken = buildToken; 6982 // Optionally wire in some hacks into the token-rendering 6983 // algorithm, to deal with browser quirks. 6984 if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) 6985 builder.addToken = buildTokenBadBidi(builder.addToken, order); 6986 builder.map = [];
6987 var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); 6988 insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); 6989 if (line.styleClasses) { 6990 if (line.styleClasses.bgClass) 6991 builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); 6992 if (line.styleClasses.textClass) 6993 builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); 6994 } 6995 6996 // Ensure at least a single node is present, for measuring. 6997 if (builder.map.length == 0) 6998 builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); 6999 7000 // Store the map and a cache object for the current logical line 7001 if (i == 0) { 7002 lineView.measure.map = builder.map; 7003 lineView.measure.cache = {}; 7004 } else { 7005 (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); 7006 (lineView.measure.caches || (lineView.measure.caches = [])).push({}); 7007 } 7008 } 7009 7010 // See issue #2901 7011 if (webkit) { 7012 var last = builder.content.lastChild 7013 if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) 7014 builder.content.className = "cm-tab-wrap-hack"; 7015 } 7016 7017 signal(cm, "renderLine", cm, lineView.line, builder.pre); 7018 if (builder.pre.className)
7019 builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); 7020 7021 return builder; 7022 } 7023 7024 function defaultSpecialCharPlaceholder(ch) { 7025 var token = elt("span", "\u2022", "cm-invalidchar"); 7026 token.title = "\\u" + ch.charCodeAt(0).toString(16); 7027 token.setAttribute("aria-label", token.title); 7028 return token; 7029 } 7030 7031 // Build up the DOM representation for a single token, and add it to 7032 // the line map. Takes care to render special characters separately. 7033 function buildToken(builder, text, style, startStyle, endStyle, title, css) { 7034 if (!text) return; 7035 var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text 7036 var special = builder.cm.state.specialChars, mustWrap = false; 7037 if (!special.test(text)) { 7038 builder.col += text.length; 7039 var content = document.createTextNode(displayText); 7040 builder.map.push(builder.pos, builder.pos + text.length, content); 7041 if (ie && ie_version < 9) mustWrap = true; 7042 builder.pos += text.length; 7043 } else { 7044 var content = document.createDocumentFragment(), pos = 0; 7045 while (true) { 7046 special.lastIndex = pos; 7047 var m = special.exec(text); 7048 var skipped = m ? m.index - pos : text.length - pos; 7049 if (skipped) { 7050 var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); 7051 if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); 7052 else content.appendChild(txt); 7053 builder.map.push(builder.pos, builder.pos + skipped, txt); 7054 builder.col += skipped; 7055 builder.pos += skipped; 7056 } 7057 if (!m) break; 7058 pos += skipped + 1; 7059 if (m[0] == "\t") { 7060 var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; 7061 var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); 7062 txt.setAttribute("role", "presentation"); 7063 txt.setAttribute("cm-text", "\t"); 7064 builder.col += tabWidth; 7065 } else if (m[0] == "\r" || m[0] == "\n") { 7066 var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); 7067 txt.setAttribute("cm-text", m[0]); 7068 builder.col += 1; 7069 } else { 7070 var txt = builder.cm.options.specialCharPlaceholder(m[0]); 7071 txt.setAttribute("cm-text", m[0]); 7072 if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); 7073 else content.appendChild(txt); 7074 builder.col += 1; 7075 } 7076 builder.map.push(builder.pos, builder.pos + 1, txt); 7077 builder.pos++; 7078 } 7079 } 7080 builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32 7081 if (style || startStyle || endStyle || mustWrap || css) { 7082 var fullStyle = style || ""; 7083 if (startStyle) fullStyle += startStyle; 7084 if (endStyle) fullStyle += endStyle; 7085 var token = elt("span", [content], fullStyle, css); 7086 if (title) token.title = title; 7087 return builder.content.appendChild(token); 7088 } 7089 builder.content.appendChild(content); 7090 } 7091 7092 function splitSpaces(text, trailingBefore) { 7093 if (text.length > 1 && !/ /.test(text)) return text 7094 var spaceBefore = trailingBefore, result = "" 7095 for (var i = 0; i < text.length; i++) { 7096 var ch = text.charAt(i) 7097 if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) 7098 ch = "\u00a0" 7099 result += ch 7100 spaceBefore = ch == " " 7101 } 7102 return result 7103 } 7104 7105 // Work around nonsense dimensions being reported for stretches of 7106 // right-to-left text. 7107 function buildTokenBadBidi(inner, order) { 7108 return function(builder, text, style, startStyle, endStyle, title, css) { 7109 style = style ? style + " cm-force-border" : "cm-force-border"; 7110 var start = builder.pos, end = start + text.length; 7111 for (;;) { 7112 // Find the part that overlaps with the start of this text 7113 for (var i = 0; i < order.length; i++) { 7114 var part = order[i]; 7115 if (part.to > start && part.from <= start) break; 7116 } 7117 if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css); 7118 inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css); 7119 startStyle = null; 7120 text = text.slice(part.to - start); 7121 start = part.to; 7122 } 7123 }; 7124 } 7125 7126 function buildCollapsedSpan(builder, size, marker, ignoreWidget) { 7127 var widget = !ignoreWidget && marker.widgetNode; 7128 if (widget) builder.map.push(builder.pos, builder.pos + size, widget); 7129 if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { 7130 if (!widget) 7131 widget = builder.content.appendChild(document.createElement("span")); 7132 widget.setAttribute("cm-marker", marker.id); 7133 } 7134 if (widget) { 7135 builder.cm.display.input.setUneditable(widget); 7136 builder.content.appendChild(widget); 7137 } 7138 builder.pos += size; 7139 builder.trailingSpace = false 7140 } 7141 7142 // Outputs a number of spans to make up a line, taking highlighting 7143 // and marked text into account. 7144 function insertLineContent(line, builder, styles) { 7145 var spans = line.markedSpans, allText = line.text, at = 0; 7146 if (!spans) { 7147 for (var i = 1; i < styles.length; i+=2) 7148 builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options)); 7149 return; 7150 } 7151 7152 var len = allText.length, pos = 0, i = 1, text = "", style, css; 7153 var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; 7154 for (;;) { 7155 if (nextChange == pos) { // Update current marker set 7156 spanStyle = spanEndStyle = spanStartStyle = title = css = ""; 7157 collapsed = null; nextChange = Infinity; 7158 var foundBookmarks = [], endStyles 7159 for (var j = 0; j < spans.length; ++j) { 7160 var sp = spans[j], m = sp.marker; 7161 if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { 7162 foundBookmarks.push(m); 7163 } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { 7164 if (sp.to != null && sp.to != pos && nextChange > sp.to) { 7165 nextChange = sp.to; 7166 spanEndStyle = ""; 7167 } 7168 if (m.className) spanStyle += " " + m.className; 7169 if (m.css) css = (css ? css + ";" : "") + m.css; 7170 if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; 7171 if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to) 7172 if (m.title && !title) title = m.title; 7173 if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) 7174 collapsed = sp; 7175 } else if (sp.from > pos && nextChange > sp.from) { 7176 nextChange = sp.from; 7177 } 7178 } 7179 if (endStyles) for (var j = 0; j < endStyles.length; j += 2) 7180 if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j] 7181 7182 if (!collapsed || collapsed.from == pos) for (var j = 0; j < foundBookmarks.length; ++j) 7183 buildCollapsedSpan(builder, 0, foundBookmarks[j]); 7184 if (collapsed && (collapsed.from || 0) == pos) { 7185 buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, 7186 collapsed.marker, collapsed.from == null); 7187 if (collapsed.to == null) return; 7188 if (collapsed.to == pos) collapsed = false;
7189 } 7190 } 7191 if (pos >= len) break; 7192 7193 var upto = Math.min(len, nextChange); 7194 while (true) { 7195 if (text) { 7196 var end = pos + text.length; 7197 if (!collapsed) { 7198 var tokenText = end > upto ? text.slice(0, upto - pos) : text; 7199 builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, 7200 spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css); 7201 } 7202 if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} 7203 pos = end; 7204 spanStartStyle = ""; 7205 } 7206 text = allText.slice(at, at = styles[i++]); 7207 style = interpretTokenStyle(styles[i++], builder.cm.options); 7208 } 7209 } 7210 } 7211 7212 // DOCUMENT DATA STRUCTURE 7213 7214 // By default, updates that start and end at the beginning of a line 7215 // are treated specially, in order to make the association of line 7216 // widgets and marker elements with the text behave more intuitive. 7217 function isWholeLineUpdate(doc, change) { 7218 return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && 7219 (!doc.cm || doc.cm.options.wholeLineUpdateBefore); 7220 } 7221 7222 // Perform a change on the document data structure. 7223 function updateDoc(doc, change, markedSpans, estimateHeight) { 7224 function spansFor(n) {return markedSpans ? markedSpans[n] : null;} 7225 function update(line, text, spans) { 7226 updateLine(line, text, spans, estimateHeight); 7227 signalLater(line, "change", line, change); 7228 } 7229 function linesFor(start, end) { 7230 for (var i = start, result = []; i < end; ++i) 7231 result.push(new Line(text[i], spansFor(i), estimateHeight)); 7232 return result; 7233 } 7234 7235 var from = change.from, to = change.to, text = change.text; 7236 var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); 7237 var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; 7238 7239 // Adjust the line structure 7240 if (change.full) { 7241 doc.insert(0, linesFor(0, text.length)); 7242 doc.remove(text.length, doc.size - text.length); 7243 } else if (isWholeLineUpdate(doc, change)) { 7244 // This is a whole-line replace. Treated specially to make 7245 // sure line objects move the way they are supposed to. 7246 var added = linesFor(0, text.length - 1); 7247 update(lastLine, lastLine.text, lastSpans); 7248 if (nlines) doc.remove(from.line, nlines); 7249 if (added.length) doc.insert(from.line, added); 7250 } else if (firstLine == lastLine) { 7251 if (text.length == 1) { 7252 update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); 7253 } else { 7254 var added = linesFor(1, text.length - 1); 7255 added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); 7256 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); 7257 doc.insert(from.line + 1, added); 7258 } 7259 } else if (text.length == 1) { 7260 update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); 7261 doc.remove(from.line + 1, nlines); 7262 } else { 7263 update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); 7264 update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); 7265 var added = linesFor(1, text.length - 1); 7266 if (nlines > 1) doc.remove(from.line + 1, nlines - 1); 7267 doc.insert(from.line + 1, added); 7268 } 7269 7270 signalLater(doc, "change", doc, change); 7271 } 7272 7273 // The document is represented as a BTree consisting of leaves, with 7274 // chunk of lines in them, and branches, with up to ten leaves or 7275 // other branch nodes below them. The top node is always a branch 7276 // node, and is the document object itself (meaning it has 7277 // additional methods and properties). 7278 // 7279 // All nodes have parent links. The tree is used both to go from 7280 // line numbers to line objects, and to go from objects to numbers. 7281 // It also indexes by height, and is used to convert between height 7282 // and line object, and to find the total height of the document. 7283 // 7284 // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html 7285 7286 function LeafChunk(lines) { 7287 this.lines = lines; 7288 this.parent = null; 7289 for (var i = 0, height = 0; i < lines.length; ++i) { 7290 lines[i].parent = this; 7291 height += lines[i].height; 7292 } 7293 this.height = height; 7294 } 7295 7296 LeafChunk.prototype = { 7297 chunkSize: function() { return this.lines.length; }, 7298 // Remove the n lines at offset 'at'. 7299 removeInner: function(at, n) { 7300 for (var i = at, e = at + n; i < e; ++i) { 7301 var line = this.lines[i];
7302 this.height -= line.height; 7303 cleanUpLine(line); 7304 signalLater(line, "delete"); 7305 } 7306 this.lines.splice(at, n); 7307 }, 7308 // Helper used to collapse a small branch into a single leaf. 7309 collapse: function(lines) { 7310 lines.push.apply(lines, this.lines); 7311 }, 7312 // Insert the given array of lines at offset 'at', count them as 7313 // having the given height. 7314 insertInner: function(at, lines, height) { 7315 this.height += height; 7316 this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); 7317 for (var i = 0; i < lines.length; ++i) lines[i].parent = this; 7318 }, 7319 // Used to iterate over a part of the tree. 7320 iterN: function(at, n, op) { 7321 for (var e = at + n; at < e; ++at) 7322 if (op(this.lines[at])) return true; 7323 } 7324 }; 7325 7326 function BranchChunk(children) { 7327 this.children = children; 7328 var size = 0, height = 0; 7329 for (var i = 0; i < children.length; ++i) { 7330 var ch = children[i]; 7331 size += ch.chunkSize(); height += ch.height; 7332 ch.parent = this; 7333 } 7334 this.size = size; 7335 this.height = height; 7336 this.parent = null; 7337 } 7338 7339 BranchChunk.prototype = { 7340 chunkSize: function() { return this.size; }, 7341 removeInner: function(at, n) { 7342 this.size -= n; 7343 for (var i = 0; i < this.children.length; ++i) { 7344 var child = this.children[i], sz = child.chunkSize(); 7345 if (at < sz) { 7346 var rm = Math.min(n, sz - at), oldHeight = child.height; 7347 child.removeInner(at, rm); 7348 this.height -= oldHeight - child.height; 7349 if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } 7350 if ((n -= rm) == 0) break; 7351 at = 0; 7352 } else at -= sz; 7353 } 7354 // If the result is smaller than 25 lines, ensure that it is a 7355 // single leaf node. 7356 if (this.size - n < 25 && 7357 (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { 7358 var lines = []; 7359 this.collapse(lines); 7360 this.children = [new LeafChunk(lines)]; 7361 this.children[0].parent = this; 7362 } 7363 }, 7364 collapse: function(lines) { 7365 for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines); 7366 }, 7367 insertInner: function(at, lines, height) { 7368 this.size += lines.length; 7369 this.height += height; 7370 for (var i = 0; i < this.children.length; ++i) { 7371 var child = this.children[i], sz = child.chunkSize(); 7372 if (at <= sz) { 7373 child.insertInner(at, lines, height); 7374 if (child.lines && child.lines.length > 50) { 7375 // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. 7376 // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. 7377 var remaining = child.lines.length % 25 + 25 7378 for (var pos = remaining; pos < child.lines.length;) { 7379 var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); 7380 child.height -= leaf.height; 7381 this.children.splice(++i, 0, leaf); 7382 leaf.parent = this; 7383 } 7384 child.lines = child.lines.slice(0, remaining); 7385 this.maybeSpill(); 7386 } 7387 break; 7388 } 7389 at -= sz; 7390 } 7391 }, 7392 // When a node has grown, check whether it should be split. 7393 maybeSpill: function() { 7394 if (this.children.length <= 10) return; 7395 var me = this; 7396 do { 7397 var spilled = me.children.splice(me.children.length - 5, 5); 7398 var sibling = new BranchChunk(spilled); 7399 if (!me.parent) { // Become the parent node 7400 var copy = new BranchChunk(me.children); 7401 copy.parent = me; 7402 me.children = [copy, sibling]; 7403 me = copy; 7404 } else { 7405 me.size -= sibling.size; 7406 me.height -= sibling.height; 7407 var myIndex = indexOf(me.parent.children, me); 7408 me.parent.children.splice(myIndex + 1, 0, sibling); 7409 } 7410 sibling.parent = me.parent; 7411 } while (me.children.length > 10); 7412 me.parent.maybeSpill(); 7413 }, 7414 iterN: function(at, n, op) { 7415 for (var i = 0; i < this.children.length; ++i) { 7416 var child = this.children[i], sz = child.chunkSize(); 7417 if (at < sz) { 7418 var used = Math.min(n, sz - at); 7419 if (child.iterN(at, used, op)) return true; 7420 if ((n -= used) == 0) break; 7421 at = 0; 7422 } else at -= sz; 7423 } 7424 } 7425 }; 7426 7427 var nextDocId = 0; 7428 var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) { 7429 if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep); 7430 if (firstLine == null) firstLine = 0; 7431 7432 BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); 7433 this.first = firstLine; 7434 this.scrollTop = this.scrollLeft = 0; 7435 this.cantEdit = false;
7436 this.cleanGeneration = 1; 7437 this.frontier = firstLine; 7438 var start = Pos(firstLine, 0); 7439 this.sel = simpleSelection(start); 7440 this.history = new History(null); 7441 this.id = ++nextDocId; 7442 this.modeOption = mode; 7443 this.lineSep = lineSep; 7444 this.extend = false; 7445 7446 if (typeof text == "string") text = this.splitLines(text); 7447 updateDoc(this, {from: start, to: start, text: text}); 7448 setSelection(this, simpleSelection(start), sel_dontScroll); 7449 }; 7450 7451 Doc.prototype = createObj(BranchChunk.prototype, { 7452 constructor: Doc, 7453 // Iterate over the document. Supports two forms -- with only one 7454 // argument, it calls that for each line in the document. With 7455 // three, it iterates over the range given by the first two (with 7456 // the second being non-inclusive). 7457 iter: function(from, to, op) { 7458 if (op) this.iterN(from - this.first, to - from, op); 7459 else this.iterN(this.first, this.first + this.size, from); 7460 }, 7461 7462 // Non-public interface for adding and removing lines. 7463 insert: function(at, lines) { 7464 var height = 0; 7465 for (var i = 0; i < lines.length; ++i) height += lines[i].height; 7466 this.insertInner(at - this.first, lines, height); 7467 }, 7468 remove: function(at, n) { this.removeInner(at - this.first, n); }, 7469 7470 // From here, the methods are part of the public interface. Most 7471 // are also available from CodeMirror (editor) instances. 7472 7473 getValue: function(lineSep) { 7474 var lines = getLines(this, this.first, this.first + this.size); 7475 if (lineSep === false) return lines; 7476 return lines.join(lineSep || this.lineSeparator()); 7477 }, 7478 setValue: docMethodOp(function(code) { 7479 var top = Pos(this.first, 0), last = this.first + this.size - 1; 7480 makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), 7481 text: this.splitLines(code), origin: "setValue", full: true}, true); 7482 setSelection(this, simpleSelection(top)); 7483 }), 7484 replaceRange: function(code, from, to, origin) { 7485 from = clipPos(this, from); 7486 to = to ? clipPos(this, to) : from; 7487 replaceRange(this, code, from, to, origin); 7488 }, 7489 getRange: function(from, to, lineSep) { 7490 var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); 7491 if (lineSep === false) return lines; 7492 return lines.join(lineSep || this.lineSeparator()); 7493 }, 7494 7495 getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, 7496 7497 getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);}, 7498 getLineNumber: function(line) {return lineNo(line);}, 7499 7500 getLineHandleVisualStart: function(line) { 7501 if (typeof line == "number") line = getLine(this, line); 7502 return visualLine(line); 7503 }, 7504 7505 lineCount: function() {return this.size;}, 7506 firstLine: function() {return this.first;}, 7507 lastLine: function() {return this.first + this.size - 1;}, 7508 7509 clipPos: function(pos) {return clipPos(this, pos);}, 7510 7511 getCursor: function(start) { 7512 var range = this.sel.primary(), pos; 7513 if (start == null || start == "head") pos = range.head; 7514 else if (start == "anchor") pos = range.anchor; 7515 else if (start == "end" || start == "to" || start === false) pos = range.to(); 7516 else pos = range.from(); 7517 return pos; 7518 }, 7519 listSelections: function() { return this.sel.ranges; }, 7520 somethingSelected: function() {return this.sel.somethingSelected();}, 7521 7522 setCursor: docMethodOp(function(line, ch, options) { 7523 setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); 7524 }), 7525 setSelection: docMethodOp(function(anchor, head, options) { 7526 setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); 7527 }), 7528 extendSelection: docMethodOp(function(head, other, options) { 7529 extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); 7530 }), 7531 extendSelections: docMethodOp(function(heads, options) { 7532 extendSelections(this, clipPosArray(this, heads), options); 7533 }), 7534 extendSelectionsBy: docMethodOp(function(f, options) { 7535 var heads = map(this.sel.ranges, f); 7536 extendSelections(this, clipPosArray(this, heads), options); 7537 }), 7538 setSelections: docMethodOp(function(ranges, primary, options) { 7539 if (!ranges.length) return; 7540 for (var i = 0, out = []; i < ranges.length; i++) 7541 out[i] = new Range(clipPos(this, ranges[i].anchor), 7542 clipPos(this, ranges[i].head)); 7543 if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex); 7544 setSelection(this, normalizeSelection(out, primary), options); 7545 }), 7546 addSelection: docMethodOp(function(anchor, head, options) { 7547 var ranges = this.sel.ranges.slice(0); 7548 ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); 7549 setSelection(this, normalizeSelection(ranges, ranges.length - 1), options); 7550 }), 7551 7552 getSelection: function(lineSep) { 7553 var ranges = this.sel.ranges, lines; 7554 for (var i = 0; i < ranges.length; i++) { 7555 var sel = getBetween(this, ranges[i].from(), ranges[i].to()); 7556 lines = lines ? lines.concat(sel) : sel; 7557 } 7558 if (lineSep === false) return lines; 7559 else return lines.join(lineSep || this.lineSeparator()); 7560 }, 7561 getSelections: function(lineSep) { 7562 var parts = [], ranges = this.sel.ranges; 7563 for (var i = 0; i < ranges.length; i++) { 7564 var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7565 if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator()); 7566 parts[i] = sel; 7567 } 7568 return parts; 7569 }, 7570 replaceSelection: function(code, collapse, origin) { 7571 var dup = []; 7572 for (var i = 0; i < this.sel.ranges.length; i++) 7573 dup[i] = code; 7574 this.replaceSelections(dup, collapse, origin || "+input"); 7575 }, 7576 replaceSelections: docMethodOp(function(code, collapse, origin) { 7577 var changes = [], sel = this.sel; 7578 for (var i = 0; i < sel.ranges.length; i++) { 7579 var range = sel.ranges[i]; 7580 changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin}; 7581 } 7582 var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); 7583 for (var i = changes.length - 1; i >= 0; i--) 7584 makeChange(this, changes[i]); 7585 if (newSel) setSelectionReplaceHistory(this, newSel); 7586 else if (this.cm) ensureCursorVisible(this.cm); 7587 }), 7588 undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), 7589 redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), 7590 undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), 7591 redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), 7592 7593 setExtending: function(val) {this.extend = val;}, 7594 getExtending: function() {return this.extend;}, 7595 7596 historySize: function() { 7597 var hist = this.history, done = 0, undone = 0; 7598 for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done; 7599 for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone; 7600 return {undo: done, redo: undone}; 7601 }, 7602 clearHistory: function() {this.history = new History(this.history.maxGeneration);}, 7603 7604 markClean: function() { 7605 this.cleanGeneration = this.changeGeneration(true); 7606 }, 7607 changeGeneration: function(forceSplit) { 7608 if (forceSplit) 7609 this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; 7610 return this.history.generation; 7611 }, 7612 isClean: function (gen) { 7613 return this.history.generation == (gen || this.cleanGeneration); 7614 }, 7615 7616 getHistory: function() { 7617 return {done: copyHistoryArray(this.history.done), 7618 undone: copyHistoryArray(this.history.undone)}; 7619 }, 7620 setHistory: function(histData) { 7621 var hist = this.history = new History(this.history.maxGeneration); 7622 hist.done = copyHistoryArray(histData.done.slice(0), null, true); 7623 hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); 7624 }, 7625 7626 addLineClass: docMethodOp(function(handle, where, cls) { 7627 return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { 7628 var prop = where == "text" ? "textClass" 7629 : where == "background" ? "bgClass" 7630 : where == "gutter" ? "gutterClass" : "wrapClass"; 7631 if (!line[prop]) line[prop] = cls; 7632 else if (classTest(cls).test(line[prop])) return false; 7633 else line[prop] += " " + cls; 7634 return true; 7635 }); 7636 }), 7637 removeLineClass: docMethodOp(function(handle, where, cls) { 7638 return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { 7639 var prop = where == "text" ? "textClass" 7640 : where == "background" ? "bgClass" 7641 : where == "gutter" ? "gutterClass" : "wrapClass"; 7642 var cur = line[prop]; 7643 if (!cur) return false; 7644 else if (cls == null) line[prop] = null; 7645 else { 7646 var found = cur.match(classTest(cls)); 7647 if (!found) return false; 7648 var end = found.index + found[0].length; 7649 line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; 7650 } 7651 return true; 7652 }); 7653 }), 7654 7655 addLineWidget: docMethodOp(function(handle, node, options) { 7656 return addLineWidget(this, handle, node, options); 7657 }), 7658 removeLineWidget: function(widget) { widget.clear(); }, 7659 7660 markText: function(from, to, options) { 7661 return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range"); 7662 }, 7663 setBookmark: function(pos, options) { 7664 var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), 7665 insertLeft: options && options.insertLeft, 7666 clearWhenEmpty: false, shared: options && options.shared, 7667 handleMouseEvents: options && options.handleMouseEvents}; 7668 pos = clipPos(this, pos); 7669 return markText(this, pos, pos, realOpts, "bookmark"); 7670 }, 7671 findMarksAt: function(pos) { 7672 pos = clipPos(this, pos); 7673 var markers = [], spans = getLine(this, pos.line).markedSpans; 7674 if (spans) for (var i = 0; i < spans.length; ++i) { 7675 var span = spans[i]; 7676 if ((span.from == null || span.from <= pos.ch) && 7677 (span.to == null || span.to >= pos.ch)) 7678 markers.push(span.marker.parent || span.marker); 7679 } 7680 return markers; 7681 }, 7682 findMarks: function(from, to, filter) { 7683 from = clipPos(this, from); to = clipPos(this, to); 7684 var found = [], lineNo = from.line; 7685 this.iter(from.line, to.line + 1, function(line) { 7686 var spans = line.markedSpans; 7687 if (spans) for (var i = 0; i < spans.length; i++) { 7688 var span = spans[i]; 7689 if (!(span.to != null && lineNo == from.line && from.ch >= span.to || 7690 span.from == null && lineNo != from.line || 7691 span.from != null && lineNo == to.line && span.from >= to.ch) && 7692 (!filter || filter(span.marker))) 7693 found.push(span.marker.parent || span.marker); 7694 } 7695 ++lineNo; 7696 }); 7697 return found; 7698 }, 7699 getAllMarks: function() { 7700 var markers = []; 7701 this.iter(function(line) { 7702 var sps = line.markedSpans; 7703 if (sps) for (var i = 0; i < sps.length; ++i) 7704 if (sps[i].from != null) markers.push(sps[i].marker); 7705 }); 7706 return markers; 7707 }, 7708 7709 posFromIndex: function(off) { 7710 var ch, lineNo = this.first, sepSize = this.lineSeparator().length; 7711 this.iter(function(line) { 7712 var sz = line.text.length + sepSize; 7713 if (sz > off) { ch = off; return true; } 7714 off -= sz; 7715 ++lineNo; 7716 }); 7717 return clipPos(this, Pos(lineNo, ch)); 7718 }, 7719 indexFromPos: function (coords) { 7720 coords = clipPos(this, coords); 7721 var index = coords.ch; 7722 if (coords.line < this.first || coords.ch < 0) return 0; 7723 var sepSize = this.lineSeparator().length; 7724 this.iter(this.first, coords.line, function (line) { 7725 index += line.text.length + sepSize; 7726 }); 7727 return index; 7728 }, 7729 7730 copy: function(copyHistory) { 7731 var doc = new Doc(getLines(this, this.first, this.first + this.size), 7732 this.modeOption, this.first, this.lineSep); 7733 doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; 7734 doc.sel = this.sel; 7735 doc.extend = false;
7736 if (copyHistory) { 7737 doc.history.undoDepth = this.history.undoDepth; 7738 doc.setHistory(this.getHistory()); 7739 } 7740 return doc; 7741 }, 7742 7743 linkedDoc: function(options) { 7744 if (!options) options = {}; 7745 var from = this.first, to = this.first + this.size; 7746 if (options.from != null && options.from > from) from = options.from; 7747 if (options.to != null && options.to < to) to = options.to; 7748 var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep); 7749 if (options.sharedHist) copy.history = this.history; 7750 (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); 7751 copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; 7752 copySharedMarkers(copy, findSharedMarkers(this)); 7753 return copy; 7754 }, 7755 unlinkDoc: function(other) { 7756 if (other instanceof CodeMirror) other = other.doc; 7757 if (this.linked) for (var i = 0; i < this.linked.length; ++i) { 7758 var link = this.linked[i]; 7759 if (link.doc != other) continue; 7760 this.linked.splice(i, 1); 7761 other.unlinkDoc(this); 7762 detachSharedMarkers(findSharedMarkers(this)); 7763 break; 7764 } 7765 // If the histories were shared, split them again 7766 if (other.history == this.history) { 7767 var splitIds = [other.id]; 7768 linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); 7769 other.history = new History(null); 7770 other.history.done = copyHistoryArray(this.history.done, splitIds); 7771 other.history.undone = copyHistoryArray(this.history.undone, splitIds); 7772 } 7773 }, 7774 iterLinkedDocs: function(f) {linkedDocs(this, f);}, 7775 7776 getMode: function() {return this.mode;}, 7777 getEditor: function() {return this.cm;}, 7778 7779 splitLines: function(str) { 7780 if (this.lineSep) return str.split(this.lineSep); 7781 return splitLinesAuto(str); 7782 }, 7783 lineSeparator: function() { return this.lineSep || "\n"; } 7784 }); 7785 7786 // Public alias. 7787 Doc.prototype.eachLine = Doc.prototype.iter; 7788 7789 // Set up methods on CodeMirror's prototype to redirect to the editor's document. 7790 var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); 7791 for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) 7792 CodeMirror.prototype[prop] = (function(method) { 7793 return function() {return method.apply(this.doc, arguments);}; 7794 })(Doc.prototype[prop]); 7795 7796 eventMixin(Doc); 7797 7798 // Call f for all linked documents. 7799 function linkedDocs(doc, f, sharedHistOnly) { 7800 function propagate(doc, skip, sharedHist) { 7801 if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { 7802 var rel = doc.linked[i]; 7803 if (rel.doc == skip) continue; 7804 var shared = sharedHist && rel.sharedHist; 7805 if (sharedHistOnly && !shared) continue; 7806 f(rel.doc, shared); 7807 propagate(rel.doc, doc, shared); 7808 } 7809 } 7810 propagate(doc, null, true); 7811 } 7812 7813 // Attach a document to an editor. 7814 function attachDoc(cm, doc) { 7815 if (doc.cm) throw new Error("This document is already in use."); 7816 cm.doc = doc; 7817 doc.cm = cm; 7818 estimateLineHeights(cm); 7819 loadMode(cm); 7820 if (!cm.options.lineWrapping) findMaxLine(cm); 7821 cm.options.mode = doc.modeOption; 7822 regChange(cm); 7823 } 7824 7825 // LINE UTILITIES 7826 7827 // Find the line object corresponding to the given line number. 7828 function getLine(doc, n) { 7829 n -= doc.first; 7830 if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document."); 7831 for (var chunk = doc; !chunk.lines;) { 7832 for (var i = 0;; ++i) { 7833 var child = chunk.children[i], sz = child.chunkSize(); 7834 if (n < sz) { chunk = child; break; } 7835 n -= sz; 7836 } 7837 } 7838 return chunk.lines[n]; 7839 } 7840 7841 // Get the part of a document between two positions, as an array of 7842 // strings. 7843 function getBetween(doc, start, end) { 7844 var out = [], n = start.line; 7845 doc.iter(start.line, end.line + 1, function(line) { 7846 var text = line.text; 7847 if (n == end.line) text = text.slice(0, end.ch); 7848 if (n == start.line) text = text.slice(start.ch); 7849 out.push(text); 7850 ++n; 7851 }); 7852 return out; 7853 }
7854 // Get the lines between from and to, as array of strings. 7855 function getLines(doc, from, to) { 7856 var out = []; 7857 doc.iter(from, to, function(line) { out.push(line.text); }); 7858 return out; 7859 } 7860 7861 // Update the height of a line, propagating the height change 7862 // upwards to parent nodes. 7863 function updateLineHeight(line, height) { 7864 var diff = height - line.height; 7865 if (diff) for (var n = line; n; n = n.parent) n.height += diff; 7866 } 7867 7868 // Given a line object, find its line number by walking up through 7869 // its parent links. 7870 function lineNo(line) { 7871 if (line.parent == null) return null; 7872 var cur = line.parent, no = indexOf(cur.lines, line); 7873 for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { 7874 for (var i = 0;; ++i) { 7875 if (chunk.children[i] == cur) break; 7876 no += chunk.children[i].chunkSize(); 7877 } 7878 } 7879 return no + cur.first; 7880 } 7881 7882 // Find the line at the given vertical position, using the height 7883 // information in the document tree. 7884 function lineAtHeight(chunk, h) { 7885 var n = chunk.first; 7886 outer: do { 7887 for (var i = 0; i < chunk.children.length; ++i) { 7888 var child = chunk.children[i], ch = child.height; 7889 if (h < ch) { chunk = child; continue outer; } 7890 h -= ch; 7891 n += child.chunkSize(); 7892 } 7893 return n; 7894 } while (!chunk.lines); 7895 for (var i = 0; i < chunk.lines.length; ++i) { 7896 var line = chunk.lines[i], lh = line.height; 7897 if (h < lh) break; 7898 h -= lh; 7899 } 7900 return n + i; 7901 } 7902 7903 7904 // Find the height above the given line. 7905 function heightAtLine(lineObj) { 7906 lineObj = visualLine(lineObj); 7907 7908 var h = 0, chunk = lineObj.parent; 7909 for (var i = 0; i < chunk.lines.length; ++i) { 7910 var line = chunk.lines[i]; 7911 if (line == lineObj) break; 7912 else h += line.height; 7913 } 7914 for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { 7915 for (var i = 0; i < p.children.length; ++i) { 7916 var cur = p.children[i]; 7917 if (cur == chunk) break; 7918 else h += cur.height; 7919 } 7920 } 7921 return h; 7922 } 7923 7924 // Get the bidi ordering for the given line (and cache it). Returns 7925 // false for lines that are fully left-to-right, and an array of 7926 // BidiSpan objects otherwise. 7927 function getOrder(line) { 7928 var order = line.order; 7929 if (order == null) order = line.order = bidiOrdering(line.text); 7930 return order; 7931 } 7932 7933 // HISTORY 7934 7935 function History(startGen) { 7936 // Arrays of change events and selections. Doing something adds an 7937 // event to done and clears undo. Undoing moves events from done 7938 // to undone, redoing moves them in the other direction. 7939 this.done = []; this.undone = []; 7940 this.undoDepth = Infinity; 7941 // Used to track when changes can be merged into a single undo 7942 // event 7943 this.lastModTime = this.lastSelTime = 0; 7944 this.lastOp = this.lastSelOp = null; 7945 this.lastOrigin = this.lastSelOrigin = null; 7946 // Used by the isClean() method 7947 this.generation = this.maxGeneration = startGen || 1; 7948 } 7949 7950 // Create a history change event from an updateDoc-style change 7951 // object. 7952 function historyChangeFromChange(doc, change) { 7953 var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; 7954 attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); 7955 linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); 7956 return histChange; 7957 } 7958 7959 // Pop all selection events off the end of a history array. Stop at 7960 // a change event. 7961 function clearSelectionEvents(array) { 7962 while (array.length) { 7963 var last = lst(array); 7964 if (last.ranges) array.pop(); 7965 else break; 7966 } 7967 } 7968 7969 // Find the top change event in the history. Pop off selection 7970 // events that are in the way. 7971 function lastChangeEvent(hist, force) { 7972 if (force) { 7973 clearSelectionEvents(hist.done); 7974 return lst(hist.done); 7975 } else if (hist.done.length && !lst(hist.done).ranges) { 7976 return lst(hist.done); 7977 } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { 7978 hist.done.pop(); 7979 return lst(hist.done); 7980 } 7981 } 7982 7983 // Register a change in the history. Merges changes that are within 7984 // a single operation, or are close together with an origin that 7985 // allows merging (starting with "+") into a single event. 7986 function addChangeToHistory(doc, change, selAfter, opId) { 7987 var hist = doc.history; 7988 hist.undone.length = 0; 7989 var time = +new Date, cur; 7990 7991 if ((hist.lastOp == opId || 7992 hist.lastOrigin == change.origin && change.origin && 7993 ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || 7994 change.origin.charAt(0) == "*")) && 7995 (cur = lastChangeEvent(hist, hist.lastOp == opId))) { 7996 // Merge this change into the last event 7997 var last = lst(cur.changes); 7998 if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { 7999 // Optimized case for simple insertion -- don't want to add 8000 // new changesets for every character typed 8001 last.to = changeEnd(change); 8002 } else { 8003 // Add new sub-event 8004 cur.changes.push(historyChangeFromChange(doc, change)); 8005 } 8006 } else { 8007 // Can not be merged, start a new event. 8008 var before = lst(hist.done); 8009 if (!before || !before.ranges) 8010 pushSelectionToHistory(doc.sel, hist.done); 8011 cur = {changes: [historyChangeFromChange(doc, change)], 8012 generation: hist.generation}; 8013 hist.done.push(cur); 8014 while (hist.done.length > hist.undoDepth) { 8015 hist.done.shift(); 8016 if (!hist.done[0].ranges) hist.done.shift(); 8017 } 8018 } 8019 hist.done.push(selAfter);
8020 hist.generation = ++hist.maxGeneration; 8021 hist.lastModTime = hist.lastSelTime = time; 8022 hist.lastOp = hist.lastSelOp = opId; 8023 hist.lastOrigin = hist.lastSelOrigin = change.origin; 8024 8025 if (!last) signal(doc, "historyAdded"); 8026 } 8027 8028 function selectionEventCanBeMerged(doc, origin, prev, sel) { 8029 var ch = origin.charAt(0); 8030 return ch == "*" || 8031 ch == "+" && 8032 prev.ranges.length == sel.ranges.length && 8033 prev.somethingSelected() == sel.somethingSelected() && 8034 new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); 8035 } 8036 8037 // Called whenever the selection changes, sets the new selection as 8038 // the pending selection in the history, and pushes the old pending 8039 // selection into the 'done' array when it was significantly 8040 // different (in number of selected ranges, emptiness, or time). 8041 function addSelectionToHistory(doc, sel, opId, options) { 8042 var hist = doc.history, origin = options && options.origin; 8043 8044 // A new event is started when the previous origin does not match 8045 // the current, or the origins don't allow matching. Origins 8046 // starting with * are always merged, those starting with + are 8047 // merged when similar and close together in time. 8048 if (opId == hist.lastSelOp || 8049 (origin && hist.lastSelOrigin == origin && 8050 (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || 8051 selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) 8052 hist.done[hist.done.length - 1] = sel; 8053 else 8054 pushSelectionToHistory(sel, hist.done); 8055 8056 hist.lastSelTime = +new Date; 8057 hist.lastSelOrigin = origin; 8058 hist.lastSelOp = opId; 8059 if (options && options.clearRedo !== false) 8060 clearSelectionEvents(hist.undone); 8061 } 8062 8063 function pushSelectionToHistory(sel, dest) { 8064 var top = lst(dest); 8065 if (!(top && top.ranges && top.equals(sel))) 8066 dest.push(sel); 8067 } 8068 8069 // Used to store marked span information in the history. 8070 function attachLocalSpans(doc, change, from, to) { 8071 var existing = change["spans_" + doc.id], n = 0; 8072 doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) { 8073 if (line.markedSpans) 8074 (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; 8075 ++n; 8076 }); 8077 } 8078 8079 // When un/re-doing restores text containing marked spans, those 8080 // that have been explicitly cleared should not be restored. 8081 function removeClearedSpans(spans) { 8082 if (!spans) return null; 8083 for (var i = 0, out; i < spans.length; ++i) { 8084 if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } 8085 else if (out) out.push(spans[i]); 8086 } 8087 return !out ? spans : out.length ? out : null; 8088 } 8089 8090 // Retrieve and filter the old marked spans stored in a change event. 8091 function getOldSpans(doc, change) { 8092 var found = change["spans_" + doc.id]; 8093 if (!found) return null; 8094 for (var i = 0, nw = []; i < change.text.length; ++i) 8095 nw.push(removeClearedSpans(found[i])); 8096 return nw; 8097 } 8098 8099 // Used both to provide a JSON-safe object in .getHistory, and, when 8100 // detaching a document, to split the history in two 8101 function copyHistoryArray(events, newGroup, instantiateSel) { 8102 for (var i = 0, copy = []; i < events.length; ++i) { 8103 var event = events[i]; 8104 if (event.ranges) { 8105 copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); 8106 continue; 8107 } 8108 var changes = event.changes, newChanges = []; 8109 copy.push({changes: newChanges}); 8110 for (var j = 0; j < changes.length; ++j) { 8111 var change = changes[j], m; 8112 newChanges.push({from: change.from, to: change.to, text: change.text}); 8113 if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { 8114 if (indexOf(newGroup, Number(m[1])) > -1) { 8115 lst(newChanges)[prop] = change[prop]; 8116 delete change[prop]; 8117 } 8118 } 8119 } 8120 } 8121 return copy; 8122 } 8123 8124 // Rebasing/resetting history to deal with externally-sourced changes 8125 8126 function rebaseHistSelSingle(pos, from, to, diff) { 8127 if (to < pos.line) { 8128 pos.line += diff; 8129 } else if (from < pos.line) { 8130 pos.line = from; 8131 pos.ch = 0; 8132 } 8133 } 8134 8135 // Tries to rebase an array of history events given a change in the 8136 // document. If the change touches the same lines as the event, the 8137 // event, and everything 'behind' it, is discarded. If the change is 8138 // before the event, the event's positions are updated. Uses a 8139 // copy-on-write scheme for the positions, to avoid having to 8140 // reallocate them all on every rebase, but also avoid problems with 8141 // shared position objects being unsafely updated. 8142 function rebaseHistArray(array, from, to, diff) { 8143 for (var i = 0; i < array.length; ++i) { 8144 var sub = array[i], ok = true; 8145 if (sub.ranges) { 8146 if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } 8147 for (var j = 0; j < sub.ranges.length; j++) { 8148 rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); 8149 rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); 8150 } 8151 continue; 8152 } 8153 for (var j = 0; j < sub.changes.length; ++j) { 8154 var cur = sub.changes[j]; 8155 if (to < cur.from.line) { 8156 cur.from = Pos(cur.from.line + diff, cur.from.ch); 8157 cur.to = Pos(cur.to.line + diff, cur.to.ch); 8158 } else if (from <= cur.to.line) { 8159 ok = false;
8160 break; 8161 } 8162 } 8163 if (!ok) { 8164 array.splice(0, i + 1); 8165 i = 0; 8166 } 8167 } 8168 } 8169 8170 function rebaseHist(hist, change) { 8171 var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; 8172 rebaseHistArray(hist.done, from, to, diff); 8173 rebaseHistArray(hist.undone, from, to, diff); 8174 } 8175 8176 // EVENT UTILITIES 8177 8178 // Due to the fact that we still support jurassic IE versions, some 8179 // compatibility wrappers are needed. 8180 8181 var e_preventDefault = CodeMirror.e_preventDefault = function(e) { 8182 if (e.preventDefault) e.preventDefault(); 8183 else e.returnValue = false; 8184 }; 8185 var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) { 8186 if (e.stopPropagation) e.stopPropagation(); 8187 else e.cancelBubble = true; 8188 }; 8189 function e_defaultPrevented(e) { 8190 return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; 8191 } 8192 var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);}; 8193 8194 function e_target(e) {return e.target || e.srcElement;} 8195 function e_button(e) { 8196 var b = e.which; 8197 if (b == null) { 8198 if (e.button & 1) b = 1; 8199 else if (e.button & 2) b = 3; 8200 else if (e.button & 4) b = 2; 8201 } 8202 if (mac && e.ctrlKey && b == 1) b = 3; 8203 return b; 8204 } 8205 8206 // EVENT HANDLING 8207 8208 // Lightweight event framework. on/off also work on DOM nodes, 8209 // registering native DOM handlers. 8210 8211 var on = CodeMirror.on = function(emitter, type, f) { 8212 if (emitter.addEventListener) 8213 emitter.addEventListener(type, f, false); 8214 else if (emitter.attachEvent) 8215 emitter.attachEvent("on" + type, f); 8216 else { 8217 var map = emitter._handlers || (emitter._handlers = {}); 8218 var arr = map[type] || (map[type] = []); 8219 arr.push(f); 8220 } 8221 }; 8222 8223 var noHandlers = [] 8224 function getHandlers(emitter, type, copy) { 8225 var arr = emitter._handlers && emitter._handlers[type] 8226 if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers 8227 else return arr || noHandlers 8228 } 8229 8230 var off = CodeMirror.off = function(emitter, type, f) { 8231 if (emitter.removeEventListener) 8232 emitter.removeEventListener(type, f, false); 8233 else if (emitter.detachEvent) 8234 emitter.detachEvent("on" + type, f); 8235 else { 8236 var handlers = getHandlers(emitter, type, false) 8237 for (var i = 0; i < handlers.length; ++i) 8238 if (handlers[i] == f) { handlers.splice(i, 1); break; } 8239 } 8240 }; 8241 8242 var signal = CodeMirror.signal = function(emitter, type /*, values...*/) { 8243 var handlers = getHandlers(emitter, type, true) 8244 if (!handlers.length) return; 8245 var args = Array.prototype.slice.call(arguments, 2); 8246 for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args); 8247 }; 8248 8249 var orphanDelayedCallbacks = null; 8250 8251 // Often, we want to signal events at a point where we are in the 8252 // middle of some work, but don't want the handler to start calling 8253 // other methods on the editor, which might be in an inconsistent 8254 // state or simply not expect any other events to happen. 8255 // signalLater looks whether there are any handlers, and schedules 8256 // them to be executed when the last operation ends, or, if no 8257 // operation is active, when a timeout fires. 8258 function signalLater(emitter, type /*, values...*/) { 8259 var arr = getHandlers(emitter, type, false) 8260 if (!arr.length) return; 8261 var args = Array.prototype.slice.call(arguments, 2), list; 8262 if (operationGroup) { 8263 list = operationGroup.delayedCallbacks; 8264 } else if (orphanDelayedCallbacks) { 8265 list = orphanDelayedCallbacks; 8266 } else { 8267 list = orphanDelayedCallbacks = []; 8268 setTimeout(fireOrphanDelayed, 0); 8269 } 8270 function bnd(f) {return function(){f.apply(null, args);};}; 8271 for (var i = 0; i < arr.length; ++i) 8272 list.push(bnd(arr[i])); 8273 } 8274 8275 function fireOrphanDelayed() { 8276 var delayed = orphanDelayedCallbacks; 8277 orphanDelayedCallbacks = null; 8278 for (var i = 0; i < delayed.length; ++i) delayed[i](); 8279 } 8280 8281 // The DOM events that CodeMirror handles can be overridden by 8282 // registering a (non-DOM) handler on the editor for the event name, 8283 // and preventDefault-ing the event in that handler. 8284 function signalDOMEvent(cm, e, override) { 8285 if (typeof e == "string") 8286 e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; 8287 signal(cm, override || e.type, cm, e); 8288 return e_defaultPrevented(e) || e.codemirrorIgnore; 8289 } 8290 8291 function signalCursorActivity(cm) { 8292 var arr = cm._handlers && cm._handlers.cursorActivity; 8293 if (!arr) return; 8294 var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); 8295 for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1) 8296 set.push(arr[i]); 8297 } 8298 8299 function hasHandler(emitter, type) { 8300 return getHandlers(emitter, type).length > 0 8301 } 8302 8303 // Add on and off methods to a constructor's prototype, to make 8304 // registering events on such objects more convenient. 8305 function eventMixin(ctor) { 8306 ctor.prototype.on = function(type, f) {on(this, type, f);}; 8307 ctor.prototype.off = function(type, f) {off(this, type, f);}; 8308 } 8309 8310 // MISC UTILITIES 8311 8312 // Number of pixels added to scroller and sizer to hide scrollbar
8313 var scrollerGap = 30; 8314 8315 // Returned or thrown by various protocols to signal 'I'm not 8316 // handling this'. 8317 var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; 8318 8319 // Reused option objects for setSelection & friends 8320 var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; 8321 8322 function Delayed() {this.id = null;} 8323 Delayed.prototype.set = function(ms, f) { 8324 clearTimeout(this.id); 8325 this.id = setTimeout(f, ms); 8326 }; 8327 8328 // Counts the column offset in a string, taking tabs into account. 8329 // Used mostly to find indentation. 8330 var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) { 8331 if (end == null) { 8332 end = string.search(/[^\s\u00a0]/); 8333 if (end == -1) end = string.length; 8334 } 8335 for (var i = startIndex || 0, n = startValue || 0;;) { 8336 var nextTab = string.indexOf("\t", i); 8337 if (nextTab < 0 || nextTab >= end) 8338 return n + (end - i); 8339 n += nextTab - i; 8340 n += tabSize - (n % tabSize); 8341 i = nextTab + 1; 8342 } 8343 }; 8344 8345 // The inverse of countColumn -- find the offset that corresponds to 8346 // a particular column. 8347 var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) { 8348 for (var pos = 0, col = 0;;) { 8349 var nextTab = string.indexOf("\t", pos); 8350 if (nextTab == -1) nextTab = string.length; 8351 var skipped = nextTab - pos; 8352 if (nextTab == string.length || col + skipped >= goal) 8353 return pos + Math.min(skipped, goal - col); 8354 col += nextTab - pos; 8355 col += tabSize - (col % tabSize); 8356 pos = nextTab + 1; 8357 if (col >= goal) return pos; 8358 } 8359 } 8360 8361 var spaceStrs = [""]; 8362 function spaceStr(n) { 8363 while (spaceStrs.length <= n) 8364 spaceStrs.push(lst(spaceStrs) + " "); 8365 return spaceStrs[n]; 8366 } 8367 8368 function lst(arr) { return arr[arr.length-1]; } 8369 8370 var selectInput = function(node) { node.select(); }; 8371 if (ios) // Mobile Safari apparently has a bug where select() is broken. 8372 selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; 8373 else if (ie) // Suppress mysterious IE10 errors 8374 selectInput = function(node) { try { node.select(); } catch(_e) {} }; 8375 8376 function indexOf(array, elt) { 8377 for (var i = 0; i < array.length; ++i) 8378 if (array[i] == elt) return i; 8379 return -1; 8380 } 8381 function map(array, f) { 8382 var out = []; 8383 for (var i = 0; i < array.length; i++) out[i] = f(array[i], i); 8384 return out; 8385 } 8386 8387 function insertSorted(array, value, score) { 8388 var pos = 0, priority = score(value) 8389 while (pos < array.length && score(array[pos]) <= priority) pos++ 8390 array.splice(pos, 0, value) 8391 } 8392 8393 function nothing() {} 8394 8395 function createObj(base, props) { 8396 var inst; 8397 if (Object.create) { 8398 inst = Object.create(base); 8399 } else { 8400 nothing.prototype = base; 8401 inst = new nothing(); 8402 } 8403 if (props) copyObj(props, inst); 8404 return inst; 8405 }; 8406 8407 function copyObj(obj, target, overwrite) { 8408 if (!target) target = {}; 8409 for (var prop in obj) 8410 if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) 8411 target[prop] = obj[prop]; 8412 return target; 8413 } 8414 8415 function bind(f) { 8416 var args = Array.prototype.slice.call(arguments, 1); 8417 return function(){return f.apply(null, args);}; 8418 } 8419 8420 var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; 8421 var isWordCharBasic = CodeMirror.isWordChar = function(ch) { 8422 return /\w/.test(ch) || ch > "\x80" && 8423 (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); 8424 }; 8425 function isWordChar(ch, helper) { 8426 if (!helper) return isWordCharBasic(ch); 8427 if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true; 8428 return helper.test(ch); 8429 } 8430 8431 function isEmpty(obj) { 8432 for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; 8433 return true; 8434 } 8435 8436 // Extending unicode characters. A series of a non-extending char + 8437 // any number of extending chars is treated as a single unit as far 8438 // as editing and measuring is concerned. This is not fully correct, 8439 // since some scripts/fonts/browsers also treat other configurations 8440 // of code points as a group.
8441 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]/; 8442 function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); } 8443 8444 // DOM UTILITIES 8445 8446 function elt(tag, content, className, style) { 8447 var e = document.createElement(tag); 8448 if (className) e.className = className; 8449 if (style) e.style.cssText = style; 8450 if (typeof content == "string") e.appendChild(document.createTextNode(content)); 8451 else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); 8452 return e; 8453 } 8454 8455 var range; 8456 if (document.createRange) range = function(node, start, end, endNode) { 8457 var r = document.createRange(); 8458 r.setEnd(endNode || node, end); 8459 r.setStart(node, start); 8460 return r; 8461 }; 8462 else range = function(node, start, end) { 8463 var r = document.body.createTextRange(); 8464 try { r.moveToElementText(node.parentNode); } 8465 catch(e) { return r; } 8466 r.collapse(true); 8467 r.moveEnd("character", end); 8468 r.moveStart("character", start); 8469 return r; 8470 }; 8471 8472 function removeChildren(e) { 8473 for (var count = e.childNodes.length; count > 0; --count) 8474 e.removeChild(e.firstChild); 8475 return e; 8476 } 8477 8478 function removeChildrenAndAdd(parent, e) { 8479 return removeChildren(parent).appendChild(e); 8480 } 8481 8482 var contains = CodeMirror.contains = function(parent, child) { 8483 if (child.nodeType == 3) // Android browser always returns false when child is a textnode 8484 child = child.parentNode; 8485 if (parent.contains) 8486 return parent.contains(child); 8487 do { 8488 if (child.nodeType == 11) child = child.host; 8489 if (child == parent) return true; 8490 } while (child = child.parentNode); 8491 }; 8492 8493 function activeElt() { 8494 var activeElement = document.activeElement; 8495 while (activeElement && activeElement.root && activeElement.root.activeElement) 8496 activeElement = activeElement.root.activeElement; 8497 return activeElement; 8498 } 8499 // Older versions of IE throws unspecified error when touching 8500 // document.activeElement in some cases (during loading, in iframe) 8501 if (ie && ie_version < 11) activeElt = function() { 8502 try { return document.activeElement; } 8503 catch(e) { return document.body; } 8504 }; 8505
8506 function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); } 8507 var rmClass = CodeMirror.rmClass = function(node, cls) { 8508 var current = node.className; 8509 var match = classTest(cls).exec(current); 8510 if (match) { 8511 var after = current.slice(match.index + match[0].length); 8512 node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); 8513 } 8514 }; 8515 var addClass = CodeMirror.addClass = function(node, cls) { 8516 var current = node.className; 8517 if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls; 8518 }; 8519 function joinClasses(a, b) { 8520 var as = a.split(" "); 8521 for (var i = 0; i < as.length; i++) 8522 if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i]; 8523 return b; 8524 } 8525 8526 // WINDOW-WIDE EVENTS 8527 8528 // These must be handled carefully, because naively registering a 8529 // handler for each editor will cause the editors to never be 8530 // garbage collected. 8531 8532 function forEachCodeMirror(f) { 8533 if (!document.body.getElementsByClassName) return; 8534 var byClass = document.body.getElementsByClassName("CodeMirror"); 8535 for (var i = 0; i < byClass.length; i++) { 8536 var cm = byClass[i].CodeMirror; 8537 if (cm) f(cm); 8538 } 8539 } 8540 8541 var globalsRegistered = false; 8542 function ensureGlobalHandlers() { 8543 if (globalsRegistered) return; 8544 registerGlobalHandlers(); 8545 globalsRegistered = true; 8546 } 8547 function registerGlobalHandlers() { 8548 // When the window resizes, we need to refresh active editors. 8549 var resizeTimer; 8550 on(window, "resize", function() { 8551 if (resizeTimer == null) resizeTimer = setTimeout(function() { 8552 resizeTimer = null; 8553 forEachCodeMirror(onResize); 8554 }, 100); 8555 }); 8556 // When the window loses focus, we want to show the editor as blurred 8557 on(window, "blur", function() { 8558 forEachCodeMirror(onBlur); 8559 }); 8560 } 8561 8562 // FEATURE DETECTION 8563 8564 // Detect drag-and-drop 8565 var dragAndDrop = function() { 8566 // There is *some* kind of drag-and-drop support in IE6-8, but I 8567 // couldn't get it to work yet. 8568 if (ie && ie_version < 9) return false; 8569 var div = elt('div'); 8570 return "draggable" in div || "dragDrop" in div; 8571 }(); 8572 8573 var zwspSupported; 8574 function zeroWidthElement(measure) { 8575 if (zwspSupported == null) { 8576 var test = elt("span", "\u200b"); 8577 removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); 8578 if (measure.firstChild.offsetHeight != 0) 8579 zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); 8580 } 8581 var node = zwspSupported ? elt("span", "\u200b") : 8582 elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); 8583 node.setAttribute("cm-text", ""); 8584 return node; 8585 } 8586 8587 // Feature-detect IE's crummy client rect reporting for bidi text 8588 var badBidiRects; 8589 function hasBadBidiRects(measure) { 8590 if (badBidiRects != null) return badBidiRects; 8591 var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); 8592 var r0 = range(txt, 0, 1).getBoundingClientRect(); 8593 var r1 = range(txt, 1, 2).getBoundingClientRect(); 8594 removeChildren(measure); 8595 if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780) 8596 return badBidiRects = (r1.right - r0.right < 3); 8597 } 8598 8599 // See if "".split is the broken IE version, if so, provide an 8600 // alternative way to split lines. 8601 var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { 8602 var pos = 0, result = [], l = string.length; 8603 while (pos <= l) { 8604 var nl = string.indexOf("\n", pos); 8605 if (nl == -1) nl = string.length; 8606 var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); 8607 var rt = line.indexOf("\r"); 8608 if (rt != -1) { 8609 result.push(line.slice(0, rt)); 8610 pos += rt + 1; 8611 } else { 8612 result.push(line); 8613 pos = nl + 1; 8614 } 8615 } 8616 return result; 8617 } : function(string){return string.split(/\r\n?|\n/);}; 8618 8619 var hasSelection = window.getSelection ? function(te) {
8620 try { return te.selectionStart != te.selectionEnd; } 8621 catch(e) { return false; } 8622 } : function(te) { 8623 try {var range = te.ownerDocument.selection.createRange();} 8624 catch(e) {} 8625 if (!range || range.parentElement() != te) return false; 8626 return range.compareEndPoints("StartToEnd", range) != 0; 8627 }; 8628 8629 var hasCopyEvent = (function() { 8630 var e = elt("div"); 8631 if ("oncopy" in e) return true; 8632 e.setAttribute("oncopy", "return;"); 8633 return typeof e.oncopy == "function"; 8634 })(); 8635 8636 var badZoomedRects = null; 8637 function hasBadZoomedRects(measure) { 8638 if (badZoomedRects != null) return badZoomedRects; 8639 var node = removeChildrenAndAdd(measure, elt("span", "x")); 8640 var normal = node.getBoundingClientRect(); 8641 var fromRange = range(node, 0, 1).getBoundingClientRect(); 8642 return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; 8643 } 8644 8645 // KEY NAMES 8646 8647 var keyNames = CodeMirror.keyNames = { 8648 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 8649 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 8650 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 8651 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 8652 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", 8653 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 8654 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", 8655 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" 8656 }; 8657 (function() { 8658 // Number keys 8659 for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i); 8660 // Alphabetic keys 8661 for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); 8662 // Function keys 8663 for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; 8664 })(); 8665 8666 // BIDI HELPERS 8667 8668 function iterateBidiSections(order, from, to, f) { 8669 if (!order) return f(from, to, "ltr"); 8670 var found = false; 8671 for (var i = 0; i < order.length; ++i) { 8672 var part = order[i]; 8673 if (part.from < to && part.to > from || from == to && part.to == from) { 8674 f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); 8675 found = true; 8676 } 8677 } 8678 if (!found) f(from, to, "ltr"); 8679 } 8680 8681 function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } 8682 function bidiRight(part) { return part.level % 2 ? part.from : part.to; } 8683 8684 function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } 8685 function lineRight(line) { 8686 var order = getOrder(line); 8687 if (!order) return line.text.length; 8688 return bidiRight(lst(order)); 8689 } 8690 8691 function lineStart(cm, lineN) { 8692 var line = getLine(cm.doc, lineN); 8693 var visual = visualLine(line); 8694 if (visual != line) lineN = lineNo(visual); 8695 var order = getOrder(visual); 8696 var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); 8697 return Pos(lineN, ch); 8698 } 8699 function lineEnd(cm, lineN) { 8700 var merged, line = getLine(cm.doc, lineN); 8701 while (merged = collapsedSpanAtEnd(line)) { 8702 line = merged.find(1, true).line; 8703 lineN = null; 8704 } 8705 var order = getOrder(line); 8706 var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); 8707 return Pos(lineN == null ? lineNo(line) : lineN, ch); 8708 } 8709 function lineStartSmart(cm, pos) { 8710 var start = lineStart(cm, pos.line); 8711 var line = getLine(cm.doc, start.line); 8712 var order = getOrder(line); 8713 if (!order || order[0].level == 0) { 8714 var firstNonWS = Math.max(0, line.text.search(/\S/)); 8715 var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; 8716 return Pos(start.line, inWS ? 0 : firstNonWS); 8717 } 8718 return start; 8719 } 8720 8721 function compareBidiLevel(order, a, b) { 8722 var linedir = order[0].level; 8723 if (a == linedir) return true; 8724 if (b == linedir) return false; 8725 return a < b; 8726 } 8727 var bidiOther; 8728 function getBidiPartAt(order, pos) { 8729 bidiOther = null; 8730 for (var i = 0, found; i < order.length; ++i) { 8731 var cur = order[i]; 8732 if (cur.from < pos && cur.to > pos) return i; 8733 if ((cur.from == pos || cur.to == pos)) { 8734 if (found == null) { 8735 found = i; 8736 } else if (compareBidiLevel(order, cur.level, order[found].level)) { 8737 if (cur.from != cur.to) bidiOther = found; 8738 return i; 8739 } else { 8740 if (cur.from != cur.to) bidiOther = i; 8741 return found; 8742 } 8743 } 8744 } 8745 return found; 8746 } 8747 8748 function moveInLine(line, pos, dir, byUnit) { 8749 if (!byUnit) return pos + dir; 8750 do pos += dir; 8751 while (pos > 0 && isExtendingChar(line.text.charAt(pos))); 8752 return pos; 8753 } 8754 8755 // This is needed in order to move 'visually' through bi-directional 8756 // text -- i.e., pressing left should make the cursor go left, even 8757 // when in RTL text. The tricky part is the 'jumps', where RTL and 8758 // LTR text touch each other. This often requires the cursor offset 8759 // to move more than one unit, in order to visually move one unit. 8760 function moveVisually(line, start, dir, byUnit) { 8761 var bidi = getOrder(line); 8762 if (!bidi) return moveLogically(line, start, dir, byUnit); 8763 var pos = getBidiPartAt(bidi, start), part = bidi[pos]; 8764 var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); 8765 8766 for (;;) { 8767 if (target > part.from && target < part.to) return target; 8768 if (target == part.from || target == part.to) { 8769 if (getBidiPartAt(bidi, target) == pos) return target; 8770 part = bidi[pos += dir]; 8771 return (dir > 0) == part.level % 2 ? part.to : part.from; 8772 } else { 8773 part = bidi[pos += dir]; 8774 if (!part) return null; 8775 if ((dir > 0) == part.level % 2) 8776 target = moveInLine(line, part.to, -1, byUnit); 8777 else
8778 target = moveInLine(line, part.from, 1, byUnit); 8779 } 8780 } 8781 } 8782 8783 function moveLogically(line, start, dir, byUnit) { 8784 var target = start + dir; 8785 if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir; 8786 return target < 0 || target > line.text.length ? null : target; 8787 } 8788 8789 // Bidirectional ordering algorithm 8790 // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm 8791 // that this (partially) implements. 8792 8793 // One-char codes used for character types: 8794 // L (L): Left-to-Right 8795 // R (R): Right-to-Left 8796 // r (AL): Right-to-Left Arabic 8797 // 1 (EN): European Number 8798 // + (ES): European Number Separator 8799 // % (ET): European Number Terminator 8800 // n (AN): Arabic Number 8801 // , (CS): Common Number Separator 8802 // m (NSM): Non-Spacing Mark 8803 // b (BN): Boundary Neutral 8804 // s (B): Paragraph Separator 8805 // t (S): Segment Separator 8806 // w (WS): Whitespace 8807 // N (ON): Other Neutrals 8808 8809 // Returns null if characters are ordered as they appear 8810 // (left-to-right), or an array of sections ({from, to, level} 8811 // objects) in the order in which they occur visually. 8812 var bidiOrdering = (function() { 8813 // Character types for codepoints 0 to 0xff 8814 var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; 8815 // Character types for codepoints 0x600 to 0x6ff 8816 var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm"; 8817 function charType(code) { 8818 if (code <= 0xf7) return lowTypes.charAt(code); 8819 else if (0x590 <= code && code <= 0x5f4) return "R"; 8820 else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600); 8821 else if (0x6ee <= code && code <= 0x8ac) return "r"; 8822 else if (0x2000 <= code && code <= 0x200b) return "w"; 8823 else if (code == 0x200c) return "b"; 8824 else return "L"; 8825 } 8826 8827 var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; 8828 var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; 8829 // Browsers seem to always treat the boundaries of block elements as being L. 8830 var outerType = "L"; 8831 8832 function BidiSpan(level, from, to) { 8833 this.level = level; 8834 this.from = from; this.to = to; 8835 } 8836 8837 return function(str) { 8838 if (!bidiRE.test(str)) return false; 8839 var len = str.length, types = []; 8840 for (var i = 0, type; i < len; ++i) 8841 types.push(type = charType(str.charCodeAt(i))); 8842 8843 // W1. Examine each non-spacing mark (NSM) in the level run, and 8844 // change the type of the NSM to the type of the previous 8845 // character. If the NSM is at the start of the level run, it will 8846 // get the type of sor. 8847 for (var i = 0, prev = outerType; i < len; ++i) { 8848 var type = types[i]; 8849 if (type == "m") types[i] = prev; 8850 else prev = type; 8851 } 8852 8853 // W2. Search backwards from each instance of a European number 8854 // until the first strong type (R, L, AL, or sor) is found. If an 8855 // AL is found, change the type of the European number to Arabic 8856 // number. 8857 // W3. Change all ALs to R. 8858 for (var i = 0, cur = outerType; i < len; ++i) { 8859 var type = types[i]; 8860 if (type == "1" && cur == "r") types[i] = "n"; 8861 else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } 8862 } 8863 8864 // W4. A single European separator between two European numbers 8865 // changes to a European number. A single common separator between 8866 // two numbers of the same type changes to that type. 8867 for (var i = 1, prev = types[0]; i < len - 1; ++i) { 8868 var type = types[i]; 8869 if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; 8870 else if (type == "," && prev == types[i+1] && 8871 (prev == "1" || prev == "n")) types[i] = prev; 8872 prev = type; 8873 } 8874 8875 // W5. A sequence of European terminators adjacent to European 8876 // numbers changes to all European numbers. 8877 // W6. Otherwise, separators and terminators change to Other 8878 // Neutral. 8879 for (var i = 0; i < len; ++i) { 8880 var type = types[i]; 8881 if (type == ",") types[i] = "N"; 8882 else if (type == "%") { 8883 for (var end = i + 1; end < len && types[end] == "%"; ++end) {} 8884 var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; 8885 for (var j = i; j < end; ++j) types[j] = replace; 8886 i = end - 1; 8887 } 8888 } 8889 8890 // W7. Search backwards from each instance of a European number 8891 // until the first strong type (R, L, or sor) is found. If an L is 8892 // found, then change the type of the European number to L. 8893 for (var i = 0, cur = outerType; i < len; ++i) { 8894 var type = types[i]; 8895 if (cur == "L" && type == "1") types[i] = "L"; 8896 else if (isStrong.test(type)) cur = type; 8897 } 8898 8899 // N1. A sequence of neutrals takes the direction of the 8900 // surrounding strong text if the text on both sides has the same 8901 // direction. European and Arabic numbers act as if they were R in 8902 // terms of their influence on neutrals. Start-of-level-run (sor) 8903 // and end-of-level-run (eor) are used at level run boundaries. 8904 // N2. Any remaining neutrals take the embedding direction. 8905 for (var i = 0; i < len; ++i) { 8906 if (isNeutral.test(types[i])) { 8907 for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} 8908 var before = (i ? types[i-1] : outerType) == "L"; 8909 var after = (end < len ? types[end] : outerType) == "L"; 8910 var replace = before || after ? "L" : "R"; 8911 for (var j = i; j < end; ++j) types[j] = replace; 8912 i = end - 1; 8913 } 8914 } 8915 8916 // Here we depart from the documented algorithm, in order to avoid 8917 // building up an actual levels array. Since there are only three 8918 // levels (0, 1, 2) in an implementation that doesn't take 8919 // explicit embedding into account, we can build up the order on 8920 // the fly, without following the level-based algorithm. 8921 var order = [], m; 8922 for (var i = 0; i < len;) { 8923 if (countsAsLeft.test(types[i])) { 8924 var start = i; 8925 for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} 8926 order.push(new BidiSpan(0, start, i)); 8927 } else { 8928 var pos = i, at = order.length; 8929 for (++i; i < len && types[i] != "L"; ++i) {} 8930 for (var j = pos; j < i;) { 8931 if (countsAsNum.test(types[j])) { 8932 if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j)); 8933 var nstart = j; 8934 for (++j; j < i && countsAsNum.test(types[j]); ++j) {} 8935 order.splice(at, 0, new BidiSpan(2, nstart, j)); 8936 pos = j; 8937 } else ++j; 8938 } 8939 if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i)); 8940 } 8941 } 8942 if (order[0].level == 1 && (m = str.match(/^\s+/))) { 8943 order[0].from = m[0].length; 8944 order.unshift(new BidiSpan(0, 0, m[0].length)); 8945 } 8946 if (lst(order).level == 1 && (m = str.match(/\s+$/))) { 8947 lst(order).to -= m[0].length; 8948 order.push(new BidiSpan(0, len - m[0].length, len)); 8949 } 8950 if (order[0].level == 2) 8951 order.unshift(new BidiSpan(1, order[0].to, order[0].to)); 8952 if (order[0].level != lst(order).level) 8953 order.push(new BidiSpan(order[0].level, len, len)); 8954 8955 return order; 8956 }; 8957 })(); 8958 8959 // THE END 8960 8961 CodeMirror.version = "5.19.0"; 8962 8963 return CodeMirror; 8964});
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.