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