1// CodeMirror version 3.1 2// 3// CodeMirror is the only global var we claim 4window.CodeMirror = (function() { 5 "use strict"; 6 7 // BROWSER SNIFFING 8 9 // Crude, but necessary to handle a number of hard-to-feature-detect 10 // bugs and behavior differences. 11 var gecko = /gecko\/\d/i.test(navigator.userAgent); 12 var ie = /MSIE \d/.test(navigator.userAgent); 13 var ie_lt8 = ie && (document.documentMode == null || document.documentMode < 8); 14 var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9); 15 var webkit = /WebKit\//.test(navigator.userAgent); 16 var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); 17 var chrome = /Chrome\//.test(navigator.userAgent); 18 var opera = /Opera\//.test(navigator.userAgent); 19 var safari = /Apple Computer/.test(navigator.vendor); 20 var khtml = /KHTML\//.test(navigator.userAgent); 21 var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent); 22 var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent); 23 var phantom = /PhantomJS/.test(navigator.userAgent); 24 25 var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); 26 // This is woefully incomplete. Suggestions for alternative methods welcome. 27 var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent); 28 var mac = ios || /Mac/.test(navigator.platform); 29 var windows = /windows/i.test(navigator.platform); 30 31 var opera_version = opera && navigator.userAgent.match(/Version\/(\d*\.\d*)/); 32 if (opera_version) opera_version = Number(opera_version[1]); 33 // Some browsers use the wrong event properties to signal cmd/ctrl on OS X 34 var flipCtrlCmd = mac && (qtwebkit || opera && (opera_version == null || opera_version < 12.11)); 35 var captureMiddleClick = gecko || (ie && !ie_lt9); 36 37 // Optimize some code when these features are not used 38 var sawReadOnlySpans = false, sawCollapsedSpans = false; 39 40 // CONSTRUCTOR 41 42 function CodeMirror(place, options) { 43 if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); 44 45 this.options = options = options || {}; 46 // Determine effective options based on given values and defaults. 47 for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt)) 48 options[opt] = defaults[opt]; 49 setGuttersForLineNumbers(options); 50 51 var docStart = typeof options.value == "string" ? 0 : options.value.first; 52 var display = this.display = makeDisplay(place, docStart); 53 display.wrapper.CodeMirror = this; 54 updateGutters(this); 55 if (options.autofocus && !mobile) focusInput(this); 56 57 this.state = {keyMaps: [], 58 overlays: [], 59 modeGen: 0, 60 overwrite: false, focused: false, 61 suppressEdits: false, pasteIncoming: false, 62 draggingText: false, 63 highlight: new Delayed()}; 64 65 themeChanged(this); 66 if (options.lineWrapping) 67 this.display.wrapper.className += " CodeMirror-wrap"; 68 69 var doc = options.value; 70 if (typeof doc == "string") doc = new Doc(options.value, options.mode); 71 operation(this, attachDoc)(this, doc); 72 73 // Override magic textarea content restore that IE sometimes does 74 // on our hidden textarea on reload 75 if (ie) setTimeout(bind(resetInput, this, true), 20); 76 77 registerEventHandlers(this); 78 // IE throws unspecified error in certain cases, when 79 // trying to access activeElement before onload 80 var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { } 81 if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20); 82 else onBlur(this); 83 84 operation(this, function() { 85 for (var opt in optionHandlers) 86 if (optionHandlers.propertyIsEnumerable(opt)) 87 optionHandlers[opt](this, options[opt], Init); 88 for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); 89 })(); 90 } 91 92 // DISPLAY CONSTRUCTOR 93 94 function makeDisplay(place, docStart) { 95 var d = {}; 96 var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none;"); 97 if (webkit) input.style.width = "1000px"; 98 else input.setAttribute("wrap", "off"); 99 input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); 100 // Wraps and hides input textarea 101 d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); 102 // The actual fake scrollbars. 103 d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar"); 104 d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar"); 105 d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); 106 // DIVs containing the selection and the actual code 107 d.lineDiv = elt("div"); 108 d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); 109 // Blinky cursor, and element used to ensure cursor fits at the end of a line 110 d.cursor = elt("div", "\u00a0", "CodeMirror-cursor"); 111 // Secondary cursor, shown when on a 'jump' in bi-directional text 112 d.otherCursor = elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"); 113 // Used to measure text size 114 d.measure = elt("div", null, "CodeMirror-measure"); 115 // Wraps everything that needs to exist inside the vertically-padded coordinate system 116 d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor], 117 null, "position: relative; outline: none"); 118 // Moved around its parent to cover visible view 119 d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); 120 // Set to the height of the text, causes scrolling 121 d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); 122 // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers 123 d.heightForcer = elt("div", "\u00a0", null, "position: absolute; height: " + scrollerCutOff + "px"); 124 // Will contain the gutters, if any 125 d.gutters = elt("div", null, "CodeMirror-gutters"); 126 d.lineGutter = null; 127 // Helper element to properly size the gutter backgrounds 128 var scrollerInner = elt("div", [d.sizer, d.heightForcer, d.gutters], null, "position: relative; min-height: 100%"); 129 // Provides scrolling 130 d.scroller = elt("div", [scrollerInner], "CodeMirror-scroll"); 131 d.scroller.setAttribute("tabIndex", "-1"); 132 // The element in which the editor lives. 133 d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV, 134 d.scrollbarFiller, d.scroller], "CodeMirror"); 135 // Work around IE7 z-index bug 136 if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } 137 if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper); 138 139 // Needed to hide big blue blinking cursor on Mobile Safari 140 if (ios) input.style.width = "0px"; 141 if (!webkit) d.scroller.draggable = true; 142 // Needed to handle Tab key in KHTML 143 if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; } 144 // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). 145 else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px"; 146 147 // Current visible range (may be bigger than the view window). 148 d.viewOffset = d.lastSizeC = 0; 149 d.showingFrom = d.showingTo = docStart; 150 151 // Used to only resize the line number gutter when necessary (when
152 // the amount of lines crosses a boundary that makes its width change) 153 d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; 154 // See readInput and resetInput 155 d.prevInput = ""; 156 // Set to true when a non-horizontal-scrolling widget is added. As 157 // an optimization, widget aligning is skipped when d is false. 158 d.alignWidgets = false; 159 // Flag that indicates whether we currently expect input to appear 160 // (after some event like 'keypress' or 'input') and are polling 161 // intensively. 162 d.pollingFast = false; 163 // Self-resetting timeout for the poller 164 d.poll = new Delayed(); 165 // True when a drag from the editor is active 166 d.draggingText = false; 167 168 d.cachedCharWidth = d.cachedTextHeight = null; 169 d.measureLineCache = []; 170 d.measureLineCachePos = 0; 171 172 // Tracks when resetInput has punted to just putting a short 173 // string instead of the (large) selection. 174 d.inaccurateSelection = false; 175 176 // Tracks the maximum line length so that the horizontal scrollbar 177 // can be kept static when scrolling. 178 d.maxLine = null; 179 d.maxLineLength = 0; 180 d.maxLineChanged = false; 181 182 // Used for measuring wheel scrolling granularity 183 d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; 184 185 return d; 186 } 187 188 // STATE UPDATES 189 190 // Used to get the editor into a consistent state again when options change. 191 192 function loadMode(cm) { 193 cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); 194 cm.doc.iter(function(line) { 195 if (line.stateAfter) line.stateAfter = null; 196 if (line.styles) line.styles = null; 197 }); 198 cm.doc.frontier = cm.doc.first; 199 startWorker(cm, 100); 200 cm.state.modeGen++; 201 if (cm.curOp) regChange(cm); 202 } 203 204 function wrappingChanged(cm) { 205 if (cm.options.lineWrapping) { 206 cm.display.wrapper.className += " CodeMirror-wrap"; 207 cm.display.sizer.style.minWidth = ""; 208 } else { 209 cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", ""); 210 computeMaxLength(cm); 211 } 212 estimateLineHeights(cm); 213 regChange(cm); 214 clearCaches(cm); 215 setTimeout(function(){updateScrollbars(cm.display, cm.doc.height);}, 100); 216 } 217 218 function estimateHeight(cm) { 219 var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; 220 var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); 221 return function(line) { 222 if (lineIsHidden(cm.doc, line)) 223 return 0; 224 else if (wrapping) 225 return (Math.ceil(line.text.length / perLine) || 1) * th; 226 else 227 return th; 228 }; 229 } 230 231 function estimateLineHeights(cm) { 232 var doc = cm.doc, est = estimateHeight(cm); 233 doc.iter(function(line) { 234 var estHeight = est(line); 235 if (estHeight != line.height) updateLineHeight(line, estHeight); 236 }); 237 } 238 239 function keyMapChanged(cm) { 240 var style = keyMap[cm.options.keyMap].style; 241 cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") + 242 (style ? " cm-keymap-" + style : ""); 243 } 244 245 function themeChanged(cm) { 246 cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + 247 cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); 248 clearCaches(cm); 249 } 250 251 function guttersChanged(cm) { 252 updateGutters(cm); 253 regChange(cm); 254 } 255 256 function updateGutters(cm) { 257 var gutters = cm.display.gutters, specs = cm.options.gutters; 258 removeChildren(gutters); 259 for (var i = 0; i < specs.length; ++i) { 260 var gutterClass = specs[i]; 261 var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); 262 if (gutterClass == "CodeMirror-linenumbers") { 263 cm.display.lineGutter = gElt; 264 gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; 265 } 266 } 267 gutters.style.display = i ? "" : "none"; 268 } 269 270 function lineLength(doc, line) { 271 if (line.height == 0) return 0; 272 var len = line.text.length, merged, cur = line; 273 while (merged = collapsedSpanAtStart(cur)) { 274 var found = merged.find(); 275 cur = getLine(doc, found.from.line); 276 len += found.from.ch - found.to.ch; 277 } 278 cur = line; 279 while (merged = collapsedSpanAtEnd(cur)) { 280 var found = merged.find(); 281 len -= cur.text.length - found.from.ch; 282 cur = getLine(doc, found.to.line); 283 len += cur.text.length - found.to.ch; 284 } 285 return len; 286 } 287 288 function computeMaxLength(cm) { 289 var d = cm.display, doc = cm.doc; 290 d.maxLine = getLine(doc, doc.first); 291 d.maxLineLength = lineLength(doc, d.maxLine); 292 d.maxLineChanged = true; 293 doc.iter(function(line) { 294 var len = lineLength(doc, line); 295 if (len > d.maxLineLength) { 296 d.maxLineLength = len; 297 d.maxLine = line; 298 } 299 }); 300 } 301 302 // Make sure the gutters options contains the element 303 // "CodeMirror-linenumbers" when the lineNumbers option is true. 304 function setGuttersForLineNumbers(options) { 305 var found = false;
306 for (var i = 0; i < options.gutters.length; ++i) { 307 if (options.gutters[i] == "CodeMirror-linenumbers") { 308 if (options.lineNumbers) found = true; 309 else options.gutters.splice(i--, 1); 310 } 311 } 312 if (!found && options.lineNumbers) 313 options.gutters.push("CodeMirror-linenumbers"); 314 } 315 316 // SCROLLBARS 317 318 // Re-synchronize the fake scrollbars with the actual size of the 319 // content. Optionally force a scrollTop. 320 function updateScrollbars(d /* display */, docHeight) { 321 var totalHeight = docHeight + 2 * paddingTop(d); 322 d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px"; 323 var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight); 324 var needsH = d.scroller.scrollWidth > d.scroller.clientWidth; 325 var needsV = scrollHeight > d.scroller.clientHeight; 326 if (needsV) { 327 d.scrollbarV.style.display = "block"; 328 d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0"; 329 d.scrollbarV.firstChild.style.height = 330 (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px"; 331 } else d.scrollbarV.style.display = ""; 332 if (needsH) { 333 d.scrollbarH.style.display = "block"; 334 d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0"; 335 d.scrollbarH.firstChild.style.width = 336 (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px"; 337 } else d.scrollbarH.style.display = ""; 338 if (needsH && needsV) { 339 d.scrollbarFiller.style.display = "block"; 340 d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px"; 341 } else d.scrollbarFiller.style.display = ""; 342 343 if (mac_geLion && scrollbarWidth(d.measure) === 0) 344 d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px"; 345 } 346 347 function visibleLines(display, doc, viewPort) { 348 var top = display.scroller.scrollTop, height = display.wrapper.clientHeight; 349 if (typeof viewPort == "number") top = viewPort; 350 else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;} 351 top = Math.floor(top - paddingTop(display)); 352 var bottom = Math.ceil(top + height); 353 return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)}; 354 } 355 356 // LINE NUMBERS 357 358 function alignHorizontally(cm) { 359 var display = cm.display; 360 if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; 361 var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; 362 var gutterW = display.gutters.offsetWidth, l = comp + "px"; 363 for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) { 364 for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l; 365 } 366 if (cm.options.fixedGutter) 367 display.gutters.style.left = (comp + gutterW) + "px"; 368 } 369 370 function maybeUpdateLineNumberWidth(cm) { 371 if (!cm.options.lineNumbers) return false; 372 var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; 373 if (last.length != display.lineNumChars) { 374 var test = display.measure.appendChild(elt("div", [elt("div", last)], 375 "CodeMirror-linenumber CodeMirror-gutter-elt")); 376 var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; 377 display.lineGutter.style.width = ""; 378 display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding); 379 display.lineNumWidth = display.lineNumInnerWidth + padding; 380 display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; 381 display.lineGutter.style.width = display.lineNumWidth + "px"; 382 return true; 383 } 384 return false; 385 } 386 387 function lineNumberFor(options, i) { 388 return String(options.lineNumberFormatter(i + options.firstLineNumber)); 389 } 390 function compensateForHScroll(display) { 391 return getRect(display.scroller).left - getRect(display.sizer).left; 392 } 393 394 // DISPLAY DRAWING 395 396 function updateDisplay(cm, changes, viewPort) { 397 var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo; 398 var updated = updateDisplayInner(cm, changes, viewPort); 399 if (updated) { 400 signalLater(cm, "update", cm); 401 if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo) 402 signalLater(cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo); 403 } 404 updateSelection(cm); 405 updateScrollbars(cm.display, cm.doc.height); 406 407 return updated; 408 } 409 410 // Uses a set of changes plus the current scroll position to 411 // determine which DOM updates have to be made, and makes the 412 // updates. 413 function updateDisplayInner(cm, changes, viewPort) { 414 var display = cm.display, doc = cm.doc; 415 if (!display.wrapper.clientWidth) { 416 display.showingFrom = display.showingTo = doc.first; 417 display.viewOffset = 0; 418 return; 419 } 420 421 // Compute the new visible window 422 // If scrollTop is specified, use that to determine which lines 423 // to render instead of the current scrollbar position. 424 var visible = visibleLines(display, doc, viewPort); 425 // Bail out if the visible area is already rendered and nothing changed. 426 if (changes.length == 0 && 427 visible.from > display.showingFrom && visible.to < display.showingTo) 428 return; 429 430 if (maybeUpdateLineNumberWidth(cm)) 431 changes = [{from: doc.first, to: doc.first + doc.size}]; 432 var gutterW = display.sizer.style.marginLeft = display.gutters.offsetWidth + "px"; 433 display.scrollbarH.style.left = cm.options.fixedGutter ? gutterW : "0"; 434 435 // Used to determine which lines need their line numbers updated 436 var positionsChangedFrom = Infinity; 437 if (cm.options.lineNumbers) 438 for (var i = 0; i < changes.length; ++i) 439 if (changes[i].diff) { positionsChangedFrom = changes[i].from; break; } 440 441 var end = doc.first + doc.size; 442 var from = Math.max(visible.from - cm.options.viewportMargin, doc.first); 443 var to = Math.min(end, visible.to + cm.options.viewportMargin); 444 if (display.showingFrom < from && from - display.showingFrom < 20) from = Math.max(doc.first, display.showingFrom); 445 if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(end, display.showingTo); 446 if (sawCollapsedSpans) { 447 from = lineNo(visualLine(doc, getLine(doc, from))); 448 while (to < end && lineIsHidden(doc, getLine(doc, to))) ++to; 449 } 450 451 // Create a range of theoretically intact lines, and punch holes 452 // in that using the change info. 453 var intact = [{from: Math.max(display.showingFrom, doc.first), 454 to: Math.min(display.showingTo, end)}]; 455 if (intact[0].from >= intact[0].to) intact = []; 456 else intact = computeIntact(intact, changes); 457 // When merged lines are present, we might have to reduce the 458 // intact ranges because changes in continued fragments of the 459 // intact lines do require the lines to be redrawn. 460 if (sawCollapsedSpans) 461 for (var i = 0; i < intact.length; ++i) { 462 var range = intact[i], merged; 463 while (merged = collapsedSpanAtEnd(getLine(doc, range.to - 1))) { 464 var newTo = merged.find().from.line; 465 if (newTo > range.from) range.to = newTo; 466 else { intact.splice(i--, 1); break; } 467 } 468 } 469 470 // Clip off the parts that won't be visible 471 var intactLines = 0; 472 for (var i = 0; i < intact.length; ++i) { 473 var range = intact[i]; 474 if (range.from < from) range.from = from; 475 if (range.to > to) range.to = to; 476 if (range.from >= range.to) intact.splice(i--, 1); 477 else intactLines += range.to - range.from; 478 } 479 if (intactLines == to - from && from == display.showingFrom && to == display.showingTo) { 480 updateViewOffset(cm); 481 return; 482 } 483 intact.sort(function(a, b) {return a.from - b.from;}); 484 485 var focused = document.activeElement; 486 if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none"; 487 patchDisplay(cm, from, to, intact, positionsChangedFrom); 488 display.lineDiv.style.display = ""; 489 if (document.activeElement != focused && focused.offsetHeight) focused.focus(); 490 491 var different = from != display.showingFrom || to != display.showingTo || 492 display.lastSizeC != display.wrapper.clientHeight; 493 // This is just a bogus formula that detects when the editor is 494 // resized or the font size changes. 495 if (different) display.lastSizeC = display.wrapper.clientHeight; 496 display.showingFrom = from; display.showingTo = to; 497 startWorker(cm, 100); 498 499 var prevBottom = display.lineDiv.offsetTop; 500 for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) { 501 if (ie_lt8) { 502 var bot = node.offsetTop + node.offsetHeight; 503 height = bot - prevBottom; 504 prevBottom = bot; 505 } else { 506 var box = getRect(node); 507 height = box.bottom - box.top; 508 } 509 var diff = node.lineObj.height - height; 510 if (height < 2) height = textHeight(display); 511 if (diff > .001 || diff < -.001) { 512 updateLineHeight(node.lineObj, height); 513 var widgets = node.lineObj.widgets; 514 if (widgets) for (var i = 0; i < widgets.length; ++i) 515 widgets[i].height = widgets[i].node.offsetHeight; 516 } 517 } 518 updateViewOffset(cm); 519 520 if (visibleLines(display, doc, viewPort).to > to) 521 updateDisplayInner(cm, [], viewPort); 522 return true; 523 } 524 525 function updateViewOffset(cm) { 526 var off = cm.display.viewOffset = heightAtLine(cm, getLine(cm.doc, cm.display.showingFrom)); 527 // Position the mover div to align with the current virtual scroll position 528 cm.display.mover.style.top = off + "px"; 529 } 530 531 function computeIntact(intact, changes) { 532 for (var i = 0, l = changes.length || 0; i < l; ++i) { 533 var change = changes[i], intact2 = [], diff = change.diff || 0; 534 for (var j = 0, l2 = intact.length; j < l2; ++j) { 535 var range = intact[j]; 536 if (change.to <= range.from && change.diff) { 537 intact2.push({from: range.from + diff, to: range.to + diff}); 538 } else if (change.to <= range.from || change.from >= range.to) { 539 intact2.push(range); 540 } else { 541 if (change.from > range.from) 542 intact2.push({from: range.from, to: change.from}); 543 if (change.to < range.to) 544 intact2.push({from: change.to + diff, to: range.to + diff}); 545 } 546 } 547 intact = intact2; 548 } 549 return intact; 550 } 551 552 function getDimensions(cm) { 553 var d = cm.display, left = {}, width = {}; 554 for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { 555 left[cm.options.gutters[i]] = n.offsetLeft; 556 width[cm.options.gutters[i]] = n.offsetWidth; 557 } 558 return {fixedPos: compensateForHScroll(d), 559 gutterTotalWidth: d.gutters.offsetWidth, 560 gutterLeft: left, 561 gutterWidth: width,
562 wrapperWidth: d.wrapper.clientWidth}; 563 } 564 565 function patchDisplay(cm, from, to, intact, updateNumbersFrom) { 566 var dims = getDimensions(cm); 567 var display = cm.display, lineNumbers = cm.options.lineNumbers; 568 if (!intact.length && (!webkit || !cm.display.currentWheelTarget)) 569 removeChildren(display.lineDiv); 570 var container = display.lineDiv, cur = container.firstChild; 571 572 function rm(node) { 573 var next = node.nextSibling; 574 if (webkit && mac && cm.display.currentWheelTarget == node) { 575 node.style.display = "none"; 576 node.lineObj = null; 577 } else { 578 node.parentNode.removeChild(node); 579 } 580 return next; 581 } 582 583 var nextIntact = intact.shift(), lineN = from; 584 cm.doc.iter(from, to, function(line) { 585 if (nextIntact && nextIntact.to == lineN) nextIntact = intact.shift(); 586 if (lineIsHidden(cm.doc, line)) { 587 if (line.height != 0) updateLineHeight(line, 0); 588 if (line.widgets && cur.previousSibling) for (var i = 0; i < line.widgets.length; ++i) 589 if (line.widgets[i].showIfHidden) { 590 var prev = cur.previousSibling; 591 if (/pre/i.test(prev.nodeName)) { 592 var wrap = elt("div", null, null, "position: relative"); 593 prev.parentNode.replaceChild(wrap, prev); 594 wrap.appendChild(prev); 595 prev = wrap; 596 } 597 var wnode = prev.appendChild(elt("div", [line.widgets[i].node], "CodeMirror-linewidget")); 598 positionLineWidget(line.widgets[i], wnode, prev, dims); 599 } 600 } else if (nextIntact && nextIntact.from <= lineN && nextIntact.to > lineN) { 601 // This line is intact. Skip to the actual node. Update its 602 // line number if needed. 603 while (cur.lineObj != line) cur = rm(cur); 604 if (lineNumbers && updateNumbersFrom <= lineN && cur.lineNumber) 605 setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineN)); 606 cur = cur.nextSibling; 607 } else { 608 // For lines with widgets, make an attempt to find and reuse 609 // the existing element, so that widgets aren't needlessly 610 // removed and re-inserted into the dom 611 if (line.widgets) for (var j = 0, search = cur, reuse; search && j < 20; ++j, search = search.nextSibling) 612 if (search.lineObj == line && /div/i.test(search.nodeName)) { reuse = search; break; } 613 // This line needs to be generated. 614 var lineNode = buildLineElement(cm, line, lineN, dims, reuse); 615 if (lineNode != reuse) { 616 container.insertBefore(lineNode, cur); 617 } else { 618 while (cur != reuse) cur = rm(cur); 619 cur = cur.nextSibling; 620 } 621 622 lineNode.lineObj = line; 623 } 624 ++lineN; 625 }); 626 while (cur) cur = rm(cur); 627 } 628 629 function buildLineElement(cm, line, lineNo, dims, reuse) { 630 var lineElement = lineContent(cm, line); 631 var markers = line.gutterMarkers, display = cm.display, wrap; 632 633 if (!cm.options.lineNumbers && !markers && !line.bgClass && !line.wrapClass && !line.widgets) 634 return lineElement; 635 636 // Lines with gutter elements, widgets or a background class need 637 // to be wrapped again, and have the extra elements added to the 638 // wrapper div 639 640 if (reuse) { 641 reuse.alignable = null; 642 var isOk = true, widgetsSeen = 0; 643 for (var n = reuse.firstChild, next; n; n = next) { 644 next = n.nextSibling; 645 if (!/\bCodeMirror-linewidget\b/.test(n.className)) { 646 reuse.removeChild(n); 647 } else { 648 for (var i = 0, first = true; i < line.widgets.length; ++i) { 649 var widget = line.widgets[i], isFirst = false; 650 if (!widget.above) { isFirst = first; first = false; } 651 if (widget.node == n.firstChild) { 652 positionLineWidget(widget, n, reuse, dims); 653 ++widgetsSeen; 654 if (isFirst) reuse.insertBefore(lineElement, n); 655 break; 656 } 657 } 658 if (i == line.widgets.length) { isOk = false; break; } 659 } 660 } 661 if (isOk && widgetsSeen == line.widgets.length) { 662 wrap = reuse; 663 reuse.className = line.wrapClass || ""; 664 } 665 } 666 if (!wrap) { 667 wrap = elt("div", null, line.wrapClass, "position: relative"); 668 wrap.appendChild(lineElement); 669 } 670 // Kludge to make sure the styled element lies behind the selection (by z-index) 671 if (line.bgClass) 672 wrap.insertBefore(elt("div", "\u00a0", line.bgClass + " CodeMirror-linebackground"), wrap.firstChild); 673 if (cm.options.lineNumbers || markers) { 674 var gutterWrap = wrap.insertBefore(elt("div", null, null, "position: absolute; left: " + 675 (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"), 676 wrap.firstChild); 677 if (cm.options.fixedGutter) (wrap.alignable || (wrap.alignable = [])).push(gutterWrap); 678 if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) 679 wrap.lineNumber = gutterWrap.appendChild( 680 elt("div", lineNumberFor(cm.options, lineNo),
681 "CodeMirror-linenumber CodeMirror-gutter-elt", 682 "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " 683 + display.lineNumInnerWidth + "px")); 684 if (markers) 685 for (var k = 0; k < cm.options.gutters.length; ++k) { 686 var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; 687 if (found) 688 gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + 689 dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); 690 } 691 } 692 if (ie_lt8) wrap.style.zIndex = 2; 693 if (line.widgets && wrap != reuse) for (var i = 0, ws = line.widgets; i < ws.length; ++i) { 694 var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); 695 positionLineWidget(widget, node, wrap, dims); 696 if (widget.above) 697 wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement); 698 else 699 wrap.appendChild(node); 700 signalLater(widget, "redraw"); 701 } 702 return wrap; 703 } 704 705 function positionLineWidget(widget, node, wrap, dims) { 706 if (widget.noHScroll) { 707 (wrap.alignable || (wrap.alignable = [])).push(node); 708 var width = dims.wrapperWidth; 709 node.style.left = dims.fixedPos + "px"; 710 if (!widget.coverGutter) { 711 width -= dims.gutterTotalWidth; 712 node.style.paddingLeft = dims.gutterTotalWidth + "px"; 713 } 714 node.style.width = width + "px"; 715 } 716 if (widget.coverGutter) { 717 node.style.zIndex = 5; 718 node.style.position = "relative"; 719 if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; 720 } 721 } 722 723 // SELECTION / CURSOR 724 725 function updateSelection(cm) { 726 var display = cm.display; 727 var collapsed = posEq(cm.doc.sel.from, cm.doc.sel.to); 728 if (collapsed || cm.options.showCursorWhenSelecting) 729 updateSelectionCursor(cm); 730 else 731 display.cursor.style.display = display.otherCursor.style.display = "none"; 732 if (!collapsed) 733 updateSelectionRange(cm); 734 else 735 display.selectionDiv.style.display = "none"; 736 737 // Move the hidden textarea near the cursor to prevent scrolling artifacts 738 var headPos = cursorCoords(cm, cm.doc.sel.head, "div"); 739 var wrapOff = getRect(display.wrapper), lineOff = getRect(display.lineDiv); 740 display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10, 741 headPos.top + lineOff.top - wrapOff.top)) + "px"; 742 display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10, 743 headPos.left + lineOff.left - wrapOff.left)) + "px"; 744 } 745 746 // No selection, plain cursor 747 function updateSelectionCursor(cm) { 748 var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div"); 749 display.cursor.style.left = pos.left + "px"; 750 display.cursor.style.top = pos.top + "px"; 751 display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; 752 display.cursor.style.display = ""; 753 754 if (pos.other) { 755 display.otherCursor.style.display = ""; 756 display.otherCursor.style.left = pos.other.left + "px"; 757 display.otherCursor.style.top = pos.other.top + "px"; 758 display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; 759 } else { display.otherCursor.style.display = "none"; } 760 } 761 762 // Highlight selection 763 function updateSelectionRange(cm) { 764 var display = cm.display, doc = cm.doc, sel = cm.doc.sel; 765 var fragment = document.createDocumentFragment(); 766 var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display); 767 768 function add(left, top, width, bottom) { 769 if (top < 0) top = 0; 770 fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + 771 "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) + 772 "px; height: " + (bottom - top) + "px")); 773 } 774 775 function drawForLine(line, fromArg, toArg, retTop) { 776 var lineObj = getLine(doc, line); 777 var lineLen = lineObj.text.length, rVal = retTop ? Infinity : -Infinity; 778 function coords(ch) { 779 return charCoords(cm, Pos(line, ch), "div", lineObj); 780 } 781 782 iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { 783 var leftPos = coords(dir == "rtl" ? to - 1 : from);
784 var rightPos = coords(dir == "rtl" ? from : to - 1); 785 var left = leftPos.left, right = rightPos.right; 786 if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part 787 add(left, leftPos.top, null, leftPos.bottom); 788 left = pl; 789 if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); 790 } 791 if (toArg == null && to == lineLen) right = clientWidth; 792 if (fromArg == null && from == 0) left = pl; 793 rVal = retTop ? Math.min(rightPos.top, rVal) : Math.max(rightPos.bottom, rVal); 794 if (left < pl + 1) left = pl; 795 add(left, rightPos.top, right - left, rightPos.bottom); 796 }); 797 return rVal; 798 } 799 800 if (sel.from.line == sel.to.line) { 801 drawForLine(sel.from.line, sel.from.ch, sel.to.ch); 802 } else { 803 var fromObj = getLine(doc, sel.from.line); 804 var cur = fromObj, merged, path = [sel.from.line, sel.from.ch], singleLine; 805 while (merged = collapsedSpanAtEnd(cur)) { 806 var found = merged.find(); 807 path.push(found.from.ch, found.to.line, found.to.ch); 808 if (found.to.line == sel.to.line) { 809 path.push(sel.to.ch); 810 singleLine = true; 811 break; 812 } 813 cur = getLine(doc, found.to.line); 814 } 815 816 // This is a single, merged line 817 if (singleLine) { 818 for (var i = 0; i < path.length; i += 3) 819 drawForLine(path[i], path[i+1], path[i+2]); 820 } else { 821 var middleTop, middleBot, toObj = getLine(doc, sel.to.line); 822 if (sel.from.ch) 823 // Draw the first line of selection. 824 middleTop = drawForLine(sel.from.line, sel.from.ch, null, false); 825 else 826 // Simply include it in the middle block. 827 middleTop = heightAtLine(cm, fromObj) - display.viewOffset; 828 829 if (!sel.to.ch) 830 middleBot = heightAtLine(cm, toObj) - display.viewOffset; 831 else 832 middleBot = drawForLine(sel.to.line, collapsedSpanAtStart(toObj) ? null : 0, sel.to.ch, true); 833 834 if (middleTop < middleBot) add(pl, middleTop, null, middleBot); 835 } 836 } 837 838 removeChildrenAndAdd(display.selectionDiv, fragment); 839 display.selectionDiv.style.display = ""; 840 } 841 842 // Cursor-blinking 843 function restartBlink(cm) { 844 var display = cm.display; 845 clearInterval(display.blinker); 846 var on = true; 847 display.cursor.style.visibility = display.otherCursor.style.visibility = ""; 848 display.blinker = setInterval(function() { 849 if (!display.cursor.offsetHeight) return; 850 display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden"; 851 }, cm.options.cursorBlinkRate); 852 } 853 854 // HIGHLIGHT WORKER 855 856 function startWorker(cm, time) { 857 if (cm.doc.mode.startState && cm.doc.frontier < cm.display.showingTo) 858 cm.state.highlight.set(time, bind(highlightWorker, cm)); 859 } 860 861 function highlightWorker(cm) { 862 var doc = cm.doc; 863 if (doc.frontier < doc.first) doc.frontier = doc.first; 864 if (doc.frontier >= cm.display.showingTo) return; 865 var end = +new Date + cm.options.workTime;
866 var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); 867 var changed = [], prevChange; 868 doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.showingTo + 500), function(line) { 869 if (doc.frontier >= cm.display.showingFrom) { // Visible 870 var oldStyles = line.styles; 871 line.styles = highlightLine(cm, line, state); 872 var ischange = !oldStyles || oldStyles.length != line.styles.length; 873 for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; 874 if (ischange) { 875 if (prevChange && prevChange.end == doc.frontier) prevChange.end++; 876 else changed.push(prevChange = {start: doc.frontier, end: doc.frontier + 1}); 877 } 878 line.stateAfter = copyState(doc.mode, state); 879 } else { 880 processLine(cm, line, state); 881 line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; 882 } 883 ++doc.frontier; 884 if (+new Date > end) { 885 startWorker(cm, cm.options.workDelay); 886 return true; 887 } 888 }); 889 if (changed.length) 890 operation(cm, function() { 891 for (var i = 0; i < changed.length; ++i) 892 regChange(this, changed[i].start, changed[i].end); 893 })(); 894 } 895 896 // Finds the line to start with when starting a parse. Tries to 897 // find a line with a stateAfter, so that it can start with a 898 // valid state. If that fails, it returns the line with the 899 // smallest indentation, which tends to need the least context to 900 // parse correctly. 901 function findStartLine(cm, n) { 902 var minindent, minline, doc = cm.doc; 903 for (var search = n, lim = n - 100; search > lim; --search) { 904 if (search <= doc.first) return doc.first; 905 var line = getLine(doc, search - 1); 906 if (line.stateAfter) return search; 907 var indented = countColumn(line.text, null, cm.options.tabSize); 908 if (minline == null || minindent > indented) { 909 minline = search - 1; 910 minindent = indented; 911 } 912 } 913 return minline; 914 } 915 916 function getStateBefore(cm, n) { 917 var doc = cm.doc, display = cm.display; 918 if (!doc.mode.startState) return true; 919 var pos = findStartLine(cm, n), state = pos > doc.first && getLine(doc, pos-1).stateAfter; 920 if (!state) state = startState(doc.mode); 921 else state = copyState(doc.mode, state); 922 doc.iter(pos, n, function(line) { 923 processLine(cm, line, state); 924 var save = pos == n - 1 || pos % 5 == 0 || pos >= display.showingFrom && pos < display.showingTo; 925 line.stateAfter = save ? copyState(doc.mode, state) : null; 926 ++pos; 927 }); 928 return state; 929 } 930 931 // POSITION MEASUREMENT 932 933 function paddingTop(display) {return display.lineSpace.offsetTop;} 934 function paddingLeft(display) { 935 var e = removeChildrenAndAdd(display.measure, elt("pre", null, null, "text-align: left")).appendChild(elt("span", "x")); 936 return e.offsetLeft; 937 } 938 939 function measureChar(cm, line, ch, data) { 940 var dir = -1; 941 data = data || measureLine(cm, line); 942 943 for (var pos = ch;; pos += dir) { 944 var r = data[pos]; 945 if (r) break; 946 if (dir < 0 && pos == 0) dir = 1; 947 } 948 return {left: pos < ch ? r.right : r.left, 949 right: pos > ch ? r.left : r.right, 950 top: r.top, bottom: r.bottom}; 951 } 952 953 function measureLine(cm, line) { 954 // First look in the cache 955 var display = cm.display, cache = cm.display.measureLineCache; 956 for (var i = 0; i < cache.length; ++i) { 957 var memo = cache[i]; 958 if (memo.text == line.text && memo.markedSpans == line.markedSpans && 959 display.scroller.clientWidth == memo.width && 960 memo.classes == line.textClass + "|" + line.bgClass + "|" + line.wrapClass) 961 return memo.measure; 962 } 963 964 var measure = measureLineInner(cm, line); 965 // Store result in the cache 966 var memo = {text: line.text, width: display.scroller.clientWidth, 967 markedSpans: line.markedSpans, measure: measure, 968 classes: line.textClass + "|" + line.bgClass + "|" + line.wrapClass}; 969 if (cache.length == 16) cache[++display.measureLineCachePos % 16] = memo; 970 else cache.push(memo); 971 return measure; 972 } 973 974 function measureLineInner(cm, line) { 975 var display = cm.display, measure = emptyArray(line.text.length); 976 var pre = lineContent(cm, line, measure); 977 978 // IE does not cache element positions of inline elements between 979 // calls to getBoundingClientRect. This makes the loop below, 980 // which gathers the positions of all the characters on the line, 981 // do an amount of layout work quadratic to the number of 982 // characters. When line wrapping is off, we try to improve things 983 // by first subdividing the line into a bunch of inline blocks, so 984 // that IE can reuse most of the layout information from caches 985 // for those blocks. This does interfere with line wrapping, so it 986 // doesn't work when wrapping is on, but in that case the 987 // situation is slightly better, since IE does cache line-wrapping 988 // information and only recomputes per-line. 989 if (ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) { 990 var fragment = document.createDocumentFragment(); 991 var chunk = 10, n = pre.childNodes.length; 992 for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) {
993 var wrap = elt("div", null, null, "display: inline-block"); 994 for (var j = 0; j < chunk && n; ++j) { 995 wrap.appendChild(pre.firstChild); 996 --n; 997 } 998 fragment.appendChild(wrap); 999 } 1000 pre.appendChild(fragment); 1001 } 1002 1003 removeChildrenAndAdd(display.measure, pre); 1004 1005 var outer = getRect(display.lineDiv); 1006 var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight; 1007 // Work around an IE7/8 bug where it will sometimes have randomly 1008 // replaced our pre with a clone at this point. 1009 if (ie_lt9 && display.measure.first != pre) 1010 removeChildrenAndAdd(display.measure, pre); 1011 1012 for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) { 1013 var size = getRect(cur); 1014 var top = Math.max(0, size.top - outer.top), bot = Math.min(size.bottom - outer.top, maxBot); 1015 for (var j = 0; j < vranges.length; j += 2) { 1016 var rtop = vranges[j], rbot = vranges[j+1]; 1017 if (rtop > bot || rbot < top) continue; 1018 if (rtop <= top && rbot >= bot || 1019 top <= rtop && bot >= rbot || 1020 Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) { 1021 vranges[j] = Math.min(top, rtop); 1022 vranges[j+1] = Math.max(bot, rbot); 1023 break; 1024 } 1025 } 1026 if (j == vranges.length) vranges.push(top, bot); 1027 var right = size.right; 1028 if (cur.measureRight) right = getRect(cur.measureRight).left; 1029 data[i] = {left: size.left - outer.left, right: right - outer.left, top: j}; 1030 } 1031 for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) { 1032 var vr = cur.top; 1033 cur.top = vranges[vr]; cur.bottom = vranges[vr+1]; 1034 } 1035 if (!cm.options.lineWrapping) { 1036 var last = pre.lastChild; 1037 if (last.nodeType == 3) last = pre.appendChild(elt("span", "\u200b")); 1038 data.width = getRect(last).right - outer.left; 1039 } 1040 1041 return data; 1042 } 1043 1044 function clearCaches(cm) { 1045 cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0; 1046 cm.display.cachedCharWidth = cm.display.cachedTextHeight = null; 1047 cm.display.maxLineChanged = true; 1048 cm.display.lineNumChars = null; 1049 } 1050 1051 // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page" 1052 function intoCoordSystem(cm, lineObj, rect, context) { 1053 if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { 1054 var size = widgetHeight(lineObj.widgets[i]); 1055 rect.top += size; rect.bottom += size; 1056 } 1057 if (context == "line") return rect; 1058 if (!context) context = "local"; 1059 var yOff = heightAtLine(cm, lineObj); 1060 if (context != "local") yOff -= cm.display.viewOffset; 1061 if (context == "page") { 1062 var lOff = getRect(cm.display.lineSpace); 1063 yOff += lOff.top + (window.pageYOffset || (document.documentElement || document.body).scrollTop); 1064 var xOff = lOff.left + (window.pageXOffset || (document.documentElement || document.body).scrollLeft); 1065 rect.left += xOff; rect.right += xOff; 1066 } 1067 rect.top += yOff; rect.bottom += yOff; 1068 return rect; 1069 } 1070 1071 function charCoords(cm, pos, context, lineObj) { 1072 if (!lineObj) lineObj = getLine(cm.doc, pos.line); 1073 return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch), context); 1074 } 1075 1076 function cursorCoords(cm, pos, context, lineObj, measurement) { 1077 lineObj = lineObj || getLine(cm.doc, pos.line); 1078 if (!measurement) measurement = measureLine(cm, lineObj); 1079 function get(ch, right) { 1080 var m = measureChar(cm, lineObj, ch, measurement); 1081 if (right) m.left = m.right; else m.right = m.left; 1082 return intoCoordSystem(cm, lineObj, m, context); 1083 } 1084 var order = getOrder(lineObj), ch = pos.ch; 1085 if (!order) return get(ch); 1086 var main, other, linedir = order[0].level; 1087 for (var i = 0; i < order.length; ++i) { 1088 var part = order[i], rtl = part.level % 2, nb, here; 1089 if (part.from < ch && part.to > ch) return get(ch, rtl); 1090 var left = rtl ? part.to : part.from, right = rtl ? part.from : part.to; 1091 if (left == ch) { 1092 // IE returns bogus offsets and widths for edges where the 1093 // direction flips, but only for the side with the lower 1094 // level. So we try to use the side with the higher level. 1095 if (i && part.level < (nb = order[i-1]).level) here = get(nb.level % 2 ? nb.from : nb.to - 1, true); 1096 else here = get(rtl && part.from != part.to ? ch - 1 : ch); 1097 if (rtl == linedir) main = here; else other = here; 1098 } else if (right == ch) { 1099 var nb = i < order.length - 1 && order[i+1]; 1100 if (!rtl && nb && nb.from == nb.to) continue; 1101 if (nb && part.level < nb.level) here = get(nb.level % 2 ? nb.to - 1 : nb.from); 1102 else here = get(rtl ? ch : ch - 1, true); 1103 if (rtl == linedir) main = here; else other = here; 1104 } 1105 } 1106 if (linedir && !ch) other = get(order[0].to - 1); 1107 if (!main) return other; 1108 if (other) main.other = other; 1109 return main; 1110 } 1111 1112 function PosMaybeOutside(line, ch, outside) { 1113 var pos = new Pos(line, ch); 1114 if (outside) pos.outside = true; 1115 return pos; 1116 } 1117 1118 // Coords must be lineSpace-local 1119 function coordsChar(cm, x, y) { 1120 var doc = cm.doc;
1121 y += cm.display.viewOffset; 1122 if (y < 0) return PosMaybeOutside(doc.first, 0, true); 1123 var lineNo = lineAtHeight(doc, y), last = doc.first + doc.size - 1; 1124 if (lineNo > last) 1125 return PosMaybeOutside(doc.first + doc.size - 1, getLine(doc, last).text.length, true); 1126 if (x < 0) x = 0; 1127 1128 for (;;) { 1129 var lineObj = getLine(doc, lineNo); 1130 var found = coordsCharInner(cm, lineObj, lineNo, x, y); 1131 var merged = collapsedSpanAtEnd(lineObj); 1132 var mergedPos = merged && merged.find(); 1133 if (merged && found.ch >= mergedPos.from.ch) 1134 lineNo = mergedPos.to.line; 1135 else 1136 return found; 1137 } 1138 } 1139 1140 function coordsCharInner(cm, lineObj, lineNo, x, y) { 1141 var innerOff = y - heightAtLine(cm, lineObj); 1142 var wrongLine = false, cWidth = cm.display.wrapper.clientWidth; 1143 var measurement = measureLine(cm, lineObj); 1144 1145 function getX(ch) { 1146 var sp = cursorCoords(cm, Pos(lineNo, ch), "line", 1147 lineObj, measurement); 1148 wrongLine = true; 1149 if (innerOff > sp.bottom) return Math.max(0, sp.left - cWidth); 1150 else if (innerOff < sp.top) return sp.left + cWidth; 1151 else wrongLine = false; 1152 return sp.left; 1153 } 1154 1155 var bidi = getOrder(lineObj), dist = lineObj.text.length; 1156 var from = lineLeft(lineObj), to = lineRight(lineObj); 1157 var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; 1158 1159 if (x > toX) return PosMaybeOutside(lineNo, to, toOutside); 1160 // Do a binary search between these bounds. 1161 for (;;) { 1162 if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { 1163 var after = x - fromX < toX - x, ch = after ? from : to; 1164 while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch; 1165 var pos = PosMaybeOutside(lineNo, ch, after ? fromOutside : toOutside); 1166 pos.after = after; 1167 return pos; 1168 } 1169 var step = Math.ceil(dist / 2), middle = from + step; 1170 if (bidi) { 1171 middle = from; 1172 for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); 1173 } 1174 var middleX = getX(middle); 1175 if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist -= step;} 1176 else {from = middle; fromX = middleX; fromOutside = wrongLine; dist = step;} 1177 } 1178 } 1179 1180 var measureText; 1181 function textHeight(display) { 1182 if (display.cachedTextHeight != null) return display.cachedTextHeight; 1183 if (measureText == null) { 1184 measureText = elt("pre"); 1185 // Measure a bunch of lines, for browsers that compute 1186 // fractional heights. 1187 for (var i = 0; i < 49; ++i) { 1188 measureText.appendChild(document.createTextNode("x")); 1189 measureText.appendChild(elt("br")); 1190 } 1191 measureText.appendChild(document.createTextNode("x")); 1192 } 1193 removeChildrenAndAdd(display.measure, measureText); 1194 var height = measureText.offsetHeight / 50; 1195 if (height > 3) display.cachedTextHeight = height; 1196 removeChildren(display.measure); 1197 return height || 1; 1198 } 1199 1200 function charWidth(display) { 1201 if (display.cachedCharWidth != null) return display.cachedCharWidth; 1202 var anchor = elt("span", "x"); 1203 var pre = elt("pre", [anchor]); 1204 removeChildrenAndAdd(display.measure, pre); 1205 var width = anchor.offsetWidth; 1206 if (width > 2) display.cachedCharWidth = width; 1207 return width || 10; 1208 } 1209 1210 // OPERATIONS 1211 1212 // Operations are used to wrap changes in such a way that each 1213 // change won't have to update the cursor and display (which would 1214 // be awkward, slow, and error-prone), but instead updates are 1215 // batched and then all combined and executed at once. 1216 1217 var nextOpId = 0; 1218 function startOperation(cm) { 1219 cm.curOp = { 1220 // An array of ranges of lines that have to be updated. See 1221 // updateDisplay. 1222 changes: [], 1223 updateInput: null, 1224 userSelChange: null, 1225 textChanged: null, 1226 selectionChanged: false, 1227 updateMaxLine: false, 1228 updateScrollPos: false, 1229 id: ++nextOpId 1230 }; 1231 if (!delayedCallbackDepth++) delayedCallbacks = []; 1232 } 1233 1234 function endOperation(cm) { 1235 var op = cm.curOp, doc = cm.doc, display = cm.display; 1236 cm.curOp = null; 1237 1238 if (op.updateMaxLine) computeMaxLength(cm); 1239 if (display.maxLineChanged && !cm.options.lineWrapping) { 1240 var width = measureLine(cm, display.maxLine).width; 1241 display.sizer.style.minWidth = Math.max(0, width + 3 + scrollerCutOff) + "px"; 1242 display.maxLineChanged = false;
1243 var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + display.sizer.offsetWidth - display.scroller.clientWidth); 1244 if (maxScrollLeft < doc.scrollLeft && !op.updateScrollPos) 1245 setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true); 1246 } 1247 var newScrollPos, updated; 1248 if (op.updateScrollPos) { 1249 newScrollPos = op.updateScrollPos; 1250 } else if (op.selectionChanged && display.scroller.clientHeight) { // don't rescroll if not visible 1251 var coords = cursorCoords(cm, doc.sel.head); 1252 newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom); 1253 } 1254 if (op.changes.length || newScrollPos && newScrollPos.scrollTop != null) 1255 updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop); 1256 if (!updated && op.selectionChanged) updateSelection(cm); 1257 if (op.updateScrollPos) { 1258 display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = newScrollPos.scrollTop; 1259 display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = newScrollPos.scrollLeft; 1260 alignHorizontally(cm); 1261 } else if (newScrollPos) { 1262 scrollCursorIntoView(cm); 1263 } 1264 if (op.selectionChanged) restartBlink(cm); 1265 1266 if (cm.state.focused && op.updateInput) 1267 resetInput(cm, op.userSelChange); 1268 1269 var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; 1270 if (hidden) for (var i = 0; i < hidden.length; ++i) 1271 if (!hidden[i].lines.length) signal(hidden[i], "hide"); 1272 if (unhidden) for (var i = 0; i < unhidden.length; ++i) 1273 if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); 1274 1275 var delayed; 1276 if (!--delayedCallbackDepth) { 1277 delayed = delayedCallbacks; 1278 delayedCallbacks = null; 1279 } 1280 if (op.textChanged) 1281 signal(cm, "change", cm, op.textChanged); 1282 if (op.selectionChanged) signal(cm, "cursorActivity", cm); 1283 if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i](); 1284 } 1285 1286 // Wraps a function in an operation. Returns the wrapped function. 1287 function operation(cm1, f) { 1288 return function() { 1289 var cm = cm1 || this, withOp = !cm.curOp; 1290 if (withOp) startOperation(cm); 1291 try { var result = f.apply(cm, arguments); } 1292 finally { if (withOp) endOperation(cm); } 1293 return result; 1294 }; 1295 } 1296 function docOperation(f) { 1297 return function() { 1298 var withOp = this.cm && !this.cm.curOp, result; 1299 if (withOp) startOperation(this.cm); 1300 try { result = f.apply(this, arguments); } 1301 finally { if (withOp) endOperation(this.cm); } 1302 return result; 1303 }; 1304 } 1305 function runInOp(cm, f) { 1306 var withOp = !cm.curOp, result; 1307 if (withOp) startOperation(cm); 1308 try { result = f(); } 1309 finally { if (withOp) endOperation(cm); } 1310 return result; 1311 } 1312 1313 function regChange(cm, from, to, lendiff) { 1314 if (from == null) from = cm.doc.first; 1315 if (to == null) to = cm.doc.first + cm.doc.size; 1316 cm.curOp.changes.push({from: from, to: to, diff: lendiff}); 1317 } 1318 1319 // INPUT HANDLING 1320 1321 function slowPoll(cm) { 1322 if (cm.display.pollingFast) return; 1323 cm.display.poll.set(cm.options.pollInterval, function() { 1324 readInput(cm); 1325 if (cm.state.focused) slowPoll(cm); 1326 }); 1327 } 1328 1329 function fastPoll(cm) { 1330 var missed = false; 1331 cm.display.pollingFast = true; 1332 function p() { 1333 var changed = readInput(cm); 1334 if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);} 1335 else {cm.display.pollingFast = false; slowPoll(cm);} 1336 } 1337 cm.display.poll.set(20, p); 1338 } 1339 1340 // prevInput is a hack to work with IME. If we reset the textarea 1341 // on every change, that breaks IME. So we look for changes 1342 // compared to the previous content instead. (Modern browsers have 1343 // events that indicate IME taking place, but these are not widely 1344 // supported or compatible enough yet to rely on.) 1345 function readInput(cm) { 1346 var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc, sel = doc.sel; 1347 if (!cm.state.focused || hasSelection(input) || isReadOnly(cm)) return false;
1348 var text = input.value; 1349 if (text == prevInput && posEq(sel.from, sel.to)) return false; 1350 // IE enjoys randomly deselecting our input's text when 1351 // re-focusing. If the selection is gone but the cursor is at the 1352 // start of the input, that's probably what happened. 1353 if (ie && text && input.selectionStart === 0) { 1354 resetInput(cm, true); 1355 return false; 1356 } 1357 var withOp = !cm.curOp; 1358 if (withOp) startOperation(cm); 1359 sel.shift = false; 1360 var same = 0, l = Math.min(prevInput.length, text.length); 1361 while (same < l && prevInput[same] == text[same]) ++same; 1362 var from = sel.from, to = sel.to; 1363 if (same < prevInput.length) 1364 from = Pos(from.line, from.ch - (prevInput.length - same)); 1365 else if (cm.state.overwrite && posEq(from, to) && !cm.state.pasteIncoming) 1366 to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + (text.length - same))); 1367 var updateInput = cm.curOp.updateInput; 1368 makeChange(cm.doc, {from: from, to: to, text: splitLines(text.slice(same)), 1369 origin: cm.state.pasteIncoming ? "paste" : "+input"}, "end"); 1370 1371 cm.curOp.updateInput = updateInput; 1372 if (text.length > 1000) input.value = cm.display.prevInput = ""; 1373 else cm.display.prevInput = text; 1374 if (withOp) endOperation(cm); 1375 cm.state.pasteIncoming = false; 1376 return true; 1377 } 1378 1379 function resetInput(cm, user) { 1380 var minimal, selected, doc = cm.doc; 1381 if (!posEq(doc.sel.from, doc.sel.to)) { 1382 cm.display.prevInput = ""; 1383 minimal = hasCopyEvent && 1384 (doc.sel.to.line - doc.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000); 1385 if (minimal) cm.display.input.value = "-"; 1386 else cm.display.input.value = selected || cm.getSelection(); 1387 if (cm.state.focused) selectInput(cm.display.input); 1388 }
1388 else if (user) cm.display.prevInput = cm.display.input.value = ""; 1389 cm.display.inaccurateSelection = minimal; 1390 } 1391 1392 function focusInput(cm) { 1393 if (cm.options.readOnly != "nocursor" && (!mobile || document.activeElement != cm.display.input)) 1394 cm.display.input.focus(); 1395 } 1396 1397 function isReadOnly(cm) { 1398 return cm.options.readOnly || cm.doc.cantEdit; 1399 } 1400 1401 // EVENT HANDLERS 1402 1403 function registerEventHandlers(cm) { 1404 var d = cm.display; 1405 on(d.scroller, "mousedown", operation(cm, onMouseDown)); 1406 on(d.scroller, "dblclick", operation(cm, e_preventDefault)); 1407 on(d.lineSpace, "selectstart", function(e) { 1408 if (!eventInWidget(d, e)) e_preventDefault(e); 1409 }); 1410 // Gecko browsers fire contextmenu *after* opening the menu, at 1411 // which point we can't mess with it anymore. Context menu is 1412 // handled in onMouseDown for Gecko. 1413 if (!captureMiddleClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); 1414 1415 on(d.scroller, "scroll", function() { 1416 setScrollTop(cm, d.scroller.scrollTop); 1417 setScrollLeft(cm, d.scroller.scrollLeft, true); 1418 signal(cm, "scroll", cm); 1419 }); 1420 on(d.scrollbarV, "scroll", function() { 1421 setScrollTop(cm, d.scrollbarV.scrollTop); 1422 }); 1423 on(d.scrollbarH, "scroll", function() { 1424 setScrollLeft(cm, d.scrollbarH.scrollLeft); 1425 }); 1426 1427 on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); 1428 on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); 1429 1430 function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); } 1431 on(d.scrollbarH, "mousedown", reFocus); 1432 on(d.scrollbarV, "mousedown", reFocus); 1433 // Prevent wrapper from ever scrolling 1434 on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); 1435 1436 function onResize() { 1437 // Might be a text scaling operation, clear size caches. 1438 d.cachedCharWidth = d.cachedTextHeight = null; 1439 clearCaches(cm); 1440 runInOp(cm, bind(regChange, cm)); 1441 } 1442 on(window, "resize", onResize); 1443 // Above handler holds on to the editor and its data structures. 1444 // Here we poll to unregister it when the editor is no longer in 1445 // the document, so that it can be garbage-collected. 1446 function unregister() { 1447 for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNode) {} 1448 if (p) setTimeout(unregister, 5000); 1449 else off(window, "resize", onResize); 1450 } 1451 setTimeout(unregister, 5000); 1452 1453 on(d.input, "keyup", operation(cm, function(e) { 1454 if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; 1455 if (e.keyCode == 16) cm.doc.sel.shift = false; 1456 })); 1457 on(d.input, "input", bind(fastPoll, cm)); 1458 on(d.input, "keydown", operation(cm, onKeyDown)); 1459 on(d.input, "keypress", operation(cm, onKeyPress));
1460 on(d.input, "focus", bind(onFocus, cm)); 1461 on(d.input, "blur", bind(onBlur, cm)); 1462 1463 function drag_(e) { 1464 if (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return; 1465 e_stop(e); 1466 } 1467 if (cm.options.dragDrop) { 1468 on(d.scroller, "dragstart", function(e){onDragStart(cm, e);}); 1469 on(d.scroller, "dragenter", drag_); 1470 on(d.scroller, "dragover", drag_); 1471 on(d.scroller, "drop", operation(cm, onDrop)); 1472 } 1473 on(d.scroller, "paste", function(e){ 1474 if (eventInWidget(d, e)) return; 1475 focusInput(cm); 1476 fastPoll(cm); 1477 }); 1478 on(d.input, "paste", function() { 1479 cm.state.pasteIncoming = true; 1480 fastPoll(cm); 1481 }); 1482 1483 function prepareCopy() { 1484 if (d.inaccurateSelection) { 1485 d.prevInput = ""; 1486 d.inaccurateSelection = false; 1487 d.input.value = cm.getSelection(); 1488 selectInput(d.input); 1489 } 1490 } 1491 on(d.input, "cut", prepareCopy); 1492 on(d.input, "copy", prepareCopy); 1493 1494 // Needed to handle Tab key in KHTML 1495 if (khtml) on(d.sizer, "mouseup", function() { 1496 if (document.activeElement == d.input) d.input.blur(); 1497 focusInput(cm); 1498 }); 1499 } 1500 1501 function eventInWidget(display, e) { 1502 for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { 1503 if (!n) return true; 1504 if (/\bCodeMirror-(?:line)?widget\b/.test(n.className) || 1505 n.parentNode == display.sizer && n != display.mover) return true; 1506 } 1507 } 1508 1509 function posFromMouse(cm, e, liberal) { 1510 var display = cm.display; 1511 if (!liberal) { 1512 var target = e_target(e); 1513 if (target == display.scrollbarH || target == display.scrollbarH.firstChild || 1514 target == display.scrollbarV || target == display.scrollbarV.firstChild || 1515 target == display.scrollbarFiller) return null; 1516 } 1517 var x, y, space = getRect(display.lineSpace); 1518 // Fails unpredictably on IE[67] when mouse is dragged around quickly. 1519 try { x = e.clientX; y = e.clientY; } catch (e) { return null; } 1520 return coordsChar(cm, x - space.left, y - space.top); 1521 } 1522 1523 var lastClick, lastDoubleClick; 1524 function onMouseDown(e) { 1525 var cm = this, display = cm.display, doc = cm.doc, sel = doc.sel; 1526 sel.shift = e.shiftKey; 1527 1528 if (eventInWidget(display, e)) { 1529 if (!webkit) { 1530 display.scroller.draggable = false; 1531 setTimeout(function(){display.scroller.draggable = true;}, 100); 1532 } 1533 return; 1534 } 1535 if (clickInGutter(cm, e)) return; 1536 var start = posFromMouse(cm, e); 1537 1538 switch (e_button(e)) { 1539 case 3: 1540 if (captureMiddleClick) onContextMenu.call(cm, cm, e); 1541 return; 1542 case 2: 1543 if (start) extendSelection(cm.doc, start); 1544 setTimeout(bind(focusInput, cm), 20); 1545 e_preventDefault(e); 1546 return; 1547 } 1548 // For button 1, if it was clicked inside the editor 1549 // (posFromMouse returning non-null), we have to adjust the 1550 // selection. 1551 if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;} 1552 1553 if (!cm.state.focused) onFocus(cm); 1554 1555 var now = +new Date, type = "single"; 1556 if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) { 1557 type = "triple"; 1558 e_preventDefault(e); 1559 setTimeout(bind(focusInput, cm), 20); 1560 selectLine(cm, start.line); 1561 } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) { 1562 type = "double"; 1563 lastDoubleClick = {time: now, pos: start}; 1564 e_preventDefault(e); 1565 var word = findWordAt(getLine(doc, start.line).text, start); 1566 extendSelection(cm.doc, word.from, word.to); 1567 } else { lastClick = {time: now, pos: start}; } 1568 1569 var last = start; 1570 if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) && 1571 !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") { 1572 var dragEnd = operation(cm, function(e2) { 1573 if (webkit) display.scroller.draggable = false; 1574 cm.state.draggingText = false; 1575 off(document, "mouseup", dragEnd); 1576 off(display.scroller, "drop", dragEnd); 1577 if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { 1578 e_preventDefault(e2); 1579 extendSelection(cm.doc, start); 1580 focusInput(cm); 1581 } 1582 }); 1583 // Let the drag handler handle this. 1584 if (webkit) display.scroller.draggable = true; 1585 cm.state.draggingText = dragEnd; 1586 // IE's approach to draggable 1587 if (display.scroller.dragDrop) display.scroller.dragDrop(); 1588 on(document, "mouseup", dragEnd); 1589 on(display.scroller, "drop", dragEnd); 1590 return; 1591 } 1592 e_preventDefault(e); 1593 if (type == "single") extendSelection(cm.doc, clipPos(doc, start)); 1594 1595 var startstart = sel.from, startend = sel.to; 1596 1597 function doSelect(cur) { 1598 if (type == "single") { 1599 extendSelection(cm.doc, clipPos(doc, start), cur); 1600 return; 1601 } 1602 1603 startstart = clipPos(doc, startstart); 1604 startend = clipPos(doc, startend); 1605 if (type == "double") { 1606 var word = findWordAt(getLine(doc, cur.line).text, cur); 1607 if (posLess(cur, startstart)) extendSelection(cm.doc, word.from, startend); 1608 else extendSelection(cm.doc, startstart, word.to); 1609 } else if (type == "triple") { 1610 if (posLess(cur, startstart)) extendSelection(cm.doc, startend, clipPos(doc, Pos(cur.line, 0))); 1611 else extendSelection(cm.doc, startstart, clipPos(doc, Pos(cur.line + 1, 0))); 1612 } 1613 } 1614 1615 var editorSize = getRect(display.wrapper);
1616 // Used to ensure timeout re-tries don't fire when another extend 1617 // happened in the meantime (clearTimeout isn't reliable -- at 1618 // least on Chrome, the timeouts still happen even when cleared, 1619 // if the clear happens after their scheduled firing time). 1620 var counter = 0; 1621 1622 function extend(e) { 1623 var curCount = ++counter; 1624 var cur = posFromMouse(cm, e, true); 1625 if (!cur) return; 1626 if (!posEq(cur, last)) { 1627 if (!cm.state.focused) onFocus(cm); 1628 last = cur; 1629 doSelect(cur); 1630 var visible = visibleLines(display, doc); 1631 if (cur.line >= visible.to || cur.line < visible.from) 1632 setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); 1633 } else { 1634 var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; 1635 if (outside) setTimeout(operation(cm, function() { 1636 if (counter != curCount) return; 1637 display.scroller.scrollTop += outside; 1638 extend(e); 1639 }), 50); 1640 } 1641 } 1642 1643 function done(e) { 1644 counter = Infinity; 1645 var cur = posFromMouse(cm, e); 1646 if (cur) doSelect(cur); 1647 e_preventDefault(e); 1648 focusInput(cm); 1649 off(document, "mousemove", move); 1650 off(document, "mouseup", up); 1651 } 1652 1653 var move = operation(cm, function(e) { 1654 if (!ie && !e_button(e)) done(e); 1655 else extend(e); 1656 }); 1657 var up = operation(cm, done); 1658 on(document, "mousemove", move); 1659 on(document, "mouseup", up); 1660 } 1661 1662 function onDrop(e) { 1663 var cm = this; 1664 if (eventInWidget(cm.display, e) || (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e)))) 1665 return; 1666 e_preventDefault(e); 1667 var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; 1668 if (!pos || isReadOnly(cm)) return; 1669 if (files && files.length && window.FileReader && window.File) { 1670 var n = files.length, text = Array(n), read = 0; 1671 var loadFile = function(file, i) { 1672 var reader = new FileReader; 1673 reader.onload = function() { 1674 text[i] = reader.result; 1675 if (++read == n) { 1676 pos = clipPos(cm.doc, pos); 1677 replaceRange(cm.doc, text.join(""), pos, "around", "paste"); 1678 } 1679 }; 1680 reader.readAsText(file); 1681 }; 1682 for (var i = 0; i < n; ++i) loadFile(files[i], i); 1683 } else { 1684 // Don't do a replace if the drop happened inside of the selected text. 1685 if (cm.state.draggingText && !(posLess(pos, cm.doc.sel.from) || posLess(cm.doc.sel.to, pos))) { 1686 cm.state.draggingText(e); 1687 // Ensure the editor is re-focused 1688 setTimeout(bind(focusInput, cm), 20); 1689 return; 1690 } 1691 try { 1692 var text = e.dataTransfer.getData("Text"); 1693 if (text) { 1694 var curFrom = cm.doc.sel.from, curTo = cm.doc.sel.to; 1695 setSelection(cm.doc, pos, pos); 1696 if (cm.state.draggingText) replaceRange(cm.doc, "", curFrom, curTo, "paste"); 1697 cm.replaceSelection(text, null, "paste"); 1698 focusInput(cm); 1699 onFocus(cm); 1700 } 1701 } 1702 catch(e){} 1703 } 1704 } 1705 1706 function clickInGutter(cm, e) { 1707 var display = cm.display; 1708 try { var mX = e.clientX, mY = e.clientY; } 1709 catch(e) { return false; } 1710 1711 if (mX >= Math.floor(getRect(display.gutters).right)) return false; 1712 e_preventDefault(e); 1713 if (!hasHandler(cm, "gutterClick")) return true; 1714 1715 var lineBox = getRect(display.lineDiv); 1716 if (mY > lineBox.bottom) return true; 1717 mY -= lineBox.top - display.viewOffset; 1718 1719 for (var i = 0; i < cm.options.gutters.length; ++i) { 1720 var g = display.gutters.childNodes[i]; 1721 if (g && getRect(g).right >= mX) { 1722 var line = lineAtHeight(cm.doc, mY); 1723 var gutter = cm.options.gutters[i]; 1724 signalLater(cm, "gutterClick", cm, line, gutter, e); 1725 break; 1726 } 1727 } 1728 return true; 1729 } 1730 1731 function onDragStart(cm, e) { 1732 if (eventInWidget(cm.display, e)) return; 1733 1734 var txt = cm.getSelection(); 1735 e.dataTransfer.setData("Text", txt); 1736 1737 // Use dummy image instead of default browsers image. 1738 // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. 1739 if (e.dataTransfer.setDragImage && !safari) { 1740 var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); 1741 if (opera) {
1742 img.width = img.height = 1; 1743 cm.display.wrapper.appendChild(img); 1744 // Force a relayout, or Opera won't use our image for some obscure reason 1745 img._top = img.offsetTop; 1746 } 1747 e.dataTransfer.setDragImage(img, 0, 0); 1748 if (opera) img.parentNode.removeChild(img); 1749 } 1750 } 1751 1752 function setScrollTop(cm, val) { 1753 if (Math.abs(cm.doc.scrollTop - val) < 2) return; 1754 cm.doc.scrollTop = val; 1755 if (!gecko) updateDisplay(cm, [], val); 1756 if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; 1757 if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val; 1758 if (gecko) updateDisplay(cm, []); 1759 } 1760 function setScrollLeft(cm, val, isScroller) { 1761 if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; 1762 val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); 1763 cm.doc.scrollLeft = val; 1764 alignHorizontally(cm); 1765 if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; 1766 if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val; 1767 } 1768 1769 // Since the delta values reported on mouse wheel events are 1770 // unstandardized between browsers and even browser versions, and 1771 // generally horribly unpredictable, this code starts by measuring 1772 // the scroll effect that the first few mouse wheel events have, 1773 // and, from that, detects the way it can convert deltas to pixel 1774 // offsets afterwards. 1775 // 1776 // The reason we want to know the amount a wheel event will scroll 1777 // is that it gives us a chance to update the display before the 1778 // actual scrolling happens, reducing flickering. 1779 1780 var wheelSamples = 0, wheelPixelsPerUnit = null; 1781 // Fill in a browser-detected starting value on browsers where we 1782 // know one. These don't have to be accurate -- the result of them 1783 // being wrong would just be a slight flicker on the first wheel 1784 // scroll (if it is large enough). 1785 if (ie) wheelPixelsPerUnit = -.53; 1786 else if (gecko) wheelPixelsPerUnit = 15; 1787 else if (chrome) wheelPixelsPerUnit = -.7; 1788 else if (safari) wheelPixelsPerUnit = -1/3; 1789 1790 function onScrollWheel(cm, e) { 1791 var dx = e.wheelDeltaX, dy = e.wheelDeltaY; 1792 if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; 1793 if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; 1794 else if (dy == null) dy = e.wheelDelta; 1795 1796 // Webkit browsers on OS X abort momentum scrolls when the target 1797 // of the scroll event is removed from the scrollable element. 1798 // This hack (see related code in patchDisplay) makes sure the 1799 // element is kept around. 1800 if (dy && mac && webkit) { 1801 for (var cur = e.target; cur != scroll; cur = cur.parentNode) { 1802 if (cur.lineObj) { 1803 cm.display.currentWheelTarget = cur; 1804 break; 1805 } 1806 } 1807 } 1808 1809 var display = cm.display, scroll = display.scroller; 1810 // On some browsers, horizontal scrolling will cause redraws to 1811 // happen before the gutter has been realigned, causing it to 1812 // wriggle around in a most unseemly way. When we have an 1813 // estimated pixels/delta value, we just handle horizontal 1814 // scrolling entirely here. It'll be slightly off from native, but 1815 // better than glitching out. 1816 if (dx && !gecko && !opera && wheelPixelsPerUnit != null) { 1817 if (dy) 1818 setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); 1819 setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); 1820 e_preventDefault(e); 1821 display.wheelStartX = null; // Abort measurement, if in progress 1822 return; 1823 } 1824 1825 if (dy && wheelPixelsPerUnit != null) { 1826 var pixels = dy * wheelPixelsPerUnit; 1827 var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; 1828 if (pixels < 0) top = Math.max(0, top + pixels - 50); 1829 else bot = Math.min(cm.doc.height, bot + pixels + 50); 1830 updateDisplay(cm, [], {top: top, bottom: bot}); 1831 } 1832 1833 if (wheelSamples < 20) { 1834 if (display.wheelStartX == null) { 1835 display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; 1836 display.wheelDX = dx; display.wheelDY = dy; 1837 setTimeout(function() { 1838 if (display.wheelStartX == null) return; 1839 var movedX = scroll.scrollLeft - display.wheelStartX; 1840 var movedY = scroll.scrollTop - display.wheelStartY; 1841 var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || 1842 (movedX && display.wheelDX && movedX / display.wheelDX); 1843 display.wheelStartX = display.wheelStartY = null; 1844 if (!sample) return; 1845 wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); 1846 ++wheelSamples; 1847 }, 200); 1848 } else { 1849 display.wheelDX += dx; display.wheelDY += dy; 1850 } 1851 } 1852 } 1853 1854 function doHandleBinding(cm, bound, dropShift) { 1855 if (typeof bound == "string") { 1856 bound = commands[bound]; 1857 if (!bound) return false;
1858 } 1859 // Ensure previous input has been read, so that the handler sees a 1860 // consistent view of the document 1861 if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false; 1862 var doc = cm.doc, prevShift = doc.sel.shift, done = false; 1863 try { 1864 if (isReadOnly(cm)) cm.state.suppressEdits = true; 1865 if (dropShift) doc.sel.shift = false; 1866 done = bound(cm) != Pass; 1867 } finally { 1868 doc.sel.shift = prevShift; 1869 cm.state.suppressEdits = false; 1870 } 1871 return done; 1872 } 1873 1874 function allKeyMaps(cm) { 1875 var maps = cm.state.keyMaps.slice(0); 1876 maps.push(cm.options.keyMap); 1877 if (cm.options.extraKeys) maps.unshift(cm.options.extraKeys); 1878 return maps; 1879 } 1880 1881 var maybeTransition; 1882 function handleKeyBinding(cm, e) { 1883 // Handle auto keymap transitions 1884 var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto; 1885 clearTimeout(maybeTransition); 1886 if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() { 1887 if (getKeyMap(cm.options.keyMap) == startMap) 1888 cm.options.keyMap = (next.call ? next.call(null, cm) : next); 1889 }, 50); 1890 1891 var name = keyName(e, true), handled = false; 1892 if (!name) return false; 1893 var keymaps = allKeyMaps(cm); 1894 1895 if (e.shiftKey) { 1896 // First try to resolve full name (including 'Shift-'). Failing 1897 // that, see if there is a cursor-motion command (starting with
1898 // 'go') bound to the keyname without 'Shift-'. 1899 handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);}) 1900 || lookupKey(name, keymaps, function(b) { 1901 if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(cm, b); 1902 }); 1903 } else { 1904 handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); }); 1905 } 1906 if (handled == "stop") handled = false; 1907 1908 if (handled) { 1909 e_preventDefault(e); 1910 restartBlink(cm); 1911 if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; } 1912 } 1913 return handled; 1914 } 1915 1916 function handleCharBinding(cm, e, ch) { 1917 var handled = lookupKey("'" + ch + "'", allKeyMaps(cm), 1918 function(b) { return doHandleBinding(cm, b, true); }); 1919 if (handled) { 1920 e_preventDefault(e); 1921 restartBlink(cm); 1922 } 1923 return handled; 1924 } 1925 1926 var lastStoppedKey = null; 1927 function onKeyDown(e) { 1928 var cm = this; 1929 if (!cm.state.focused) onFocus(cm); 1930 if (ie && e.keyCode == 27) { e.returnValue = false; } 1931 if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; 1932 var code = e.keyCode; 1933 // IE does strange things with escape. 1934 cm.doc.sel.shift = code == 16 || e.shiftKey; 1935 // First give onKeyEvent option a chance to handle this. 1936 var handled = handleKeyBinding(cm, e); 1937 if (opera) { 1938 lastStoppedKey = handled ? code : null; 1939 // Opera has no cut event... we try to at least catch the key combo 1940 if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) 1941 cm.replaceSelection(""); 1942 } 1943 } 1944 1945 function onKeyPress(e) { 1946 var cm = this; 1947 if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; 1948 var keyCode = e.keyCode, charCode = e.charCode; 1949 if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} 1950 if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return; 1951 var ch = String.fromCharCode(charCode == null ? keyCode : charCode); 1952 if (this.options.electricChars && this.doc.mode.electricChars && 1953 this.options.smartIndent && !isReadOnly(this) && 1954 this.doc.mode.electricChars.indexOf(ch) > -1) 1955 setTimeout(operation(cm, function() {indentLine(cm, cm.doc.sel.to.line, "smart");}), 75); 1956 if (handleCharBinding(cm, e, ch)) return; 1957 fastPoll(cm); 1958 } 1959 1960 function onFocus(cm) { 1961 if (cm.options.readOnly == "nocursor") return; 1962 if (!cm.state.focused) { 1963 signal(cm, "focus", cm); 1964 cm.state.focused = true; 1965 if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1) 1966 cm.display.wrapper.className += " CodeMirror-focused"; 1967 resetInput(cm, true); 1968 } 1969 slowPoll(cm); 1970 restartBlink(cm); 1971 } 1972 function onBlur(cm) { 1973 if (cm.state.focused) { 1974 signal(cm, "blur", cm); 1975 cm.state.focused = false; 1976 cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-focused", ""); 1977 } 1978 clearInterval(cm.display.blinker); 1979 setTimeout(function() {if (!cm.state.focused) cm.doc.sel.shift = false;}, 150); 1980 } 1981 1982 var detectingSelectAll; 1983 function onContextMenu(cm, e) { 1984 var display = cm.display, sel = cm.doc.sel; 1985 if (eventInWidget(display, e)) return; 1986 1987 var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; 1988 if (!pos || opera) return; // Opera is difficult. 1989 if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to)) 1990 operation(cm, setSelection)(cm.doc, pos, pos); 1991 1992 var oldCSS = display.input.style.cssText; 1993 display.inputDiv.style.position = "absolute"; 1994 display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + 1995 "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" + 1996 "border-width: 0; outline: none; overflow: hidden; opacity: .05; -ms-opacity: .05; filter: alpha(opacity=5);"; 1997 focusInput(cm); 1998 resetInput(cm, true); 1999 // Adds "Select all" to context menu in FF 2000 if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " "; 2001 2002 function rehide() { 2003 display.inputDiv.style.position = "relative"; 2004 display.input.style.cssText = oldCSS; 2005 if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos; 2006 slowPoll(cm); 2007 2008 // Try to detect the user choosing select-all 2009 if (display.input.selectionStart != null && (!ie || ie_lt9)) { 2010 clearTimeout(detectingSelectAll); 2011 var extval = display.input.value = " " + (posEq(sel.from, sel.to) ? "" : display.input.value), i = 0; 2012 display.prevInput = " "; 2013 display.input.selectionStart = 1; display.input.selectionEnd = extval.length; 2014 var poll = function(){ 2015 if (display.prevInput == " " && display.input.selectionStart == 0) 2016 operation(cm, commands.selectAll)(cm); 2017 else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500); 2018 else resetInput(cm); 2019 }; 2020 detectingSelectAll = setTimeout(poll, 200); 2021 } 2022 } 2023 2024 if (captureMiddleClick) { 2025 e_stop(e); 2026 var mouseup = function() { 2027 off(window, "mouseup", mouseup); 2028 setTimeout(rehide, 20); 2029 }; 2030 on(window, "mouseup", mouseup); 2031 } else { 2032 setTimeout(rehide, 50); 2033 } 2034 } 2035 2036 // UPDATING 2037 2038 function changeEnd(change) { 2039 return Pos(change.from.line + change.text.length - 1, 2040 lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); 2041 } 2042 2043 // Make sure a position will be valid after the given change. 2044 function clipPostChange(doc, change, pos) { 2045 if (!posLess(change.from, pos)) return clipPos(doc, pos); 2046 var diff = (change.text.length - 1) - (change.to.line - change.from.line); 2047 if (pos.line > change.to.line + diff) { 2048 var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1; 2049 if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length);
2050 return clipToLen(pos, getLine(doc, preLine).text.length); 2051 } 2052 if (pos.line == change.to.line + diff) 2053 return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) + 2054 getLine(doc, change.to.line).text.length - change.to.ch); 2055 var inside = pos.line - change.from.line; 2056 return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch)); 2057 } 2058 2059 // Hint can be null|"end"|"start"|"around"|{anchor,head} 2060 function computeSelAfterChange(doc, change, hint) { 2061 if (hint && typeof hint == "object") // Assumed to be {anchor, head} object 2062 return {anchor: clipPostChange(doc, change, hint.anchor), 2063 head: clipPostChange(doc, change, hint.head)}; 2064 2065 if (hint == "start") return {anchor: change.from, head: change.from}; 2066 2067 var end = changeEnd(change); 2068 if (hint == "around") return {anchor: change.from, head: end}; 2069 if (hint == "end") return {anchor: end, head: end}; 2070 2071 // hint is null, leave the selection alone as much as possible 2072 var adjustPos = function(pos) { 2073 if (posLess(pos, change.from)) return pos; 2074 if (!posLess(change.to, pos)) return end; 2075 2076 var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; 2077 if (pos.line == change.to.line) ch += end.ch - change.to.ch; 2078 return Pos(line, ch); 2079 }; 2080 return {anchor: adjustPos(doc.sel.anchor), head: adjustPos(doc.sel.head)}; 2081 } 2082 2083 function filterChange(doc, change) { 2084 var obj = { 2085 canceled: false, 2086 from: change.from, 2087 to: change.to, 2088 text: change.text, 2089 origin: change.origin, 2090 update: function(from, to, text, origin) { 2091 if (from) this.from = clipPos(doc, from); 2092 if (to) this.to = clipPos(doc, to); 2093 if (text) this.text = text; 2094 if (origin !== undefined) this.origin = origin; 2095 }, 2096 cancel: function() { this.canceled = true; } 2097 }; 2098 signal(doc, "beforeChange", doc, obj); 2099 if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); 2100 2101 if (obj.canceled) return null; 2102 return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; 2103 } 2104 2105 // Replace the range from from to to by the strings in replacement. 2106 // change is a {from, to, text [, origin]} object 2107 function makeChange(doc, change, selUpdate, ignoreReadOnly) { 2108 if (doc.cm) { 2109 if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, selUpdate, ignoreReadOnly); 2110 if (doc.cm.state.suppressEdits) return; 2111 } 2112 2113 if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { 2114 change = filterChange(doc, change); 2115 if (!change) return; 2116 } 2117 2118 // Possibly split or suppress the update based on the presence 2119 // of read-only spans in its range. 2120 var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); 2121 if (split) { 2122 for (var i = split.length - 1; i >= 1; --i) 2123 makeChangeNoReadonly(doc, {from: split[i].from, to: split[i].to, text: [""]}); 2124 if (split.length) 2125 makeChangeNoReadonly(doc, {from: split[0].from, to: split[0].to, text: change.text}, selUpdate); 2126 } else { 2127 makeChangeNoReadonly(doc, change, selUpdate); 2128 } 2129 } 2130 2131 function makeChangeNoReadonly(doc, change, selUpdate) { 2132 var selAfter = computeSelAfterChange(doc, change, selUpdate); 2133 addToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); 2134 2135 makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); 2136 var rebased = []; 2137 2138 linkedDocs(doc, function(doc, sharedHist) { 2139 if (!sharedHist && indexOf(rebased, doc.history) == -1) { 2140 rebaseHist(doc.history, change); 2141 rebased.push(doc.history); 2142 } 2143 makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); 2144 }); 2145 } 2146 2147 function makeChangeFromHistory(doc, type) { 2148 var hist = doc.history; 2149 var event = (type == "undo" ? hist.done : hist.undone).pop(); 2150 if (!event) return; 2151 hist.dirtyCounter += type == "undo" ? -1 : 1; 2152 2153 var anti = {changes: [], anchorBefore: event.anchorAfter, headBefore: event.headAfter, 2154 anchorAfter: event.anchorBefore, headAfter: event.headBefore}; 2155 (type == "undo" ? hist.undone : hist.done).push(anti); 2156 2157 for (var i = event.changes.length - 1; i >= 0; --i) { 2158 var change = event.changes[i]; 2159 change.origin = type; 2160 anti.changes.push(historyChangeFromChange(doc, change)); 2161 2162 var after = i ? computeSelAfterChange(doc, change, null) 2163 : {anchor: event.anchorBefore, head: event.headBefore}; 2164 makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); 2165 var rebased = []; 2166 2167 linkedDocs(doc, function(doc, sharedHist) { 2168 if (!sharedHist && indexOf(rebased, doc.history) == -1) { 2169 rebaseHist(doc.history, change); 2170 rebased.push(doc.history); 2171 } 2172 makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); 2173 }); 2174 } 2175 } 2176 2177 function shiftDoc(doc, distance) { 2178 function shiftPos(pos) {return Pos(pos.line + distance, pos.ch);} 2179 doc.first += distance; 2180 if (doc.cm) regChange(doc.cm, doc.first, doc.first, distance); 2181 doc.sel.head = shiftPos(doc.sel.head); doc.sel.anchor = shiftPos(doc.sel.anchor); 2182 doc.sel.from = shiftPos(doc.sel.from); doc.sel.to = shiftPos(doc.sel.to); 2183 } 2184 2185 function makeChangeSingleDoc(doc, change, selAfter, spans) { 2186 if (doc.cm && !doc.cm.curOp) 2187 return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); 2188 2189 if (change.to.line < doc.first) { 2190 shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); 2191 return; 2192 } 2193 if (change.from.line >
2193 doc.lastLine()) return; 2194 2195 // Clip the change to the size of this doc 2196 if (change.from.line < doc.first) { 2197 var shift = change.text.length - 1 - (doc.first - change.from.line); 2198 shiftDoc(doc, shift); 2199 change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), 2200 text: [lst(change.text)], origin: change.origin}; 2201 } 2202 var last = doc.lastLine(); 2203 if (change.to.line > last) { 2204 change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), 2205 text: [change.text[0]], origin: change.origin}; 2206 } 2207 2208 if (!selAfter) selAfter = computeSelAfterChange(doc, change, null); 2209 if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans, selAfter); 2210 else updateDoc(doc, change, spans, selAfter); 2211 } 2212 2213 function makeChangeSingleDocInEditor(cm, change, spans, selAfter) { 2214 var doc = cm.doc, display = cm.display, from = change.from, to = change.to; 2215 2216 var recomputeMaxLength = false, checkWidthStart = from.line; 2217 if (!cm.options.lineWrapping) { 2218 checkWidthStart = lineNo(visualLine(doc, getLine(doc, from.line))); 2219 doc.iter(checkWidthStart, to.line + 1, function(line) { 2220 if (line == display.maxLine) { 2221 recomputeMaxLength = true; 2222 return true; 2223 } 2224 }); 2225 } 2226 2227 updateDoc(doc, change, spans, selAfter, estimateHeight(cm)); 2228 2229 if (!cm.options.lineWrapping) { 2230 doc.iter(checkWidthStart, from.line + change.text.length, function(line) { 2231 var len = lineLength(doc, line); 2232 if (len > display.maxLineLength) { 2233 display.maxLine = line; 2234 display.maxLineLength = len; 2235 display.maxLineChanged = true; 2236 recomputeMaxLength = false; 2237 } 2238 }); 2239 if (recomputeMaxLength) cm.curOp.updateMaxLine = true; 2240 } 2241 2242 // Adjust frontier, schedule worker 2243 doc.frontier = Math.min(doc.frontier, from.line); 2244 startWorker(cm, 400); 2245 2246 var lendiff = change.text.length - (to.line - from.line) - 1; 2247 // Remember that these lines changed, for updating the display 2248 regChange(cm, from.line, to.line + 1, lendiff); 2249 if (hasHandler(cm, "change")) { 2250 var changeObj = {from: from, to: to, text: change.text, origin: change.origin}; 2251 if (cm.curOp.textChanged) { 2252 for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {} 2253 cur.next = changeObj; 2254 } else cm.curOp.textChanged = changeObj; 2255 } 2256 } 2257 2258 function replaceRange(doc, code, from, to, origin) { 2259 if (!to) to = from; 2260 if (posLess(to, from)) { var tmp = to; to = from; from = tmp; } 2261 if (typeof code == "string") code = splitLines(code); 2262 makeChange(doc, {from: from, to: to, text: code, origin: origin}, null); 2263 } 2264 2265 // POSITION OBJECT 2266 2267 function Pos(line, ch) { 2268 if (!(this instanceof Pos)) return new Pos(line, ch); 2269 this.line = line; this.ch = ch; 2270 } 2271 CodeMirror.Pos = Pos; 2272 2273 function posEq(a, b) {return a.line == b.line && a.ch == b.ch;} 2274 function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);} 2275 function copyPos(x) {return Pos(x.line, x.ch);} 2276 2277 // SELECTION 2278 2279 function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} 2280 function clipPos(doc, pos) { 2281 if (pos.line < doc.first) return Pos(doc.first, 0); 2282 var last = doc.first + doc.size - 1; 2283 if (pos.line > last) return Pos(last, getLine(doc, last).text.length); 2284 return clipToLen(pos, getLine(doc, pos.line).text.length); 2285 } 2286 function clipToLen(pos, linelen) { 2287 var ch = pos.ch; 2288 if (ch == null || ch > linelen) return Pos(pos.line, linelen); 2289 else if (ch < 0) return Pos(pos.line, 0); 2290 else return pos; 2291 } 2292 function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} 2293 2294 // If shift is held, this will move the selection anchor. Otherwise, 2295 // it'll set the whole selection. 2296 function extendSelection(doc, pos, other, bias) { 2297 if (doc.sel.shift || doc.sel.extend) { 2298 var anchor = doc.sel.anchor; 2299 if (other) { 2300 var posBefore = posLess(pos, anchor); 2301 if (posBefore != posLess(other, anchor)) { 2302 anchor = pos; 2303 pos = other; 2304 } else if (posBefore != posLess(pos, other)) { 2305 pos = other; 2306 } 2307 } 2308 setSelection(doc, anchor, pos, bias); 2309 } else { 2310 setSelection(doc, pos, other || pos, bias); 2311 } 2312 if (doc.cm) doc.cm.curOp.userSelChange = true; 2313 } 2314 2315 function filterSelectionChange(doc, anchor, head) { 2316 var obj = {anchor: anchor, head: head}; 2317 signal(doc, "beforeSelectionChange", doc, obj); 2318 if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); 2319 obj.anchor = clipPos(doc, obj.anchor); obj.head = clipPos(doc, obj.head); 2320 return obj; 2321 } 2322 2323 // Update the selection. Last two args are only used by 2324 // updateDoc, since they have to be expressed in the line 2325 // numbers before the update. 2326 function setSelection(doc, anchor, head, bias, checkAtomic) { 2327 if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { 2328 var filtered = filterSelectionChange(doc, anchor, head); 2329 head = filtered.head; 2330 anchor = filtered.anchor; 2331 } 2332 2333 var sel = doc.sel; 2334 sel.goalColumn = null; 2335 // Skip over atomic spans. 2336 if (checkAtomic || !posEq(anchor, sel.anchor)) 2337 anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push");
2338 if (checkAtomic || !posEq(head, sel.head)) 2339 head = skipAtomic(doc, head, bias, checkAtomic != "push"); 2340 2341 if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return; 2342 2343 sel.anchor = anchor; sel.head = head; 2344 var inv = posLess(head, anchor); 2345 sel.from = inv ? head : anchor; 2346 sel.to = inv ? anchor : head; 2347 2348 if (doc.cm) 2349 doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; 2350 2351 signalLater(doc, "cursorActivity", doc); 2352 } 2353 2354 function reCheckSelection(cm) { 2355 setSelection(cm.doc, cm.doc.sel.from, cm.doc.sel.to, null, "push"); 2356 } 2357 2358 function skipAtomic(doc, pos, bias, mayClear) { 2359 var flipped = false, curPos = pos; 2360 var dir = bias || 1; 2361 doc.cantEdit = false; 2362 search: for (;;) { 2363 var line = getLine(doc, curPos.line), toClear; 2364 if (line.markedSpans) { 2365 for (var i = 0; i < line.markedSpans.length; ++i) { 2366 var sp = line.markedSpans[i], m = sp.marker; 2367 if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) && 2368 (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { 2369 if (mayClear && m.clearOnEnter) { 2370 (toClear || (toClear = [])).push(m); 2371 continue; 2372 } else if (!m.atomic) continue; 2373 var newPos = m.find()[dir < 0 ? "from" : "to"]; 2374 if (posEq(newPos, curPos)) { 2375 newPos.ch += dir; 2376 if (newPos.ch < 0) { 2377 if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1)); 2378 else newPos = null; 2379 } else if (newPos.ch > line.text.length) { 2380 if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0); 2381 else newPos = null; 2382 } 2383 if (!newPos) { 2384 if (flipped) { 2385 // Driven in a corner -- no valid cursor position found at all 2386 // -- try again *with* clearing, if we didn't already 2387 if (!mayClear) return skipAtomic(doc, pos, bias, true); 2388 // Otherwise, turn off editing until further notice, and return the start of the doc 2389 doc.cantEdit = true; 2390 return Pos(doc.first, 0); 2391 } 2392 flipped = true; newPos = pos; dir = -dir; 2393 } 2394 } 2395 curPos = newPos; 2396 continue search; 2397 } 2398 } 2399 if (toClear) for (var i = 0; i < toClear.length; ++i) toClear[i].clear(); 2400 } 2401 return curPos; 2402 } 2403 } 2404 2405 // SCROLLING 2406 2407 function scrollCursorIntoView(cm) { 2408 var coords = scrollPosIntoView(cm, cm.doc.sel.head); 2409 if (!cm.state.focused) return; 2410 var display = cm.display, box = getRect(display.sizer), doScroll = null; 2411 if (coords.top + box.top < 0) doScroll = true; 2412 else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; 2413 if (doScroll != null && !phantom) { 2414 var hidden = display.cursor.style.display == "none"; 2415 if (hidden) { 2416 display.cursor.style.display = ""; 2417 display.cursor.style.left = coords.left + "px"; 2418 display.cursor.style.top = (coords.top - display.viewOffset) + "px"; 2419 } 2420 display.cursor.scrollIntoView(doScroll); 2421 if (hidden) display.cursor.style.display = "none"; 2422 } 2423 } 2424 2425 function scrollPosIntoView(cm, pos) { 2426 for (;;) { 2427 var changed = false, coords = cursorCoords(cm, pos); 2428 var scrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom); 2429 var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; 2430 if (scrollPos.scrollTop != null) { 2431 setScrollTop(cm, scrollPos.scrollTop); 2432 if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; 2433 } 2434 if (scrollPos.scrollLeft != null) { 2435 setScrollLeft(cm, scrollPos.scrollLeft); 2436 if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; 2437 } 2438 if (!changed) return coords; 2439 } 2440 } 2441 2442 function scrollIntoView(cm, x1, y1, x2, y2) { 2443 var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); 2444 if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); 2445 if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); 2446 } 2447 2448 function calculateScrollPos(cm, x1, y1, x2, y2) { 2449 var display = cm.display, pt = paddingTop(display); 2450 y1 += pt; y2 += pt; 2451 var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {}; 2452 var docBottom = cm.doc.height + 2 * pt; 2453 var atTop = y1 < pt + 10, atBottom = y2 + pt > docBottom - 10; 2454 if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1); 2455 else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2) - screen; 2456
2457 var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft; 2458 x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth; 2459 var gutterw = display.gutters.offsetWidth; 2460 var atLeft = x1 < gutterw + 10; 2461 if (x1 < screenleft + gutterw || atLeft) { 2462 if (atLeft) x1 = 0; 2463 result.scrollLeft = Math.max(0, x1 - 10 - gutterw); 2464 } else if (x2 > screenw + screenleft - 3) { 2465 result.scrollLeft = x2 + 10 - screenw; 2466 } 2467 return result; 2468 } 2469 2470 // API UTILITIES 2471 2472 function indentLine(cm, n, how, aggressive) { 2473 var doc = cm.doc; 2474 if (!how) how = "add"; 2475 if (how == "smart") { 2476 if (!cm.doc.mode.indent) how = "prev"; 2477 else var state = getStateBefore(cm, n); 2478 } 2479 2480 var tabSize = cm.options.tabSize; 2481 var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); 2482 var curSpaceString = line.text.match(/^\s*/)[0], indentation; 2483 if (how == "smart") { 2484 indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); 2485 if (indentation == Pass) { 2486 if (!aggressive) return; 2487 how = "prev"; 2488 } 2489 } 2490 if (how == "prev") { 2491 if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); 2492 else indentation = 0; 2493 } else if (how == "add") { 2494 indentation = curSpace + cm.options.indentUnit; 2495 } else if (how == "subtract") { 2496 indentation = curSpace - cm.options.indentUnit; 2497 } 2498 indentation = Math.max(0, indentation); 2499 2500 var indentString = "", pos = 0; 2501 if (cm.options.indentWithTabs) 2502 for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} 2503 if (pos < indentation) indentString += spaceStr(indentation - pos); 2504 2505 if (indentString != curSpaceString) 2506 replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); 2507 line.stateAfter = null; 2508 } 2509 2510 function changeLine(cm, handle, op) { 2511 var no = handle, line = handle, doc = cm.doc; 2512 if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); 2513 else no = lineNo(handle); 2514 if (no == null) return null; 2515 if (op(line, no)) regChange(cm, no, no + 1); 2516 else return null; 2517 return line; 2518 } 2519 2520 function findPosH(doc, pos, dir, unit, visually) { 2521 var line = pos.line, ch = pos.ch; 2522 var lineObj = getLine(doc, line); 2523 var possible = true; 2524 function findNextLine() { 2525 var l = line + dir; 2526 if (l < doc.first || l >= doc.first + doc.size) return (possible = false); 2527 line = l; 2528 return lineObj = getLine(doc, l); 2529 } 2530 function moveOnce(boundToLine) { 2531 var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); 2532 if (next == null) { 2533 if (!boundToLine && findNextLine()) { 2534 if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); 2535 else ch = dir < 0 ? lineObj.text.length : 0; 2536 } else return (possible = false); 2537 } else ch = next; 2538 return true; 2539 } 2540 2541 if (unit == "char") moveOnce(); 2542 else if (unit == "column") moveOnce(true); 2543 else if (unit == "word") { 2544 var sawWord = false; 2545 for (;;) { 2546 if (dir < 0) if (!moveOnce()) break; 2547 if (isWordChar(lineObj.text.charAt(ch))) sawWord = true; 2548 else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;} 2549 if (dir > 0) if (!moveOnce()) break; 2550 } 2551 } 2552 var result = skipAtomic(doc, Pos(line, ch), dir, true); 2553 if (!possible) result.hitSide = true; 2554 return result; 2555 } 2556 2557 function findPosV(cm, pos, dir, unit) { 2558 var doc = cm.doc, x = pos.left, y; 2559 if (unit == "page") { 2560 var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); 2561 y = pos.top + dir * pageSize; 2562 } else if (unit == "line") { 2563 y = dir > 0 ? pos.bottom + 3 : pos.top - 3; 2564 } 2565 for (;;) { 2566 var target = coordsChar(cm, x, y); 2567 if (!target.outside) break; 2568 if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } 2569 y += dir * 5; 2570 } 2571 return target; 2572 } 2573 2574 function findWordAt(line, pos) { 2575 var start = pos.ch, end = pos.ch; 2576 if (line) { 2577 if (pos.after === false || end == line.length) --start; else ++end; 2578 var startChar = line.charAt(start); 2579 var check = isWordChar(startChar) ? isWordChar : 2580 /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} : 2581 function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; 2582 while (start > 0 && check(line.charAt(start - 1))) --start; 2583 while (end < line.length && check(line.charAt(end))) ++end; 2584 } 2585 return {from: Pos(pos.line, start), to: Pos(pos.line, end)}; 2586 } 2587 2588 function selectLine(cm, line) { 2589 extendSelection(cm.doc, Pos(line, 0), clipPos(cm.doc, Pos(line + 1, 0))); 2590 } 2591 2592 // PROTOTYPE 2593 2594 // The publicly visible API. Note that operation(null, f) means 2595 // 'wrap f in an operation, performed on its `this` parameter' 2596 2597 CodeMirror.prototype = { 2598 focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);}, 2599 2600 setOption: function(option, value) { 2601 var options = this.options, old = options[option]; 2602 if (options[option] == value && option != "mode") return; 2603 options[option] = value; 2604 if (optionHandlers.hasOwnProperty(option)) 2605 operation(this, optionHandlers[option])(this, value, old); 2606 }, 2607 2608 getOption: function(option) {return this.options[option];}, 2609 getDoc: function() {return this.doc;}, 2610 2611 addKeyMap: function(map) { 2612 this.state.keyMaps.push(map); 2613 }, 2614 removeKeyMap: function(map) { 2615 var maps = this.state.keyMaps; 2616 for (var i = 0; i < maps.length; ++i) 2617 if ((typeof map == "string" ? maps[i].name : maps[i]) == map) { 2618 maps.splice(i, 1); 2619 return true; 2620 } 2621 }, 2622 2623 addOverlay: operation(null, function(spec, options) { 2624 var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); 2625 if (mode.startState) throw new Error("Overlays may not be stateful."); 2626 this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); 2627 this.state.modeGen++; 2628 regChange(this); 2629 }), 2630 removeOverlay: operation(null, function(spec) { 2631 var overlays = this.state.overlays; 2632 for (var i = 0; i < overlays.length; ++i) { 2633 if (overlays[i].modeSpec == spec) { 2634 overlays.splice(i, 1); 2635 this.state.modeGen++; 2636 regChange(this); 2637 return; 2638 } 2639 } 2640 }), 2641 2642 indentLine: operation(null, function(n, dir, aggressive) { 2643 if (typeof dir != "string") { 2644 if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; 2645 else dir = dir ? "add" : "subtract"; 2646 } 2647 if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); 2648 }), 2649 indentSelection: operation(null, function(how) { 2650 var sel = this.doc.sel; 2651 if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how); 2652 var e = sel.to.line - (sel.to.ch ? 0 : 1); 2653 for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how); 2654 }), 2655 2656 // Fetch the parser token for a given character. Useful for hacks 2657 // that want to inspect the mode state (say, for completion). 2658 getTokenAt: function(pos) { 2659 var doc = this.doc; 2660 pos = clipPos(doc, pos); 2661 var state = getStateBefore(this, pos.line), mode = this.doc.mode; 2662 var line = getLine(doc, pos.line); 2663 var stream = new StringStream(line.text, this.options.tabSize); 2664 while (stream.pos < pos.ch && !stream.eol()) { 2665 stream.start = stream.pos; 2666 var style = mode.token(stream, state); 2667 } 2668 return {start: stream.start, 2669 end: stream.pos,
2670 string: stream.current(), 2671 className: style || null, // Deprecated, use 'type' instead 2672 type: style || null, 2673 state: state}; 2674 }, 2675 2676 getStateAfter: function(line) { 2677 var doc = this.doc; 2678 line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); 2679 return getStateBefore(this, line + 1); 2680 }, 2681 2682 cursorCoords: function(start, mode) { 2683 var pos, sel = this.doc.sel; 2684 if (start == null) pos = sel.head; 2685 else if (typeof start == "object") pos = clipPos(this.doc, start); 2686 else pos = start ? sel.from : sel.to; 2687 return cursorCoords(this, pos, mode || "page"); 2688 }, 2689 2690 charCoords: function(pos, mode) { 2691 return charCoords(this, clipPos(this.doc, pos), mode || "page"); 2692 }, 2693 2694 coordsChar: function(coords) { 2695 var off = getRect(this.display.lineSpace); 2696 var scrollY = window.pageYOffset || (document.documentElement || document.body).scrollTop; 2697 var scrollX = window.pageXOffset || (document.documentElement || document.body).scrollLeft; 2698 return coordsChar(this, coords.left - off.left - scrollX, coords.top - off.top - scrollY); 2699 }, 2700 2701 defaultTextHeight: function() { return textHeight(this.display); }, 2702 2703 setGutterMarker: operation(null, function(line, gutterID, value) { 2704 return changeLine(this, line, function(line) { 2705 var markers = line.gutterMarkers || (line.gutterMarkers = {}); 2706 markers[gutterID] = value; 2707 if (!value && isEmpty(markers)) line.gutterMarkers = null; 2708 return true; 2709 }); 2710 }), 2711 2712 clearGutter: operation(null, function(gutterID) { 2713 var cm = this, doc = cm.doc, i = doc.first; 2714 doc.iter(function(line) { 2715 if (line.gutterMarkers && line.gutterMarkers[gutterID]) { 2716 line.gutterMarkers[gutterID] = null; 2717 regChange(cm, i, i + 1); 2718 if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; 2719 } 2720 ++i; 2721 }); 2722 }), 2723 2724 addLineClass: operation(null, function(handle, where, cls) { 2725 return changeLine(this, handle, function(line) { 2726 var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; 2727 if (!line[prop]) line[prop] = cls; 2728 else if (new RegExp("\\b" + cls + "\\b").test(line[prop])) return false; 2729 else line[prop] += " " + cls; 2730 return true; 2731 }); 2732 }), 2733 2734 removeLineClass: operation(null, function(handle, where, cls) { 2735 return changeLine(this, handle, function(line) { 2736 var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; 2737 var cur = line[prop]; 2738 if (!cur) return false; 2739 else if (cls == null) line[prop] = null; 2740 else { 2741 var upd = cur.replace(new RegExp("^" + cls + "\\b\\s*|\\s*\\b" + cls + "\\b"), ""); 2742 if (upd == cur) return false; 2743 line[prop] = upd || null; 2744 } 2745 return true; 2746 }); 2747 }), 2748 2749 addLineWidget: operation(null, function(handle, node, options) { 2750 return addLineWidget(this, handle, node, options); 2751 }), 2752 2753 removeLineWidget: function(widget) { widget.clear(); }, 2754 2755 lineInfo: function(line) { 2756 if (typeof line == "number") { 2757 if (!isLine(this.doc, line)) return null; 2758 var n = line; 2759 line = getLine(this.doc, line); 2760 if (!line) return null; 2761 } else { 2762 var n = lineNo(line); 2763 if (n == null) return null; 2764 } 2765 return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, 2766 textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, 2767 widgets: line.widgets}; 2768 }, 2769 2770 getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};}, 2771 2772 addWidget: function(pos, node, scroll, vert, horiz) { 2773 var display = this.display; 2774 pos = cursorCoords(this, clipPos(this.doc, pos)); 2775 var top = pos.bottom, left = pos.left; 2776 node.style.position = "absolute"; 2777 display.sizer.appendChild(node); 2778 if (vert == "over") { 2779 top = pos.top; 2780 } else if (vert == "above" || vert == "near") { 2781 var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), 2782 hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); 2783 // Default to positioning above (if specified and possible); otherwise default to positioning below 2784 if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) 2785 top = pos.top - node.offsetHeight; 2786 else if (pos.bottom + node.offsetHeight <= vspace) 2787 top = pos.bottom; 2788 if (left + node.offsetWidth > hspace) 2789 left = hspace - node.offsetWidth; 2790 } 2791 node.style.top = (top + paddingTop(display)) + "px"; 2792 node.style.left = node.style.right = ""; 2793 if (horiz == "right") { 2794 left = display.sizer.clientWidth - node.offsetWidth; 2795 node.style.right = "0px"; 2796 } else { 2797 if (horiz == "left") left = 0; 2798 else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; 2799 node.style.left = left + "px"; 2800 } 2801 if (scroll) 2802 scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight); 2803 }, 2804 2805 triggerOnKeyDown: operation(null, onKeyDown), 2806
2807 execCommand: function(cmd) {return commands[cmd](this);}, 2808 2809 findPosH: function(from, amount, unit, visually) { 2810 var dir = 1; 2811 if (amount < 0) { dir = -1; amount = -amount; } 2812 for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { 2813 cur = findPosH(this.doc, cur, dir, unit, visually); 2814 if (cur.hitSide) break; 2815 } 2816 return cur; 2817 }, 2818 2819 moveH: operation(null, function(dir, unit) { 2820 var sel = this.doc.sel, pos; 2821 if (sel.shift || sel.extend || posEq(sel.from, sel.to)) 2822 pos = findPosH(this.doc, sel.head, dir, unit, this.options.rtlMoveVisually); 2823 else 2824 pos = dir < 0 ? sel.from : sel.to; 2825 extendSelection(this.doc, pos, pos, dir); 2826 }), 2827 2828 deleteH: operation(null, function(dir, unit) { 2829 var sel = this.doc.sel; 2830 if (!posEq(sel.from, sel.to)) replaceRange(this.doc, "", sel.from, sel.to, "+delete"); 2831 else replaceRange(this.doc, "", sel.from, findPosH(this.doc, sel.head, dir, unit, false), "+delete"); 2832 this.curOp.userSelChange = true; 2833 }), 2834 2835 findPosV: function(from, amount, unit, goalColumn) { 2836 var dir = 1, x = goalColumn; 2837 if (amount < 0) { dir = -1; amount = -amount; } 2838 for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { 2839 var coords = cursorCoords(this, cur, "div"); 2840 if (x == null) x = coords.left; 2841 else coords.left = x; 2842 cur = findPosV(this, coords, dir, unit); 2843 if (cur.hitSide) break; 2844 } 2845 return cur; 2846 }, 2847 2848 moveV: operation(null, function(dir, unit) { 2849 var sel = this.doc.sel; 2850 var pos = cursorCoords(this, sel.head, "div"); 2851 if (sel.goalColumn != null) pos.left = sel.goalColumn; 2852 var target = findPosV(this, pos, dir, unit); 2853 2854 if (unit == "page") 2855 this.display.scrollbarV.scrollTop += charCoords(this, target, "div").top - pos.top; 2856 extendSelection(this.doc, target, target, dir); 2857 sel.goalColumn = pos.left; 2858 }), 2859 2860 toggleOverwrite: function() { 2861 if (this.state.overwrite = !this.state.overwrite) 2862 this.display.cursor.className += " CodeMirror-overwrite"; 2863 else 2864 this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", ""); 2865 }, 2866 2867 scrollTo: operation(null, function(x, y) { 2868 this.curOp.updateScrollPos = {scrollLeft: x, scrollTop: y}; 2869 }), 2870 getScrollInfo: function() { 2871 var scroller = this.display.scroller, co = scrollerCutOff; 2872 return {left: scroller.scrollLeft, top: scroller.scrollTop, 2873 height: scroller.scrollHeight - co, width: scroller.scrollWidth - co, 2874 clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co}; 2875 }, 2876 2877 scrollIntoView: function(pos) { 2878 if (typeof pos == "number") pos = Pos(pos, 0); 2879 if (!pos || pos.line != null) { 2880 pos = pos ? clipPos(this.doc, pos) : this.doc.sel.head; 2881 scrollPosIntoView(this, pos); 2882 } else { 2883 scrollIntoView(this, pos.left, pos.top, pos.right, pos.bottom); 2884 } 2885 }, 2886 2887 setSize: function(width, height) { 2888 function interpret(val) { 2889 return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; 2890 } 2891 if (width != null) this.display.wrapper.style.width = interpret(width); 2892 if (height != null) this.display.wrapper.style.height = interpret(height); 2893 this.refresh(); 2894 }, 2895 2896 on: function(type, f) {on(this, type, f);}, 2897 off: function(type, f) {off(this, type, f);}, 2898 2899 operation: function(f){return runInOp(this, f);}, 2900 2901 refresh: operation(null, function() { 2902 clearCaches(this); 2903 this.curOp.updateScrollPos = {scrollTop: this.doc.scrollTop, scrollLeft: this.doc.scrollLeft}; 2904 regChange(this); 2905 }), 2906 2907 swapDoc: operation(null, function(doc) { 2908 var old = this.doc; 2909 old.cm = null; 2910 attachDoc(this, doc); 2911 clearCaches(this); 2912 this.curOp.updateScrollPos = {scrollTop: doc.scrollTop, scrollLeft: doc.scrollLeft}; 2913 return old; 2914 }), 2915 2916 getInputField: function(){return this.display.input;}, 2917 getWrapperElement: function(){return this.display.wrapper;}, 2918 getScrollerElement: function(){return this.display.scroller;}, 2919 getGutterElement: function(){return this.display.gutters;} 2920 }; 2921 2922 // OPTION DEFAULTS 2923 2924 var optionHandlers = CodeMirror.optionHandlers = {}; 2925 2926 // The default configuration options. 2927 var defaults = CodeMirror.defaults = {}; 2928 2929 function option(name, deflt, handle, notOnInit) { 2930 CodeMirror.defaults[name] = deflt; 2931 if (handle) optionHandlers[name] = 2932 notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; 2933 } 2934 2935 var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; 2936 2937 // These two are, on init, called from the constructor because they 2938 // have to be initialized before the editor can start at all. 2939 option("value", "", function(cm, val) { 2940 cm.setValue(val); 2941 }, true); 2942 option("mode", null, function(cm, val) { 2943 cm.doc.modeOption = val;
2944 loadMode(cm); 2945 }, true); 2946 2947 option("indentUnit", 2, loadMode, true); 2948 option("indentWithTabs", false); 2949 option("smartIndent", true); 2950 option("tabSize", 4, function(cm) { 2951 loadMode(cm); 2952 clearCaches(cm); 2953 regChange(cm); 2954 }, true); 2955 option("electricChars", true); 2956 option("rtlMoveVisually", !windows); 2957 2958 option("theme", "default", function(cm) { 2959 themeChanged(cm); 2960 guttersChanged(cm); 2961 }, true); 2962 option("keyMap", "default", keyMapChanged); 2963 option("extraKeys", null); 2964 2965 option("onKeyEvent", null); 2966 option("onDragEvent", null); 2967 2968 option("lineWrapping", false, wrappingChanged, true); 2969 option("gutters", [], function(cm) { 2970 setGuttersForLineNumbers(cm.options); 2971 guttersChanged(cm); 2972 }, true); 2973 option("fixedGutter", true, function(cm, val) { 2974 cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; 2975 cm.refresh(); 2976 }, true); 2977 option("lineNumbers", false, function(cm) { 2978 setGuttersForLineNumbers(cm.options); 2979 guttersChanged(cm); 2980 }, true); 2981 option("firstLineNumber", 1, guttersChanged, true); 2982 option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true); 2983 option("showCursorWhenSelecting", false, updateSelection, true); 2984 2985 option("readOnly", false, function(cm, val) { 2986 if (val == "nocursor") {onBlur(cm); cm.display.input.blur();} 2987 else if (!val) resetInput(cm, true); 2988 }); 2989 option("dragDrop", true); 2990 2991 option("cursorBlinkRate", 530); 2992 option("cursorHeight", 1); 2993 option("workTime", 100); 2994 option("workDelay", 100); 2995 option("flattenSpans", true); 2996 option("pollInterval", 100); 2997 option("undoDepth", 40, function(cm, val){cm.doc.history.undoDepth = val;}); 2998 option("viewportMargin", 10, function(cm){cm.refresh();}, true); 2999 3000 option("tabindex", null, function(cm, val) { 3001 cm.display.input.tabIndex = val || ""; 3002 }); 3003 option("autofocus", null); 3004 3005 // MODE DEFINITION AND QUERYING 3006 3007 // Known modes, by name and by MIME 3008 var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; 3009 3010 CodeMirror.defineMode = function(name, mode) { 3011 if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; 3012 if (arguments.length > 2) { 3013 mode.dependencies = []; 3014 for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]); 3015 } 3016 modes[name] = mode; 3017 }; 3018 3019 CodeMirror.defineMIME = function(mime, spec) { 3020 mimeModes[mime] = spec; 3021 }; 3022 3023 CodeMirror.resolveMode = function(spec) { 3024 if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) 3025 spec = mimeModes[spec]; 3026 else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) 3027 return CodeMirror.resolveMode("application/xml"); 3028 if (typeof spec == "string") return {name: spec}; 3029 else return spec || {name: "null"}; 3030 }; 3031 3032 CodeMirror.getMode = function(options, spec) { 3033 spec = CodeMirror.resolveMode(spec); 3034 var mfactory = modes[spec.name]; 3035 if (!mfactory) return CodeMirror.getMode(options, "text/plain"); 3036 var modeObj = mfactory(options, spec); 3037 if (modeExtensions.hasOwnProperty(spec.name)) { 3038 var exts = modeExtensions[spec.name]; 3039 for (var prop in exts) { 3040 if (!exts.hasOwnProperty(prop)) continue; 3041 if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; 3042 modeObj[prop] = exts[prop]; 3043 } 3044 } 3045 modeObj.name = spec.name; 3046 return modeObj; 3047 }; 3048 3049 CodeMirror.defineMode("null", function() { 3050 return {token: function(stream) {stream.skipToEnd();}}; 3051 }); 3052 CodeMirror.defineMIME("text/plain", "null"); 3053 3054 var modeExtensions = CodeMirror.modeExtensions = {}; 3055 CodeMirror.extendMode = function(mode, properties) { 3056 var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); 3057 copyObj(properties, exts); 3058 }; 3059 3060 // EXTENSIONS 3061 3062 CodeMirror.defineExtension = function(name, func) { 3063 CodeMirror.prototype[name] = func; 3064 }; 3065 3066 CodeMirror.defineOption = option; 3067 3068 var initHooks = []; 3069 CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; 3070 3071 // MODE STATE HANDLING 3072 3073 // Utility functions for working with state. Exported because modes 3074 // sometimes need to do this. 3075 function copyState(mode, state) { 3076 if (state === true) return state; 3077 if (mode.copyState) return mode.copyState(state); 3078 var nstate = {}; 3079 for (var n in state) { 3080 var val = state[n]; 3081 if (val instanceof Array) val = val.concat([]); 3082 nstate[n] = val; 3083 } 3084 return nstate; 3085 } 3086 CodeMirror.copyState = copyState; 3087 3088 function startState(mode, a1, a2) { 3089 return mode.startState ? mode.startState(a1, a2) : true; 3090 } 3091 CodeMirror.startState = startState; 3092 3093 CodeMirror.innerMode = function(mode, state) { 3094 while (mode.innerMode) { 3095 var info = mode.innerMode(state); 3096 state = info.state; 3097 mode = info.mode; 3098 } 3099 return info || {mode: mode, state: state}; 3100 }; 3101 3102 // STANDARD COMMANDS 3103 3104 var commands = CodeMirror.commands = { 3105 selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()
3105));}, 3106 killLine: function(cm) { 3107 var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to); 3108 if (!sel && cm.getLine(from.line).length == from.ch) 3109 cm.replaceRange("", from, Pos(from.line + 1, 0), "+delete"); 3110 else cm.replaceRange("", from, sel ? to : Pos(from.line), "+delete"); 3111 }, 3112 deleteLine: function(cm) { 3113 var l = cm.getCursor().line; 3114 cm.replaceRange("", Pos(l, 0), Pos(l), "+delete"); 3115 }, 3116 undo: function(cm) {cm.undo();}, 3117 redo: function(cm) {cm.redo();}, 3118 goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, 3119 goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, 3120 goLineStart: function(cm) { 3121 cm.extendSelection(lineStart(cm, cm.getCursor().line)); 3122 }, 3123 goLineStartSmart: function(cm) { 3124 var cur = cm.getCursor(), start = lineStart(cm, cur.line); 3125 var line = cm.getLineHandle(start.line); 3126 var order = getOrder(line); 3127 if (!order || order[0].level == 0) { 3128 var firstNonWS = Math.max(0, line.text.search(/\S/)); 3129 var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch; 3130 cm.extendSelection(Pos(start.line, inWS ? 0 : firstNonWS)); 3131 } else cm.extendSelection(start); 3132 }, 3133 goLineEnd: function(cm) { 3134 cm.extendSelection(lineEnd(cm, cm.getCursor().line)); 3135 }, 3136 goLineUp: function(cm) {cm.moveV(-1, "line");}, 3137 goLineDown: function(cm) {cm.moveV(1, "line");}, 3138 goPageUp: function(cm) {cm.moveV(-1, "page");}, 3139 goPageDown: function(cm) {cm.moveV(1, "page");}, 3140 goCharLeft: function(cm) {cm.moveH(-1, "char");}, 3141 goCharRight: function(cm) {cm.moveH(1, "char");}, 3142 goColumnLeft: function(cm) {cm.moveH(-1, "column");}, 3143 goColumnRight: function(cm) {cm.moveH(1, "column");}, 3144 goWordLeft: function(cm) {cm.moveH(-1, "word");}, 3145 goWordRight: function(cm) {cm.moveH(1, "word");}, 3146 delCharBefore: function(cm) {cm.deleteH(-1, "char");}, 3147 delCharAfter: function(cm) {cm.deleteH(1, "char");}, 3148 delWordBefore: function(cm) {cm.deleteH(-1, "word");}, 3149 delWordAfter: function(cm) {cm.deleteH(1, "word");}, 3150 indentAuto: function(cm) {cm.indentSelection("smart");}, 3151 indentMore: function(cm) {cm.indentSelection("add");}, 3152 indentLess: function(cm) {cm.indentSelection("subtract");}, 3153 insertTab: function(cm) {cm.replaceSelection("\t", "end", "+input");}, 3154 defaultTab: function(cm) { 3155 if (cm.somethingSelected()) cm.indentSelection("add"); 3156 else cm.replaceSelection("\t", "end", "+input"); 3157 }, 3158 transposeChars: function(cm) { 3159 var cur = cm.getCursor(), line = cm.getLine(cur.line); 3160 if (cur.ch > 0 && cur.ch < line.length - 1) 3161 cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1), 3162 Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1)); 3163 }, 3164 newlineAndIndent: function(cm) { 3165 operation(cm, function() { 3166 cm.replaceSelection("\n", "end", "+input"); 3167 cm.indentLine(cm.getCursor().line, null, true); 3168 })(); 3169 }, 3170 toggleOverwrite: function(cm) {cm.toggleOverwrite();} 3171 }; 3172 3173 // STANDARD KEYMAPS 3174 3175 var keyMap = CodeMirror.keyMap = {}; 3176 keyMap.basic = { 3177 "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", 3178 "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", 3179 "Delete": "delCharAfter", "Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto", 3180 "Enter": "newlineAndIndent", "Insert": "toggleOverwrite" 3181 }; 3182 // Note that the save and find-related commands aren't defined by 3183 // default. Unknown commands are simply ignored. 3184 keyMap.pcDefault = { 3185 "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", 3186 "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd", 3187 "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", 3188 "Ctrl-Backspace": "delWordBefore", "Ctrl-Delete": "delWordAfter", "Ctrl-S": "save", "Ctrl-F": "find", 3189 "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", 3190 "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", 3191 fallthrough: "basic" 3192 }; 3193 keyMap.macDefault = { 3194 "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", 3195 "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt
3195-Left": "goWordLeft", 3196 "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordBefore", 3197 "Ctrl-Alt-Backspace": "delWordAfter", "Alt-Delete": "delWordAfter", "Cmd-S": "save", "Cmd-F": "find", 3198 "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", 3199 "Cmd-[": "indentLess", "Cmd-]": "indentMore", 3200 fallthrough: ["basic", "emacsy"] 3201 }; 3202 keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; 3203 keyMap.emacsy = { 3204 "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", 3205 "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", 3206 "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", 3207 "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" 3208 }; 3209 3210 // KEYMAP DISPATCH 3211 3212 function getKeyMap(val) { 3213 if (typeof val == "string") return keyMap[val]; 3214 else return val; 3215 } 3216 3217 function lookupKey(name, maps, handle) { 3218 function lookup(map) { 3219 map = getKeyMap(map); 3220 var found = map[name]; 3221 if (found === false) return "stop"; 3222 if (found != null && handle(found)) return true; 3223 if (map.nofallthrough) return "stop"; 3224 3225 var fallthrough = map.fallthrough; 3226 if (fallthrough == null) return false; 3227 if (Object.prototype.toString.call(fallthrough) != "[object Array]") 3228 return lookup(fallthrough); 3229 for (var i = 0, e = fallthrough.length; i < e; ++i) { 3230 var done = lookup(fallthrough[i]); 3231 if (done) return done; 3232 } 3233 return false; 3234 } 3235 3236 for (var i = 0; i < maps.length; ++i) { 3237 var done = lookup(maps[i]); 3238 if (done) return done; 3239 } 3240 } 3241 function isModifierKey(event) { 3242 var name = keyNames[event.keyCode]; 3243 return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; 3244 } 3245 function keyName(event, noShift) { 3246 var name = keyNames[event.keyCode]; 3247 if (name == null || event.altGraphKey) return false; 3248 if (event.altKey) name = "Alt-" + name; 3249 if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name; 3250 if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name; 3251 if (!noShift && event.shiftKey) name = "Shift-" + name; 3252 return name; 3253 } 3254 CodeMirror.lookupKey = lookupKey; 3255 CodeMirror.isModifierKey = isModifierKey; 3256 CodeMirror.keyName = keyName; 3257 3258 // FROMTEXTAREA 3259 3260 CodeMirror.fromTextArea = function(textarea, options) { 3261 if (!options) options = {}; 3262 options.value = textarea.value; 3263 if (!options.tabindex && textarea.tabindex) 3264 options.tabindex = textarea.tabindex; 3265 // Set autofocus to true if this textarea is focused, or if it has 3266 // autofocus and no other element is focused. 3267 if (options.autofocus == null) { 3268 var hasFocus = document.body; 3269 // doc.activeElement occasionally throws on IE 3270 try { hasFocus = document.activeElement; } catch(e) {} 3271 options.autofocus = hasFocus == textarea || 3272 textarea.getAttribute("autofocus") != null && hasFocus == document.body; 3273 } 3274 3275 function save() {textarea.value = cm.getValue();} 3276 if (textarea.form) { 3277 // Deplorable hack to make the submit method do the right thing. 3278 on(textarea.form, "submit", save); 3279 var form = textarea.form, realSubmit = form.submit; 3280 try { 3281 var wrappedSubmit = form.submit = function() { 3282 save(); 3283 form.submit = realSubmit; 3284 form.submit(); 3285 form.submit = wrappedSubmit; 3286 }; 3287 } catch(e) {} 3288 } 3289 3290 textarea.style.display = "none"; 3291 var cm = CodeMirror(function(node) { 3292 textarea.parentNode.insertBefore(node, textarea.nextSibling); 3293 }, options); 3294 cm.save = save; 3295 cm.getTextArea = function() { return textarea; }; 3296 cm.toTextArea = function() { 3297 save(); 3298 textarea.parentNode.removeChild(cm.getWrapperElement()); 3299 textarea.style.display = ""; 3300 if (textarea.form) { 3301 off(textarea.form, "submit", save); 3302 if (typeof textarea.form.submit == "function") 3303 textarea.form.submit = realSubmit; 3304 } 3305 }; 3306 return cm; 3307 }; 3308 3309 // STRING STREAM 3310 3311 // Fed to the mode parsers, provides helper functions to make 3312 // parsers more succinct. 3313 3314 // The character stream used by a mode's parser. 3315 function StringStream(string, tabSize) { 3316 this.pos = this.start = 0; 3317 this.string = string; 3318 this.tabSize = tabSize || 8; 3319 } 3320 3321 StringStream.prototype = { 3322 eol: function() {return this.pos >= this.string.length;}, 3323 sol: function() {return this.pos == 0;}, 3324 peek: function() {return this.string.charAt(this.pos) || undefined;}, 3325 next: function() { 3326 if (this.pos < this.string.length) 3327 return this.string.charAt(this.pos++); 3328 }, 3329 eat: function(match) { 3330 var ch = this.string.charAt(this.pos); 3331 if (typeof match == "string") var ok = ch == match; 3332 else var ok = ch && (match.test ? match.test(ch) : match(ch)); 3333 if (ok) {++this.pos; return ch;} 3334 }, 3335 eatWhile: function(match) { 3336 var start = this.pos; 3337 while (this.eat(match)){} 3338 return this.pos > start; 3339 }, 3340 eatSpace: function() { 3341 var start = this.pos; 3342 while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; 3343 return this.pos > start; 3344 }, 3345 skipToEnd: function() {this.pos = this.string.length;}, 3346 skipTo: function(ch) { 3347 var found = this.string.indexOf(ch, this.pos); 3348 if (found > -1) {this.pos = found; return true;} 3349 }, 3350 backUp: function(n) {this.pos -= n;}, 3351 column: function() {return countColumn(this.string, this.start, this.tabSize);}, 3352 indentation: function() {return countColumn(this.string, null, this.tabSize);}, 3353 match: function(pattern, consume, caseInsensitive) { 3354 if (typeof pattern == "string") { 3355 var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; 3356 if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) { 3357 if (consume !== false) this.pos += pattern.length; 3358 return true; 3359 } 3360 } else { 3361 var match = this.string.slice(this.pos).match(pattern); 3362 if (match && match.index > 0) return null; 3363 if (match && consume !== false) this.pos += match[0].length; 3364 return match; 3365 } 3366 }, 3367 current: function(){return this.string.slice(this.start, this.pos);} 3368 }; 3369 CodeMirror.StringStream = StringStream; 3370 3371 // TEXTMARKERS 3372 3373 function TextMarker(doc, type) { 3374 this.lines = []; 3375 this.type = type; 3376 this.doc = doc; 3377 } 3378 CodeMirror.TextMarker = TextMarker; 3379 3380 TextMarker.prototype.clear = function() { 3381 if (this.explicitlyCleared) return; 3382 var cm = this.doc.cm, withOp = cm && !cm.curOp; 3383 if (withOp) startOperation(cm); 3384 var min = null, max = null; 3385 for (var i = 0; i < this.lines.length; ++i) { 3386 var line = this.lines[i]; 3387 var span = getMarkedSpanFor(line.markedSpans, this); 3388 if (span.to != null) max = lineNo(line); 3389 line.markedSpans = removeMarkedSpan(line.markedSpans, span); 3390 if (span.from != null) 3391 min = lineNo(line); 3392 else if (this.collapsed && !lineIsHidden(this.doc, line) && cm) 3393 updateLineHeight(line, textHeight(cm.display)); 3394 } 3395 if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
3396 var visual = visualLine(cm.doc, this.lines[i]), len = lineLength(cm.doc, visual); 3397 if (len > cm.display.maxLineLength) { 3398 cm.display.maxLine = visual; 3399 cm.display.maxLineLength = len; 3400 cm.display.maxLineChanged = true; 3401 } 3402 } 3403 3404 if (min != null && cm) regChange(cm, min, max + 1); 3405 this.lines.length = 0; 3406 this.explicitlyCleared = true; 3407 if (this.collapsed && this.doc.cantEdit) { 3408 this.doc.cantEdit = false; 3409 if (cm) reCheckSelection(cm); 3410 } 3411 if (withOp) endOperation(cm); 3412 signalLater(this, "clear"); 3413 }; 3414 3415 TextMarker.prototype.find = function() { 3416 var from, to; 3417 for (var i = 0; i < this.lines.length; ++i) { 3418 var line = this.lines[i]; 3419 var span = getMarkedSpanFor(line.markedSpans, this); 3420 if (span.from != null || span.to != null) { 3421 var found = lineNo(line); 3422 if (span.from != null) from = Pos(found, span.from); 3423 if (span.to != null) to = Pos(found, span.to); 3424 } 3425 } 3426 if (this.type == "bookmark") return from; 3427 return from && {from: from, to: to}; 3428 }; 3429 3430 TextMarker.prototype.getOptions = function(copyWidget) { 3431 var repl = this.replacedWith; 3432 return {className: this.className, 3433 inclusiveLeft: this.inclusiveLeft, inclusiveRight: this.inclusiveRight, 3434 atomic: this.atomic, 3435 collapsed: this.collapsed, 3436 clearOnEnter: this.clearOnEnter, 3437 replacedWith: copyWidget ? repl && repl.cloneNode(true) : repl, 3438 readOnly: this.readOnly, 3439 startStyle: this.startStyle, endStyle: this.endStyle}; 3440 }; 3441 3442 TextMarker.prototype.attachLine = function(line) { 3443 if (!this.lines.length && this.doc.cm) { 3444 var op = this.doc.cm.curOp; 3445 if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) 3446 (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); 3447 } 3448 this.lines.push(line); 3449 }; 3450 TextMarker.prototype.detachLine = function(line) { 3451 this.lines.splice(indexOf(this.lines, line), 1); 3452 if (!this.lines.length && this.doc.cm) { 3453 var op = this.doc.cm.curOp; 3454 (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); 3455 } 3456 }; 3457 3458 function markText(doc, from, to, options, type) { 3459 if (options && options.shared) return markTextShared(doc, from, to, options, type); 3460 if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); 3461 3462 var marker = new TextMarker(doc, type); 3463 if (type == "range" && !posLess(from, to)) return marker; 3464 if (options) copyObj(options, marker); 3465 if (marker.replacedWith) { 3466 marker.collapsed = true; 3467 marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget"); 3468 } 3469 if (marker.collapsed) sawCollapsedSpans = true; 3470 3471 var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd, cm = doc.cm, updateMaxLine; 3472 doc.iter(curLine, to.line + 1, function(line) { 3473 if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(doc, line) == cm.display.maxLine) 3474 updateMaxLine = true; 3475 var span = {from: null, to: null, marker: marker}; 3476 size += line.text.length; 3477 if (curLine == from.line) {span.from = from.ch; size -= from.ch;} 3478 if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;} 3479 if (marker.collapsed) { 3480 if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch); 3481 if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch); 3482 else updateLineHeight(line, 0); 3483 } 3484 addMarkedSpan(line, span); 3485 ++curLine; 3486 }); 3487 if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { 3488 if (lineIsHidden(doc, line)) updateLineHeight(line, 0); 3489 }); 3490 3491 if (marker.readOnly) { 3492 sawReadOnlySpans = true; 3493 if (doc.history.done.length || doc.history.undone.length) 3494 doc.clearHistory(); 3495 } 3496 if (marker.collapsed) { 3497 if (collapsedAtStart != collapsedAtEnd) 3498 throw new Error("Inserting collapsed marker overlapping an existing one"); 3499 marker.size = size; 3500 marker.atomic = true; 3501 } 3502 if (cm) { 3503 if (updateMaxLine) cm.curOp.updateMaxLine = true; 3504 if (marker.className || marker.startStyle || marker.endStyle || marker.collapsed) 3505 regChange(cm, from.line, to.line + 1); 3506 if (marker.atomic) reCheckSelection(cm); 3507 } 3508 return marker; 3509 } 3510 3511 // SHARED TEXTMARKERS 3512 3513 function SharedTextMarker(markers, primary) { 3514 this.markers = markers; 3515 this.primary = primary; 3516 for (var i = 0, me = this; i < markers.length; ++i) { 3517 markers[i].parent = this; 3518 on(markers[i], "clear", function(){me.clear();}); 3519 } 3520 } 3521 CodeMirror.SharedTextMarker = SharedTextMarker; 3522 3523 SharedTextMarker.prototype.clear = function() { 3524 if (this.explicitlyCleared) return; 3525 this.explicitlyCleared = true; 3526 for (var i = 0; i < this.markers.length; ++i) 3527 this.markers[i].clear(); 3528 signalLater(this, "clear"); 3529 }; 3530 SharedTextMarker.prototype.find = function() { 3531 return this.primary.find(); 3532 }; 3533 SharedTextMarker.prototype.getOptions = function(copyWidget) { 3534 var inner = this.primary.getOptions(copyWidget); 3535 inner.shared = true; 3536 return inner; 3537 }; 3538 3539 function markTextShared(doc, from, to, options, type) { 3540 options = copyObj(options); 3541 options.shared = false;
3542 var markers = [markText(doc, from, to, options, type)], primary = markers[0]; 3543 linkedDocs(doc, function(doc) { 3544 markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); 3545 for (var i = 0; i < doc.linked.length; ++i) 3546 if (doc.linked[i].isParent) return; 3547 primary = lst(markers); 3548 }); 3549 return new SharedTextMarker(markers, primary); 3550 } 3551 3552 // TEXTMARKER SPANS 3553 3554 function getMarkedSpanFor(spans, marker) { 3555 if (spans) for (var i = 0; i < spans.length; ++i) { 3556 var span = spans[i]; 3557 if (span.marker == marker) return span; 3558 } 3559 } 3560 function removeMarkedSpan(spans, span) { 3561 for (var r, i = 0; i < spans.length; ++i) 3562 if (spans[i] != span) (r || (r = [])).push(spans[i]); 3563 return r; 3564 } 3565 function addMarkedSpan(line, span) { 3566 line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; 3567 span.marker.attachLine(line); 3568 } 3569 3570 function markedSpansBefore(old, startCh, isInsert) { 3571 if (old) for (var i = 0, nw; i < old.length; ++i) { 3572 var span = old[i], marker = span.marker; 3573 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); 3574 if (startsBefore || marker.type == "bookmark" && span.from == startCh && (!isInsert || !span.marker.insertLeft)) { 3575 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); 3576 (nw || (nw = [])).push({from: span.from, 3577 to: endsAfter ? null : span.to, 3578 marker: marker}); 3579 } 3580 } 3581 return nw; 3582 } 3583 3584 function markedSpansAfter(old, endCh, isInsert) { 3585 if (old) for (var i = 0, nw; i < old.length; ++i) { 3586 var span = old[i], marker = span.marker; 3587 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); 3588 if (endsAfter || marker.type == "bookmark" && span.from == endCh && (!isInsert || span.marker.insertLeft)) { 3589 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); 3590 (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh, 3591 to: span.to == null ? null : span.to - endCh, 3592 marker: marker}); 3593 } 3594 } 3595 return nw; 3596 } 3597 3598 function stretchSpansOverChange(doc, change) { 3599 var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; 3600 var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; 3601 if (!oldFirst && !oldLast) return null; 3602 3603 var startCh = change.from.ch, endCh = change.to.ch, isInsert = posEq(change.from, change.to); 3604 // Get the spans that 'stick out' on both sides 3605 var first = markedSpansBefore(oldFirst, startCh, isInsert); 3606 var last = markedSpansAfter(oldLast, endCh, isInsert); 3607 3608 // Next, merge those two ends 3609 var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); 3610 if (first) { 3611 // Fix up .to properties of first 3612 for (var i = 0; i < first.length; ++i) { 3613 var span = first[i]; 3614 if (span.to == null) { 3615 var found = getMarkedSpanFor(last, span.marker); 3616 if (!found) span.to = startCh; 3617 else if (sameLine) span.to = found.to == null ? null : found.to + offset; 3618 } 3619 } 3620 } 3621 if (last) { 3622 // Fix up .from in last (or move them into first in case of sameLine) 3623 for (var i = 0; i < last.length; ++i) { 3624 var span = last[i]; 3625 if (span.to != null) span.to += offset; 3626 if (span.from == null) { 3627 var found = getMarkedSpanFor(first, span.marker); 3628 if (!found) { 3629 span.from = offset; 3630 if (sameLine) (first || (first = [])).push(span); 3631 } 3632 } else { 3633 span.from += offset; 3634 if (sameLine) (first || (first = [])).push(span); 3635 } 3636 } 3637 } 3638 3639 var newMarkers = [first]; 3640 if (!sameLine) { 3641 // Fill gap with whole-line-spans 3642 var gap = change.text.length - 2, gapMarkers; 3643 if (gap > 0 && first) 3644 for (var i = 0; i < first.length; ++i) 3645 if (first[i].to == null) 3646 (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker}); 3647 for (var i = 0; i < gap; ++i) 3648 newMarkers.push(gapMarkers); 3649 newMarkers.push(last); 3650 } 3651 return newMarkers; 3652 } 3653 3654 function mergeOldSpans(doc, change) { 3655 var old = getOldSpans(doc, change); 3656 var stretched = stretchSpansOverChange(doc, change); 3657 if (!old) return stretched; 3658 if (!stretched) return old; 3659 3660 for (var i = 0; i < old.length; ++i) { 3661 var oldCur = old[i], stretchCur = stretched[i]; 3662 if (oldCur && stretchCur) { 3663 spans: for (var j = 0; j < stretchCur.length; ++j) { 3664 var span = stretchCur[j]; 3665 for (var k = 0; k < oldCur.length; ++k) 3666 if (oldCur[k].marker == span.marker) continue spans; 3667 oldCur.push(span); 3668 } 3669 } else if (stretchCur) { 3670 old[i] = stretchCur; 3671 } 3672 } 3673 return old; 3674 } 3675 3676 function removeReadOnlyRanges(doc, from, to) { 3677 var markers = null; 3678 doc.iter(from.line, to.line + 1, function(line) { 3679 if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { 3680 var mark = line.markedSpans[i].marker; 3681 if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) 3682 (markers || (markers = [])).push(mark); 3683 } 3684 }); 3685 if (!markers) return null; 3686 var parts = [{from: from, to: to}]; 3687 for (var i = 0; i < markers.length; ++i) { 3688 var mk = markers[i], m = mk.find(); 3689 for (var j = 0; j < parts.length; ++j) { 3690 var p = parts[j]; 3691 if (posLess(p.to, m.from) || posLess(m.to, p.from)) continue; 3692 var newParts = [j, 1]; 3693 if (posLess(p.from, m.from) || !mk.inclusiveLeft && posEq(p.from, m.from)) 3694 newParts.push({from: p.from, to: m.from}); 3695 if (posLess(m.to, p.to) || !mk.inclusiveRight && posEq(p.to, m.to)) 3696 newParts.push({from: m.to, to: p.to}); 3697 parts.splice.apply(parts, newParts); 3698 j += newParts.length - 1; 3699 } 3700 } 3701 return parts; 3702 } 3703 3704 function collapsedSpanAt(line, ch) { 3705 var sps = sawCollapsedSpans && line.markedSpans, found; 3706 if (sps) for (var sp, i = 0; i < sps.length; ++i) { 3707 sp = sps[i]; 3708 if (!sp.marker.collapsed) continue; 3709 if ((sp.from == null || sp.from < ch) && 3710 (sp.to == null || sp.to > ch) && 3711 (!found || found.width < sp.marker.width)) 3712 found = sp.marker; 3713 } 3714 return found; 3715 } 3716 function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); } 3717 function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); } 3718 3719 function visualLine(doc, line) { 3720 var merged; 3721 while (merged = collapsedSpanAtStart(line)) 3722 line = getLine(doc, merged.find().from.line); 3723 return line; 3724 } 3725 3726 function lineIsHidden(doc, line) { 3727 var sps = sawCollapsedSpans && line.markedSpans; 3728 if (sps) for (var sp, i = 0; i < sps.length; ++i) { 3729 sp = sps[i]; 3730 if (!sp.marker.collapsed) continue; 3731 if (sp.from == null) return true; 3732 if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) 3733 return true; 3734 } 3735 } 3736 function lineIsHiddenInner(doc, line, span) { 3737 if (span.to == null) { 3738 var end = span.marker.find().to, endLine = getLine(doc, end.line); 3739 return lineIsHiddenInner(doc, endLine, getMarkedSpanFor(endLine.markedSpans, span.marker)); 3740 } 3741 if (span.marker.inclusiveRight && span.to == line.text.length) 3742 return true; 3743 for (var sp, i = 0; i < line.markedSpans.length; ++i) { 3744 sp = line.markedSpans[i]; 3745 if (sp.marker.collapsed && sp.from == span.to && 3746 (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && 3747 lineIsHiddenInner(doc, line, sp)) return true; 3748 } 3749 } 3750 3751 function detachMarkedSpans(line) { 3752 var spans = line.markedSpans; 3753 if (!spans) return; 3754 for (var i = 0; i < spans.length; ++i) 3755 spans[i].marker.detachLine(line); 3756 line.markedSpans = null; 3757 } 3758 3759 function attachMarkedSpans(line, spans) { 3760 if (!spans) return; 3761 for (var i = 0; i < spans.length; ++i) 3762 spans[i].marker.attachLine(line); 3763 line.markedSpans = spans; 3764 } 3765 3766 // LINE WIDGETS 3767 3768 var LineWidget = CodeMirror.LineWidget = function(cm, node, options) { 3769 for (var opt in options) if (options.hasOwnProperty(opt)) 3770 this[opt] = options[opt]; 3771 this.cm = cm; 3772 this.node = node; 3773 }; 3774 function widgetOperation(f) { 3775 return function() { 3776 var withOp = !this.cm.curOp; 3777 if (withOp) startOperation(this.cm);
3778 try {var result = f.apply(this, arguments);} 3779 finally {if (withOp) endOperation(this.cm);} 3780 return result; 3781 }; 3782 } 3783 LineWidget.prototype.clear = widgetOperation(function() { 3784 var ws = this.line.widgets, no = lineNo(this.line); 3785 if (no == null || !ws) return; 3786 for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); 3787 if (!ws.length) this.line.widgets = null; 3788 updateLineHeight(this.line, Math.max(0, this.line.height - widgetHeight(this))); 3789 regChange(this.cm, no, no + 1); 3790 }); 3791 LineWidget.prototype.changed = widgetOperation(function() { 3792 var oldH = this.height; 3793 this.height = null; 3794 var diff = widgetHeight(this) - oldH; 3795 if (!diff) return; 3796 updateLineHeight(this.line, this.line.height + diff); 3797 var no = lineNo(this.line); 3798 regChange(this.cm, no, no + 1); 3799 }); 3800 3801 function widgetHeight(widget) { 3802 if (widget.height != null) return widget.height; 3803 if (!widget.node.parentNode || widget.node.parentNode.nodeType != 1) 3804 removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative")); 3805 return widget.height = widget.node.offsetHeight; 3806 } 3807 3808 function addLineWidget(cm, handle, node, options) { 3809 var widget = new LineWidget(cm, node, options); 3810 if (widget.noHScroll) cm.display.alignWidgets = true; 3811 changeLine(cm, handle, function(line) { 3812 (line.widgets || (line.widgets = [])).push(widget); 3813 widget.line = line; 3814 if (!lineIsHidden(cm.doc, line) || widget.showIfHidden) { 3815 var aboveVisible = heightAtLine(cm, line) < cm.display.scroller.scrollTop; 3816 updateLineHeight(line, line.height + widgetHeight(widget)); 3817 if (aboveVisible) 3818 cm.curOp.updateScrollPos = {scrollTop: cm.doc.scrollTop + widget.height, 3819 scrollLeft: cm.doc.scrollLeft}; 3820 } 3821 return true; 3822 }); 3823 return widget; 3824 } 3825 3826 // LINE DATA STRUCTURE 3827 3828 // Line objects. These hold state related to a line, including 3829 // highlighting info (the styles array). 3830 function makeLine(text, markedSpans, estimateHeight) { 3831 var line = {text: text}; 3832 attachMarkedSpans(line, markedSpans); 3833 line.height = estimateHeight ? estimateHeight(line) : 1; 3834 return line; 3835 } 3836 3837 function updateLine(line, text, markedSpans, estimateHeight) { 3838 line.text = text; 3839 if (line.stateAfter) line.stateAfter = null; 3840 if (line.styles) line.styles = null; 3841 if (line.order != null) line.order = null; 3842 detachMarkedSpans(line); 3843 attachMarkedSpans(line, markedSpans); 3844 var estHeight = estimateHeight ? estimateHeight(line) : 1; 3845 if (estHeight != line.height) updateLineHeight(line, estHeight); 3846 signalLater(line, "change"); 3847 } 3848 3849 function cleanUpLine(line) { 3850 line.parent = null; 3851 detachMarkedSpans(line); 3852 } 3853 3854 // Run the given mode's parser over a line, update the styles 3855 // array, which contains alternating fragments of text and CSS 3856 // classes. 3857 function runMode(cm, text, mode, state, f) { 3858 var flattenSpans = cm.options.flattenSpans; 3859 var curText = "", curStyle = null; 3860 var stream = new StringStream(text, cm.options.tabSize); 3861 if (text == "" && mode.blankLine) mode.blankLine(state); 3862 while (!stream.eol()) { 3863 var style = mode.token(stream, state); 3864 if (stream.pos > 5000) { 3865 flattenSpans = false; 3866 // Webkit seems to refuse to render text nodes longer than 57444 characters 3867 stream.pos = Math.min(text.length, stream.start + 50000); 3868 style = null; 3869 } 3870 var substr = stream.current(); 3871 stream.start = stream.pos; 3872 if (!flattenSpans || curStyle != style) { 3873 if (curText) f(curText, curStyle); 3874 curText = substr; curStyle = style; 3875 } else curText = curText + substr; 3876 } 3877 if (curText) f(curText, curStyle); 3878 } 3879 3880 function highlightLine(cm, line, state) { 3881 // A styles array always starts with a number identifying the 3882 // mode/overlays that it is based on (for easy invalidation). 3883 var st = [cm.state.modeGen]; 3884 // Compute the base array of styles 3885 runMode(cm, line.text, cm.doc.mode, state, function(txt, style) {st.push(txt, style);}); 3886
3887 // Run overlays, adjust style array. 3888 for (var o = 0; o < cm.state.overlays.length; ++o) { 3889 var overlay = cm.state.overlays[o], i = 1; 3890 runMode(cm, line.text, overlay.mode, true, function(txt, style) { 3891 var start = i, len = txt.length; 3892 // Ensure there's a token end at the current position, and that i points at it 3893 while (len) { 3894 var cur = st[i], len_ = cur.length; 3895 if (len_ <= len) { 3896 len -= len_; 3897 } else { 3898 st.splice(i, 1, cur.slice(0, len), st[i+1], cur.slice(len)); 3899 len = 0; 3900 } 3901 i += 2; 3902 } 3903 if (!style) return; 3904 if (overlay.opaque) { 3905 st.splice(start, i - start, txt, style); 3906 i = start + 2; 3907 } else { 3908 for (; start < i; start += 2) { 3909 var cur = st[start+1]; 3910 st[start+1] = cur ? cur + " " + style : style; 3911 } 3912 } 3913 }); 3914 } 3915 3916 return st; 3917 } 3918 3919 function getLineStyles(cm, line) { 3920 if (!line.styles || line.styles[0] != cm.state.modeGen) 3921 line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line))); 3922 return line.styles; 3923 } 3924 3925 // Lightweight form of highlight -- proceed over this line and 3926 // update state, but don't save a style array. 3927 function processLine(cm, line, state) { 3928 var mode = cm.doc.mode; 3929 var stream = new StringStream(line.text, cm.options.tabSize); 3930 if (line.text == "" && mode.blankLine) mode.blankLine(state); 3931 while (!stream.eol() && stream.pos <= 5000) { 3932 mode.token(stream, state); 3933 stream.start = stream.pos; 3934 } 3935 } 3936 3937 var styleToClassCache = {}; 3938 function styleToClass(style) { 3939 if (!style) return null; 3940 return styleToClassCache[style] || 3941 (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-")); 3942 } 3943 3944 function lineContent(cm, realLine, measure) { 3945 var merged, line = realLine, lineBefore, sawBefore, simple = true; 3946 while (merged = collapsedSpanAtStart(line)) { 3947 simple = false; 3948 line = getLine(cm.doc, merged.find().from.line); 3949 if (!lineBefore) lineBefore = line; 3950 } 3951 3952 var builder = {pre: elt("pre"), col: 0, pos: 0, display: !measure, 3953 measure: null, addedOne: false, cm: cm}; 3954 if (line.textClass) builder.pre.className = line.textClass; 3955 3956 do { 3957 builder.measure = line == realLine && measure; 3958 builder.pos = 0; 3959 builder.addToken = builder.measure ? buildTokenMeasure : buildToken; 3960 if (measure && sawBefore && line != realLine && !builder.addedOne) { 3961 measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure)); 3962 builder.addedOne = true; 3963 } 3964 var next = insertLineContent(line, builder, getLineStyles(cm, line)); 3965 sawBefore = line == lineBefore; 3966 if (next) { 3967 line = getLine(cm.doc, next.to.line); 3968 simple = false; 3969 } 3970 } while (next); 3971 3972 if (measure && !builder.addedOne) 3973 measure[0] = builder.pre.appendChild(simple ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure)); 3974 if (!builder.pre.firstChild && !lineIsHidden(cm.doc, realLine)) 3975 builder.pre.appendChild(document.createTextNode("\u00a0")); 3976 3977 var order; 3978 // Work around problem with the reported dimensions of single-char 3979 // direction spans on IE (issue #1129). See also the comment in 3980 // cursorCoords. 3981 if (measure && ie && (order = getOrder(line))) { 3982 var l = order.length - 1; 3983 if (order[l].from == order[l].to) --l; 3984 var last = order[l], prev = order[l - 1]; 3985 if (last.from + 1 == last.to && prev && last.level < prev.level) { 3986 var span = measure[builder.pos - 1]; 3987 if (span) span.parentNode.insertBefore(span.measureRight = zeroWidthElement(cm.display.measure), 3988 span.nextSibling); 3989 } 3990 } 3991 3992 return builder.pre; 3993 } 3994 3995 var tokenSpecialChars = /[\t\u0000-\u0019\u200b\u2028\u2029\uFEFF]/g; 3996 function buildToken(builder, text, style, startStyle, endStyle) { 3997 if (!text) return; 3998 if (!tokenSpecialChars.test(text)) { 3999 builder.col += text.length; 4000 var content = document.createTextNode(text); 4001 } else { 4002 var content = document.createDocumentFragment(), pos = 0; 4003 while (true) { 4004 tokenSpecialChars.lastIndex = pos; 4005 var m = tokenSpecialChars.exec(text); 4006 var skipped = m ? m.index - pos : text.length - pos; 4007 if (skipped) { 4008 content.appendChild(document.createTextNode(text.slice(pos, pos + skipped))); 4009 builder.col += skipped; 4010 } 4011 if (!m) break; 4012 pos += skipped + 1; 4013 if (m[0] == "\t") { 4014 var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; 4015 content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); 4016 builder.col += tabWidth; 4017 } else { 4018 var token = elt("span", "\u2022", "cm-invalidchar");
4019 token.title = "\\u" + m[0].charCodeAt(0).toString(16); 4020 content.appendChild(token); 4021 builder.col += 1; 4022 } 4023 } 4024 } 4025 if (style || startStyle || endStyle || builder.measure) { 4026 var fullStyle = style || ""; 4027 if (startStyle) fullStyle += startStyle; 4028 if (endStyle) fullStyle += endStyle; 4029 return builder.pre.appendChild(elt("span", [content], fullStyle)); 4030 } 4031 builder.pre.appendChild(content); 4032 } 4033 4034 function buildTokenMeasure(builder, text, style, startStyle, endStyle) { 4035 for (var i = 0; i < text.length; ++i) { 4036 var ch = text.charAt(i), start = i == 0; 4037 if (ch >= "\ud800" && ch < "\udbff" && i < text.length - 1) { 4038 ch = text.slice(i, i + 2); 4039 ++i; 4040 } else if (i && builder.cm.options.lineWrapping && 4041 spanAffectsWrapping.test(text.slice(i - 1, i + 1))) { 4042 builder.pre.appendChild(elt("wbr")); 4043 } 4044 builder.measure[builder.pos] = 4045 buildToken(builder, ch, style, 4046 start && startStyle, i == text.length - 1 && endStyle); 4047 builder.pos += ch.length; 4048 } 4049 if (text.length) builder.addedOne = true; 4050 } 4051 4052 function buildCollapsedSpan(builder, size, widget) { 4053 if (widget) { 4054 if (!builder.display) widget = widget.cloneNode(true); 4055 builder.pre.appendChild(widget); 4056 if (builder.measure && size) { 4057 builder.measure[builder.pos] = widget; 4058 builder.addedOne = true; 4059 } 4060 } 4061 builder.pos += size; 4062 } 4063 4064 // Outputs a number of spans to make up a line, taking highlighting 4065 // and marked text into account. 4066 function insertLineContent(line, builder, styles) { 4067 var spans = line.markedSpans; 4068 if (!spans) { 4069 for (var i = 1; i < styles.length; i+=2) 4070 builder.addToken(builder, styles[i], styleToClass(styles[i+1])); 4071 return; 4072 } 4073 4074 var allText = line.text, len = allText.length; 4075 var pos = 0, i = 1, text = "", style; 4076 var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed; 4077 for (;;) { 4078 if (nextChange == pos) { // Update current marker set 4079 spanStyle = spanEndStyle = spanStartStyle = ""; 4080 collapsed = null; nextChange = Infinity; 4081 var foundBookmark = null; 4082 for (var j = 0; j < spans.length; ++j) { 4083 var sp = spans[j], m = sp.marker; 4084 if (sp.from <= pos && (sp.to == null || sp.to > pos)) { 4085 if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; } 4086 if (m.className) spanStyle += " " + m.className; 4087 if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; 4088 if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; 4089 if (m.collapsed && (!collapsed || collapsed.marker.width < m.width)) 4090 collapsed = sp; 4091 } else if (sp.from > pos && nextChange > sp.from) { 4092 nextChange = sp.from; 4093 } 4094 if (m.type == "bookmark" && sp.from == pos && m.replacedWith) 4095 foundBookmark = m.replacedWith; 4096 } 4097 if (collapsed && (collapsed.from || 0) == pos) { 4098 buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos, 4099 collapsed.from != null && collapsed.marker.replacedWith); 4100 if (collapsed.to == null) return collapsed.marker.find(); 4101 } 4102 if (foundBookmark && !collapsed) buildCollapsedSpan(builder, 0, foundBookmark); 4103 } 4104 if (pos >= len) break; 4105 4106 var upto = Math.min(len, nextChange); 4107 while (true) { 4108 if (text) { 4109 var end = pos + text.length; 4110 if (!collapsed) { 4111 var tokenText = end > upto ? text.slice(0, upto - pos) : text; 4112 builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, 4113 spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : ""); 4114 } 4115 if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} 4116 pos = end; 4117 spanStartStyle = ""; 4118 } 4119 text = styles[i++]; style = styleToClass(styles[i++]); 4120 } 4121 } 4122 } 4123 4124 // DOCUMENT DATA STRUCTURE 4125 4126 function updateDoc(doc, change, markedSpans, selAfter, estimateHeight) { 4127 function spansFor(n) {return markedSpans ? markedSpans[n] : null;} 4128 4129 var from = change.from, to = change.to, text = change.text; 4130 var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); 4131 var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; 4132
4133 // First adjust the line structure 4134 if (from.ch == 0 && to.ch == 0 && lastText == "") { 4135 // This is a whole-line replace. Treated specially to make 4136 // sure line objects move the way they are supposed to. 4137 for (var i = 0, e = text.length - 1, added = []; i < e; ++i) 4138 added.push(makeLine(text[i], spansFor(i), estimateHeight)); 4139 updateLine(lastLine, lastLine.text, lastSpans, estimateHeight); 4140 if (nlines) doc.remove(from.line, nlines); 4141 if (added.length) doc.insert(from.line, added); 4142 } else if (firstLine == lastLine) { 4143 if (text.length == 1) { 4144 updateLine(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), 4145 lastSpans, estimateHeight); 4146 } else { 4147 for (var added = [], i = 1, e = text.length - 1; i < e; ++i) 4148 added.push(makeLine(text[i], spansFor(i), estimateHeight)); 4149 added.push(makeLine(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); 4150 updateLine(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0), estimateHeight); 4151 doc.insert(from.line + 1, added); 4152 } 4153 } else if (text.length == 1) { 4154 updateLine(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), 4155 spansFor(0), estimateHeight); 4156 doc.remove(from.line + 1, nlines); 4157 } else { 4158 updateLine(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0), estimateHeight); 4159 updateLine(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans, estimateHeight); 4160 for (var i = 1, e = text.length - 1, added = []; i < e; ++i) 4161 added.push(makeLine(text[i], spansFor(i), estimateHeight)); 4162 if (nlines > 1) doc.remove(from.line + 1, nlines - 1); 4163 doc.insert(from.line + 1, added); 4164 } 4165 4166 signalLater(doc, "change", doc, change); 4167 setSelection(doc, selAfter.anchor, selAfter.head, null, true); 4168 } 4169 4170 function LeafChunk(lines) { 4171 this.lines = lines; 4172 this.parent = null; 4173 for (var i = 0, e = lines.length, height = 0; i < e; ++i) { 4174 lines[i].parent = this; 4175 height += lines[i].height; 4176 } 4177 this.height = height; 4178 } 4179 4180 LeafChunk.prototype = { 4181 chunkSize: function() { return this.lines.length; }, 4182 removeInner: function(at, n) { 4183 for (var i = at, e = at + n; i < e; ++i) { 4184 var line = this.lines[i]; 4185 this.height -= line.height; 4186 cleanUpLine(line); 4187 signalLater(line, "delete"); 4188 } 4189 this.lines.splice(at, n); 4190 }, 4191 collapse: function(lines) { 4192 lines.splice.apply(lines, [lines.length, 0].concat(this.lines)); 4193 }, 4194 insertInner: function(at, lines, height) { 4195 this.height += height; 4196 this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); 4197 for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this; 4198 }, 4199 iterN: function(at, n, op) { 4200 for (var e = at + n; at < e; ++at) 4201 if (op(this.lines[at])) return true; 4202 } 4203 }; 4204 4205 function BranchChunk(children) { 4206 this.children = children; 4207 var size = 0, height = 0; 4208 for (var i = 0, e = children.length; i < e; ++i) { 4209 var ch = children[i]; 4210 size += ch.chunkSize(); height += ch.height; 4211 ch.parent = this; 4212 } 4213 this.size = size; 4214 this.height = height; 4215 this.parent = null; 4216 } 4217 4218 BranchChunk.prototype = { 4219 chunkSize: function() { return this.size; }, 4220 removeInner: function(at, n) { 4221 this.size -= n; 4222 for (var i = 0; i < this.children.length; ++i) { 4223 var child = this.children[i], sz = child.chunkSize(); 4224 if (at < sz) { 4225 var rm = Math.min(n, sz - at), oldHeight = child.height; 4226 child.removeInner(at, rm); 4227 this.height -= oldHeight - child.height; 4228 if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } 4229 if ((n -= rm) == 0) break; 4230 at = 0; 4231 } else at -= sz; 4232 } 4233 if (this.size - n < 25) { 4234 var lines = []; 4235 this.collapse(lines); 4236 this.children = [new LeafChunk(lines)]; 4237 this.children[0].parent = this; 4238 } 4239 }, 4240 collapse: function(lines) { 4241 for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines); 4242 }, 4243 insertInner: function(at, lines, height) { 4244 this.size += lines.length; 4245 this.height += height; 4246 for (var i = 0, e = this.children.length; i < e; ++i) { 4247 var child = this.children[i], sz = child.chunkSize(); 4248 if (at <= sz) { 4249 child.insertInner(at, lines, height); 4250 if (child.lines && child.lines.length > 50) { 4251 while (child.lines.length > 50) { 4252 var spilled = child.lines.splice(child.lines.length - 25, 25); 4253 var newleaf = new LeafChunk(spilled); 4254 child.height -= newleaf.height; 4255 this.children.splice(i + 1, 0, newleaf); 4256 newleaf.parent = this; 4257 } 4258 this.maybeSpill(); 4259 } 4260 break; 4261 } 4262 at -= sz; 4263 } 4264 }, 4265 maybeSpill: function() { 4266 if (this.children.length <= 10) return; 4267 var me = this; 4268 do { 4269 var spilled = me.children.splice(me.children.length - 5, 5); 4270 var sibling = new BranchChunk(spilled); 4271 if (!me.parent) { // Become the parent node 4272 var copy = new BranchChunk(me.children); 4273 copy.parent = me; 4274 me.children = [copy, sibling]; 4275 me = copy; 4276 } else { 4277 me.size -= sibling.size; 4278 me.height -= sibling.height; 4279 var myIndex = indexOf(me.parent.children, me); 4280 me.parent.children.splice(myIndex + 1, 0, sibling); 4281 } 4282 sibling.parent = me.parent; 4283 } while (me.children.length > 10); 4284 me.parent.maybeSpill(); 4285 }, 4286 iterN: function(at, n, op) { 4287 for (var i = 0, e = this.children.length; i < e; ++i) { 4288 var child = this.children[i], sz = child.chunkSize(); 4289 if (at < sz) { 4290 var used = Math.min(n, sz - at); 4291 if (child.iterN(at, used, op)) return true; 4292 if ((n -= used) == 0) break; 4293 at = 0; 4294 } else at -= sz; 4295 } 4296 } 4297 }; 4298 4299 var nextDocId = 0; 4300 var Doc = CodeMirror.Doc = function(text, mode, firstLine) { 4301 if (!(this instanceof Doc)) return new Doc(text, mode, firstLine); 4302 if (firstLine == null) firstLine = 0; 4303 4304 BranchChunk.call(this, [new LeafChunk([makeLine("", null)])]); 4305 this.first = firstLine; 4306 this.scrollTop = this.scrollLeft = 0; 4307 this.cantEdit = false;
4308 this.history = makeHistory(); 4309 this.frontier = firstLine; 4310 var start = Pos(firstLine, 0); 4311 this.sel = {from: start, to: start, head: start, anchor: start, shift: false, extend: false, goalColumn: null}; 4312 this.id = ++nextDocId; 4313 this.modeOption = mode; 4314 4315 if (typeof text == "string") text = splitLines(text); 4316 updateDoc(this, {from: start, to: start, text: text}, null, {head: start, anchor: start}); 4317 }; 4318 4319 Doc.prototype = createObj(BranchChunk.prototype, { 4320 iter: function(from, to, op) { 4321 if (op) this.iterN(from - this.first, to - from, op); 4322 else this.iterN(this.first, this.first + this.size, from); 4323 }, 4324 4325 insert: function(at, lines) { 4326 var height = 0; 4327 for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height; 4328 this.insertInner(at - this.first, lines, height); 4329 }, 4330 remove: function(at, n) { this.removeInner(at - this.first, n); }, 4331 4332 getValue: function(lineSep) { 4333 var lines = getLines(this, this.first, this.first + this.size); 4334 if (lineSep === false) return lines; 4335 return lines.join(lineSep || "\n"); 4336 }, 4337 setValue: function(code) { 4338 var top = Pos(this.first, 0), last = this.first + this.size - 1; 4339 makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), 4340 text: splitLines(code), origin: "setValue"}, 4341 {head: top, anchor: top}, true); 4342 }, 4343 replaceRange: function(code, from, to, origin) { 4344 from = clipPos(this, from); 4345 to = to ? clipPos(this, to) : from; 4346 replaceRange(this, code, from, to, origin); 4347 }, 4348 getRange: function(from, to, lineSep) { 4349 var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); 4350 if (lineSep === false) return lines; 4351 return lines.join(lineSep || "\n"); 4352 }, 4353 4354 getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, 4355 setLine: function(line, text) { 4356 if (isLine(this, line)) 4357 replaceRange(this, text, Pos(line, 0), clipPos(this, Pos(line))); 4358 }, 4359 removeLine: function(line) { 4360 if (isLine(this, line)) 4361 replaceRange(this, "", Pos(line, 0), clipPos(this, Pos(line + 1, 0))); 4362 }, 4363 4364 getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);}, 4365 getLineNumber: function(line) {return lineNo(line);}, 4366 4367 lineCount: function() {return this.size;}, 4368 firstLine: function() {return this.first;}, 4369 lastLine: function() {return this.first + this.size - 1;}, 4370 4371 clipPos: function(pos) {return clipPos(this, pos);}, 4372 4373 getCursor: function(start) { 4374 var sel = this.sel, pos; 4375 if (start == null || start == "head") pos = sel.head; 4376 else if (start == "anchor") pos = sel.anchor; 4377 else if (start == "end" || start === false) pos = sel.to; 4378 else pos = sel.from; 4379 return copyPos(pos); 4380 }, 4381 somethingSelected: function() {return !posEq(this.sel.head, this.sel.anchor);}, 4382 4383 setCursor: docOperation(function(line, ch, extend) { 4384 var pos = clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line); 4385 if (extend) extendSelection(this, pos); 4386 else setSelection(this, pos, pos); 4387 }), 4388 setSelection: docOperation(function(anchor, head) { 4389 setSelection(this, clipPos(this, anchor), clipPos(this, head || anchor)); 4390 }), 4391 extendSelection: docOperation(function(from, to) { 4392 extendSelection(this, clipPos(this, from), to && clipPos(this, to)); 4393 }), 4394 4395 getSelection: function(lineSep) {return this.getRange(this.sel.from, this.sel.to, lineSep);}, 4396 replaceSelection: function(code, collapse, origin) { 4397 makeChange(this, {from: this.sel.from, to: this.sel.to, text: splitLines(code), origin: origin}, collapse || "around"); 4398 }, 4399 undo: docOperation(function() {makeChangeFromHistory(this, "undo");}), 4400 redo: docOperation(function() {makeChangeFromHistory(this, "redo");}), 4401 4402 setExtending: function(val) {this.sel.extend = val;}, 4403 4404 historySize: function() { 4405 var hist = this.history; 4406 return {undo: hist.done.length, redo: hist.undone.length}; 4407 }, 4408 clearHistory: function() {this.history = makeHistory();}, 4409 4410 markClean: function() { 4411 this.history.dirtyCounter = 0; 4412 this.history.lastOp = this.history.lastOrigin = null; 4413 }, 4414 isClean: function () {return this.history.dirtyCounter == 0;}, 4415 4416 getHistory: function() { 4417 return {done: copyHistoryArray(this.history.done), 4418 undone: copyHistoryArray(this.history.undone)}; 4419 }, 4420 setHistory: function(histData) { 4421 var hist = this.history = makeHistory(); 4422 hist.done = histData.done.slice(0); 4423 hist.undone = histData.undone.slice(0); 4424 }, 4425 4426 markText: function(from, to, options) { 4427 return markText(this, clipPos(this, from), clipPos(this, to), options, "range"); 4428 }, 4429 setBookmark: function(pos, options) { 4430 var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), 4431 insertLeft: options && options.insertLeft}; 4432 pos = clipPos(this, pos); 4433 return markText(this, pos, pos, realOpts, "bookmark"); 4434 }, 4435 findMarksAt: function(pos) { 4436 pos = clipPos(this, pos); 4437 var markers = [], spans = getLine(this, pos.line).markedSpans; 4438 if (spans) for (var i = 0; i < spans.length; ++i) { 4439 var span = spans[i]; 4440 if ((span.from == null || span.from <= pos.ch) && 4441 (span.to == null || span.to >= pos.ch)) 4442 markers.push(span.marker.parent || span.marker); 4443 } 4444 return markers; 4445 }, 4446 getAllMarks: function() { 4447 var markers = []; 4448 this.iter(function(line) { 4449 var sps = line.markedSpans; 4450 if (sps) for (var i = 0; i < sps.length; ++i) 4451 if (sps[i].from != null) markers.push(sps[i].marker); 4452 }); 4453 return markers; 4454 }, 4455 4456 posFromIndex: function(off) { 4457 var ch, lineNo = this.first; 4458 this.iter(function(line) { 4459 var sz = line.text.length + 1; 4460 if (sz > off) { ch = off; return true; } 4461 off -= sz; 4462 ++lineNo; 4463 }); 4464 return clipPos(this, Pos(lineNo, ch)); 4465 }, 4466 indexFromPos: function (coords) { 4467 coords = clipPos(this, coords); 4468 var index = coords.ch; 4469 if (coords.line < this.first || coords.ch < 0) return 0; 4470 this.iter(this.first, coords.line, function (line) { 4471 index += line.text.length + 1; 4472 }); 4473 return index; 4474 }, 4475 4476 copy: function(copyHistory) { 4477 var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first); 4478 doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; 4479 doc.sel = {from: this.sel.from, to: this.sel.to, head: this.sel.head, anchor: this.sel.anchor, 4480 shift: this.sel.shift, extend: false, goalColumn: this.sel.goalColumn}; 4481 if (copyHistory) { 4482 doc.history.undoDepth = this.history.undoDepth; 4483 doc.setHistory(this.getHistory()); 4484 } 4485 return doc; 4486 }, 4487 4488 linkedDoc: function(options) { 4489 if (!options) options = {}; 4490 var from = this.first, to = this.first + this.size; 4491 if (options.from != null && options.from > from) from = options.from; 4492 if (options.to != null && options.to < to) to = options.to; 4493 var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from); 4494 if (options.sharedHist) copy.history = this.history; 4495 (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); 4496 copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; 4497 return copy; 4498 }, 4499 unlinkDoc: function(other) { 4500 if (other instanceof CodeMirror) other = other.doc; 4501 if (this.linked) for (var i = 0; i < this.linked.length; ++i) { 4502 var link = this.linked[i]; 4503 if (link.doc != other) continue; 4504 this.linked.splice(i, 1); 4505 other.unlinkDoc(this); 4506 break; 4507 } 4508 // If the histories were shared, split them again 4509 if (other.history == this.history) { 4510 var splitIds = [other.id];
vendor: 9,623 bytes, lines 4511-4787
4511 linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); 4512 other.history = makeHistory(); 4513 other.history.done = copyHistoryArray(this.history.done, splitIds); 4514 other.history.undone = copyHistoryArray(this.history.undone, splitIds); 4515 } 4516 }, 4517 iterLinkedDocs: function(f) {linkedDocs(this, f);}, 4518 4519 getMode: function() {return this.mode;}, 4520 getEditor: function() {return this.cm;} 4521 }); 4522 4523 Doc.prototype.eachLine = Doc.prototype.iter; 4524 4525 // The Doc methods that should be available on CodeMirror instances 4526 var dontDelegate = "iter insert remove copy getEditor".split(" "); 4527 for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) 4528 CodeMirror.prototype[prop] = (function(method) { 4529 return function() {return method.apply(this.doc, arguments);}; 4530 })(Doc.prototype[prop]); 4531 4532 function linkedDocs(doc, f, sharedHistOnly) { 4533 function propagate(doc, skip, sharedHist) { 4534 if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { 4535 var rel = doc.linked[i]; 4536 if (rel.doc == skip) continue; 4537 var shared = sharedHist && rel.sharedHist; 4538 if (sharedHistOnly && !shared) continue; 4539 f(rel.doc, shared); 4540 propagate(rel.doc, doc, shared); 4541 } 4542 } 4543 propagate(doc, null, true); 4544 } 4545 4546 function attachDoc(cm, doc) { 4547 if (doc.cm) throw new Error("This document is already in use."); 4548 cm.doc = doc; 4549 doc.cm = cm; 4550 estimateLineHeights(cm); 4551 loadMode(cm); 4552 if (!cm.options.lineWrapping) computeMaxLength(cm); 4553 cm.options.mode = doc.modeOption; 4554 regChange(cm); 4555 } 4556 4557 // LINE UTILITIES 4558 4559 function getLine(chunk, n) { 4560 n -= chunk.first; 4561 while (!chunk.lines) { 4562 for (var i = 0;; ++i) { 4563 var child = chunk.children[i], sz = child.chunkSize(); 4564 if (n < sz) { chunk = child; break; } 4565 n -= sz; 4566 } 4567 } 4568 return chunk.lines[n]; 4569 } 4570 4571 function getBetween(doc, start, end) { 4572 var out = [], n = start.line; 4573 doc.iter(start.line, end.line + 1, function(line) { 4574 var text = line.text; 4575 if (n == end.line) text = text.slice(0, end.ch); 4576 if (n == start.line) text = text.slice(start.ch); 4577 out.push(text); 4578 ++n; 4579 }); 4580 return out; 4581 } 4582 function getLines(doc, from, to) { 4583 var out = []; 4584 doc.iter(from, to, function(line) { out.push(line.text); }); 4585 return out; 4586 } 4587 4588 function updateLineHeight(line, height) { 4589 var diff = height - line.height; 4590 for (var n = line; n; n = n.parent) n.height += diff; 4591 } 4592 4593 function lineNo(line) { 4594 if (line.parent == null) return null; 4595 var cur = line.parent, no = indexOf(cur.lines, line); 4596 for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { 4597 for (var i = 0;; ++i) { 4598 if (chunk.children[i] == cur) break; 4599 no += chunk.children[i].chunkSize(); 4600 } 4601 } 4602 return no + cur.first; 4603 } 4604 4605 function lineAtHeight(chunk, h) { 4606 var n = chunk.first; 4607 outer: do { 4608 for (var i = 0, e = chunk.children.length; i < e; ++i) { 4609 var child = chunk.children[i], ch = child.height; 4610 if (h < ch) { chunk = child; continue outer; } 4611 h -= ch; 4612 n += child.chunkSize(); 4613 } 4614 return n; 4615 } while (!chunk.lines); 4616 for (var i = 0, e = chunk.lines.length; i < e; ++i) { 4617 var line = chunk.lines[i], lh = line.height; 4618 if (h < lh) break; 4619 h -= lh; 4620 } 4621 return n + i; 4622 } 4623 4624 function heightAtLine(cm, lineObj) { 4625 lineObj = visualLine(cm.doc, lineObj); 4626 4627 var h = 0, chunk = lineObj.parent; 4628 for (var i = 0; i < chunk.lines.length; ++i) { 4629 var line = chunk.lines[i]; 4630 if (line == lineObj) break; 4631 else h += line.height; 4632 } 4633 for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { 4634 for (var i = 0; i < p.children.length; ++i) { 4635 var cur = p.children[i]; 4636 if (cur == chunk) break; 4637 else h += cur.height; 4638 } 4639 } 4640 return h; 4641 } 4642 4643 function getOrder(line) { 4644 var order = line.order; 4645 if (order == null) order = line.order = bidiOrdering(line.text); 4646 return order; 4647 } 4648 4649 // HISTORY 4650 4651 function makeHistory() { 4652 return { 4653 // Arrays of history events. Doing something adds an event to 4654 // done and clears undo. Undoing moves events from done to 4655 // undone, redoing moves them in the other direction. 4656 done: [], undone: [], undoDepth: Infinity, 4657 // Used to track when changes can be merged into a single undo 4658 // event 4659 lastTime: 0, lastOp: null, lastOrigin: null, 4660 // Used by the isClean() method 4661 dirtyCounter: 0 4662 }; 4663 } 4664 4665 function attachLocalSpans(doc, change, from, to) { 4666 var existing = change["spans_" + doc.id], n = 0; 4667 doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) { 4668 if (line.markedSpans) 4669 (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; 4670 ++n; 4671 }); 4672 } 4673 4674 function historyChangeFromChange(doc, change) { 4675 var histChange = {from: change.from, to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; 4676 attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); 4677 linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); 4678 return histChange; 4679 } 4680 4681 function addToHistory(doc, change, selAfter, opId) { 4682 var hist = doc.history; 4683 hist.undone.length = 0; 4684 var time = +new Date, cur = lst(hist.done); 4685 4686 if (cur && 4687 (hist.lastOp == opId || 4688 hist.lastOrigin == change.origin && change.origin && 4689 ((change.origin.charAt(0) == "+" && hist.lastTime > time - 600) || change.origin.charAt(0) == "*"))) { 4690 // Merge this change into the last event 4691 var last = lst(cur.changes); 4692 if (posEq(change.from, change.to) && posEq(change.from, last.to)) { 4693 // Optimized case for simple insertion -- don't want to add 4694 // new changesets for every character typed 4695 last.to = changeEnd(change); 4696 } else { 4697 // Add new sub-event 4698 cur.changes.push(historyChangeFromChange(doc, change)); 4699 } 4700 cur.anchorAfter = selAfter.anchor; cur.headAfter = selAfter.head; 4701 } else { 4702 // Can not be merged, start a new event. 4703 cur = {changes: [historyChangeFromChange(doc, change)], 4704 anchorBefore: doc.sel.anchor, headBefore: doc.sel.head, 4705 anchorAfter: selAfter.anchor, headAfter: selAfter.head}; 4706 hist.done.push(cur); 4707 while (hist.done.length > hist.undoDepth) 4708 hist.done.shift(); 4709 if (hist.dirtyCounter < 0) 4710 // The user has made a change after undoing past the last clean state. 4711 // We can never get back to a clean state now until markClean() is called. 4712 hist.dirtyCounter = NaN; 4713 else 4714 hist.dirtyCounter++; 4715 } 4716 hist.lastTime = time; 4717 hist.lastOp = opId; 4718 hist.lastOrigin = change.origin; 4719 } 4720 4721 function removeClearedSpans(spans) { 4722 if (!spans) return null; 4723 for (var i = 0, out; i < spans.length; ++i) { 4724 if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } 4725 else if (out) out.push(spans[i]); 4726 } 4727 return !out ? spans : out.length ? out : null; 4728 } 4729 4730 function getOldSpans(doc, change) { 4731 var found = change["spans_" + doc.id]; 4732 if (!found) return null; 4733 for (var i = 0, nw = []; i < change.text.length; ++i) 4734 nw.push(removeClearedSpans(found[i])); 4735 return nw; 4736 } 4737 4738 // Used both to provide a JSON-safe object in .getHistory, and, when 4739 // detaching a document, to split the history in two 4740 function copyHistoryArray(events, newGroup) { 4741 for (var i = 0, copy = []; i < events.length; ++i) { 4742 var event = events[i], changes = event.changes, newChanges = []; 4743 copy.push({changes: newChanges, anchorBefore: event.anchorBefore, headBefore: event.headBefore, 4744 anchorAfter: event.anchorAfter, headAfter: event.headAfter}); 4745 for (var j = 0; j < changes.length; ++j) { 4746 var change = changes[j], m; 4747 newChanges.push({from: change.from, to: change.to, text: change.text}); 4748 if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { 4749 if (indexOf(newGroup, Number(m[1])) > -1) { 4750 lst(newChanges)[prop] = change[prop]; 4751 delete change[prop]; 4752 } 4753 } 4754 } 4755 } 4756 return copy; 4757 } 4758 4759 // Rebasing/resetting history to deal with externally-sourced changes 4760 4761 function rebaseHistSel(pos, from, to, diff) { 4762 if (to < pos.line) { 4763 pos.line += diff; 4764 } else if (from < pos.line) { 4765 pos.line = from; 4766 pos.ch = 0; 4767 } 4768 } 4769 4770 // Tries to rebase an array of history events given a change in the 4771 // document. If the change touches the same lines as the event, the 4772 // event, and everything 'behind' it, is discarded. If the change is 4773 // before the event, the event's positions are updated. Uses a 4774 // copy-on-write scheme for the positions, to avoid having to 4775 // reallocate them all on every rebase, but also avoid problems with 4776 // shared position objects being unsafely updated. 4777 function rebaseHistArray(array, from, to, diff) { 4778 for (var i = 0; i < array.length; ++i) { 4779 var sub = array[i], ok = true; 4780 for (var j = 0; j < sub.changes.length; ++j) { 4781 var cur = sub.changes[j]; 4782 if (!sub.copied) { cur.from = copyPos(cur.from); cur.to = copyPos(cur.to); } 4783 if (to < cur.from.line) { 4784 cur.from.line += diff; 4785 cur.to.line += diff; 4786 } else if (from <= cur.to.line) { 4787 ok = false;
4788 break; 4789 } 4790 } 4791 if (!sub.copied) { 4792 sub.anchorBefore = copyPos(sub.anchorBefore); sub.headBefore = copyPos(sub.headBefore); 4793 sub.anchorAfter = copyPos(sub.anchorAfter); sub.readAfter = copyPos(sub.headAfter); 4794 sub.copied = true; 4795 } 4796 if (!ok) { 4797 array.splice(0, i + 1); 4798 i = 0; 4799 } else { 4800 rebaseHistSel(sub.anchorBefore); rebaseHistSel(sub.headBefore); 4801 rebaseHistSel(sub.anchorAfter); rebaseHistSel(sub.headAfter); 4802 } 4803 } 4804 } 4805 4806 function rebaseHist(hist, change) { 4807 var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; 4808 rebaseHistArray(hist.done, from, to, diff); 4809 rebaseHistArray(hist.undone, from, to, diff); 4810 } 4811 4812 // EVENT OPERATORS 4813 4814 function stopMethod() {e_stop(this);} 4815 // Ensure an event has a stop method. 4816 function addStop(event) { 4817 if (!event.stop) event.stop = stopMethod; 4818 return event; 4819 } 4820 4821 function e_preventDefault(e) { 4822 if (e.preventDefault) e.preventDefault(); 4823 else e.returnValue = false; 4824 } 4825 function e_stopPropagation(e) { 4826 if (e.stopPropagation) e.stopPropagation(); 4827 else e.cancelBubble = true; 4828 } 4829 function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} 4830 CodeMirror.e_stop = e_stop; 4831 CodeMirror.e_preventDefault = e_preventDefault; 4832 CodeMirror.e_stopPropagation = e_stopPropagation; 4833 4834 function e_target(e) {return e.target || e.srcElement;} 4835 function e_button(e) { 4836 var b = e.which; 4837 if (b == null) { 4838 if (e.button & 1) b = 1; 4839 else if (e.button & 2) b = 3; 4840 else if (e.button & 4) b = 2; 4841 } 4842 if (mac && e.ctrlKey && b == 1) b = 3; 4843 return b; 4844 } 4845 4846 // EVENT HANDLING 4847 4848 function on(emitter, type, f) { 4849 if (emitter.addEventListener) 4850 emitter.addEventListener(type, f, false); 4851 else if (emitter.attachEvent) 4852 emitter.attachEvent("on" + type, f); 4853 else { 4854 var map = emitter._handlers || (emitter._handlers = {}); 4855 var arr = map[type] || (map[type] = []); 4856 arr.push(f); 4857 } 4858 } 4859 4860 function off(emitter, type, f) { 4861 if (emitter.removeEventListener) 4862 emitter.removeEventListener(type, f, false); 4863 else if (emitter.detachEvent) 4864 emitter.detachEvent("on" + type, f); 4865 else { 4866 var arr = emitter._handlers && emitter._handlers[type]; 4867 if (!arr) return; 4868 for (var i = 0; i < arr.length; ++i) 4869 if (arr[i] == f) { arr.splice(i, 1); break; } 4870 } 4871 } 4872 4873 function signal(emitter, type /*, values...*/) { 4874 var arr = emitter._handlers && emitter._handlers[type]; 4875 if (!arr) return; 4876 var args = Array.prototype.slice.call(arguments, 2); 4877 for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); 4878 } 4879 4880 var delayedCallbacks, delayedCallbackDepth = 0; 4881 function signalLater(emitter, type /*, values...*/) { 4882 var arr = emitter._handlers && emitter._handlers[type]; 4883 if (!arr) return; 4884 var args = Array.prototype.slice.call(arguments, 2); 4885 if (!delayedCallbacks) { 4886 ++delayedCallbackDepth; 4887 delayedCallbacks = []; 4888 setTimeout(fireDelayed, 0); 4889 } 4890 function bnd(f) {return function(){f.apply(null, args);};}; 4891 for (var i = 0; i < arr.length; ++i) 4892 delayedCallbacks.push(bnd(arr[i])); 4893 } 4894 4895 function fireDelayed() { 4896 --delayedCallbackDepth; 4897 var delayed = delayedCallbacks; 4898 delayedCallbacks = null; 4899 for (var i = 0; i < delayed.length; ++i) delayed[i](); 4900 } 4901 4902 function hasHandler(emitter, type) { 4903 var arr = emitter._handlers && emitter._handlers[type]; 4904 return arr && arr.length > 0; 4905 } 4906 4907 CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal; 4908 4909 // MISC UTILITIES 4910 4911 // Number of pixels added to scroller and sizer to hide scrollbar 4912 var scrollerCutOff = 30; 4913 4914 // Returned or thrown by various protocols to signal 'I'm not 4915 // handling this'. 4916 var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; 4917 4918 function Delayed() {this.id = null;} 4919 Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}}; 4920 4921 // Counts the column offset in a string, taking tabs into account. 4922 // Used mostly to find indentation. 4923 function countColumn(string, end, tabSize) { 4924 if (end == null) { 4925 end = string.search(/[^\s\u00a0]/); 4926 if (end == -1) end = string.length; 4927 } 4928 for (var i = 0, n = 0; i < end; ++i) { 4929 if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); 4930 else ++n; 4931 } 4932 return n; 4933 } 4934 CodeMirror.countColumn = countColumn; 4935 4936 var spaceStrs = [""]; 4937 function spaceStr(n) { 4938 while (spaceStrs.length <= n) 4939 spaceStrs.push(lst(spaceStrs) + " "); 4940 return spaceStrs[n]; 4941 } 4942 4943 function lst(arr) { return arr[arr.length-1]; } 4944 4945 function selectInput(node) { 4946 if (ios) { // Mobile Safari apparently has a bug where select() is broken. 4947 node.selectionStart = 0; 4948 node.selectionEnd = node.value.length; 4949 } else node.select(); 4950 } 4951 4952 function indexOf(collection, elt) { 4953 if (collection.indexOf) return collection.indexOf(elt); 4954 for (var i = 0, e = collection.length; i < e; ++i) 4955 if (collection[i] == elt) return i; 4956 return -1; 4957 } 4958 4959 function createObj(base, props) { 4960 function Obj() {} 4961 Obj.prototype = base; 4962 var inst = new Obj(); 4963 if (props) copyObj(props, inst); 4964 return inst; 4965 } 4966 4967 function copyObj(obj, target) { 4968 if (!target) target = {}; 4969 for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop]; 4970 return target; 4971 } 4972 4973 function emptyArray(size) { 4974 for (var a = [], i = 0; i < size; ++i) a.push(undefined); 4975 return a; 4976 } 4977 4978 function bind(f) { 4979 var args = Array.prototype.slice.call(arguments, 1);
4980 return function(){return f.apply(null, args);}; 4981 } 4982 4983 var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc]/; 4984 function isWordChar(ch) { 4985 return /\w/.test(ch) || ch > "\x80" && 4986 (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); 4987 } 4988 4989 function isEmpty(obj) { 4990 for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; 4991 return true; 4992 } 4993 4994 var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F\udc00-\udfff]/; 4995 4996 // DOM UTILITIES 4997 4998 function elt(tag, content, className, style) { 4999 var e = document.createElement(tag); 5000 if (className) e.className = className; 5001 if (style) e.style.cssText = style; 5002 if (typeof content == "string") setTextContent(e, content); 5003 else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); 5004 return e; 5005 } 5006 5007 function removeChildren(e) { 5008 // IE will break all parent-child relations in subnodes when setting innerHTML 5009 if (!ie) e.innerHTML = ""; 5010 else while (e.firstChild) e.removeChild(e.firstChild); 5011 return e; 5012 } 5013 5014 function removeChildrenAndAdd(parent, e) { 5015 return removeChildren(parent).appendChild(e); 5016 } 5017 5018 function setTextContent(e, str) { 5019 if (ie_lt9) { 5020 e.innerHTML = ""; 5021 e.appendChild(document.createTextNode(str)); 5022 } else e.textContent = str; 5023 } 5024 5025 function getRect(node) { 5026 return node.getBoundingClientRect(); 5027 } 5028 CodeMirror.replaceGetRect = function(f) { getRect = f; }; 5029 5030 // FEATURE DETECTION 5031 5032 // Detect drag-and-drop 5033 var dragAndDrop = function() { 5034 // There is *some* kind of drag-and-drop support in IE6-8, but I 5035 // couldn't get it to work yet. 5036 if (ie_lt9) return false; 5037 var div = elt('div'); 5038 return "draggable" in div || "dragDrop" in div; 5039 }(); 5040 5041 // For a reason I have yet to figure out, some browsers disallow 5042 // word wrapping between certain characters *only* if a new inline 5043 // element is started between them. This makes it hard to reliably 5044 // measure the position of things, since that requires inserting an 5045 // extra span. This terribly fragile set of regexps matches the 5046 // character combinations that suffer from this phenomenon on the 5047 // various browsers. 5048 var spanAffectsWrapping = /^$/; // Won't match any two-character string 5049 if (gecko) spanAffectsWrapping = /$'/; 5050 else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/; 5051 else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/; 5052 5053 var knownScrollbarWidth; 5054 function scrollbarWidth(measure) { 5055 if (knownScrollbarWidth != null) return knownScrollbarWidth; 5056 var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll"); 5057 removeChildrenAndAdd(measure, test); 5058 if (test.offsetWidth) 5059 knownScrollbarWidth = test.offsetHeight - test.clientHeight; 5060 return knownScrollbarWidth || 0; 5061 } 5062 5063 var zwspSupported; 5064 function zeroWidthElement(measure) { 5065 if (zwspSupported == null) { 5066 var test = elt("span", "\u200b"); 5067 removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); 5068 if (measure.firstChild.offsetHeight != 0) 5069 zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_lt8; 5070 } 5071 if (zwspSupported) return elt("span", "\u200b"); 5072 else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); 5073 } 5074 5075 // See if "".split is the broken IE version, if so, provide an 5076 // alternative way to split lines. 5077 var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { 5078 var pos = 0, result = [], l = string.length; 5079 while (pos <= l) { 5080 var nl = string.indexOf("\n", pos); 5081 if (nl == -1) nl = string.length; 5082 var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); 5083 var rt = line.indexOf("\r"); 5084 if (rt != -1) { 5085 result.push(line.slice(0, rt)); 5086 pos += rt + 1; 5087 } else { 5088 result.push(line); 5089 pos = nl + 1; 5090 } 5091 } 5092 return result; 5093 } : function(string){return string.split(/\r\n?|\n/);}; 5094 CodeMirror.splitLines = splitLines; 5095 5096 var hasSelection = window.getSelection ? function(te) {
5097 try { return te.selectionStart != te.selectionEnd; } 5098 catch(e) { return false; } 5099 } : function(te) { 5100 try {var range = te.ownerDocument.selection.createRange();} 5101 catch(e) {} 5102 if (!range || range.parentElement() != te) return false; 5103 return range.compareEndPoints("StartToEnd", range) != 0; 5104 }; 5105 5106 var hasCopyEvent = (function() { 5107 var e = elt("div"); 5108 if ("oncopy" in e) return true; 5109 e.setAttribute("oncopy", "return;"); 5110 return typeof e.oncopy == 'function'; 5111 })(); 5112 5113 // KEY NAMING 5114 5115 var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 5116 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 5117 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 5118 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete", 5119 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 5120 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home", 5121 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"}; 5122 CodeMirror.keyNames = keyNames; 5123 (function() { 5124 // Number keys 5125 for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i); 5126 // Alphabetic keys 5127 for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); 5128 // Function keys 5129 for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; 5130 })(); 5131 5132 // BIDI HELPERS 5133 5134 function iterateBidiSections(order, from, to, f) { 5135 if (!order) return f(from, to, "ltr"); 5136 for (var i = 0; i < order.length; ++i) { 5137 var part = order[i]; 5138 if (part.from < to && part.to > from || from == to && part.to == from) 5139 f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); 5140 } 5141 } 5142 5143 function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } 5144 function bidiRight(part) { return part.level % 2 ? part.from : part.to; } 5145 5146 function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } 5147 function lineRight(line) { 5148 var order = getOrder(line); 5149 if (!order) return line.text.length; 5150 return bidiRight(lst(order)); 5151 } 5152 5153 function lineStart(cm, lineN) { 5154 var line = getLine(cm.doc, lineN); 5155 var visual = visualLine(cm.doc, line); 5156 if (visual != line) lineN = lineNo(visual); 5157 var order = getOrder(visual); 5158 var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); 5159 return Pos(lineN, ch); 5160 } 5161 function lineEnd(cm, lineN) { 5162 var merged, line; 5163 while (merged = collapsedSpanAtEnd(line = getLine(cm.doc, lineN))) 5164 lineN = merged.find().to.line; 5165 var order = getOrder(line); 5166 var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); 5167 return Pos(lineN, ch); 5168 } 5169 5170 // This is somewhat involved. It is needed in order to move 5171 // 'visually' through bi-directional text -- i.e., pressing left 5172 // should make the cursor go left, even when in RTL text. The 5173 // tricky part is the 'jumps', where RTL and LTR text touch each 5174 // other. This often requires the cursor offset to move more than 5175 // one unit, in order to visually move one unit. 5176 function moveVisually(line, start, dir, byUnit) { 5177 var bidi = getOrder(line); 5178 if (!bidi) return moveLogically(line, start, dir, byUnit); 5179 var moveOneUnit = byUnit ? function(pos, dir) { 5180 do pos += dir; 5181 while (pos > 0 && isExtendingChar.test(line.text.charAt(pos))); 5182 return pos; 5183 } : function(pos, dir) { return pos + dir; }; 5184 var linedir = bidi[0].level; 5185 for (var i = 0; i < bidi.length; ++i) { 5186 var part = bidi[i], sticky = part.level % 2 == linedir; 5187 if ((part.from < start && part.to > start) || 5188 (sticky && (part.from == start || part.to == start))) break; 5189 } 5190 var target = moveOneUnit(start, part.level % 2 ? -dir : dir); 5191 5192 while (target != null) { 5193 if (part.level % 2 == linedir) { 5194 if (target < part.from || target > part.to) { 5195 part = bidi[i += dir]; 5196 target = part && (dir > 0 == part.level % 2 ? moveOneUnit(part.to, -1) : moveOneUnit(part.from, 1)); 5197 } else break; 5198 } else { 5199 if (target == bidiLeft(part)) { 5200 part = bidi[--i]; 5201 target = part && bidiRight(part); 5202 } else if (target == bidiRight(part)) { 5203 part = bidi[++i]; 5204 target = part && bidiLeft(part); 5205 } else break; 5206 } 5207 } 5208 5209 return target < 0 || target > line.text.length ? null : target; 5210 } 5211 5212 function moveLogically(line, start, dir, byUnit) { 5213 var target = start + dir;
5214 if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir; 5215 return target < 0 || target > line.text.length ? null : target; 5216 } 5217 5218 // Bidirectional ordering algorithm 5219 // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm 5220 // that this (partially) implements. 5221 5222 // One-char codes used for character types: 5223 // L (L): Left-to-Right 5224 // R (R): Right-to-Left 5225 // r (AL): Right-to-Left Arabic 5226 // 1 (EN): European Number 5227 // + (ES): European Number Separator 5228 // % (ET): European Number Terminator 5229 // n (AN): Arabic Number 5230 // , (CS): Common Number Separator 5231 // m (NSM): Non-Spacing Mark 5232 // b (BN): Boundary Neutral 5233 // s (B): Paragraph Separator 5234 // t (S): Segment Separator 5235 // w (WS): Whitespace 5236 // N (ON): Other Neutrals 5237 5238 // Returns null if characters are ordered as they appear 5239 // (left-to-right), or an array of sections ({from, to, level} 5240 // objects) in the order in which they occur visually. 5241 var bidiOrdering = (function() { 5242 // Character types for codepoints 0 to 0xff 5243 var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL"; 5244 // Character types for codepoints 0x600 to 0x6ff 5245 var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr"; 5246 function charType(code) { 5247 if (code <= 0xff) return lowTypes.charAt(code); 5248 else if (0x590 <= code && code <= 0x5f4) return "R"; 5249 else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600); 5250 else if (0x700 <= code && code <= 0x8ac) return "r"; 5251 else return "L"; 5252 } 5253 5254 var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; 5255 var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; 5256 // Browsers seem to always treat the boundaries of block elements as being L. 5257 var outerType = "L"; 5258 5259 return function(str) { 5260 if (!bidiRE.test(str)) return false; 5261 var len = str.length, types = []; 5262 for (var i = 0, type; i < len; ++i) 5263 types.push(type = charType(str.charCodeAt(i))); 5264 5265 // W1. Examine each non-spacing mark (NSM) in the level run, and 5266 // change the type of the NSM to the type of the previous 5267 // character. If the NSM is at the start of the level run, it will 5268 // get the type of sor. 5269 for (var i = 0, prev = outerType; i < len; ++i) { 5270 var type = types[i]; 5271 if (type == "m") types[i] = prev; 5272 else prev = type; 5273 } 5274 5275 // W2. Search backwards from each instance of a European number 5276 // until the first strong type (R, L, AL, or sor) is found. If an 5277 // AL is found, change the type of the European number to Arabic 5278 // number. 5279 // W3. Change all ALs to R. 5280 for (var i = 0, cur = outerType; i < len; ++i) { 5281 var type = types[i]; 5282 if (type == "1" && cur == "r") types[i] = "n"; 5283 else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } 5284 } 5285 5286 // W4. A single European separator between two European numbers 5287 // changes to a European number. A single common separator between 5288 // two numbers of the same type changes to that type. 5289 for (var i = 1, prev = types[0]; i < len - 1; ++i) { 5290 var type = types[i]; 5291 if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; 5292 else if (type == "," && prev == types[i+1] && 5293 (prev == "1" || prev == "n")) types[i] = prev; 5294 prev = type; 5295 } 5296 5297 // W5. A sequence of European terminators adjacent to European 5298 // numbers changes to all European numbers. 5299 // W6. Otherwise, separators and terminators change to Other 5300 // Neutral. 5301 for (var i = 0; i < len; ++i) { 5302 var type = types[i]; 5303 if (type == ",") types[i] = "N"; 5304 else if (type == "%") { 5305 for (var end = i + 1; end < len && types[end] == "%"; ++end) {} 5306 var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N"; 5307 for (var j = i; j < end; ++j) types[j] = replace; 5308 i = end - 1; 5309 } 5310 } 5311 5312 // W7. Search backwards from each instance of a European number 5313 // until the first strong type (R, L, or sor) is found. If an L is 5314 // found, then change the type of the European number to L. 5315 for (var i = 0, cur = outerType; i < len; ++i) { 5316 var type = types[i]; 5317 if (cur == "L" && type == "1") types[i] = "L"; 5318 else if (isStrong.test(type)) cur = type; 5319 } 5320 5321 // N1. A sequence of neutrals takes the direction of the 5322 // surrounding strong text if the text on both sides has the same 5323 // direction. European and Arabic numbers act as if they were R in 5324 // terms of their influence on neutrals. Start-of-level-run (sor) 5325 // and end-of-level-run (eor) are used at level run boundaries. 5326 // N2. Any remaining neutrals take the embedding direction. 5327 for (var i = 0; i < len; ++i) { 5328 if (isNeutral.test(types[i])) { 5329 for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} 5330 var before = (i ? types[i-1] : outerType) == "L"; 5331 var after = (end < len - 1 ? types[end] : outerType) == "L"; 5332 var replace = before || after ? "L" : "R"; 5333 for (var j = i; j < end; ++j) types[j] = replace; 5334 i = end - 1; 5335 } 5336 } 5337 5338 // Here we depart from the documented algorithm, in order to avoid 5339 // building up an actual levels array. Since there are only three 5340 // levels (0, 1, 2) in an implementation that doesn't take 5341 // explicit embedding into account, we can build up the order on 5342 // the fly, without following the level-based algorithm. 5343 var order = [], m; 5344 for (var i = 0; i < len;) { 5345 if (countsAsLeft.test(types[i])) { 5346 var start = i; 5347 for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} 5348 order.push({from: start, to: i, level: 0}); 5349 } else { 5350 var pos = i, at = order.length; 5351 for (++i; i < len && types[i] != "L"; ++i) {} 5352 for (var j = pos; j < i;) { 5353 if (countsAsNum.test(types[j])) { 5354 if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1}); 5355 var nstart = j; 5356 for (++j; j < i && countsAsNum.test(types[j]); ++j) {} 5357 order.splice(at, 0, {from: nstart, to: j, level: 2}); 5358 pos = j; 5359 } else ++j; 5360 } 5361 if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1}); 5362 } 5363 } 5364 if (order[0].level == 1 && (m = str.match(/^\s+/))) { 5365 order[0].from = m[0].length; 5366 order.unshift({from: 0, to: m[0].length, level: 0}); 5367 } 5368 if (lst(order).level == 1 && (m = str.match(/\s+$/))) { 5369 lst(order).to -= m[0].length; 5370 order.push({from: len - m[0].length, to: len, level: 0}); 5371 } 5372 if (order[0].level != lst(order).level) 5373 order.push({from: len, to: len, level: order[0].level}); 5374 5375 return order; 5376 }; 5377 })(); 5378 5379 // THE END 5380 5381 CodeMirror.version = "3.1"; 5382 5383 return CodeMirror; 5384})();
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.