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