phrebejk@460: // CodeMirror version 3.0 phrebejk@460: // phrebejk@460: // CodeMirror is the only global var we claim phrebejk@460: window.CodeMirror = (function() { phrebejk@460: "use strict"; phrebejk@460: phrebejk@460: // BROWSER SNIFFING phrebejk@460: phrebejk@460: // Crude, but necessary to handle a number of hard-to-feature-detect phrebejk@460: // bugs and behavior differences. phrebejk@460: var gecko = /gecko\/\d/i.test(navigator.userAgent); phrebejk@460: var ie = /MSIE \d/.test(navigator.userAgent); phrebejk@460: var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent); phrebejk@460: var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent); phrebejk@460: var webkit = /WebKit\//.test(navigator.userAgent); phrebejk@460: var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); phrebejk@460: var chrome = /Chrome\//.test(navigator.userAgent); phrebejk@460: var opera = /Opera\//.test(navigator.userAgent); phrebejk@460: var safari = /Apple Computer/.test(navigator.vendor); phrebejk@460: var khtml = /KHTML\//.test(navigator.userAgent); phrebejk@460: var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent); phrebejk@460: var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent); phrebejk@460: var phantom = /PhantomJS/.test(navigator.userAgent); phrebejk@460: phrebejk@460: var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); phrebejk@460: // This is woefully incomplete. Suggestions for alternative methods welcome. phrebejk@460: var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|IEMobile/i.test(navigator.userAgent); phrebejk@460: var mac = ios || /Mac/.test(navigator.platform); phrebejk@460: phrebejk@460: // Optimize some code when these features are not used phrebejk@460: var sawReadOnlySpans = false, sawCollapsedSpans = false; phrebejk@460: phrebejk@460: // CONSTRUCTOR phrebejk@460: phrebejk@460: function CodeMirror(place, options) { phrebejk@460: if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); phrebejk@460: phrebejk@460: this.options = options = options || {}; phrebejk@460: // Determine effective options based on given values and defaults. phrebejk@460: for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt)) phrebejk@460: options[opt] = defaults[opt]; phrebejk@460: setGuttersForLineNumbers(options); phrebejk@460: phrebejk@460: var display = this.display = makeDisplay(place); phrebejk@460: display.wrapper.CodeMirror = this; phrebejk@460: updateGutters(this); phrebejk@460: if (options.autofocus && !mobile) focusInput(this); phrebejk@460: phrebejk@460: this.view = makeView(new BranchChunk([new LeafChunk([makeLine("", null, textHeight(display))])])); phrebejk@460: this.nextOpId = 0; phrebejk@460: loadMode(this); phrebejk@460: themeChanged(this); phrebejk@460: if (options.lineWrapping) phrebejk@460: this.display.wrapper.className += " CodeMirror-wrap"; phrebejk@460: phrebejk@460: // Initialize the content. phrebejk@460: this.setValue(options.value || ""); phrebejk@460: // Override magic textarea content restore that IE sometimes does phrebejk@460: // on our hidden textarea on reload phrebejk@460: if (ie) setTimeout(bind(resetInput, this, true), 20); phrebejk@460: this.view.history = makeHistory(); phrebejk@460: phrebejk@460: registerEventHandlers(this); phrebejk@460: // IE throws unspecified error in certain cases, when phrebejk@460: // trying to access activeElement before onload phrebejk@460: var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { } phrebejk@460: if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20); phrebejk@460: else onBlur(this); phrebejk@460: phrebejk@460: operation(this, function() { phrebejk@460: for (var opt in optionHandlers) phrebejk@460: if (optionHandlers.propertyIsEnumerable(opt)) phrebejk@460: optionHandlers[opt](this, options[opt], Init); phrebejk@460: for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); phrebejk@460: })(); phrebejk@460: } phrebejk@460: phrebejk@460: // DISPLAY CONSTRUCTOR phrebejk@460: phrebejk@460: function makeDisplay(place) { phrebejk@460: var d = {}; phrebejk@460: var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none;"); phrebejk@460: input.setAttribute("wrap", "off"); input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); phrebejk@460: // Wraps and hides input textarea phrebejk@460: d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); phrebejk@460: // The actual fake scrollbars. phrebejk@460: d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar"); phrebejk@460: d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar"); phrebejk@460: d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); phrebejk@460: // DIVs containing the selection and the actual code phrebejk@460: d.lineDiv = elt("div"); phrebejk@460: d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); phrebejk@460: // Blinky cursor, and element used to ensure cursor fits at the end of a line phrebejk@460: d.cursor = elt("pre", "\u00a0", "CodeMirror-cursor"); phrebejk@460: // Secondary cursor, shown when on a 'jump' in bi-directional text phrebejk@460: d.otherCursor = elt("pre", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"); phrebejk@460: // Used to measure text size phrebejk@460: d.measure = elt("div", null, "CodeMirror-measure"); phrebejk@460: // Wraps everything that needs to exist inside the vertically-padded coordinate system phrebejk@460: d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor], phrebejk@460: null, "position: relative; outline: none"); phrebejk@460: // Moved around its parent to cover visible view phrebejk@460: d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); phrebejk@460: // Set to the height of the text, causes scrolling phrebejk@460: d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); phrebejk@460: // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers phrebejk@460: d.heightForcer = elt("div", "\u00a0", null, "position: absolute; height: " + scrollerCutOff + "px"); phrebejk@460: // Will contain the gutters, if any phrebejk@460: d.gutters = elt("div", null, "CodeMirror-gutters"); phrebejk@460: d.lineGutter = null; phrebejk@460: // Helper element to properly size the gutter backgrounds phrebejk@460: var scrollerInner = elt("div", [d.sizer, d.heightForcer, d.gutters], null, "position: relative; min-height: 100%"); phrebejk@460: // Provides scrolling phrebejk@460: d.scroller = elt("div", [scrollerInner], "CodeMirror-scroll"); phrebejk@460: d.scroller.setAttribute("tabIndex", "-1"); phrebejk@460: // The element in which the editor lives. phrebejk@460: d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV, phrebejk@460: d.scrollbarFiller, d.scroller], "CodeMirror"); phrebejk@460: // Work around IE7 z-index bug phrebejk@460: if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } phrebejk@460: if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper); phrebejk@460: phrebejk@460: // Needed to hide big blue blinking cursor on Mobile Safari phrebejk@460: if (ios) input.style.width = "0px"; phrebejk@460: if (!webkit) d.scroller.draggable = true; phrebejk@460: // Needed to handle Tab key in KHTML phrebejk@460: if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; } phrebejk@460: // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). phrebejk@460: else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px"; phrebejk@460: phrebejk@460: // Current visible range (may be bigger than the view window). phrebejk@460: d.viewOffset = d.showingFrom = d.showingTo = d.lastSizeC = 0; phrebejk@460: phrebejk@460: // Used to only resize the line number gutter when necessary (when phrebejk@460: // the amount of lines crosses a boundary that makes its width change) phrebejk@460: d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; phrebejk@460: // See readInput and resetInput phrebejk@460: d.prevInput = ""; phrebejk@460: // Set to true when a non-horizontal-scrolling widget is added. As phrebejk@460: // an optimization, widget aligning is skipped when d is false. phrebejk@460: d.alignWidgets = false; phrebejk@460: // Flag that indicates whether we currently expect input to appear phrebejk@460: // (after some event like 'keypress' or 'input') and are polling phrebejk@460: // intensively. phrebejk@460: d.pollingFast = false; phrebejk@460: // Self-resetting timeout for the poller phrebejk@460: d.poll = new Delayed(); phrebejk@460: // True when a drag from the editor is active phrebejk@460: d.draggingText = false; phrebejk@460: phrebejk@460: d.cachedCharWidth = d.cachedTextHeight = null; phrebejk@460: d.measureLineCache = []; phrebejk@460: d.measureLineCachePos = 0; phrebejk@460: phrebejk@460: // Tracks when resetInput has punted to just putting a short phrebejk@460: // string instead of the (large) selection. phrebejk@460: d.inaccurateSelection = false; phrebejk@460: phrebejk@460: // Used to adjust overwrite behaviour when a paste has been phrebejk@460: // detected phrebejk@460: d.pasteIncoming = false; phrebejk@460: phrebejk@460: return d; phrebejk@460: } phrebejk@460: phrebejk@460: // VIEW CONSTRUCTOR phrebejk@460: phrebejk@460: function makeView(doc) { phrebejk@460: var selPos = {line: 0, ch: 0}; phrebejk@460: return { phrebejk@460: doc: doc, phrebejk@460: // frontier is the point up to which the content has been parsed, phrebejk@460: frontier: 0, highlight: new Delayed(), phrebejk@460: sel: {from: selPos, to: selPos, head: selPos, anchor: selPos, shift: false, extend: false}, phrebejk@460: scrollTop: 0, scrollLeft: 0, phrebejk@460: overwrite: false, focused: false, phrebejk@460: // Tracks the maximum line length so that phrebejk@460: // the horizontal scrollbar can be kept phrebejk@460: // static when scrolling. phrebejk@460: maxLine: getLine(doc, 0), phrebejk@460: maxLineLength: 0, phrebejk@460: maxLineChanged: false, phrebejk@460: suppressEdits: false, phrebejk@460: goalColumn: null, phrebejk@460: cantEdit: false, phrebejk@460: keyMaps: [] phrebejk@460: }; phrebejk@460: } phrebejk@460: phrebejk@460: // STATE UPDATES phrebejk@460: phrebejk@460: // Used to get the editor into a consistent state again when options change. phrebejk@460: phrebejk@460: function loadMode(cm) { phrebejk@460: var doc = cm.view.doc; phrebejk@460: cm.view.mode = CodeMirror.getMode(cm.options, cm.options.mode); phrebejk@460: doc.iter(0, doc.size, function(line) { line.stateAfter = null; }); phrebejk@460: cm.view.frontier = 0; phrebejk@460: startWorker(cm, 100); phrebejk@460: } phrebejk@460: phrebejk@460: function wrappingChanged(cm) { phrebejk@460: var doc = cm.view.doc, th = textHeight(cm.display); phrebejk@460: if (cm.options.lineWrapping) { phrebejk@460: cm.display.wrapper.className += " CodeMirror-wrap"; phrebejk@460: var perLine = cm.display.scroller.clientWidth / charWidth(cm.display) - 3; phrebejk@460: doc.iter(0, doc.size, function(line) { phrebejk@460: if (line.height == 0) return; phrebejk@460: var guess = Math.ceil(line.text.length / perLine) || 1; phrebejk@460: if (guess != 1) updateLineHeight(line, guess * th); phrebejk@460: }); phrebejk@460: cm.display.sizer.style.minWidth = ""; phrebejk@460: } else { phrebejk@460: cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", ""); phrebejk@460: computeMaxLength(cm.view); phrebejk@460: doc.iter(0, doc.size, function(line) { phrebejk@460: if (line.height != 0) updateLineHeight(line, th); phrebejk@460: }); phrebejk@460: } phrebejk@460: regChange(cm, 0, doc.size); phrebejk@460: clearCaches(cm); phrebejk@460: setTimeout(function(){updateScrollbars(cm.display, cm.view.doc.height);}, 100); phrebejk@460: } phrebejk@460: phrebejk@460: function keyMapChanged(cm) { phrebejk@460: var style = keyMap[cm.options.keyMap].style; phrebejk@460: cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") + phrebejk@460: (style ? " cm-keymap-" + style : ""); phrebejk@460: } phrebejk@460: phrebejk@460: function themeChanged(cm) { phrebejk@460: cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + phrebejk@460: cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); phrebejk@460: clearCaches(cm); phrebejk@460: } phrebejk@460: phrebejk@460: function guttersChanged(cm) { phrebejk@460: updateGutters(cm); phrebejk@460: updateDisplay(cm, true); phrebejk@460: } phrebejk@460: phrebejk@460: function updateGutters(cm) { phrebejk@460: var gutters = cm.display.gutters, specs = cm.options.gutters; phrebejk@460: removeChildren(gutters); phrebejk@460: for (var i = 0; i < specs.length; ++i) { phrebejk@460: var gutterClass = specs[i]; phrebejk@460: var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); phrebejk@460: if (gutterClass == "CodeMirror-linenumbers") { phrebejk@460: cm.display.lineGutter = gElt; phrebejk@460: gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; phrebejk@460: } phrebejk@460: } phrebejk@460: gutters.style.display = i ? "" : "none"; phrebejk@460: } phrebejk@460: phrebejk@460: function lineLength(doc, line) { phrebejk@460: if (line.height == 0) return 0; phrebejk@460: var len = line.text.length, merged, cur = line; phrebejk@460: while (merged = collapsedSpanAtStart(cur)) { phrebejk@460: var found = merged.find(); phrebejk@460: cur = getLine(doc, found.from.line); phrebejk@460: len += found.from.ch - found.to.ch; phrebejk@460: } phrebejk@460: cur = line; phrebejk@460: while (merged = collapsedSpanAtEnd(cur)) { phrebejk@460: var found = merged.find(); phrebejk@460: len -= cur.text.length - found.from.ch; phrebejk@460: cur = getLine(doc, found.to.line); phrebejk@460: len += cur.text.length - found.to.ch; phrebejk@460: } phrebejk@460: return len; phrebejk@460: } phrebejk@460: phrebejk@460: function computeMaxLength(view) { phrebejk@460: view.maxLine = getLine(view.doc, 0); phrebejk@460: view.maxLineLength = lineLength(view.doc, view.maxLine); phrebejk@460: view.maxLineChanged = true; phrebejk@460: view.doc.iter(1, view.doc.size, function(line) { phrebejk@460: var len = lineLength(view.doc, line); phrebejk@460: if (len > view.maxLineLength) { phrebejk@460: view.maxLineLength = len; phrebejk@460: view.maxLine = line; phrebejk@460: } phrebejk@460: }); phrebejk@460: } phrebejk@460: phrebejk@460: // Make sure the gutters options contains the element phrebejk@460: // "CodeMirror-linenumbers" when the lineNumbers option is true. phrebejk@460: function setGuttersForLineNumbers(options) { phrebejk@460: var found = false; phrebejk@460: for (var i = 0; i < options.gutters.length; ++i) { phrebejk@460: if (options.gutters[i] == "CodeMirror-linenumbers") { phrebejk@460: if (options.lineNumbers) found = true; phrebejk@460: else options.gutters.splice(i--, 1); phrebejk@460: } phrebejk@460: } phrebejk@460: if (!found && options.lineNumbers) phrebejk@460: options.gutters.push("CodeMirror-linenumbers"); phrebejk@460: } phrebejk@460: phrebejk@460: // SCROLLBARS phrebejk@460: phrebejk@460: // Re-synchronize the fake scrollbars with the actual size of the phrebejk@460: // content. Optionally force a scrollTop. phrebejk@460: function updateScrollbars(d /* display */, docHeight) { phrebejk@460: var totalHeight = docHeight + 2 * paddingTop(d); phrebejk@460: d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px"; phrebejk@460: var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight); phrebejk@460: var needsH = d.scroller.scrollWidth > d.scroller.clientWidth; phrebejk@460: var needsV = scrollHeight > d.scroller.clientHeight; phrebejk@460: if (needsV) { phrebejk@460: d.scrollbarV.style.display = "block"; phrebejk@460: d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0"; phrebejk@460: d.scrollbarV.firstChild.style.height = phrebejk@460: (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px"; phrebejk@460: } else d.scrollbarV.style.display = ""; phrebejk@460: if (needsH) { phrebejk@460: d.scrollbarH.style.display = "block"; phrebejk@460: d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0"; phrebejk@460: d.scrollbarH.firstChild.style.width = phrebejk@460: (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px"; phrebejk@460: } else d.scrollbarH.style.display = ""; phrebejk@460: if (needsH && needsV) { phrebejk@460: d.scrollbarFiller.style.display = "block"; phrebejk@460: d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px"; phrebejk@460: } else d.scrollbarFiller.style.display = ""; phrebejk@460: phrebejk@460: if (mac_geLion && scrollbarWidth(d.measure) === 0) phrebejk@460: d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px"; phrebejk@460: } phrebejk@460: phrebejk@460: function visibleLines(display, doc, viewPort) { phrebejk@460: var top = display.scroller.scrollTop, height = display.wrapper.clientHeight; phrebejk@460: if (typeof viewPort == "number") top = viewPort; phrebejk@460: else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;} phrebejk@460: top = Math.floor(top - paddingTop(display)); phrebejk@460: var bottom = Math.ceil(top + height); phrebejk@460: return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)}; phrebejk@460: } phrebejk@460: phrebejk@460: // LINE NUMBERS phrebejk@460: phrebejk@460: function alignHorizontally(cm) { phrebejk@460: var display = cm.display; phrebejk@460: if (!display.alignWidgets && !display.gutters.firstChild) return; phrebejk@460: var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.view.scrollLeft; phrebejk@460: var gutterW = display.gutters.offsetWidth, l = comp + "px"; phrebejk@460: for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) { phrebejk@460: for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l; phrebejk@460: } phrebejk@460: display.gutters.style.left = (comp + gutterW) + "px"; phrebejk@460: } phrebejk@460: phrebejk@460: function maybeUpdateLineNumberWidth(cm) { phrebejk@460: if (!cm.options.lineNumbers) return false; phrebejk@460: var doc = cm.view.doc, last = lineNumberFor(cm.options, doc.size - 1), display = cm.display; phrebejk@460: if (last.length != display.lineNumChars) { phrebejk@460: var test = display.measure.appendChild(elt("div", [elt("div", last)], phrebejk@460: "CodeMirror-linenumber CodeMirror-gutter-elt")); phrebejk@460: var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; phrebejk@460: display.lineGutter.style.width = ""; phrebejk@460: display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding); phrebejk@460: display.lineNumWidth = display.lineNumInnerWidth + padding; phrebejk@460: display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; phrebejk@460: display.lineGutter.style.width = display.lineNumWidth + "px"; phrebejk@460: return true; phrebejk@460: } phrebejk@460: return false; phrebejk@460: } phrebejk@460: phrebejk@460: function lineNumberFor(options, i) { phrebejk@460: return String(options.lineNumberFormatter(i + options.firstLineNumber)); phrebejk@460: } phrebejk@460: function compensateForHScroll(display) { phrebejk@460: return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; phrebejk@460: } phrebejk@460: phrebejk@460: // DISPLAY DRAWING phrebejk@460: phrebejk@460: function updateDisplay(cm, changes, viewPort) { phrebejk@460: var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo; phrebejk@460: var updated = updateDisplayInner(cm, changes, viewPort); phrebejk@460: if (updated) { phrebejk@460: signalLater(cm, cm, "update", cm); phrebejk@460: if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo) phrebejk@460: signalLater(cm, cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo); phrebejk@460: } phrebejk@460: updateSelection(cm); phrebejk@460: updateScrollbars(cm.display, cm.view.doc.height); phrebejk@460: phrebejk@460: return updated; phrebejk@460: } phrebejk@460: phrebejk@460: // Uses a set of changes plus the current scroll position to phrebejk@460: // determine which DOM updates have to be made, and makes the phrebejk@460: // updates. phrebejk@460: function updateDisplayInner(cm, changes, viewPort) { phrebejk@460: var display = cm.display, doc = cm.view.doc; phrebejk@460: if (!display.wrapper.clientWidth) { phrebejk@460: display.showingFrom = display.showingTo = display.viewOffset = 0; phrebejk@460: return; phrebejk@460: } phrebejk@460: phrebejk@460: // Compute the new visible window phrebejk@460: // If scrollTop is specified, use that to determine which lines phrebejk@460: // to render instead of the current scrollbar position. phrebejk@460: var visible = visibleLines(display, doc, viewPort); phrebejk@460: // Bail out if the visible area is already rendered and nothing changed. phrebejk@460: if (changes !== true && changes.length == 0 && phrebejk@460: visible.from > display.showingFrom && visible.to < display.showingTo) phrebejk@460: return; phrebejk@460: phrebejk@460: if (changes && maybeUpdateLineNumberWidth(cm)) phrebejk@460: changes = true; phrebejk@460: display.sizer.style.marginLeft = display.scrollbarH.style.left = display.gutters.offsetWidth + "px"; phrebejk@460: phrebejk@460: // When merged lines are present, the line that needs to be phrebejk@460: // redrawn might not be the one that was changed. phrebejk@460: if (changes !== true && sawCollapsedSpans) phrebejk@460: for (var i = 0; i < changes.length; ++i) { phrebejk@460: var ch = changes[i], merged; phrebejk@460: while (merged = collapsedSpanAtStart(getLine(doc, ch.from))) { phrebejk@460: var from = merged.find().from.line; phrebejk@460: if (ch.diff) ch.diff -= ch.from - from; phrebejk@460: ch.from = from; phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: // Used to determine which lines need their line numbers updated phrebejk@460: var positionsChangedFrom = changes === true ? 0 : Infinity; phrebejk@460: if (cm.options.lineNumbers && changes && changes !== true) phrebejk@460: for (var i = 0; i < changes.length; ++i) phrebejk@460: if (changes[i].diff) { positionsChangedFrom = changes[i].from; break; } phrebejk@460: phrebejk@460: var from = Math.max(visible.from - cm.options.viewportMargin, 0); phrebejk@460: var to = Math.min(doc.size, visible.to + cm.options.viewportMargin); phrebejk@460: if (display.showingFrom < from && from - display.showingFrom < 20) from = display.showingFrom; phrebejk@460: if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(doc.size, display.showingTo); phrebejk@460: if (sawCollapsedSpans) { phrebejk@460: from = lineNo(visualLine(doc, getLine(doc, from))); phrebejk@460: while (to < doc.size && lineIsHidden(getLine(doc, to))) ++to; phrebejk@460: } phrebejk@460: phrebejk@460: // Create a range of theoretically intact lines, and punch holes phrebejk@460: // in that using the change info. phrebejk@460: var intact = changes === true ? [] : phrebejk@460: computeIntact([{from: display.showingFrom, to: display.showingTo}], changes); phrebejk@460: // Clip off the parts that won't be visible phrebejk@460: var intactLines = 0; phrebejk@460: for (var i = 0; i < intact.length; ++i) { phrebejk@460: var range = intact[i]; phrebejk@460: if (range.from < from) range.from = from; phrebejk@460: if (range.to > to) range.to = to; phrebejk@460: if (range.from >= range.to) intact.splice(i--, 1); phrebejk@460: else intactLines += range.to - range.from; phrebejk@460: } phrebejk@460: if (intactLines == to - from && from == display.showingFrom && to == display.showingTo) phrebejk@460: return; phrebejk@460: intact.sort(function(a, b) {return a.from - b.from;}); phrebejk@460: phrebejk@460: if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none"; phrebejk@460: patchDisplay(cm, from, to, intact, positionsChangedFrom); phrebejk@460: display.lineDiv.style.display = ""; phrebejk@460: phrebejk@460: var different = from != display.showingFrom || to != display.showingTo || phrebejk@460: display.lastSizeC != display.wrapper.clientHeight; phrebejk@460: // This is just a bogus formula that detects when the editor is phrebejk@460: // resized or the font size changes. phrebejk@460: if (different) display.lastSizeC = display.wrapper.clientHeight; phrebejk@460: display.showingFrom = from; display.showingTo = to; phrebejk@460: startWorker(cm, 100); phrebejk@460: phrebejk@460: var prevBottom = display.lineDiv.offsetTop; phrebejk@460: for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) { phrebejk@460: if (ie_lt8) { phrebejk@460: var bot = node.offsetTop + node.offsetHeight; phrebejk@460: height = bot - prevBottom; phrebejk@460: prevBottom = bot; phrebejk@460: } else { phrebejk@460: var box = node.getBoundingClientRect(); phrebejk@460: height = box.bottom - box.top; phrebejk@460: } phrebejk@460: var diff = node.lineObj.height - height; phrebejk@460: if (height < 2) height = textHeight(display); phrebejk@460: if (diff > .001 || diff < -.001) phrebejk@460: updateLineHeight(node.lineObj, height); phrebejk@460: } phrebejk@460: display.viewOffset = heightAtLine(cm, getLine(doc, from)); phrebejk@460: // Position the mover div to align with the current virtual scroll position phrebejk@460: display.mover.style.top = display.viewOffset + "px"; phrebejk@460: return true; phrebejk@460: } phrebejk@460: phrebejk@460: function computeIntact(intact, changes) { phrebejk@460: for (var i = 0, l = changes.length || 0; i < l; ++i) { phrebejk@460: var change = changes[i], intact2 = [], diff = change.diff || 0; phrebejk@460: for (var j = 0, l2 = intact.length; j < l2; ++j) { phrebejk@460: var range = intact[j]; phrebejk@460: if (change.to <= range.from && change.diff) { phrebejk@460: intact2.push({from: range.from + diff, to: range.to + diff}); phrebejk@460: } else if (change.to <= range.from || change.from >= range.to) { phrebejk@460: intact2.push(range); phrebejk@460: } else { phrebejk@460: if (change.from > range.from) phrebejk@460: intact2.push({from: range.from, to: change.from}); phrebejk@460: if (change.to < range.to) phrebejk@460: intact2.push({from: change.to + diff, to: range.to + diff}); phrebejk@460: } phrebejk@460: } phrebejk@460: intact = intact2; phrebejk@460: } phrebejk@460: return intact; phrebejk@460: } phrebejk@460: phrebejk@460: function getDimensions(cm) { phrebejk@460: var d = cm.display, left = {}, width = {}; phrebejk@460: for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { phrebejk@460: left[cm.options.gutters[i]] = n.offsetLeft; phrebejk@460: width[cm.options.gutters[i]] = n.offsetWidth; phrebejk@460: } phrebejk@460: return {fixedPos: compensateForHScroll(d), phrebejk@460: gutterTotalWidth: d.gutters.offsetWidth, phrebejk@460: gutterLeft: left, phrebejk@460: gutterWidth: width, phrebejk@460: wrapperWidth: d.wrapper.clientWidth}; phrebejk@460: } phrebejk@460: phrebejk@460: function patchDisplay(cm, from, to, intact, updateNumbersFrom) { phrebejk@460: var dims = getDimensions(cm); phrebejk@460: var display = cm.display, lineNumbers = cm.options.lineNumbers; phrebejk@460: // IE does bad things to nodes when .innerHTML = "" is used on a parent phrebejk@460: // we still need widgets and markers intact to add back to the new content later phrebejk@460: if (!intact.length && !ie && (!webkit || !cm.display.currentWheelTarget)) phrebejk@460: removeChildren(display.lineDiv); phrebejk@460: var container = display.lineDiv, cur = container.firstChild; phrebejk@460: phrebejk@460: function rm(node) { phrebejk@460: var next = node.nextSibling; phrebejk@460: if (webkit && mac && cm.display.currentWheelTarget == node) { phrebejk@460: node.style.display = "none"; phrebejk@460: node.lineObj = null; phrebejk@460: } else { phrebejk@460: container.removeChild(node); phrebejk@460: } phrebejk@460: return next; phrebejk@460: } phrebejk@460: phrebejk@460: var nextIntact = intact.shift(), lineNo = from; phrebejk@460: cm.view.doc.iter(from, to, function(line) { phrebejk@460: if (nextIntact && nextIntact.to == lineNo) nextIntact = intact.shift(); phrebejk@460: if (lineIsHidden(line)) { phrebejk@460: if (line.height != 0) updateLineHeight(line, 0); phrebejk@460: } else if (nextIntact && nextIntact.from <= lineNo && nextIntact.to > lineNo) { phrebejk@460: // This line is intact. Skip to the actual node. Update its phrebejk@460: // line number if needed. phrebejk@460: while (cur.lineObj != line) cur = rm(cur); phrebejk@460: if (lineNumbers && updateNumbersFrom <= lineNo && cur.lineNumber) phrebejk@460: setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineNo)); phrebejk@460: cur = cur.nextSibling; phrebejk@460: } else { phrebejk@460: // This line needs to be generated. phrebejk@460: var lineNode = buildLineElement(cm, line, lineNo, dims); phrebejk@460: container.insertBefore(lineNode, cur); phrebejk@460: lineNode.lineObj = line; phrebejk@460: } phrebejk@460: ++lineNo; phrebejk@460: }); phrebejk@460: while (cur) cur = rm(cur); phrebejk@460: } phrebejk@460: phrebejk@460: function buildLineElement(cm, line, lineNo, dims) { phrebejk@460: var lineElement = lineContent(cm, line); phrebejk@460: var markers = line.gutterMarkers, display = cm.display; phrebejk@460: phrebejk@460: if (!cm.options.lineNumbers && !markers && !line.bgClass && !line.wrapClass && phrebejk@460: (!line.widgets || !line.widgets.length)) return lineElement; phrebejk@460: phrebejk@460: // Lines with gutter elements or a background class need phrebejk@460: // to be wrapped again, and have the extra elements added phrebejk@460: // to the wrapper div phrebejk@460: phrebejk@460: var wrap = elt("div", null, line.wrapClass, "position: relative"); phrebejk@460: if (cm.options.lineNumbers || markers) { phrebejk@460: var gutterWrap = wrap.appendChild(elt("div", null, null, "position: absolute; left: " + phrebejk@460: dims.fixedPos + "px")); phrebejk@460: wrap.alignable = [gutterWrap]; phrebejk@460: if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) phrebejk@460: wrap.lineNumber = gutterWrap.appendChild( phrebejk@460: elt("div", lineNumberFor(cm.options, lineNo), phrebejk@460: "CodeMirror-linenumber CodeMirror-gutter-elt", phrebejk@460: "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " phrebejk@460: + display.lineNumInnerWidth + "px")); phrebejk@460: if (markers) phrebejk@460: for (var k = 0; k < cm.options.gutters.length; ++k) { phrebejk@460: var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; phrebejk@460: if (found) phrebejk@460: gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + phrebejk@460: dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); phrebejk@460: } phrebejk@460: } phrebejk@460: // Kludge to make sure the styled element lies behind the selection (by z-index) phrebejk@460: if (line.bgClass) phrebejk@460: wrap.appendChild(elt("div", "\u00a0", line.bgClass + " CodeMirror-linebackground")); phrebejk@460: wrap.appendChild(lineElement); phrebejk@460: if (line.widgets) phrebejk@460: for (var i = 0, ws = line.widgets; i < ws.length; ++i) { phrebejk@460: var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); phrebejk@460: node.widget = widget; phrebejk@460: if (widget.noHScroll) { phrebejk@460: (wrap.alignable || (wrap.alignable = [])).push(node); phrebejk@460: var width = dims.wrapperWidth; phrebejk@460: node.style.left = dims.fixedPos + "px"; phrebejk@460: if (!widget.coverGutter) { phrebejk@460: width -= dims.gutterTotalWidth; phrebejk@460: node.style.paddingLeft = dims.gutterTotalWidth + "px"; phrebejk@460: } phrebejk@460: node.style.width = width + "px"; phrebejk@460: } phrebejk@460: if (widget.coverGutter) { phrebejk@460: node.style.zIndex = 5; phrebejk@460: node.style.position = "relative"; phrebejk@460: if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; phrebejk@460: } phrebejk@460: if (widget.above) phrebejk@460: wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement); phrebejk@460: else phrebejk@460: wrap.appendChild(node); phrebejk@460: } phrebejk@460: phrebejk@460: if (ie_lt8) wrap.style.zIndex = 2; phrebejk@460: return wrap; phrebejk@460: } phrebejk@460: phrebejk@460: // SELECTION / CURSOR phrebejk@460: phrebejk@460: function updateSelection(cm) { phrebejk@460: var display = cm.display; phrebejk@460: var collapsed = posEq(cm.view.sel.from, cm.view.sel.to); phrebejk@460: if (collapsed || cm.options.showCursorWhenSelecting) phrebejk@460: updateSelectionCursor(cm); phrebejk@460: else phrebejk@460: display.cursor.style.display = display.otherCursor.style.display = "none"; phrebejk@460: if (!collapsed) phrebejk@460: updateSelectionRange(cm); phrebejk@460: else phrebejk@460: display.selectionDiv.style.display = "none"; phrebejk@460: phrebejk@460: // Move the hidden textarea near the cursor to prevent scrolling artifacts phrebejk@460: var headPos = cursorCoords(cm, cm.view.sel.head, "div"); phrebejk@460: var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); phrebejk@460: display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10, phrebejk@460: headPos.top + lineOff.top - wrapOff.top)) + "px"; phrebejk@460: display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10, phrebejk@460: headPos.left + lineOff.left - wrapOff.left)) + "px"; phrebejk@460: } phrebejk@460: phrebejk@460: // No selection, plain cursor phrebejk@460: function updateSelectionCursor(cm) { phrebejk@460: var display = cm.display, pos = cursorCoords(cm, cm.view.sel.head, "div"); phrebejk@460: display.cursor.style.left = pos.left + "px"; phrebejk@460: display.cursor.style.top = pos.top + "px"; phrebejk@460: display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; phrebejk@460: display.cursor.style.display = ""; phrebejk@460: phrebejk@460: if (pos.other) { phrebejk@460: display.otherCursor.style.display = ""; phrebejk@460: display.otherCursor.style.left = pos.other.left + "px"; phrebejk@460: display.otherCursor.style.top = pos.other.top + "px"; phrebejk@460: display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; phrebejk@460: } else { display.otherCursor.style.display = "none"; } phrebejk@460: } phrebejk@460: phrebejk@460: // Highlight selection phrebejk@460: function updateSelectionRange(cm) { phrebejk@460: var display = cm.display, doc = cm.view.doc, sel = cm.view.sel; phrebejk@460: var fragment = document.createDocumentFragment(); phrebejk@460: var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display); phrebejk@460: phrebejk@460: function add(left, top, width, bottom) { phrebejk@460: if (top < 0) top = 0; phrebejk@460: fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + phrebejk@460: "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) + phrebejk@460: "px; height: " + (bottom - top) + "px")); phrebejk@460: } phrebejk@460: phrebejk@460: function drawForLine(line, fromArg, toArg, retTop) { phrebejk@460: var lineObj = getLine(doc, line); phrebejk@460: var lineLen = lineObj.text.length, rVal = retTop ? Infinity : -Infinity; phrebejk@460: function coords(ch) { phrebejk@460: return charCoords(cm, {line: line, ch: ch}, "div", lineObj); phrebejk@460: } phrebejk@460: phrebejk@460: iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { phrebejk@460: var leftPos = coords(dir == "rtl" ? to - 1 : from); phrebejk@460: var rightPos = coords(dir == "rtl" ? from : to - 1); phrebejk@460: var left = leftPos.left, right = rightPos.right; phrebejk@460: if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part phrebejk@460: add(left, leftPos.top, null, leftPos.bottom); phrebejk@460: left = pl; phrebejk@460: if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); phrebejk@460: } phrebejk@460: if (toArg == null && to == lineLen) right = clientWidth; phrebejk@460: if (fromArg == null && from == 0) left = pl; phrebejk@460: rVal = retTop ? Math.min(rightPos.top, rVal) : Math.max(rightPos.bottom, rVal); phrebejk@460: if (left < pl + 1) left = pl; phrebejk@460: add(left, rightPos.top, right - left, rightPos.bottom); phrebejk@460: }); phrebejk@460: return rVal; phrebejk@460: } phrebejk@460: phrebejk@460: if (sel.from.line == sel.to.line) { phrebejk@460: drawForLine(sel.from.line, sel.from.ch, sel.to.ch); phrebejk@460: } else { phrebejk@460: var fromObj = getLine(doc, sel.from.line); phrebejk@460: var cur = fromObj, merged, path = [sel.from.line, sel.from.ch], singleLine; phrebejk@460: while (merged = collapsedSpanAtEnd(cur)) { phrebejk@460: var found = merged.find(); phrebejk@460: path.push(found.from.ch, found.to.line, found.to.ch); phrebejk@460: if (found.to.line == sel.to.line) { phrebejk@460: path.push(sel.to.ch); phrebejk@460: singleLine = true; phrebejk@460: break; phrebejk@460: } phrebejk@460: cur = getLine(doc, found.to.line); phrebejk@460: } phrebejk@460: phrebejk@460: // This is a single, merged line phrebejk@460: if (singleLine) { phrebejk@460: for (var i = 0; i < path.length; i += 3) phrebejk@460: drawForLine(path[i], path[i+1], path[i+2]); phrebejk@460: } else { phrebejk@460: var middleTop, middleBot, toObj = getLine(doc, sel.to.line); phrebejk@460: if (sel.from.ch) phrebejk@460: // Draw the first line of selection. phrebejk@460: middleTop = drawForLine(sel.from.line, sel.from.ch, null, false); phrebejk@460: else phrebejk@460: // Simply include it in the middle block. phrebejk@460: middleTop = heightAtLine(cm, fromObj) - display.viewOffset; phrebejk@460: phrebejk@460: if (!sel.to.ch) phrebejk@460: middleBot = heightAtLine(cm, toObj) - display.viewOffset; phrebejk@460: else phrebejk@460: middleBot = drawForLine(sel.to.line, collapsedSpanAtStart(toObj) ? null : 0, sel.to.ch, true); phrebejk@460: phrebejk@460: if (middleTop < middleBot) add(pl, middleTop, null, middleBot); phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: removeChildrenAndAdd(display.selectionDiv, fragment); phrebejk@460: display.selectionDiv.style.display = ""; phrebejk@460: } phrebejk@460: phrebejk@460: // Cursor-blinking phrebejk@460: function restartBlink(cm) { phrebejk@460: var display = cm.display; phrebejk@460: clearInterval(display.blinker); phrebejk@460: var on = true; phrebejk@460: display.cursor.style.visibility = display.otherCursor.style.visibility = ""; phrebejk@460: display.blinker = setInterval(function() { phrebejk@460: if (!display.cursor.offsetHeight) return; phrebejk@460: display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden"; phrebejk@460: }, cm.options.cursorBlinkRate); phrebejk@460: } phrebejk@460: phrebejk@460: // HIGHLIGHT WORKER phrebejk@460: phrebejk@460: function startWorker(cm, time) { phrebejk@460: if (cm.view.frontier < cm.display.showingTo) phrebejk@460: cm.view.highlight.set(time, bind(highlightWorker, cm)); phrebejk@460: } phrebejk@460: phrebejk@460: function highlightWorker(cm) { phrebejk@460: var view = cm.view, doc = view.doc; phrebejk@460: if (view.frontier >= cm.display.showingTo) return; phrebejk@460: var end = +new Date + cm.options.workTime; phrebejk@460: var state = copyState(view.mode, getStateBefore(cm, view.frontier)); phrebejk@460: var changed = [], prevChange; phrebejk@460: doc.iter(view.frontier, Math.min(doc.size, cm.display.showingTo + 500), function(line) { phrebejk@460: if (view.frontier >= cm.display.showingFrom) { // Visible phrebejk@460: if (highlightLine(cm, line, state) && view.frontier >= cm.display.showingFrom) { phrebejk@460: if (prevChange && prevChange.end == view.frontier) prevChange.end++; phrebejk@460: else changed.push(prevChange = {start: view.frontier, end: view.frontier + 1}); phrebejk@460: } phrebejk@460: line.stateAfter = copyState(view.mode, state); phrebejk@460: } else { phrebejk@460: processLine(cm, line, state); phrebejk@460: line.stateAfter = view.frontier % 5 == 0 ? copyState(view.mode, state) : null; phrebejk@460: } phrebejk@460: ++view.frontier; phrebejk@460: if (+new Date > end) { phrebejk@460: startWorker(cm, cm.options.workDelay); phrebejk@460: return true; phrebejk@460: } phrebejk@460: }); phrebejk@460: if (changed.length) phrebejk@460: operation(cm, function() { phrebejk@460: for (var i = 0; i < changed.length; ++i) phrebejk@460: regChange(this, changed[i].start, changed[i].end); phrebejk@460: })(); phrebejk@460: } phrebejk@460: phrebejk@460: // Finds the line to start with when starting a parse. Tries to phrebejk@460: // find a line with a stateAfter, so that it can start with a phrebejk@460: // valid state. If that fails, it returns the line with the phrebejk@460: // smallest indentation, which tends to need the least context to phrebejk@460: // parse correctly. phrebejk@460: function findStartLine(cm, n) { phrebejk@460: var minindent, minline, doc = cm.view.doc; phrebejk@460: for (var search = n, lim = n - 100; search > lim; --search) { phrebejk@460: if (search == 0) return 0; phrebejk@460: var line = getLine(doc, search-1); phrebejk@460: if (line.stateAfter) return search; phrebejk@460: var indented = countColumn(line.text, null, cm.options.tabSize); phrebejk@460: if (minline == null || minindent > indented) { phrebejk@460: minline = search - 1; phrebejk@460: minindent = indented; phrebejk@460: } phrebejk@460: } phrebejk@460: return minline; phrebejk@460: } phrebejk@460: phrebejk@460: function getStateBefore(cm, n) { phrebejk@460: var view = cm.view; phrebejk@460: var pos = findStartLine(cm, n), state = pos && getLine(view.doc, pos-1).stateAfter; phrebejk@460: if (!state) state = startState(view.mode); phrebejk@460: else state = copyState(view.mode, state); phrebejk@460: view.doc.iter(pos, n, function(line) { phrebejk@460: processLine(cm, line, state); phrebejk@460: var save = pos == n - 1 || pos % 5 == 0 || pos >= view.showingFrom && pos < view.showingTo; phrebejk@460: line.stateAfter = save ? copyState(view.mode, state) : null; phrebejk@460: ++pos; phrebejk@460: }); phrebejk@460: return state; phrebejk@460: } phrebejk@460: phrebejk@460: // POSITION MEASUREMENT phrebejk@460: phrebejk@460: function paddingTop(display) {return display.lineSpace.offsetTop;} phrebejk@460: function paddingLeft(display) { phrebejk@460: var e = removeChildrenAndAdd(display.measure, elt("pre")).appendChild(elt("span", "x")); phrebejk@460: return e.offsetLeft; phrebejk@460: } phrebejk@460: phrebejk@460: function measureChar(cm, line, ch, data) { phrebejk@460: var data = data || measureLine(cm, line), dir = -1; phrebejk@460: for (var pos = ch;; pos += dir) { phrebejk@460: var r = data[pos]; phrebejk@460: if (r) break; phrebejk@460: if (dir < 0 && pos == 0) dir = 1; phrebejk@460: } phrebejk@460: return {left: pos < ch ? r.right : r.left, phrebejk@460: right: pos > ch ? r.left : r.right, phrebejk@460: top: r.top, bottom: r.bottom}; phrebejk@460: } phrebejk@460: phrebejk@460: function measureLine(cm, line) { phrebejk@460: // First look in the cache phrebejk@460: var display = cm.display, cache = cm.display.measureLineCache; phrebejk@460: for (var i = 0; i < cache.length; ++i) { phrebejk@460: var memo = cache[i]; phrebejk@460: if (memo.text == line.text && memo.markedSpans == line.markedSpans && phrebejk@460: display.scroller.clientWidth == memo.width) phrebejk@460: return memo.measure; phrebejk@460: } phrebejk@460: phrebejk@460: var measure = measureLineInner(cm, line); phrebejk@460: // Store result in the cache phrebejk@460: var memo = {text: line.text, width: display.scroller.clientWidth, phrebejk@460: markedSpans: line.markedSpans, measure: measure}; phrebejk@460: if (cache.length == 16) cache[++display.measureLineCachePos % 16] = memo; phrebejk@460: else cache.push(memo); phrebejk@460: return measure; phrebejk@460: } phrebejk@460: phrebejk@460: function measureLineInner(cm, line) { phrebejk@460: var display = cm.display, measure = emptyArray(line.text.length); phrebejk@460: var pre = lineContent(cm, line, measure); phrebejk@460: phrebejk@460: // IE does not cache element positions of inline elements between phrebejk@460: // calls to getBoundingClientRect. This makes the loop below, phrebejk@460: // which gathers the positions of all the characters on the line, phrebejk@460: // do an amount of layout work quadratic to the number of phrebejk@460: // characters. When line wrapping is off, we try to improve things phrebejk@460: // by first subdividing the line into a bunch of inline blocks, so phrebejk@460: // that IE can reuse most of the layout information from caches phrebejk@460: // for those blocks. This does interfere with line wrapping, so it phrebejk@460: // doesn't work when wrapping is on, but in that case the phrebejk@460: // situation is slightly better, since IE does cache line-wrapping phrebejk@460: // information and only recomputes per-line. phrebejk@460: if (ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) { phrebejk@460: var fragment = document.createDocumentFragment(); phrebejk@460: var chunk = 10, n = pre.childNodes.length; phrebejk@460: for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) { phrebejk@460: var wrap = elt("div", null, null, "display: inline-block"); phrebejk@460: for (var j = 0; j < chunk && n; ++j) { phrebejk@460: wrap.appendChild(pre.firstChild); phrebejk@460: --n; phrebejk@460: } phrebejk@460: fragment.appendChild(wrap); phrebejk@460: } phrebejk@460: pre.appendChild(fragment); phrebejk@460: } phrebejk@460: phrebejk@460: removeChildrenAndAdd(display.measure, pre); phrebejk@460: phrebejk@460: var outer = display.lineDiv.getBoundingClientRect(); phrebejk@460: var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight; phrebejk@460: for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) { phrebejk@460: var size = cur.getBoundingClientRect(); phrebejk@460: var top = Math.max(0, size.top - outer.top), bot = Math.min(size.bottom - outer.top, maxBot); phrebejk@460: for (var j = 0; j < vranges.length; j += 2) { phrebejk@460: var rtop = vranges[j], rbot = vranges[j+1]; phrebejk@460: if (rtop > bot || rbot < top) continue; phrebejk@460: if (rtop <= top && rbot >= bot || phrebejk@460: top <= rtop && bot >= rbot || phrebejk@460: Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) { phrebejk@460: vranges[j] = Math.min(top, rtop); phrebejk@460: vranges[j+1] = Math.max(bot, rbot); phrebejk@460: break; phrebejk@460: } phrebejk@460: } phrebejk@460: if (j == vranges.length) vranges.push(top, bot); phrebejk@460: data[i] = {left: size.left - outer.left, right: size.right - outer.left, top: j}; phrebejk@460: } phrebejk@460: for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) { phrebejk@460: var vr = cur.top; phrebejk@460: cur.top = vranges[vr]; cur.bottom = vranges[vr+1]; phrebejk@460: } phrebejk@460: return data; phrebejk@460: } phrebejk@460: phrebejk@460: function clearCaches(cm) { phrebejk@460: cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0; phrebejk@460: cm.display.cachedCharWidth = cm.display.cachedTextHeight = null; phrebejk@460: cm.view.maxLineChanged = true; phrebejk@460: } phrebejk@460: phrebejk@460: // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page" phrebejk@460: function intoCoordSystem(cm, lineObj, rect, context) { phrebejk@460: if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { phrebejk@460: var size = lineObj.widgets[i].node.offsetHeight; phrebejk@460: rect.top += size; rect.bottom += size; phrebejk@460: } phrebejk@460: if (context == "line") return rect; phrebejk@460: if (!context) context = "local"; phrebejk@460: var yOff = heightAtLine(cm, lineObj); phrebejk@460: if (context != "local") yOff -= cm.display.viewOffset; phrebejk@460: if (context == "page") { phrebejk@460: var lOff = cm.display.lineSpace.getBoundingClientRect(); phrebejk@460: yOff += lOff.top + (window.pageYOffset || (document.documentElement || document.body).scrollTop); phrebejk@460: var xOff = lOff.left + (window.pageXOffset || (document.documentElement || document.body).scrollLeft); phrebejk@460: rect.left += xOff; rect.right += xOff; phrebejk@460: } phrebejk@460: rect.top += yOff; rect.bottom += yOff; phrebejk@460: return rect; phrebejk@460: } phrebejk@460: phrebejk@460: function charCoords(cm, pos, context, lineObj) { phrebejk@460: if (!lineObj) lineObj = getLine(cm.view.doc, pos.line); phrebejk@460: return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch), context); phrebejk@460: } phrebejk@460: phrebejk@460: function cursorCoords(cm, pos, context, lineObj, measurement) { phrebejk@460: lineObj = lineObj || getLine(cm.view.doc, pos.line); phrebejk@460: if (!measurement) measurement = measureLine(cm, lineObj); phrebejk@460: function get(ch, right) { phrebejk@460: var m = measureChar(cm, lineObj, ch, measurement); phrebejk@460: if (right) m.left = m.right; else m.right = m.left; phrebejk@460: return intoCoordSystem(cm, lineObj, m, context); phrebejk@460: } phrebejk@460: var order = getOrder(lineObj), ch = pos.ch; phrebejk@460: if (!order) return get(ch); phrebejk@460: var main, other, linedir = order[0].level; phrebejk@460: for (var i = 0; i < order.length; ++i) { phrebejk@460: var part = order[i], rtl = part.level % 2, nb, here; phrebejk@460: if (part.from < ch && part.to > ch) return get(ch, rtl); phrebejk@460: var left = rtl ? part.to : part.from, right = rtl ? part.from : part.to; phrebejk@460: if (left == ch) { phrebejk@460: // Opera and IE return bogus offsets and widths for edges phrebejk@460: // where the direction flips, but only for the side with the phrebejk@460: // lower level. So we try to use the side with the higher phrebejk@460: // level. phrebejk@460: if (i && part.level < (nb = order[i-1]).level) here = get(nb.level % 2 ? nb.from : nb.to - 1, true); phrebejk@460: else here = get(rtl && part.from != part.to ? ch - 1 : ch); phrebejk@460: if (rtl == linedir) main = here; else other = here; phrebejk@460: } else if (right == ch) { phrebejk@460: var nb = i < order.length - 1 && order[i+1]; phrebejk@460: if (!rtl && nb && nb.from == nb.to) continue; phrebejk@460: if (nb && part.level < nb.level) here = get(nb.level % 2 ? nb.to - 1 : nb.from); phrebejk@460: else here = get(rtl ? ch : ch - 1, true); phrebejk@460: if (rtl == linedir) main = here; else other = here; phrebejk@460: } phrebejk@460: } phrebejk@460: if (linedir && !ch) other = get(order[0].to - 1); phrebejk@460: if (!main) return other; phrebejk@460: if (other) main.other = other; phrebejk@460: return main; phrebejk@460: } phrebejk@460: phrebejk@460: // Coords must be lineSpace-local phrebejk@460: function coordsChar(cm, x, y) { phrebejk@460: var doc = cm.view.doc; phrebejk@460: y += cm.display.viewOffset; phrebejk@460: if (y < 0) return {line: 0, ch: 0, outside: true}; phrebejk@460: var lineNo = lineAtHeight(doc, y); phrebejk@460: if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc, doc.size - 1).text.length}; phrebejk@460: if (x < 0) x = 0; phrebejk@460: phrebejk@460: for (;;) { phrebejk@460: var lineObj = getLine(doc, lineNo); phrebejk@460: var found = coordsCharInner(cm, lineObj, lineNo, x, y); phrebejk@460: var merged = collapsedSpanAtEnd(lineObj); phrebejk@460: if (merged && found.ch == lineRight(lineObj)) phrebejk@460: lineNo = merged.find().to.line; phrebejk@460: else phrebejk@460: return found; phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: function coordsCharInner(cm, lineObj, lineNo, x, y) { phrebejk@460: var innerOff = y - heightAtLine(cm, lineObj); phrebejk@460: var wrongLine = false, cWidth = cm.display.wrapper.clientWidth; phrebejk@460: var measurement = measureLine(cm, lineObj); phrebejk@460: phrebejk@460: function getX(ch) { phrebejk@460: var sp = cursorCoords(cm, {line: lineNo, ch: ch}, "line", phrebejk@460: lineObj, measurement); phrebejk@460: wrongLine = true; phrebejk@460: if (innerOff > sp.bottom) return Math.max(0, sp.left - cWidth); phrebejk@460: else if (innerOff < sp.top) return sp.left + cWidth; phrebejk@460: else wrongLine = false; phrebejk@460: return sp.left; phrebejk@460: } phrebejk@460: phrebejk@460: var bidi = getOrder(lineObj), dist = lineObj.text.length; phrebejk@460: var from = lineLeft(lineObj), to = lineRight(lineObj); phrebejk@460: var fromX = paddingLeft(cm.display), toX = getX(to); phrebejk@460: phrebejk@460: if (x > toX) return {line: lineNo, ch: to, outside: wrongLine}; phrebejk@460: // Do a binary search between these bounds. phrebejk@460: for (;;) { phrebejk@460: if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { phrebejk@460: var after = x - fromX < toX - x, ch = after ? from : to; phrebejk@460: while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch; phrebejk@460: return {line: lineNo, ch: ch, after: after, outside: wrongLine}; phrebejk@460: } phrebejk@460: var step = Math.ceil(dist / 2), middle = from + step; phrebejk@460: if (bidi) { phrebejk@460: middle = from; phrebejk@460: for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); phrebejk@460: } phrebejk@460: var middleX = getX(middle); phrebejk@460: if (middleX > x) {to = middle; toX = middleX; if (wrongLine) toX += 1000; dist -= step;} phrebejk@460: else {from = middle; fromX = middleX; dist = step;} phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: var measureText; phrebejk@460: function textHeight(display) { phrebejk@460: if (display.cachedTextHeight != null) return display.cachedTextHeight; phrebejk@460: if (measureText == null) { phrebejk@460: measureText = elt("pre"); phrebejk@460: // Measure a bunch of lines, for browsers that compute phrebejk@460: // fractional heights. phrebejk@460: for (var i = 0; i < 49; ++i) { phrebejk@460: measureText.appendChild(document.createTextNode("x")); phrebejk@460: measureText.appendChild(elt("br")); phrebejk@460: } phrebejk@460: measureText.appendChild(document.createTextNode("x")); phrebejk@460: } phrebejk@460: removeChildrenAndAdd(display.measure, measureText); phrebejk@460: var height = measureText.offsetHeight / 50; phrebejk@460: if (height > 3) display.cachedTextHeight = height; phrebejk@460: removeChildren(display.measure); phrebejk@460: return height || 1; phrebejk@460: } phrebejk@460: phrebejk@460: function charWidth(display) { phrebejk@460: if (display.cachedCharWidth != null) return display.cachedCharWidth; phrebejk@460: var anchor = elt("span", "x"); phrebejk@460: var pre = elt("pre", [anchor]); phrebejk@460: removeChildrenAndAdd(display.measure, pre); phrebejk@460: var width = anchor.offsetWidth; phrebejk@460: if (width > 2) display.cachedCharWidth = width; phrebejk@460: return width || 10; phrebejk@460: } phrebejk@460: phrebejk@460: // OPERATIONS phrebejk@460: phrebejk@460: // Operations are used to wrap changes in such a way that each phrebejk@460: // change won't have to update the cursor and display (which would phrebejk@460: // be awkward, slow, and error-prone), but instead updates are phrebejk@460: // batched and then all combined and executed at once. phrebejk@460: phrebejk@460: function startOperation(cm) { phrebejk@460: if (cm.curOp) ++cm.curOp.depth; phrebejk@460: else cm.curOp = { phrebejk@460: // Nested operations delay update until the outermost one phrebejk@460: // finishes. phrebejk@460: depth: 1, phrebejk@460: // An array of ranges of lines that have to be updated. See phrebejk@460: // updateDisplay. phrebejk@460: changes: [], phrebejk@460: delayedCallbacks: [], phrebejk@460: updateInput: null, phrebejk@460: userSelChange: null, phrebejk@460: textChanged: null, phrebejk@460: selectionChanged: false, phrebejk@460: updateMaxLine: false, phrebejk@460: id: ++cm.nextOpId phrebejk@460: }; phrebejk@460: } phrebejk@460: phrebejk@460: function endOperation(cm) { phrebejk@460: var op = cm.curOp; phrebejk@460: if (--op.depth) return; phrebejk@460: cm.curOp = null; phrebejk@460: var view = cm.view, display = cm.display; phrebejk@460: if (op.updateMaxLine) computeMaxLength(view); phrebejk@460: if (view.maxLineChanged && !cm.options.lineWrapping) { phrebejk@460: var width = measureChar(cm, view.maxLine, view.maxLine.text.length).right; phrebejk@460: display.sizer.style.minWidth = (width + 3 + scrollerCutOff) + "px"; phrebejk@460: view.maxLineChanged = false; phrebejk@460: } phrebejk@460: var newScrollPos, updated; phrebejk@460: if (op.selectionChanged) { phrebejk@460: var coords = cursorCoords(cm, view.sel.head); phrebejk@460: newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom); phrebejk@460: } phrebejk@460: if (op.changes.length || newScrollPos && newScrollPos.scrollTop != null) phrebejk@460: updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop); phrebejk@460: if (!updated && op.selectionChanged) updateSelection(cm); phrebejk@460: if (newScrollPos) scrollCursorIntoView(cm); phrebejk@460: if (op.selectionChanged) restartBlink(cm); phrebejk@460: phrebejk@460: if (view.focused && op.updateInput) phrebejk@460: resetInput(cm, op.userSelChange); phrebejk@460: phrebejk@460: if (op.textChanged) phrebejk@460: signal(cm, "change", cm, op.textChanged); phrebejk@460: if (op.selectionChanged) signal(cm, "cursorActivity", cm); phrebejk@460: for (var i = 0; i < op.delayedCallbacks.length; ++i) op.delayedCallbacks[i](cm); phrebejk@460: } phrebejk@460: phrebejk@460: // Wraps a function in an operation. Returns the wrapped function. phrebejk@460: function operation(cm1, f) { phrebejk@460: return function() { phrebejk@460: var cm = cm1 || this; phrebejk@460: startOperation(cm); phrebejk@460: try {var result = f.apply(cm, arguments);} phrebejk@460: finally {endOperation(cm);} phrebejk@460: return result; phrebejk@460: }; phrebejk@460: } phrebejk@460: phrebejk@460: function regChange(cm, from, to, lendiff) { phrebejk@460: cm.curOp.changes.push({from: from, to: to, diff: lendiff}); phrebejk@460: } phrebejk@460: phrebejk@460: // INPUT HANDLING phrebejk@460: phrebejk@460: function slowPoll(cm) { phrebejk@460: if (cm.view.pollingFast) return; phrebejk@460: cm.display.poll.set(cm.options.pollInterval, function() { phrebejk@460: readInput(cm); phrebejk@460: if (cm.view.focused) slowPoll(cm); phrebejk@460: }); phrebejk@460: } phrebejk@460: phrebejk@460: function fastPoll(cm) { phrebejk@460: var missed = false; phrebejk@460: cm.display.pollingFast = true; phrebejk@460: function p() { phrebejk@460: var changed = readInput(cm); phrebejk@460: if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);} phrebejk@460: else {cm.display.pollingFast = false; slowPoll(cm);} phrebejk@460: } phrebejk@460: cm.display.poll.set(20, p); phrebejk@460: } phrebejk@460: phrebejk@460: // prevInput is a hack to work with IME. If we reset the textarea phrebejk@460: // on every change, that breaks IME. So we look for changes phrebejk@460: // compared to the previous content instead. (Modern browsers have phrebejk@460: // events that indicate IME taking place, but these are not widely phrebejk@460: // supported or compatible enough yet to rely on.) phrebejk@460: function readInput(cm) { phrebejk@460: var input = cm.display.input, prevInput = cm.display.prevInput, view = cm.view, sel = view.sel; phrebejk@460: if (!view.focused || hasSelection(input) || isReadOnly(cm)) return false; phrebejk@460: var text = input.value; phrebejk@460: if (text == prevInput && posEq(sel.from, sel.to)) return false; phrebejk@460: startOperation(cm); phrebejk@460: view.sel.shift = false; phrebejk@460: var same = 0, l = Math.min(prevInput.length, text.length); phrebejk@460: while (same < l && prevInput[same] == text[same]) ++same; phrebejk@460: var from = sel.from, to = sel.to; phrebejk@460: if (same < prevInput.length) phrebejk@460: from = {line: from.line, ch: from.ch - (prevInput.length - same)}; phrebejk@460: else if (view.overwrite && posEq(from, to) && !cm.display.pasteIncoming) phrebejk@460: to = {line: to.line, ch: Math.min(getLine(cm.view.doc, to.line).text.length, to.ch + (text.length - same))}; phrebejk@460: var updateInput = cm.curOp.updateInput; phrebejk@460: updateDoc(cm, from, to, splitLines(text.slice(same)), "end", phrebejk@460: cm.display.pasteIncoming ? "paste" : "input", {from: from, to: to}); phrebejk@460: cm.curOp.updateInput = updateInput; phrebejk@460: if (text.length > 1000) input.value = cm.display.prevInput = ""; phrebejk@460: else cm.display.prevInput = text; phrebejk@460: endOperation(cm); phrebejk@460: cm.display.pasteIncoming = false; phrebejk@460: return true; phrebejk@460: } phrebejk@460: phrebejk@460: function resetInput(cm, user) { phrebejk@460: var view = cm.view, minimal, selected; phrebejk@460: if (!posEq(view.sel.from, view.sel.to)) { phrebejk@460: cm.display.prevInput = ""; phrebejk@460: minimal = hasCopyEvent && phrebejk@460: (view.sel.to.line - view.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000); phrebejk@460: if (minimal) cm.display.input.value = "-"; phrebejk@460: else cm.display.input.value = selected || cm.getSelection(); phrebejk@460: if (view.focused) selectInput(cm.display.input); phrebejk@460: } else if (user) cm.display.prevInput = cm.display.input.value = ""; phrebejk@460: cm.display.inaccurateSelection = minimal; phrebejk@460: } phrebejk@460: phrebejk@460: function focusInput(cm) { phrebejk@460: if (cm.options.readOnly != "nocursor" && (ie || document.activeElement != cm.display.input)) phrebejk@460: cm.display.input.focus(); phrebejk@460: } phrebejk@460: phrebejk@460: function isReadOnly(cm) { phrebejk@460: return cm.options.readOnly || cm.view.cantEdit; phrebejk@460: } phrebejk@460: phrebejk@460: // EVENT HANDLERS phrebejk@460: phrebejk@460: function registerEventHandlers(cm) { phrebejk@460: var d = cm.display; phrebejk@460: on(d.scroller, "mousedown", operation(cm, onMouseDown)); phrebejk@460: on(d.scroller, "dblclick", operation(cm, e_preventDefault)); phrebejk@460: on(d.lineSpace, "selectstart", function(e) { phrebejk@460: if (!mouseEventInWidget(d, e)) e_preventDefault(e); phrebejk@460: }); phrebejk@460: // Gecko browsers fire contextmenu *after* opening the menu, at phrebejk@460: // which point we can't mess with it anymore. Context menu is phrebejk@460: // handled in onMouseDown for Gecko. phrebejk@460: if (!gecko) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); phrebejk@460: phrebejk@460: on(d.scroller, "scroll", function() { phrebejk@460: setScrollTop(cm, d.scroller.scrollTop); phrebejk@460: setScrollLeft(cm, d.scroller.scrollLeft, true); phrebejk@460: signal(cm, "scroll", cm); phrebejk@460: }); phrebejk@460: on(d.scrollbarV, "scroll", function() { phrebejk@460: setScrollTop(cm, d.scrollbarV.scrollTop); phrebejk@460: }); phrebejk@460: on(d.scrollbarH, "scroll", function() { phrebejk@460: setScrollLeft(cm, d.scrollbarH.scrollLeft); phrebejk@460: }); phrebejk@460: phrebejk@460: on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); phrebejk@460: on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); phrebejk@460: phrebejk@460: function reFocus() { if (cm.view.focused) setTimeout(bind(focusInput, cm), 0); } phrebejk@460: on(d.scrollbarH, "mousedown", reFocus); phrebejk@460: on(d.scrollbarV, "mousedown", reFocus); phrebejk@460: // Prevent wrapper from ever scrolling phrebejk@460: on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); phrebejk@460: on(window, "resize", function resizeHandler() { phrebejk@460: // Might be a text scaling operation, clear size caches. phrebejk@460: d.cachedCharWidth = d.cachedTextHeight = null; phrebejk@460: clearCaches(cm); phrebejk@460: if (d.wrapper.parentNode) updateDisplay(cm, true); phrebejk@460: else off(window, "resize", resizeHandler); phrebejk@460: }); phrebejk@460: phrebejk@460: on(d.input, "keyup", operation(cm, function(e) { phrebejk@460: if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; phrebejk@460: if (e_prop(e, "keyCode") == 16) cm.view.sel.shift = false; phrebejk@460: })); phrebejk@460: on(d.input, "input", bind(fastPoll, cm)); phrebejk@460: on(d.input, "keydown", operation(cm, onKeyDown)); phrebejk@460: on(d.input, "keypress", operation(cm, onKeyPress)); phrebejk@460: on(d.input, "focus", bind(onFocus, cm)); phrebejk@460: on(d.input, "blur", bind(onBlur, cm)); phrebejk@460: phrebejk@460: function drag_(e) { phrebejk@460: if (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return; phrebejk@460: e_stop(e); phrebejk@460: } phrebejk@460: if (cm.options.dragDrop) { phrebejk@460: on(d.scroller, "dragstart", function(e){onDragStart(cm, e);}); phrebejk@460: on(d.scroller, "dragenter", drag_); phrebejk@460: on(d.scroller, "dragover", drag_); phrebejk@460: on(d.scroller, "drop", operation(cm, onDrop)); phrebejk@460: } phrebejk@460: on(d.scroller, "paste", function(){focusInput(cm); fastPoll(cm);}); phrebejk@460: on(d.input, "paste", function() { phrebejk@460: d.pasteIncoming = true; phrebejk@460: fastPoll(cm); phrebejk@460: }); phrebejk@460: phrebejk@460: function prepareCopy() { phrebejk@460: if (d.inaccurateSelection) { phrebejk@460: d.prevInput = ""; phrebejk@460: d.inaccurateSelection = false; phrebejk@460: d.input.value = cm.getSelection(); phrebejk@460: selectInput(d.input); phrebejk@460: } phrebejk@460: } phrebejk@460: on(d.input, "cut", prepareCopy); phrebejk@460: on(d.input, "copy", prepareCopy); phrebejk@460: phrebejk@460: // Needed to handle Tab key in KHTML phrebejk@460: if (khtml) on(d.sizer, "mouseup", function() { phrebejk@460: if (document.activeElement == d.input) d.input.blur(); phrebejk@460: focusInput(cm); phrebejk@460: }); phrebejk@460: } phrebejk@460: phrebejk@460: function mouseEventInWidget(display, e) { phrebejk@460: for (var n = e_target(e); n != display.wrapper; n = n.parentNode) phrebejk@460: if (/\bCodeMirror-(?:line)?widget\b/.test(n.className) || phrebejk@460: n.parentNode == display.sizer && n != display.mover) return true; phrebejk@460: } phrebejk@460: phrebejk@460: function posFromMouse(cm, e, liberal) { phrebejk@460: var display = cm.display; phrebejk@460: if (!liberal) { phrebejk@460: var target = e_target(e); phrebejk@460: if (target == display.scrollbarH || target == display.scrollbarH.firstChild || phrebejk@460: target == display.scrollbarV || target == display.scrollbarV.firstChild || phrebejk@460: target == display.scrollbarFiller) return null; phrebejk@460: } phrebejk@460: var x, y, space = display.lineSpace.getBoundingClientRect(); phrebejk@460: // Fails unpredictably on IE[67] when mouse is dragged around quickly. phrebejk@460: try { x = e.clientX; y = e.clientY; } catch (e) { return null; } phrebejk@460: return coordsChar(cm, x - space.left, y - space.top); phrebejk@460: } phrebejk@460: phrebejk@460: var lastClick, lastDoubleClick; phrebejk@460: function onMouseDown(e) { phrebejk@460: var cm = this, display = cm.display, view = cm.view, sel = view.sel, doc = view.doc; phrebejk@460: sel.shift = e_prop(e, "shiftKey"); phrebejk@460: phrebejk@460: if (mouseEventInWidget(display, e)) { phrebejk@460: if (!webkit) { phrebejk@460: display.scroller.draggable = false; phrebejk@460: setTimeout(function(){display.scroller.draggable = true;}, 100); phrebejk@460: } phrebejk@460: return; phrebejk@460: } phrebejk@460: if (clickInGutter(cm, e)) return; phrebejk@460: var start = posFromMouse(cm, e); phrebejk@460: phrebejk@460: switch (e_button(e)) { phrebejk@460: case 3: phrebejk@460: if (gecko) onContextMenu.call(cm, cm, e); phrebejk@460: return; phrebejk@460: case 2: phrebejk@460: if (start) extendSelection(cm, start); phrebejk@460: setTimeout(bind(focusInput, cm), 20); phrebejk@460: e_preventDefault(e); phrebejk@460: return; phrebejk@460: } phrebejk@460: // For button 1, if it was clicked inside the editor phrebejk@460: // (posFromMouse returning non-null), we have to adjust the phrebejk@460: // selection. phrebejk@460: if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;} phrebejk@460: phrebejk@460: if (!view.focused) onFocus(cm); phrebejk@460: phrebejk@460: var now = +new Date, type = "single"; phrebejk@460: if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) { phrebejk@460: type = "triple"; phrebejk@460: e_preventDefault(e); phrebejk@460: setTimeout(bind(focusInput, cm), 20); phrebejk@460: selectLine(cm, start.line); phrebejk@460: } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) { phrebejk@460: type = "double"; phrebejk@460: lastDoubleClick = {time: now, pos: start}; phrebejk@460: e_preventDefault(e); phrebejk@460: var word = findWordAt(getLine(doc, start.line).text, start); phrebejk@460: extendSelection(cm, word.from, word.to); phrebejk@460: } else { lastClick = {time: now, pos: start}; } phrebejk@460: phrebejk@460: var last = start; phrebejk@460: if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) && phrebejk@460: !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") { phrebejk@460: var dragEnd = operation(cm, function(e2) { phrebejk@460: if (webkit) display.scroller.draggable = false; phrebejk@460: view.draggingText = false; phrebejk@460: off(document, "mouseup", dragEnd); phrebejk@460: off(display.scroller, "drop", dragEnd); phrebejk@460: if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { phrebejk@460: e_preventDefault(e2); phrebejk@460: extendSelection(cm, start); phrebejk@460: focusInput(cm); phrebejk@460: } phrebejk@460: }); phrebejk@460: // Let the drag handler handle this. phrebejk@460: if (webkit) display.scroller.draggable = true; phrebejk@460: view.draggingText = dragEnd; phrebejk@460: // IE's approach to draggable phrebejk@460: if (display.scroller.dragDrop) display.scroller.dragDrop(); phrebejk@460: on(document, "mouseup", dragEnd); phrebejk@460: on(display.scroller, "drop", dragEnd); phrebejk@460: return; phrebejk@460: } phrebejk@460: e_preventDefault(e); phrebejk@460: if (type == "single") extendSelection(cm, clipPos(doc, start)); phrebejk@460: phrebejk@460: var startstart = sel.from, startend = sel.to; phrebejk@460: phrebejk@460: function doSelect(cur) { phrebejk@460: if (type == "single") { phrebejk@460: extendSelection(cm, clipPos(doc, start), cur); phrebejk@460: return; phrebejk@460: } phrebejk@460: phrebejk@460: startstart = clipPos(doc, startstart); phrebejk@460: startend = clipPos(doc, startend); phrebejk@460: if (type == "double") { phrebejk@460: var word = findWordAt(getLine(doc, cur.line).text, cur); phrebejk@460: if (posLess(cur, startstart)) extendSelection(cm, word.from, startend); phrebejk@460: else extendSelection(cm, startstart, word.to); phrebejk@460: } else if (type == "triple") { phrebejk@460: if (posLess(cur, startstart)) extendSelection(cm, startend, clipPos(doc, {line: cur.line, ch: 0})); phrebejk@460: else extendSelection(cm, startstart, clipPos(doc, {line: cur.line + 1, ch: 0})); phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: var editorSize = display.wrapper.getBoundingClientRect(); phrebejk@460: // Used to ensure timeout re-tries don't fire when another extend phrebejk@460: // happened in the meantime (clearTimeout isn't reliable -- at phrebejk@460: // least on Chrome, the timeouts still happen even when cleared, phrebejk@460: // if the clear happens after their scheduled firing time). phrebejk@460: var counter = 0; phrebejk@460: phrebejk@460: function extend(e) { phrebejk@460: var curCount = ++counter; phrebejk@460: var cur = posFromMouse(cm, e, true); phrebejk@460: if (!cur) return; phrebejk@460: if (!posEq(cur, last)) { phrebejk@460: if (!view.focused) onFocus(cm); phrebejk@460: last = cur; phrebejk@460: doSelect(cur); phrebejk@460: var visible = visibleLines(display, doc); phrebejk@460: if (cur.line >= visible.to || cur.line < visible.from) phrebejk@460: setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); phrebejk@460: } else { phrebejk@460: var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; phrebejk@460: if (outside) setTimeout(operation(cm, function() { phrebejk@460: if (counter != curCount) return; phrebejk@460: display.scroller.scrollTop += outside; phrebejk@460: extend(e); phrebejk@460: }), 50); phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: function done(e) { phrebejk@460: counter = Infinity; phrebejk@460: var cur = posFromMouse(cm, e); phrebejk@460: if (cur) doSelect(cur); phrebejk@460: e_preventDefault(e); phrebejk@460: focusInput(cm); phrebejk@460: off(document, "mousemove", move); phrebejk@460: off(document, "mouseup", up); phrebejk@460: } phrebejk@460: phrebejk@460: var move = operation(cm, function(e) { phrebejk@460: if (!ie && !e_button(e)) done(e); phrebejk@460: else extend(e); phrebejk@460: }); phrebejk@460: var up = operation(cm, done); phrebejk@460: on(document, "mousemove", move); phrebejk@460: on(document, "mouseup", up); phrebejk@460: } phrebejk@460: phrebejk@460: function onDrop(e) { phrebejk@460: var cm = this; phrebejk@460: if (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return; phrebejk@460: e_preventDefault(e); phrebejk@460: var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; phrebejk@460: if (!pos || isReadOnly(cm)) return; phrebejk@460: if (files && files.length && window.FileReader && window.File) { phrebejk@460: var n = files.length, text = Array(n), read = 0; phrebejk@460: var loadFile = function(file, i) { phrebejk@460: var reader = new FileReader; phrebejk@460: reader.onload = function() { phrebejk@460: text[i] = reader.result; phrebejk@460: if (++read == n) { phrebejk@460: pos = clipPos(cm.view.doc, pos); phrebejk@460: operation(cm, function() { phrebejk@460: var end = replaceRange(cm, text.join(""), pos, pos, "paste"); phrebejk@460: setSelection(cm, pos, end); phrebejk@460: })(); phrebejk@460: } phrebejk@460: }; phrebejk@460: reader.readAsText(file); phrebejk@460: }; phrebejk@460: for (var i = 0; i < n; ++i) loadFile(files[i], i); phrebejk@460: } else { phrebejk@460: // Don't do a replace if the drop happened inside of the selected text. phrebejk@460: if (cm.view.draggingText && !(posLess(pos, cm.view.sel.from) || posLess(cm.view.sel.to, pos))) { phrebejk@460: cm.view.draggingText(e); phrebejk@460: if (ie) setTimeout(bind(focusInput, cm), 50); phrebejk@460: return; phrebejk@460: } phrebejk@460: try { phrebejk@460: var text = e.dataTransfer.getData("Text"); phrebejk@460: if (text) { phrebejk@460: var curFrom = cm.view.sel.from, curTo = cm.view.sel.to; phrebejk@460: setSelection(cm, pos, pos); phrebejk@460: if (cm.view.draggingText) replaceRange(cm, "", curFrom, curTo, "paste"); phrebejk@460: cm.replaceSelection(text, null, "paste"); phrebejk@460: focusInput(cm); phrebejk@460: onFocus(cm); phrebejk@460: } phrebejk@460: } phrebejk@460: catch(e){} phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: function clickInGutter(cm, e) { phrebejk@460: var display = cm.display; phrebejk@460: try { var mX = e.clientX, mY = e.clientY; } phrebejk@460: catch(e) { return false; } phrebejk@460: phrebejk@460: if (mX >= Math.floor(display.gutters.getBoundingClientRect().right)) return false; phrebejk@460: e_preventDefault(e); phrebejk@460: if (!hasHandler(cm, "gutterClick")) return true; phrebejk@460: phrebejk@460: var lineBox = display.lineDiv.getBoundingClientRect(); phrebejk@460: if (mY > lineBox.bottom) return true; phrebejk@460: mY -= lineBox.top - display.viewOffset; phrebejk@460: phrebejk@460: for (var i = 0; i < cm.options.gutters.length; ++i) { phrebejk@460: var g = display.gutters.childNodes[i]; phrebejk@460: if (g && g.getBoundingClientRect().right >= mX) { phrebejk@460: var line = lineAtHeight(cm.view.doc, mY); phrebejk@460: var gutter = cm.options.gutters[i]; phrebejk@460: signalLater(cm, cm, "gutterClick", cm, line, gutter, e); phrebejk@460: break; phrebejk@460: } phrebejk@460: } phrebejk@460: return true; phrebejk@460: } phrebejk@460: phrebejk@460: function onDragStart(cm, e) { phrebejk@460: var txt = cm.getSelection(); phrebejk@460: e.dataTransfer.setData("Text", txt); phrebejk@460: phrebejk@460: // Use dummy image instead of default browsers image. phrebejk@460: // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. phrebejk@460: if (e.dataTransfer.setDragImage && !safari) phrebejk@460: e.dataTransfer.setDragImage(elt('img'), 0, 0); phrebejk@460: } phrebejk@460: phrebejk@460: function setScrollTop(cm, val) { phrebejk@460: if (Math.abs(cm.view.scrollTop - val) < 2) return; phrebejk@460: cm.view.scrollTop = val; phrebejk@460: if (!gecko) updateDisplay(cm, [], val); phrebejk@460: if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; phrebejk@460: if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val; phrebejk@460: if (gecko) updateDisplay(cm, []); phrebejk@460: } phrebejk@460: function setScrollLeft(cm, val, isScroller) { phrebejk@460: if (isScroller ? val == cm.view.scrollLeft : Math.abs(cm.view.scrollLeft - val) < 2) return; phrebejk@460: cm.view.scrollLeft = val; phrebejk@460: alignHorizontally(cm); phrebejk@460: if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; phrebejk@460: if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val; phrebejk@460: } phrebejk@460: phrebejk@460: // Since the delta values reported on mouse wheel events are phrebejk@460: // unstandardized between browsers and even browser versions, and phrebejk@460: // generally horribly unpredictable, this code starts by measuring phrebejk@460: // the scroll effect that the first few mouse wheel events have, phrebejk@460: // and, from that, detects the way it can convert deltas to pixel phrebejk@460: // offsets afterwards. phrebejk@460: // phrebejk@460: // The reason we want to know the amount a wheel event will scroll phrebejk@460: // is that it gives us a chance to update the display before the phrebejk@460: // actual scrolling happens, reducing flickering. phrebejk@460: phrebejk@460: var wheelSamples = 0, wheelDX, wheelDY, wheelStartX, wheelStartY, wheelPixelsPerUnit = null; phrebejk@460: // Fill in a browser-detected starting value on browsers where we phrebejk@460: // know one. These don't have to be accurate -- the result of them phrebejk@460: // being wrong would just be a slight flicker on the first wheel phrebejk@460: // scroll (if it is large enough). phrebejk@460: if (ie) wheelPixelsPerUnit = -.53; phrebejk@460: else if (gecko) wheelPixelsPerUnit = 15; phrebejk@460: else if (chrome) wheelPixelsPerUnit = -.7; phrebejk@460: else if (safari) wheelPixelsPerUnit = -1/3; phrebejk@460: phrebejk@460: function onScrollWheel(cm, e) { phrebejk@460: var dx = e.wheelDeltaX, dy = e.wheelDeltaY; phrebejk@460: if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; phrebejk@460: if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; phrebejk@460: else if (dy == null) dy = e.wheelDelta; phrebejk@460: phrebejk@460: // Webkit browsers on OS X abort momentum scrolls when the target phrebejk@460: // of the scroll event is removed from the scrollable element. phrebejk@460: // This hack (see related code in patchDisplay) makes sure the phrebejk@460: // element is kept around. phrebejk@460: if (dy && mac && webkit) { phrebejk@460: for (var cur = e.target; cur != scroll; cur = cur.parentNode) { phrebejk@460: if (cur.lineObj) { phrebejk@460: cm.display.currentWheelTarget = cur; phrebejk@460: break; phrebejk@460: } phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: var scroll = cm.display.scroller; phrebejk@460: // On some browsers, horizontal scrolling will cause redraws to phrebejk@460: // happen before the gutter has been realigned, causing it to phrebejk@460: // wriggle around in a most unseemly way. When we have an phrebejk@460: // estimated pixels/delta value, we just handle horizontal phrebejk@460: // scrolling entirely here. It'll be slightly off from native, but phrebejk@460: // better than glitching out. phrebejk@460: if (dx && !gecko && !opera && wheelPixelsPerUnit != null) { phrebejk@460: if (dy) phrebejk@460: setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); phrebejk@460: setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); phrebejk@460: e_preventDefault(e); phrebejk@460: wheelStartX = null; // Abort measurement, if in progress phrebejk@460: return; phrebejk@460: } phrebejk@460: phrebejk@460: if (dy && wheelPixelsPerUnit != null) { phrebejk@460: var pixels = dy * wheelPixelsPerUnit; phrebejk@460: var top = cm.view.scrollTop, bot = top + cm.display.wrapper.clientHeight; phrebejk@460: if (pixels < 0) top = Math.max(0, top + pixels - 50); phrebejk@460: else bot = Math.min(cm.view.doc.height, bot + pixels + 50); phrebejk@460: updateDisplay(cm, [], {top: top, bottom: bot}); phrebejk@460: } phrebejk@460: phrebejk@460: if (wheelSamples < 20) { phrebejk@460: if (wheelStartX == null) { phrebejk@460: wheelStartX = scroll.scrollLeft; wheelStartY = scroll.scrollTop; phrebejk@460: wheelDX = dx; wheelDY = dy; phrebejk@460: setTimeout(function() { phrebejk@460: if (wheelStartX == null) return; phrebejk@460: var movedX = scroll.scrollLeft - wheelStartX; phrebejk@460: var movedY = scroll.scrollTop - wheelStartY; phrebejk@460: var sample = (movedY && wheelDY && movedY / wheelDY) || phrebejk@460: (movedX && wheelDX && movedX / wheelDX); phrebejk@460: wheelStartX = wheelStartY = null; phrebejk@460: if (!sample) return; phrebejk@460: wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); phrebejk@460: ++wheelSamples; phrebejk@460: }, 200); phrebejk@460: } else { phrebejk@460: wheelDX += dx; wheelDY += dy; phrebejk@460: } phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: function doHandleBinding(cm, bound, dropShift) { phrebejk@460: if (typeof bound == "string") { phrebejk@460: bound = commands[bound]; phrebejk@460: if (!bound) return false; phrebejk@460: } phrebejk@460: // Ensure previous input has been read, so that the handler sees a phrebejk@460: // consistent view of the document phrebejk@460: if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false; phrebejk@460: var view = cm.view, prevShift = view.sel.shift; phrebejk@460: try { phrebejk@460: if (isReadOnly(cm)) view.suppressEdits = true; phrebejk@460: if (dropShift) view.sel.shift = false; phrebejk@460: bound(cm); phrebejk@460: } catch(e) { phrebejk@460: if (e != Pass) throw e; phrebejk@460: return false; phrebejk@460: } finally { phrebejk@460: view.sel.shift = prevShift; phrebejk@460: view.suppressEdits = false; phrebejk@460: } phrebejk@460: return true; phrebejk@460: } phrebejk@460: phrebejk@460: function allKeyMaps(cm) { phrebejk@460: var maps = cm.view.keyMaps.slice(0); phrebejk@460: maps.push(cm.options.keyMap); phrebejk@460: if (cm.options.extraKeys) maps.unshift(cm.options.extraKeys); phrebejk@460: return maps; phrebejk@460: } phrebejk@460: phrebejk@460: var maybeTransition; phrebejk@460: function handleKeyBinding(cm, e) { phrebejk@460: // Handle auto keymap transitions phrebejk@460: var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto; phrebejk@460: clearTimeout(maybeTransition); phrebejk@460: if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() { phrebejk@460: if (getKeyMap(cm.options.keyMap) == startMap) phrebejk@460: cm.options.keyMap = (next.call ? next.call(null, cm) : next); phrebejk@460: }, 50); phrebejk@460: phrebejk@460: var name = keyNames[e_prop(e, "keyCode")], handled = false; phrebejk@460: var flipCtrlCmd = mac && (opera || qtwebkit); phrebejk@460: if (name == null || e.altGraphKey) return false; phrebejk@460: if (e_prop(e, "altKey")) name = "Alt-" + name; phrebejk@460: if (e_prop(e, flipCtrlCmd ? "metaKey" : "ctrlKey")) name = "Ctrl-" + name; phrebejk@460: if (e_prop(e, flipCtrlCmd ? "ctrlKey" : "metaKey")) name = "Cmd-" + name; phrebejk@460: phrebejk@460: var stopped = false; phrebejk@460: function stop() { stopped = true; } phrebejk@460: var keymaps = allKeyMaps(cm); phrebejk@460: phrebejk@460: if (e_prop(e, "shiftKey")) { phrebejk@460: handled = lookupKey("Shift-" + name, keymaps, phrebejk@460: function(b) {return doHandleBinding(cm, b, true);}, stop) phrebejk@460: || lookupKey(name, keymaps, function(b) { phrebejk@460: if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(cm, b); phrebejk@460: }, stop); phrebejk@460: } else { phrebejk@460: handled = lookupKey(name, keymaps, phrebejk@460: function(b) { return doHandleBinding(cm, b); }, stop); phrebejk@460: } phrebejk@460: if (stopped) handled = false; phrebejk@460: if (handled) { phrebejk@460: e_preventDefault(e); phrebejk@460: restartBlink(cm); phrebejk@460: if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; } phrebejk@460: } phrebejk@460: return handled; phrebejk@460: } phrebejk@460: phrebejk@460: function handleCharBinding(cm, e, ch) { phrebejk@460: var handled = lookupKey("'" + ch + "'", allKeyMaps(cm), phrebejk@460: function(b) { return doHandleBinding(cm, b, true); }); phrebejk@460: if (handled) { phrebejk@460: e_preventDefault(e); phrebejk@460: restartBlink(cm); phrebejk@460: } phrebejk@460: return handled; phrebejk@460: } phrebejk@460: phrebejk@460: var lastStoppedKey = null; phrebejk@460: function onKeyDown(e) { phrebejk@460: var cm = this; phrebejk@460: if (!cm.view.focused) onFocus(cm); phrebejk@460: if (ie && e.keyCode == 27) { e.returnValue = false; } phrebejk@460: if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; phrebejk@460: var code = e_prop(e, "keyCode"); phrebejk@460: // IE does strange things with escape. phrebejk@460: cm.view.sel.shift = code == 16 || e_prop(e, "shiftKey"); phrebejk@460: // First give onKeyEvent option a chance to handle this. phrebejk@460: var handled = handleKeyBinding(cm, e); phrebejk@460: if (opera) { phrebejk@460: lastStoppedKey = handled ? code : null; phrebejk@460: // Opera has no cut event... we try to at least catch the key combo phrebejk@460: if (!handled && code == 88 && !hasCopyEvent && e_prop(e, mac ? "metaKey" : "ctrlKey")) phrebejk@460: cm.replaceSelection(""); phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: function onKeyPress(e) { phrebejk@460: var cm = this; phrebejk@460: if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; phrebejk@460: var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode"); phrebejk@460: if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} phrebejk@460: if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return; phrebejk@460: var ch = String.fromCharCode(charCode == null ? keyCode : charCode); phrebejk@460: if (this.options.electricChars && this.view.mode.electricChars && phrebejk@460: this.options.smartIndent && !isReadOnly(this) && phrebejk@460: this.view.mode.electricChars.indexOf(ch) > -1) phrebejk@460: setTimeout(operation(cm, function() {indentLine(cm, cm.view.sel.to.line, "smart");}), 75); phrebejk@460: if (handleCharBinding(cm, e, ch)) return; phrebejk@460: fastPoll(cm); phrebejk@460: } phrebejk@460: phrebejk@460: function onFocus(cm) { phrebejk@460: if (cm.options.readOnly == "nocursor") return; phrebejk@460: if (!cm.view.focused) { phrebejk@460: signal(cm, "focus", cm); phrebejk@460: cm.view.focused = true; phrebejk@460: if (cm.display.scroller.className.search(/\bCodeMirror-focused\b/) == -1) phrebejk@460: cm.display.scroller.className += " CodeMirror-focused"; phrebejk@460: resetInput(cm, true); phrebejk@460: } phrebejk@460: slowPoll(cm); phrebejk@460: restartBlink(cm); phrebejk@460: } phrebejk@460: function onBlur(cm) { phrebejk@460: if (cm.view.focused) { phrebejk@460: signal(cm, "blur", cm); phrebejk@460: cm.view.focused = false; phrebejk@460: cm.display.scroller.className = cm.display.scroller.className.replace(" CodeMirror-focused", ""); phrebejk@460: } phrebejk@460: clearInterval(cm.display.blinker); phrebejk@460: setTimeout(function() {if (!cm.view.focused) cm.view.sel.shift = false;}, 150); phrebejk@460: } phrebejk@460: phrebejk@460: var detectingSelectAll; phrebejk@460: function onContextMenu(cm, e) { phrebejk@460: var display = cm.display, sel = cm.view.sel; phrebejk@460: var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; phrebejk@460: if (!pos || opera) return; // Opera is difficult. phrebejk@460: if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to)) phrebejk@460: operation(cm, setSelection)(cm, pos, pos); phrebejk@460: phrebejk@460: var oldCSS = display.input.style.cssText; phrebejk@460: display.inputDiv.style.position = "absolute"; phrebejk@460: display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + phrebejk@460: "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" + phrebejk@460: "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; phrebejk@460: focusInput(cm); phrebejk@460: resetInput(cm, true); phrebejk@460: // Adds "Select all" to context menu in FF phrebejk@460: if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " "; phrebejk@460: phrebejk@460: function rehide() { phrebejk@460: display.inputDiv.style.position = "relative"; phrebejk@460: display.input.style.cssText = oldCSS; phrebejk@460: if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos; phrebejk@460: slowPoll(cm); phrebejk@460: phrebejk@460: // Try to detect the user choosing select-all phrebejk@460: if (display.input.selectionStart != null) { phrebejk@460: clearTimeout(detectingSelectAll); phrebejk@460: var extval = display.input.value = " " + (posEq(sel.from, sel.to) ? "" : display.input.value), i = 0; phrebejk@460: display.prevInput = " "; phrebejk@460: display.input.selectionStart = 1; display.input.selectionEnd = extval.length; phrebejk@460: detectingSelectAll = setTimeout(function poll(){ phrebejk@460: if (display.prevInput == " " && display.input.selectionStart == 0) phrebejk@460: operation(cm, commands.selectAll)(cm); phrebejk@460: else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500); phrebejk@460: else resetInput(cm); phrebejk@460: }, 200); phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: if (gecko) { phrebejk@460: e_stop(e); phrebejk@460: on(window, "mouseup", function mouseup() { phrebejk@460: off(window, "mouseup", mouseup); phrebejk@460: setTimeout(rehide, 20); phrebejk@460: }); phrebejk@460: } else { phrebejk@460: setTimeout(rehide, 50); phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: // UPDATING phrebejk@460: phrebejk@460: // Replace the range from from to to by the strings in newText. phrebejk@460: // Afterwards, set the selection to selFrom, selTo. phrebejk@460: function updateDoc(cm, from, to, newText, selUpdate, origin) { phrebejk@460: // Possibly split or suppress the update based on the presence phrebejk@460: // of read-only spans in its range. phrebejk@460: var split = sawReadOnlySpans && phrebejk@460: removeReadOnlyRanges(cm.view.doc, from, to); phrebejk@460: if (split) { phrebejk@460: for (var i = split.length - 1; i >= 1; --i) phrebejk@460: updateDocInner(cm, split[i].from, split[i].to, [""], origin); phrebejk@460: if (split.length) phrebejk@460: return updateDocInner(cm, split[0].from, split[0].to, newText, selUpdate, origin); phrebejk@460: } else { phrebejk@460: return updateDocInner(cm, from, to, newText, selUpdate, origin); phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: function updateDocInner(cm, from, to, newText, selUpdate, origin) { phrebejk@460: if (cm.view.suppressEdits) return; phrebejk@460: phrebejk@460: var view = cm.view, doc = view.doc, old = []; phrebejk@460: doc.iter(from.line, to.line + 1, function(line) { phrebejk@460: old.push(newHL(line.text, line.markedSpans)); phrebejk@460: }); phrebejk@460: var startSelFrom = view.sel.from, startSelTo = view.sel.to; phrebejk@460: var lines = updateMarkedSpans(hlSpans(old[0]), hlSpans(lst(old)), from.ch, to.ch, newText); phrebejk@460: var retval = updateDocNoUndo(cm, from, to, lines, selUpdate, origin); phrebejk@460: if (view.history) addChange(cm, from.line, newText.length, old, origin, phrebejk@460: startSelFrom, startSelTo, view.sel.from, view.sel.to); phrebejk@460: return retval; phrebejk@460: } phrebejk@460: phrebejk@460: function unredoHelper(cm, type) { phrebejk@460: var doc = cm.view.doc, hist = cm.view.history; phrebejk@460: var set = (type == "undo" ? hist.done : hist.undone).pop(); phrebejk@460: if (!set) return; phrebejk@460: var anti = {events: [], fromBefore: set.fromAfter, toBefore: set.toAfter, phrebejk@460: fromAfter: set.fromBefore, toAfter: set.toBefore}; phrebejk@460: for (var i = set.events.length - 1; i >= 0; i -= 1) { phrebejk@460: hist.dirtyCounter += type == "undo" ? -1 : 1; phrebejk@460: var change = set.events[i]; phrebejk@460: var replaced = [], end = change.start + change.added; phrebejk@460: doc.iter(change.start, end, function(line) { replaced.push(newHL(line.text, line.markedSpans)); }); phrebejk@460: anti.events.push({start: change.start, added: change.old.length, old: replaced}); phrebejk@460: var selPos = i ? null : {from: set.fromBefore, to: set.toBefore}; phrebejk@460: updateDocNoUndo(cm, {line: change.start, ch: 0}, {line: end - 1, ch: getLine(doc, end-1).text.length}, phrebejk@460: change.old, selPos, type); phrebejk@460: } phrebejk@460: (type == "undo" ? hist.undone : hist.done).push(anti); phrebejk@460: } phrebejk@460: phrebejk@460: function updateDocNoUndo(cm, from, to, lines, selUpdate, origin) { phrebejk@460: var view = cm.view, doc = view.doc, display = cm.display; phrebejk@460: if (view.suppressEdits) return; phrebejk@460: phrebejk@460: var nlines = to.line - from.line, firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); phrebejk@460: var recomputeMaxLength = false, checkWidthStart = from.line; phrebejk@460: if (!cm.options.lineWrapping) { phrebejk@460: checkWidthStart = lineNo(visualLine(doc, firstLine)); phrebejk@460: doc.iter(checkWidthStart, to.line + 1, function(line) { phrebejk@460: if (lineLength(doc, line) == view.maxLineLength) { phrebejk@460: recomputeMaxLength = true; phrebejk@460: return true; phrebejk@460: } phrebejk@460: }); phrebejk@460: } phrebejk@460: phrebejk@460: var lastHL = lst(lines), th = textHeight(display); phrebejk@460: phrebejk@460: // First adjust the line structure phrebejk@460: if (from.ch == 0 && to.ch == 0 && hlText(lastHL) == "") { phrebejk@460: // This is a whole-line replace. Treated specially to make phrebejk@460: // sure line objects move the way they are supposed to. phrebejk@460: var added = []; phrebejk@460: for (var i = 0, e = lines.length - 1; i < e; ++i) phrebejk@460: added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th)); phrebejk@460: updateLine(cm, lastLine, lastLine.text, hlSpans(lastHL)); phrebejk@460: if (nlines) doc.remove(from.line, nlines, cm); phrebejk@460: if (added.length) doc.insert(from.line, added); phrebejk@460: } else if (firstLine == lastLine) { phrebejk@460: if (lines.length == 1) { phrebejk@460: updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]) + phrebejk@460: firstLine.text.slice(to.ch), hlSpans(lines[0])); phrebejk@460: } else { phrebejk@460: for (var added = [], i = 1, e = lines.length - 1; i < e; ++i) phrebejk@460: added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th)); phrebejk@460: added.push(makeLine(hlText(lastHL) + firstLine.text.slice(to.ch), hlSpans(lastHL), th)); phrebejk@460: updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0])); phrebejk@460: doc.insert(from.line + 1, added); phrebejk@460: } phrebejk@460: } else if (lines.length == 1) { phrebejk@460: updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]) + phrebejk@460: lastLine.text.slice(to.ch), hlSpans(lines[0])); phrebejk@460: doc.remove(from.line + 1, nlines, cm); phrebejk@460: } else { phrebejk@460: var added = []; phrebejk@460: updateLine(cm, firstLine, firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0])); phrebejk@460: updateLine(cm, lastLine, hlText(lastHL) + lastLine.text.slice(to.ch), hlSpans(lastHL)); phrebejk@460: for (var i = 1, e = lines.length - 1; i < e; ++i) phrebejk@460: added.push(makeLine(hlText(lines[i]), hlSpans(lines[i]), th)); phrebejk@460: if (nlines > 1) doc.remove(from.line + 1, nlines - 1, cm); phrebejk@460: doc.insert(from.line + 1, added); phrebejk@460: } phrebejk@460: phrebejk@460: if (cm.options.lineWrapping) { phrebejk@460: var perLine = Math.max(5, display.scroller.clientWidth / charWidth(display) - 3); phrebejk@460: doc.iter(from.line, from.line + lines.length, function(line) { phrebejk@460: if (line.height == 0) return; phrebejk@460: var guess = (Math.ceil(line.text.length / perLine) || 1) * th; phrebejk@460: if (guess != line.height) updateLineHeight(line, guess); phrebejk@460: }); phrebejk@460: } else { phrebejk@460: doc.iter(checkWidthStart, from.line + lines.length, function(line) { phrebejk@460: var len = lineLength(doc, line); phrebejk@460: if (len > view.maxLineLength) { phrebejk@460: view.maxLine = line; phrebejk@460: view.maxLineLength = len; phrebejk@460: view.maxLineChanged = true; phrebejk@460: recomputeMaxLength = false; phrebejk@460: } phrebejk@460: }); phrebejk@460: if (recomputeMaxLength) cm.curOp.updateMaxLine = true; phrebejk@460: } phrebejk@460: phrebejk@460: // Adjust frontier, schedule worker phrebejk@460: view.frontier = Math.min(view.frontier, from.line); phrebejk@460: startWorker(cm, 400); phrebejk@460: phrebejk@460: var lendiff = lines.length - nlines - 1; phrebejk@460: // Remember that these lines changed, for updating the display phrebejk@460: regChange(cm, from.line, to.line + 1, lendiff); phrebejk@460: if (hasHandler(cm, "change")) { phrebejk@460: // Normalize lines to contain only strings, since that's what phrebejk@460: // the change event handler expects phrebejk@460: for (var i = 0; i < lines.length; ++i) phrebejk@460: if (typeof lines[i] != "string") lines[i] = lines[i].text; phrebejk@460: var changeObj = {from: from, to: to, text: lines, origin: origin}; phrebejk@460: if (cm.curOp.textChanged) { phrebejk@460: for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {} phrebejk@460: cur.next = changeObj; phrebejk@460: } else cm.curOp.textChanged = changeObj; phrebejk@460: } phrebejk@460: phrebejk@460: // Update the selection phrebejk@460: var newSelFrom, newSelTo, end = {line: from.line + lines.length - 1, phrebejk@460: ch: hlText(lastHL).length + (lines.length == 1 ? from.ch : 0)}; phrebejk@460: if (selUpdate && typeof selUpdate != "string") { phrebejk@460: if (selUpdate.from) { newSelFrom = selUpdate.from; newSelTo = selUpdate.to; } phrebejk@460: else newSelFrom = newSelTo = selUpdate; phrebejk@460: } else if (selUpdate == "end") { phrebejk@460: newSelFrom = newSelTo = end; phrebejk@460: } else if (selUpdate == "start") { phrebejk@460: newSelFrom = newSelTo = from; phrebejk@460: } else if (selUpdate == "around") { phrebejk@460: newSelFrom = from; newSelTo = end; phrebejk@460: } else { phrebejk@460: var adjustPos = function(pos) { phrebejk@460: if (posLess(pos, from)) return pos; phrebejk@460: if (!posLess(to, pos)) return end; phrebejk@460: var line = pos.line + lendiff; phrebejk@460: var ch = pos.ch; phrebejk@460: if (pos.line == to.line) phrebejk@460: ch += hlText(lastHL).length - (to.ch - (to.line == from.line ? from.ch : 0)); phrebejk@460: return {line: line, ch: ch}; phrebejk@460: }; phrebejk@460: newSelFrom = adjustPos(view.sel.from); phrebejk@460: newSelTo = adjustPos(view.sel.to); phrebejk@460: } phrebejk@460: setSelection(cm, newSelFrom, newSelTo, null, true); phrebejk@460: return end; phrebejk@460: } phrebejk@460: phrebejk@460: function replaceRange(cm, code, from, to, origin) { phrebejk@460: if (!to) to = from; phrebejk@460: if (posLess(to, from)) { var tmp = to; to = from; from = tmp; } phrebejk@460: return updateDoc(cm, from, to, splitLines(code), null, origin); phrebejk@460: } phrebejk@460: phrebejk@460: // SELECTION phrebejk@460: phrebejk@460: function posEq(a, b) {return a.line == b.line && a.ch == b.ch;} phrebejk@460: function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);} phrebejk@460: function copyPos(x) {return {line: x.line, ch: x.ch};} phrebejk@460: phrebejk@460: function clipLine(doc, n) {return Math.max(0, Math.min(n, doc.size-1));} phrebejk@460: function clipPos(doc, pos) { phrebejk@460: if (pos.line < 0) return {line: 0, ch: 0}; phrebejk@460: if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc, doc.size-1).text.length}; phrebejk@460: var ch = pos.ch, linelen = getLine(doc, pos.line).text.length; phrebejk@460: if (ch == null || ch > linelen) return {line: pos.line, ch: linelen}; phrebejk@460: else if (ch < 0) return {line: pos.line, ch: 0}; phrebejk@460: else return pos; phrebejk@460: } phrebejk@460: function isLine(doc, l) {return l >= 0 && l < doc.size;} phrebejk@460: phrebejk@460: // If shift is held, this will move the selection anchor. Otherwise, phrebejk@460: // it'll set the whole selection. phrebejk@460: function extendSelection(cm, pos, other, bias) { phrebejk@460: var sel = cm.view.sel; phrebejk@460: if (sel.shift || sel.extend) { phrebejk@460: var anchor = sel.anchor; phrebejk@460: if (other) { phrebejk@460: var posBefore = posLess(pos, anchor); phrebejk@460: if (posBefore != posLess(other, anchor)) { phrebejk@460: anchor = pos; phrebejk@460: pos = other; phrebejk@460: } else if (posBefore != posLess(pos, other)) { phrebejk@460: pos = other; phrebejk@460: } phrebejk@460: } phrebejk@460: setSelection(cm, anchor, pos, bias); phrebejk@460: } else { phrebejk@460: setSelection(cm, pos, other || pos, bias); phrebejk@460: } phrebejk@460: cm.curOp.userSelChange = true; phrebejk@460: } phrebejk@460: phrebejk@460: // Update the selection. Last two args are only used by phrebejk@460: // updateDoc, since they have to be expressed in the line phrebejk@460: // numbers before the update. phrebejk@460: function setSelection(cm, anchor, head, bias, checkAtomic) { phrebejk@460: cm.view.goalColumn = null; phrebejk@460: var sel = cm.view.sel; phrebejk@460: // Skip over atomic spans. phrebejk@460: if (checkAtomic || !posEq(anchor, sel.anchor)) phrebejk@460: anchor = skipAtomic(cm, anchor, bias, checkAtomic != "push"); phrebejk@460: if (checkAtomic || !posEq(head, sel.head)) phrebejk@460: head = skipAtomic(cm, head, bias, checkAtomic != "push"); phrebejk@460: phrebejk@460: if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return; phrebejk@460: phrebejk@460: sel.anchor = anchor; sel.head = head; phrebejk@460: var inv = posLess(head, anchor); phrebejk@460: sel.from = inv ? head : anchor; phrebejk@460: sel.to = inv ? anchor : head; phrebejk@460: phrebejk@460: cm.curOp.updateInput = true; phrebejk@460: cm.curOp.selectionChanged = true; phrebejk@460: } phrebejk@460: phrebejk@460: function reCheckSelection(cm) { phrebejk@460: setSelection(cm, cm.view.sel.from, cm.view.sel.to, null, "push"); phrebejk@460: } phrebejk@460: phrebejk@460: function skipAtomic(cm, pos, bias, mayClear) { phrebejk@460: var doc = cm.view.doc, flipped = false, curPos = pos; phrebejk@460: var dir = bias || 1; phrebejk@460: cm.view.cantEdit = false; phrebejk@460: search: for (;;) { phrebejk@460: var line = getLine(doc, curPos.line), toClear; phrebejk@460: if (line.markedSpans) { phrebejk@460: for (var i = 0; i < line.markedSpans.length; ++i) { phrebejk@460: var sp = line.markedSpans[i], m = sp.marker; phrebejk@460: if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) && phrebejk@460: (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { phrebejk@460: if (mayClear && m.clearOnEnter) { phrebejk@460: (toClear || (toClear = [])).push(m); phrebejk@460: continue; phrebejk@460: } else if (!m.atomic) continue; phrebejk@460: var newPos = m.find()[dir < 0 ? "from" : "to"]; phrebejk@460: if (posEq(newPos, curPos)) { phrebejk@460: newPos.ch += dir; phrebejk@460: if (newPos.ch < 0) { phrebejk@460: if (newPos.line) newPos = clipPos(doc, {line: newPos.line - 1}); phrebejk@460: else newPos = null; phrebejk@460: } else if (newPos.ch > line.text.length) { phrebejk@460: if (newPos.line < doc.size - 1) newPos = {line: newPos.line + 1, ch: 0}; phrebejk@460: else newPos = null; phrebejk@460: } phrebejk@460: if (!newPos) { phrebejk@460: if (flipped) { phrebejk@460: // Driven in a corner -- no valid cursor position found at all phrebejk@460: // -- try again *with* clearing, if we didn't already phrebejk@460: if (!mayClear) return skipAtomic(cm, pos, bias, true); phrebejk@460: // Otherwise, turn off editing until further notice, and return the start of the doc phrebejk@460: cm.view.cantEdit = true; phrebejk@460: return {line: 0, ch: 0}; phrebejk@460: } phrebejk@460: flipped = true; newPos = pos; dir = -dir; phrebejk@460: } phrebejk@460: } phrebejk@460: curPos = newPos; phrebejk@460: continue search; phrebejk@460: } phrebejk@460: } phrebejk@460: if (toClear) for (var i = 0; i < toClear.length; ++i) toClear[i].clear(); phrebejk@460: } phrebejk@460: return curPos; phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: // SCROLLING phrebejk@460: phrebejk@460: function scrollCursorIntoView(cm) { phrebejk@460: var view = cm.view; phrebejk@460: var coords = scrollPosIntoView(cm, view.sel.head); phrebejk@460: if (!view.focused) return; phrebejk@460: var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; phrebejk@460: if (coords.top + box.top < 0) doScroll = true; phrebejk@460: else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; phrebejk@460: if (doScroll != null && !phantom) { phrebejk@460: var hidden = display.cursor.style.display == "none"; phrebejk@460: if (hidden) { phrebejk@460: display.cursor.style.display = ""; phrebejk@460: display.cursor.style.left = coords.left + "px"; phrebejk@460: display.cursor.style.top = (coords.top - display.viewOffset) + "px"; phrebejk@460: } phrebejk@460: display.cursor.scrollIntoView(doScroll); phrebejk@460: if (hidden) display.cursor.style.display = "none"; phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: function scrollPosIntoView(cm, pos) { phrebejk@460: for (;;) { phrebejk@460: var changed = false, coords = cursorCoords(cm, pos); phrebejk@460: var scrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom); phrebejk@460: var startTop = cm.view.scrollTop, startLeft = cm.view.scrollLeft; phrebejk@460: if (scrollPos.scrollTop != null) { phrebejk@460: setScrollTop(cm, scrollPos.scrollTop); phrebejk@460: if (Math.abs(cm.view.scrollTop - startTop) > 1) changed = true; phrebejk@460: } phrebejk@460: if (scrollPos.scrollLeft != null) { phrebejk@460: setScrollLeft(cm, scrollPos.scrollLeft); phrebejk@460: if (Math.abs(cm.view.scrollLeft - startLeft) > 1) changed = true; phrebejk@460: } phrebejk@460: if (!changed) return coords; phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: function scrollIntoView(cm, x1, y1, x2, y2) { phrebejk@460: var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); phrebejk@460: if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); phrebejk@460: if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); phrebejk@460: } phrebejk@460: phrebejk@460: function calculateScrollPos(cm, x1, y1, x2, y2) { phrebejk@460: var display = cm.display, pt = paddingTop(display); phrebejk@460: y1 += pt; y2 += pt; phrebejk@460: var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {}; phrebejk@460: var docBottom = cm.view.doc.height + 2 * pt; phrebejk@460: var atTop = y1 < pt + 10, atBottom = y2 + pt > docBottom - 10; phrebejk@460: if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1); phrebejk@460: else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2) - screen; phrebejk@460: phrebejk@460: var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft; phrebejk@460: x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth; phrebejk@460: var gutterw = display.gutters.offsetWidth; phrebejk@460: var atLeft = x1 < gutterw + 10; phrebejk@460: if (x1 < screenleft + gutterw || atLeft) { phrebejk@460: if (atLeft) x1 = 0; phrebejk@460: result.scrollLeft = Math.max(0, x1 - 10 - gutterw); phrebejk@460: } else if (x2 > screenw + screenleft - 3) { phrebejk@460: result.scrollLeft = x2 + 10 - screenw; phrebejk@460: } phrebejk@460: return result; phrebejk@460: } phrebejk@460: phrebejk@460: // API UTILITIES phrebejk@460: phrebejk@460: function indentLine(cm, n, how, aggressive) { phrebejk@460: var doc = cm.view.doc; phrebejk@460: if (!how) how = "add"; phrebejk@460: if (how == "smart") { phrebejk@460: if (!cm.view.mode.indent) how = "prev"; phrebejk@460: else var state = getStateBefore(cm, n); phrebejk@460: } phrebejk@460: phrebejk@460: var tabSize = cm.options.tabSize; phrebejk@460: var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); phrebejk@460: var curSpaceString = line.text.match(/^\s*/)[0], indentation; phrebejk@460: if (how == "smart") { phrebejk@460: indentation = cm.view.mode.indent(state, line.text.slice(curSpaceString.length), line.text); phrebejk@460: if (indentation == Pass) { phrebejk@460: if (!aggressive) return; phrebejk@460: how = "prev"; phrebejk@460: } phrebejk@460: } phrebejk@460: if (how == "prev") { phrebejk@460: if (n) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); phrebejk@460: else indentation = 0; phrebejk@460: } phrebejk@460: else if (how == "add") indentation = curSpace + cm.options.indentUnit; phrebejk@460: else if (how == "subtract") indentation = curSpace - cm.options.indentUnit; phrebejk@460: indentation = Math.max(0, indentation); phrebejk@460: phrebejk@460: var indentString = "", pos = 0; phrebejk@460: if (cm.options.indentWithTabs) phrebejk@460: for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} phrebejk@460: if (pos < indentation) indentString += spaceStr(indentation - pos); phrebejk@460: phrebejk@460: if (indentString != curSpaceString) phrebejk@460: replaceRange(cm, indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length}, "input"); phrebejk@460: line.stateAfter = null; phrebejk@460: } phrebejk@460: phrebejk@460: function changeLine(cm, handle, op) { phrebejk@460: var no = handle, line = handle, doc = cm.view.doc; phrebejk@460: if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); phrebejk@460: else no = lineNo(handle); phrebejk@460: if (no == null) return null; phrebejk@460: if (op(line, no)) regChange(cm, no, no + 1); phrebejk@460: else return null; phrebejk@460: return line; phrebejk@460: } phrebejk@460: phrebejk@460: function findPosH(cm, dir, unit, visually) { phrebejk@460: var doc = cm.view.doc, end = cm.view.sel.head, line = end.line, ch = end.ch; phrebejk@460: var lineObj = getLine(doc, line); phrebejk@460: function findNextLine() { phrebejk@460: var l = line + dir; phrebejk@460: if (l < 0 || l == doc.size) return false; phrebejk@460: line = l; phrebejk@460: return lineObj = getLine(doc, l); phrebejk@460: } phrebejk@460: function moveOnce(boundToLine) { phrebejk@460: var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); phrebejk@460: if (next == null) { phrebejk@460: if (!boundToLine && findNextLine()) { phrebejk@460: if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); phrebejk@460: else ch = dir < 0 ? lineObj.text.length : 0; phrebejk@460: } else return false; phrebejk@460: } else ch = next; phrebejk@460: return true; phrebejk@460: } phrebejk@460: if (unit == "char") moveOnce(); phrebejk@460: else if (unit == "column") moveOnce(true); phrebejk@460: else if (unit == "word") { phrebejk@460: var sawWord = false; phrebejk@460: for (;;) { phrebejk@460: if (dir < 0) if (!moveOnce()) break; phrebejk@460: if (isWordChar(lineObj.text.charAt(ch))) sawWord = true; phrebejk@460: else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;} phrebejk@460: if (dir > 0) if (!moveOnce()) break; phrebejk@460: } phrebejk@460: } phrebejk@460: return skipAtomic(cm, {line: line, ch: ch}, dir, true); phrebejk@460: } phrebejk@460: phrebejk@460: function findWordAt(line, pos) { phrebejk@460: var start = pos.ch, end = pos.ch; phrebejk@460: if (line) { phrebejk@460: if (pos.after === false || end == line.length) --start; else ++end; phrebejk@460: var startChar = line.charAt(start); phrebejk@460: var check = isWordChar(startChar) ? isWordChar : phrebejk@460: /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} : phrebejk@460: function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; phrebejk@460: while (start > 0 && check(line.charAt(start - 1))) --start; phrebejk@460: while (end < line.length && check(line.charAt(end))) ++end; phrebejk@460: } phrebejk@460: return {from: {line: pos.line, ch: start}, to: {line: pos.line, ch: end}}; phrebejk@460: } phrebejk@460: phrebejk@460: function selectLine(cm, line) { phrebejk@460: extendSelection(cm, {line: line, ch: 0}, clipPos(cm.view.doc, {line: line + 1, ch: 0})); phrebejk@460: } phrebejk@460: phrebejk@460: // PROTOTYPE phrebejk@460: phrebejk@460: // The publicly visible API. Note that operation(null, f) means phrebejk@460: // 'wrap f in an operation, performed on its `this` parameter' phrebejk@460: phrebejk@460: CodeMirror.prototype = { phrebejk@460: getValue: function(lineSep) { phrebejk@460: var text = [], doc = this.view.doc; phrebejk@460: doc.iter(0, doc.size, function(line) { text.push(line.text); }); phrebejk@460: return text.join(lineSep || "\n"); phrebejk@460: }, phrebejk@460: phrebejk@460: setValue: operation(null, function(code) { phrebejk@460: var doc = this.view.doc, top = {line: 0, ch: 0}, lastLen = getLine(doc, doc.size-1).text.length; phrebejk@460: updateDocInner(this, top, {line: doc.size - 1, ch: lastLen}, splitLines(code), top, top, "setValue"); phrebejk@460: }), phrebejk@460: phrebejk@460: getSelection: function(lineSep) { return this.getRange(this.view.sel.from, this.view.sel.to, lineSep); }, phrebejk@460: phrebejk@460: replaceSelection: operation(null, function(code, collapse, origin) { phrebejk@460: var sel = this.view.sel; phrebejk@460: updateDoc(this, sel.from, sel.to, splitLines(code), collapse || "around", origin); phrebejk@460: }), phrebejk@460: phrebejk@460: focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);}, phrebejk@460: phrebejk@460: setOption: function(option, value) { phrebejk@460: var options = this.options, old = options[option]; phrebejk@460: if (options[option] == value && option != "mode") return; phrebejk@460: options[option] = value; phrebejk@460: if (optionHandlers.hasOwnProperty(option)) phrebejk@460: operation(this, optionHandlers[option])(this, value, old); phrebejk@460: }, phrebejk@460: phrebejk@460: getOption: function(option) {return this.options[option];}, phrebejk@460: phrebejk@460: getMode: function() {return this.view.mode;}, phrebejk@460: phrebejk@460: addKeyMap: function(map) { phrebejk@460: this.view.keyMaps.push(map); phrebejk@460: }, phrebejk@460: phrebejk@460: removeKeyMap: function(map) { phrebejk@460: var maps = this.view.keyMaps; phrebejk@460: for (var i = 0; i < maps.length; ++i) phrebejk@460: if ((typeof map == "string" ? maps[i].name : maps[i]) == map) { phrebejk@460: maps.splice(i, 1); phrebejk@460: return true; phrebejk@460: } phrebejk@460: }, phrebejk@460: phrebejk@460: undo: operation(null, function() {unredoHelper(this, "undo");}), phrebejk@460: redo: operation(null, function() {unredoHelper(this, "redo");}), phrebejk@460: phrebejk@460: indentLine: operation(null, function(n, dir, aggressive) { phrebejk@460: if (typeof dir != "string") { phrebejk@460: if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; phrebejk@460: else dir = dir ? "add" : "subtract"; phrebejk@460: } phrebejk@460: if (isLine(this.view.doc, n)) indentLine(this, n, dir, aggressive); phrebejk@460: }), phrebejk@460: phrebejk@460: indentSelection: operation(null, function(how) { phrebejk@460: var sel = this.view.sel; phrebejk@460: if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how); phrebejk@460: var e = sel.to.line - (sel.to.ch ? 0 : 1); phrebejk@460: for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how); phrebejk@460: }), phrebejk@460: phrebejk@460: historySize: function() { phrebejk@460: var hist = this.view.history; phrebejk@460: return {undo: hist.done.length, redo: hist.undone.length}; phrebejk@460: }, phrebejk@460: phrebejk@460: clearHistory: function() {this.view.history = makeHistory();}, phrebejk@460: phrebejk@460: markClean: function() { phrebejk@460: this.view.history.dirtyCounter = 0; phrebejk@460: this.view.history.lastOp = this.view.history.lastOrigin = null; phrebejk@460: }, phrebejk@460: phrebejk@460: isClean: function () {return this.view.history.dirtyCounter == 0;}, phrebejk@460: phrebejk@460: getHistory: function() { phrebejk@460: var hist = this.view.history; phrebejk@460: function cp(arr) { phrebejk@460: for (var i = 0, nw = [], nwelt; i < arr.length; ++i) { phrebejk@460: var set = arr[i]; phrebejk@460: nw.push({events: nwelt = [], fromBefore: set.fromBefore, toBefore: set.toBefore, phrebejk@460: fromAfter: set.fromAfter, toAfter: set.toAfter}); phrebejk@460: for (var j = 0, elt = set.events; j < elt.length; ++j) { phrebejk@460: var old = [], cur = elt[j]; phrebejk@460: nwelt.push({start: cur.start, added: cur.added, old: old}); phrebejk@460: for (var k = 0; k < cur.old.length; ++k) old.push(hlText(cur.old[k])); phrebejk@460: } phrebejk@460: } phrebejk@460: return nw; phrebejk@460: } phrebejk@460: return {done: cp(hist.done), undone: cp(hist.undone)}; phrebejk@460: }, phrebejk@460: phrebejk@460: setHistory: function(histData) { phrebejk@460: var hist = this.view.history = makeHistory(); phrebejk@460: hist.done = histData.done; phrebejk@460: hist.undone = histData.undone; phrebejk@460: }, phrebejk@460: phrebejk@460: // Fetch the parser token for a given character. Useful for hacks phrebejk@460: // that want to inspect the mode state (say, for completion). phrebejk@460: getTokenAt: function(pos) { phrebejk@460: var doc = this.view.doc; phrebejk@460: pos = clipPos(doc, pos); phrebejk@460: var state = getStateBefore(this, pos.line), mode = this.view.mode; phrebejk@460: var line = getLine(doc, pos.line); phrebejk@460: var stream = new StringStream(line.text, this.options.tabSize); phrebejk@460: while (stream.pos < pos.ch && !stream.eol()) { phrebejk@460: stream.start = stream.pos; phrebejk@460: var style = mode.token(stream, state); phrebejk@460: } phrebejk@460: return {start: stream.start, phrebejk@460: end: stream.pos, phrebejk@460: string: stream.current(), phrebejk@460: className: style || null, // Deprecated, use 'type' instead phrebejk@460: type: style || null, phrebejk@460: state: state}; phrebejk@460: }, phrebejk@460: phrebejk@460: getStateAfter: function(line) { phrebejk@460: var doc = this.view.doc; phrebejk@460: line = clipLine(doc, line == null ? doc.size - 1: line); phrebejk@460: return getStateBefore(this, line + 1); phrebejk@460: }, phrebejk@460: phrebejk@460: cursorCoords: function(start, mode) { phrebejk@460: var pos, sel = this.view.sel; phrebejk@460: if (start == null) pos = sel.head; phrebejk@460: else if (typeof start == "object") pos = clipPos(this.view.doc, start); phrebejk@460: else pos = start ? sel.from : sel.to; phrebejk@460: return cursorCoords(this, pos, mode || "page"); phrebejk@460: }, phrebejk@460: phrebejk@460: charCoords: function(pos, mode) { phrebejk@460: return charCoords(this, clipPos(this.view.doc, pos), mode || "page"); phrebejk@460: }, phrebejk@460: phrebejk@460: coordsChar: function(coords) { phrebejk@460: var off = this.display.lineSpace.getBoundingClientRect(); phrebejk@460: return coordsChar(this, coords.left - off.left, coords.top - off.top); phrebejk@460: }, phrebejk@460: phrebejk@460: defaultTextHeight: function() { return textHeight(this.display); }, phrebejk@460: phrebejk@460: markText: operation(null, function(from, to, options) { phrebejk@460: return markText(this, clipPos(this.view.doc, from), clipPos(this.view.doc, to), phrebejk@460: options, "range"); phrebejk@460: }), phrebejk@460: phrebejk@460: setBookmark: operation(null, function(pos, widget) { phrebejk@460: pos = clipPos(this.view.doc, pos); phrebejk@460: return markText(this, pos, pos, widget ? {replacedWith: widget} : {}, "bookmark"); phrebejk@460: }), phrebejk@460: phrebejk@460: findMarksAt: function(pos) { phrebejk@460: var doc = this.view.doc; phrebejk@460: pos = clipPos(doc, pos); phrebejk@460: var markers = [], spans = getLine(doc, pos.line).markedSpans; phrebejk@460: if (spans) for (var i = 0; i < spans.length; ++i) { phrebejk@460: var span = spans[i]; phrebejk@460: if ((span.from == null || span.from <= pos.ch) && phrebejk@460: (span.to == null || span.to >= pos.ch)) phrebejk@460: markers.push(span.marker); phrebejk@460: } phrebejk@460: return markers; phrebejk@460: }, phrebejk@460: phrebejk@460: setGutterMarker: operation(null, function(line, gutterID, value) { phrebejk@460: return changeLine(this, line, function(line) { phrebejk@460: var markers = line.gutterMarkers || (line.gutterMarkers = {}); phrebejk@460: markers[gutterID] = value; phrebejk@460: if (!value && isEmpty(markers)) line.gutterMarkers = null; phrebejk@460: return true; phrebejk@460: }); phrebejk@460: }), phrebejk@460: phrebejk@460: clearGutter: operation(null, function(gutterID) { phrebejk@460: var i = 0, cm = this, doc = cm.view.doc; phrebejk@460: doc.iter(0, doc.size, function(line) { phrebejk@460: if (line.gutterMarkers && line.gutterMarkers[gutterID]) { phrebejk@460: line.gutterMarkers[gutterID] = null; phrebejk@460: regChange(cm, i, i + 1); phrebejk@460: if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; phrebejk@460: } phrebejk@460: ++i; phrebejk@460: }); phrebejk@460: }), phrebejk@460: phrebejk@460: addLineClass: operation(null, function(handle, where, cls) { phrebejk@460: return changeLine(this, handle, function(line) { phrebejk@460: var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; phrebejk@460: if (!line[prop]) line[prop] = cls; phrebejk@460: else if (new RegExp("\\b" + cls + "\\b").test(line[prop])) return false; phrebejk@460: else line[prop] += " " + cls; phrebejk@460: return true; phrebejk@460: }); phrebejk@460: }), phrebejk@460: phrebejk@460: removeLineClass: operation(null, function(handle, where, cls) { phrebejk@460: return changeLine(this, handle, function(line) { phrebejk@460: var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; phrebejk@460: var cur = line[prop]; phrebejk@460: if (!cur) return false; phrebejk@460: else if (cls == null) line[prop] = null; phrebejk@460: else { phrebejk@460: var upd = cur.replace(new RegExp("^" + cls + "\\b\\s*|\\s*\\b" + cls + "\\b"), ""); phrebejk@460: if (upd == cur) return false; phrebejk@460: line[prop] = upd || null; phrebejk@460: } phrebejk@460: return true; phrebejk@460: }); phrebejk@460: }), phrebejk@460: phrebejk@460: addLineWidget: operation(null, function(handle, node, options) { phrebejk@460: var widget = options || {}; phrebejk@460: widget.node = node; phrebejk@460: if (widget.noHScroll) this.display.alignWidgets = true; phrebejk@460: changeLine(this, handle, function(line) { phrebejk@460: (line.widgets || (line.widgets = [])).push(widget); phrebejk@460: widget.line = line; phrebejk@460: return true; phrebejk@460: }); phrebejk@460: return widget; phrebejk@460: }), phrebejk@460: phrebejk@460: removeLineWidget: operation(null, function(widget) { phrebejk@460: var ws = widget.line.widgets, no = lineNo(widget.line); phrebejk@460: if (no == null) return; phrebejk@460: for (var i = 0; i < ws.length; ++i) if (ws[i] == widget) ws.splice(i--, 1); phrebejk@460: regChange(this, no, no + 1); phrebejk@460: }), phrebejk@460: phrebejk@460: lineInfo: function(line) { phrebejk@460: if (typeof line == "number") { phrebejk@460: if (!isLine(this.view.doc, line)) return null; phrebejk@460: var n = line; phrebejk@460: line = getLine(this.view.doc, line); phrebejk@460: if (!line) return null; phrebejk@460: } else { phrebejk@460: var n = lineNo(line); phrebejk@460: if (n == null) return null; phrebejk@460: } phrebejk@460: return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, phrebejk@460: textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, phrebejk@460: widgets: line.widgets}; phrebejk@460: }, phrebejk@460: phrebejk@460: getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};}, phrebejk@460: phrebejk@460: addWidget: function(pos, node, scroll, vert, horiz) { phrebejk@460: var display = this.display; phrebejk@460: pos = cursorCoords(this, clipPos(this.view.doc, pos)); phrebejk@460: var top = pos.top, left = pos.left; phrebejk@460: node.style.position = "absolute"; phrebejk@460: display.sizer.appendChild(node); phrebejk@460: if (vert == "over") top = pos.top; phrebejk@460: else if (vert == "near") { phrebejk@460: var vspace = Math.max(display.wrapper.clientHeight, this.view.doc.height), phrebejk@460: hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); phrebejk@460: if (pos.bottom + node.offsetHeight > vspace && pos.top > node.offsetHeight) phrebejk@460: top = pos.top - node.offsetHeight; phrebejk@460: if (left + node.offsetWidth > hspace) phrebejk@460: left = hspace - node.offsetWidth; phrebejk@460: } phrebejk@460: node.style.top = (top + paddingTop(display)) + "px"; phrebejk@460: node.style.left = node.style.right = ""; phrebejk@460: if (horiz == "right") { phrebejk@460: left = display.sizer.clientWidth - node.offsetWidth; phrebejk@460: node.style.right = "0px"; phrebejk@460: } else { phrebejk@460: if (horiz == "left") left = 0; phrebejk@460: else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; phrebejk@460: node.style.left = left + "px"; phrebejk@460: } phrebejk@460: if (scroll) phrebejk@460: scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight); phrebejk@460: }, phrebejk@460: phrebejk@460: lineCount: function() {return this.view.doc.size;}, phrebejk@460: phrebejk@460: clipPos: function(pos) {return clipPos(this.view.doc, pos);}, phrebejk@460: phrebejk@460: getCursor: function(start) { phrebejk@460: var sel = this.view.sel, pos; phrebejk@460: if (start == null || start == "head") pos = sel.head; phrebejk@460: else if (start == "anchor") pos = sel.anchor; phrebejk@460: else if (start == "end" || start === false) pos = sel.to; phrebejk@460: else pos = sel.from; phrebejk@460: return copyPos(pos); phrebejk@460: }, phrebejk@460: phrebejk@460: somethingSelected: function() {return !posEq(this.view.sel.from, this.view.sel.to);}, phrebejk@460: phrebejk@460: setCursor: operation(null, function(line, ch, extend) { phrebejk@460: var pos = clipPos(this.view.doc, typeof line == "number" ? {line: line, ch: ch || 0} : line); phrebejk@460: if (extend) extendSelection(this, pos); phrebejk@460: else setSelection(this, pos, pos); phrebejk@460: }), phrebejk@460: phrebejk@460: setSelection: operation(null, function(anchor, head) { phrebejk@460: var doc = this.view.doc; phrebejk@460: setSelection(this, clipPos(doc, anchor), clipPos(doc, head || anchor)); phrebejk@460: }), phrebejk@460: phrebejk@460: extendSelection: operation(null, function(from, to) { phrebejk@460: var doc = this.view.doc; phrebejk@460: extendSelection(this, clipPos(doc, from), to && clipPos(doc, to)); phrebejk@460: }), phrebejk@460: phrebejk@460: setExtending: function(val) {this.view.sel.extend = val;}, phrebejk@460: phrebejk@460: getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, phrebejk@460: phrebejk@460: getLineHandle: function(line) { phrebejk@460: var doc = this.view.doc; phrebejk@460: if (isLine(doc, line)) return getLine(doc, line); phrebejk@460: }, phrebejk@460: phrebejk@460: getLineNumber: function(line) {return lineNo(line);}, phrebejk@460: phrebejk@460: setLine: operation(null, function(line, text) { phrebejk@460: if (isLine(this.view.doc, line)) phrebejk@460: replaceRange(this, text, {line: line, ch: 0}, {line: line, ch: getLine(this.view.doc, line).text.length}); phrebejk@460: }), phrebejk@460: phrebejk@460: removeLine: operation(null, function(line) { phrebejk@460: if (isLine(this.view.doc, line)) phrebejk@460: replaceRange(this, "", {line: line, ch: 0}, clipPos(this.view.doc, {line: line+1, ch: 0})); phrebejk@460: }), phrebejk@460: phrebejk@460: replaceRange: operation(null, function(code, from, to) { phrebejk@460: var doc = this.view.doc; phrebejk@460: from = clipPos(doc, from); phrebejk@460: to = to ? clipPos(doc, to) : from; phrebejk@460: return replaceRange(this, code, from, to); phrebejk@460: }), phrebejk@460: phrebejk@460: getRange: function(from, to, lineSep) { phrebejk@460: var doc = this.view.doc; phrebejk@460: from = clipPos(doc, from); to = clipPos(doc, to); phrebejk@460: var l1 = from.line, l2 = to.line; phrebejk@460: if (l1 == l2) return getLine(doc, l1).text.slice(from.ch, to.ch); phrebejk@460: var code = [getLine(doc, l1).text.slice(from.ch)]; phrebejk@460: doc.iter(l1 + 1, l2, function(line) { code.push(line.text); }); phrebejk@460: code.push(getLine(doc, l2).text.slice(0, to.ch)); phrebejk@460: return code.join(lineSep || "\n"); phrebejk@460: }, phrebejk@460: phrebejk@460: triggerOnKeyDown: operation(null, onKeyDown), phrebejk@460: phrebejk@460: execCommand: function(cmd) {return commands[cmd](this);}, phrebejk@460: phrebejk@460: // Stuff used by commands, probably not much use to outside code. phrebejk@460: moveH: operation(null, function(dir, unit) { phrebejk@460: var sel = this.view.sel, pos = dir < 0 ? sel.from : sel.to; phrebejk@460: if (sel.shift || sel.extend || posEq(sel.from, sel.to)) pos = findPosH(this, dir, unit, true); phrebejk@460: extendSelection(this, pos, pos, dir); phrebejk@460: }), phrebejk@460: phrebejk@460: deleteH: operation(null, function(dir, unit) { phrebejk@460: var sel = this.view.sel; phrebejk@460: if (!posEq(sel.from, sel.to)) replaceRange(this, "", sel.from, sel.to, "delete"); phrebejk@460: else replaceRange(this, "", sel.from, findPosH(this, dir, unit, false), "delete"); phrebejk@460: this.curOp.userSelChange = true; phrebejk@460: }), phrebejk@460: phrebejk@460: moveV: operation(null, function(dir, unit) { phrebejk@460: var view = this.view, doc = view.doc, display = this.display; phrebejk@460: var cur = view.sel.head, pos = cursorCoords(this, cur, "div"); phrebejk@460: var x = pos.left, y; phrebejk@460: if (view.goalColumn != null) x = view.goalColumn; phrebejk@460: if (unit == "page") { phrebejk@460: var pageSize = Math.min(display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); phrebejk@460: y = pos.top + dir * pageSize; phrebejk@460: } else if (unit == "line") { phrebejk@460: y = dir > 0 ? pos.bottom + 3 : pos.top - 3; phrebejk@460: } phrebejk@460: do { phrebejk@460: var target = coordsChar(this, x, y); phrebejk@460: y += dir * 5; phrebejk@460: } while (target.outside && (dir < 0 ? y > 0 : y < doc.height)); phrebejk@460: phrebejk@460: if (unit == "page") display.scrollbarV.scrollTop += charCoords(this, target, "div").top - pos.top; phrebejk@460: extendSelection(this, target, target, dir); phrebejk@460: view.goalColumn = x; phrebejk@460: }), phrebejk@460: phrebejk@460: toggleOverwrite: function() { phrebejk@460: if (this.view.overwrite = !this.view.overwrite) phrebejk@460: this.display.cursor.className += " CodeMirror-overwrite"; phrebejk@460: else phrebejk@460: this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", ""); phrebejk@460: }, phrebejk@460: phrebejk@460: posFromIndex: function(off) { phrebejk@460: var lineNo = 0, ch, doc = this.view.doc; phrebejk@460: doc.iter(0, doc.size, function(line) { phrebejk@460: var sz = line.text.length + 1; phrebejk@460: if (sz > off) { ch = off; return true; } phrebejk@460: off -= sz; phrebejk@460: ++lineNo; phrebejk@460: }); phrebejk@460: return clipPos(doc, {line: lineNo, ch: ch}); phrebejk@460: }, phrebejk@460: indexFromPos: function (coords) { phrebejk@460: if (coords.line < 0 || coords.ch < 0) return 0; phrebejk@460: var index = coords.ch; phrebejk@460: this.view.doc.iter(0, coords.line, function (line) { phrebejk@460: index += line.text.length + 1; phrebejk@460: }); phrebejk@460: return index; phrebejk@460: }, phrebejk@460: phrebejk@460: scrollTo: function(x, y) { phrebejk@460: if (x != null) this.display.scrollbarH.scrollLeft = this.display.scroller.scrollLeft = x; phrebejk@460: if (y != null) this.display.scrollbarV.scrollTop = this.display.scroller.scrollTop = y; phrebejk@460: updateDisplay(this, []); phrebejk@460: }, phrebejk@460: getScrollInfo: function() { phrebejk@460: var scroller = this.display.scroller, co = scrollerCutOff; phrebejk@460: return {left: scroller.scrollLeft, top: scroller.scrollTop, phrebejk@460: height: scroller.scrollHeight - co, width: scroller.scrollWidth - co, phrebejk@460: clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co}; phrebejk@460: }, phrebejk@460: phrebejk@460: scrollIntoView: function(pos) { phrebejk@460: if (typeof pos == "number") pos = {line: pos, ch: 0}; phrebejk@460: pos = pos ? clipPos(this.view.doc, pos) : this.view.sel.head; phrebejk@460: scrollPosIntoView(this, pos); phrebejk@460: }, phrebejk@460: phrebejk@460: setSize: function(width, height) { phrebejk@460: function interpret(val) { phrebejk@460: return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; phrebejk@460: } phrebejk@460: if (width != null) this.display.wrapper.style.width = interpret(width); phrebejk@460: if (height != null) this.display.wrapper.style.height = interpret(height); phrebejk@460: this.refresh(); phrebejk@460: }, phrebejk@460: phrebejk@460: on: function(type, f) {on(this, type, f);}, phrebejk@460: off: function(type, f) {off(this, type, f);}, phrebejk@460: phrebejk@460: operation: function(f){return operation(this, f)();}, phrebejk@460: phrebejk@460: refresh: function() { phrebejk@460: clearCaches(this); phrebejk@460: if (this.display.scroller.scrollHeight > this.view.scrollTop) phrebejk@460: this.display.scrollbarV.scrollTop = this.display.scroller.scrollTop = this.view.scrollTop; phrebejk@460: updateDisplay(this, true); phrebejk@460: }, phrebejk@460: phrebejk@460: getInputField: function(){return this.display.input;}, phrebejk@460: getWrapperElement: function(){return this.display.wrapper;}, phrebejk@460: getScrollerElement: function(){return this.display.scroller;}, phrebejk@460: getGutterElement: function(){return this.display.gutters;} phrebejk@460: }; phrebejk@460: phrebejk@460: // OPTION DEFAULTS phrebejk@460: phrebejk@460: var optionHandlers = CodeMirror.optionHandlers = {}; phrebejk@460: phrebejk@460: // The default configuration options. phrebejk@460: var defaults = CodeMirror.defaults = {}; phrebejk@460: phrebejk@460: function option(name, deflt, handle, notOnInit) { phrebejk@460: CodeMirror.defaults[name] = deflt; phrebejk@460: if (handle) optionHandlers[name] = phrebejk@460: notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; phrebejk@460: } phrebejk@460: phrebejk@460: var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; phrebejk@460: phrebejk@460: // These two are, on init, called from the constructor because they phrebejk@460: // have to be initialized before the editor can start at all. phrebejk@460: option("value", "", function(cm, val) {cm.setValue(val);}, true); phrebejk@460: option("mode", null, loadMode, true); phrebejk@460: phrebejk@460: option("indentUnit", 2, loadMode, true); phrebejk@460: option("indentWithTabs", false); phrebejk@460: option("smartIndent", true); phrebejk@460: option("tabSize", 4, function(cm) { phrebejk@460: loadMode(cm); phrebejk@460: clearCaches(cm); phrebejk@460: updateDisplay(cm, true); phrebejk@460: }, true); phrebejk@460: option("electricChars", true); phrebejk@460: phrebejk@460: option("theme", "default", function(cm) { phrebejk@460: themeChanged(cm); phrebejk@460: guttersChanged(cm); phrebejk@460: }, true); phrebejk@460: option("keyMap", "default", keyMapChanged); phrebejk@460: option("extraKeys", null); phrebejk@460: phrebejk@460: option("onKeyEvent", null); phrebejk@460: option("onDragEvent", null); phrebejk@460: phrebejk@460: option("lineWrapping", false, wrappingChanged, true); phrebejk@460: option("gutters", [], function(cm) { phrebejk@460: setGuttersForLineNumbers(cm.options); phrebejk@460: guttersChanged(cm); phrebejk@460: }, true); phrebejk@460: option("lineNumbers", false, function(cm) { phrebejk@460: setGuttersForLineNumbers(cm.options); phrebejk@460: guttersChanged(cm); phrebejk@460: }, true); phrebejk@460: option("firstLineNumber", 1, guttersChanged, true); phrebejk@460: option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true); phrebejk@460: option("showCursorWhenSelecting", false, updateSelection, true); phrebejk@460: phrebejk@460: option("readOnly", false, function(cm, val) { phrebejk@460: if (val == "nocursor") {onBlur(cm); cm.display.input.blur();} phrebejk@460: else if (!val) resetInput(cm, true); phrebejk@460: }); phrebejk@460: option("dragDrop", true); phrebejk@460: phrebejk@460: option("cursorBlinkRate", 530); phrebejk@460: option("cursorHeight", 1); phrebejk@460: option("workTime", 100); phrebejk@460: option("workDelay", 100); phrebejk@460: option("flattenSpans", true); phrebejk@460: option("pollInterval", 100); phrebejk@460: option("undoDepth", 40); phrebejk@460: option("viewportMargin", 10, function(cm){cm.refresh();}, true); phrebejk@460: phrebejk@460: option("tabindex", null, function(cm, val) { phrebejk@460: cm.display.input.tabIndex = val || ""; phrebejk@460: }); phrebejk@460: option("autofocus", null); phrebejk@460: phrebejk@460: // MODE DEFINITION AND QUERYING phrebejk@460: phrebejk@460: // Known modes, by name and by MIME phrebejk@460: var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; phrebejk@460: phrebejk@460: CodeMirror.defineMode = function(name, mode) { phrebejk@460: if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; phrebejk@460: if (arguments.length > 2) { phrebejk@460: mode.dependencies = []; phrebejk@460: for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]); phrebejk@460: } phrebejk@460: modes[name] = mode; phrebejk@460: }; phrebejk@460: phrebejk@460: CodeMirror.defineMIME = function(mime, spec) { phrebejk@460: mimeModes[mime] = spec; phrebejk@460: }; phrebejk@460: phrebejk@460: CodeMirror.resolveMode = function(spec) { phrebejk@460: if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) phrebejk@460: spec = mimeModes[spec]; phrebejk@460: else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) phrebejk@460: return CodeMirror.resolveMode("application/xml"); phrebejk@460: if (typeof spec == "string") return {name: spec}; phrebejk@460: else return spec || {name: "null"}; phrebejk@460: }; phrebejk@460: phrebejk@460: CodeMirror.getMode = function(options, spec) { phrebejk@460: var spec = CodeMirror.resolveMode(spec); phrebejk@460: var mfactory = modes[spec.name]; phrebejk@460: if (!mfactory) return CodeMirror.getMode(options, "text/plain"); phrebejk@460: var modeObj = mfactory(options, spec); phrebejk@460: if (modeExtensions.hasOwnProperty(spec.name)) { phrebejk@460: var exts = modeExtensions[spec.name]; phrebejk@460: for (var prop in exts) { phrebejk@460: if (!exts.hasOwnProperty(prop)) continue; phrebejk@460: if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; phrebejk@460: modeObj[prop] = exts[prop]; phrebejk@460: } phrebejk@460: } phrebejk@460: modeObj.name = spec.name; phrebejk@460: return modeObj; phrebejk@460: }; phrebejk@460: phrebejk@460: CodeMirror.defineMode("null", function() { phrebejk@460: return {token: function(stream) {stream.skipToEnd();}}; phrebejk@460: }); phrebejk@460: CodeMirror.defineMIME("text/plain", "null"); phrebejk@460: phrebejk@460: var modeExtensions = CodeMirror.modeExtensions = {}; phrebejk@460: CodeMirror.extendMode = function(mode, properties) { phrebejk@460: var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); phrebejk@460: for (var prop in properties) if (properties.hasOwnProperty(prop)) phrebejk@460: exts[prop] = properties[prop]; phrebejk@460: }; phrebejk@460: phrebejk@460: // EXTENSIONS phrebejk@460: phrebejk@460: CodeMirror.defineExtension = function(name, func) { phrebejk@460: CodeMirror.prototype[name] = func; phrebejk@460: }; phrebejk@460: phrebejk@460: CodeMirror.defineOption = option; phrebejk@460: phrebejk@460: var initHooks = []; phrebejk@460: CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; phrebejk@460: phrebejk@460: // MODE STATE HANDLING phrebejk@460: phrebejk@460: // Utility functions for working with state. Exported because modes phrebejk@460: // sometimes need to do this. phrebejk@460: function copyState(mode, state) { phrebejk@460: if (state === true) return state; phrebejk@460: if (mode.copyState) return mode.copyState(state); phrebejk@460: var nstate = {}; phrebejk@460: for (var n in state) { phrebejk@460: var val = state[n]; phrebejk@460: if (val instanceof Array) val = val.concat([]); phrebejk@460: nstate[n] = val; phrebejk@460: } phrebejk@460: return nstate; phrebejk@460: } phrebejk@460: CodeMirror.copyState = copyState; phrebejk@460: phrebejk@460: function startState(mode, a1, a2) { phrebejk@460: return mode.startState ? mode.startState(a1, a2) : true; phrebejk@460: } phrebejk@460: CodeMirror.startState = startState; phrebejk@460: phrebejk@460: CodeMirror.innerMode = function(mode, state) { phrebejk@460: while (mode.innerMode) { phrebejk@460: var info = mode.innerMode(state); phrebejk@460: state = info.state; phrebejk@460: mode = info.mode; phrebejk@460: } phrebejk@460: return info || {mode: mode, state: state}; phrebejk@460: }; phrebejk@460: phrebejk@460: // STANDARD COMMANDS phrebejk@460: phrebejk@460: var commands = CodeMirror.commands = { phrebejk@460: selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});}, phrebejk@460: killLine: function(cm) { phrebejk@460: var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to); phrebejk@460: if (!sel && cm.getLine(from.line).length == from.ch) phrebejk@460: cm.replaceRange("", from, {line: from.line + 1, ch: 0}, "delete"); phrebejk@460: else cm.replaceRange("", from, sel ? to : {line: from.line}, "delete"); phrebejk@460: }, phrebejk@460: deleteLine: function(cm) { phrebejk@460: var l = cm.getCursor().line; phrebejk@460: cm.replaceRange("", {line: l, ch: 0}, {line: l}, "delete"); phrebejk@460: }, phrebejk@460: undo: function(cm) {cm.undo();}, phrebejk@460: redo: function(cm) {cm.redo();}, phrebejk@460: goDocStart: function(cm) {cm.extendSelection({line: 0, ch: 0});}, phrebejk@460: goDocEnd: function(cm) {cm.extendSelection({line: cm.lineCount() - 1});}, phrebejk@460: goLineStart: function(cm) { phrebejk@460: cm.extendSelection(lineStart(cm, cm.getCursor().line)); phrebejk@460: }, phrebejk@460: goLineStartSmart: function(cm) { phrebejk@460: var cur = cm.getCursor(), start = lineStart(cm, cur.line); phrebejk@460: var line = cm.getLineHandle(start.line); phrebejk@460: var order = getOrder(line); phrebejk@460: if (!order || order[0].level == 0) { phrebejk@460: var firstNonWS = Math.max(0, line.text.search(/\S/)); phrebejk@460: var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch; phrebejk@460: cm.extendSelection({line: start.line, ch: inWS ? 0 : firstNonWS}); phrebejk@460: } else cm.extendSelection(start); phrebejk@460: }, phrebejk@460: goLineEnd: function(cm) { phrebejk@460: cm.extendSelection(lineEnd(cm, cm.getCursor().line)); phrebejk@460: }, phrebejk@460: goLineUp: function(cm) {cm.moveV(-1, "line");}, phrebejk@460: goLineDown: function(cm) {cm.moveV(1, "line");}, phrebejk@460: goPageUp: function(cm) {cm.moveV(-1, "page");}, phrebejk@460: goPageDown: function(cm) {cm.moveV(1, "page");}, phrebejk@460: goCharLeft: function(cm) {cm.moveH(-1, "char");}, phrebejk@460: goCharRight: function(cm) {cm.moveH(1, "char");}, phrebejk@460: goColumnLeft: function(cm) {cm.moveH(-1, "column");}, phrebejk@460: goColumnRight: function(cm) {cm.moveH(1, "column");}, phrebejk@460: goWordLeft: function(cm) {cm.moveH(-1, "word");}, phrebejk@460: goWordRight: function(cm) {cm.moveH(1, "word");}, phrebejk@460: delCharBefore: function(cm) {cm.deleteH(-1, "char");}, phrebejk@460: delCharAfter: function(cm) {cm.deleteH(1, "char");}, phrebejk@460: delWordBefore: function(cm) {cm.deleteH(-1, "word");}, phrebejk@460: delWordAfter: function(cm) {cm.deleteH(1, "word");}, phrebejk@460: indentAuto: function(cm) {cm.indentSelection("smart");}, phrebejk@460: indentMore: function(cm) {cm.indentSelection("add");}, phrebejk@460: indentLess: function(cm) {cm.indentSelection("subtract");}, phrebejk@460: insertTab: function(cm) {cm.replaceSelection("\t", "end", "input");}, phrebejk@460: defaultTab: function(cm) { phrebejk@460: if (cm.somethingSelected()) cm.indentSelection("add"); phrebejk@460: else cm.replaceSelection("\t", "end", "input"); phrebejk@460: }, phrebejk@460: transposeChars: function(cm) { phrebejk@460: var cur = cm.getCursor(), line = cm.getLine(cur.line); phrebejk@460: if (cur.ch > 0 && cur.ch < line.length - 1) phrebejk@460: cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1), phrebejk@460: {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1}); phrebejk@460: }, phrebejk@460: newlineAndIndent: function(cm) { phrebejk@460: operation(cm, function() { phrebejk@460: cm.replaceSelection("\n", "end", "input"); phrebejk@460: cm.indentLine(cm.getCursor().line, null, true); phrebejk@460: })(); phrebejk@460: }, phrebejk@460: toggleOverwrite: function(cm) {cm.toggleOverwrite();} phrebejk@460: }; phrebejk@460: phrebejk@460: // STANDARD KEYMAPS phrebejk@460: phrebejk@460: var keyMap = CodeMirror.keyMap = {}; phrebejk@460: keyMap.basic = { phrebejk@460: "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", phrebejk@460: "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", phrebejk@460: "Delete": "delCharAfter", "Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto", phrebejk@460: "Enter": "newlineAndIndent", "Insert": "toggleOverwrite" phrebejk@460: }; phrebejk@460: // Note that the save and find-related commands aren't defined by phrebejk@460: // default. Unknown commands are simply ignored. phrebejk@460: keyMap.pcDefault = { phrebejk@460: "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", phrebejk@460: "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd", phrebejk@460: "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", phrebejk@460: "Ctrl-Backspace": "delWordBefore", "Ctrl-Delete": "delWordAfter", "Ctrl-S": "save", "Ctrl-F": "find", phrebejk@460: "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", phrebejk@460: "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", phrebejk@460: fallthrough: "basic" phrebejk@460: }; phrebejk@460: keyMap.macDefault = { phrebejk@460: "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", phrebejk@460: "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft", phrebejk@460: "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordBefore", phrebejk@460: "Ctrl-Alt-Backspace": "delWordAfter", "Alt-Delete": "delWordAfter", "Cmd-S": "save", "Cmd-F": "find", phrebejk@460: "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", phrebejk@460: "Cmd-[": "indentLess", "Cmd-]": "indentMore", phrebejk@460: fallthrough: ["basic", "emacsy"] phrebejk@460: }; phrebejk@460: keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; phrebejk@460: keyMap.emacsy = { phrebejk@460: "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", phrebejk@460: "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", phrebejk@460: "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", phrebejk@460: "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" phrebejk@460: }; phrebejk@460: phrebejk@460: // KEYMAP DISPATCH phrebejk@460: phrebejk@460: function getKeyMap(val) { phrebejk@460: if (typeof val == "string") return keyMap[val]; phrebejk@460: else return val; phrebejk@460: } phrebejk@460: phrebejk@460: function lookupKey(name, maps, handle, stop) { phrebejk@460: function lookup(map) { phrebejk@460: map = getKeyMap(map); phrebejk@460: var found = map[name]; phrebejk@460: if (found === false) { phrebejk@460: if (stop) stop(); phrebejk@460: return true; phrebejk@460: } phrebejk@460: if (found != null && handle(found)) return true; phrebejk@460: if (map.nofallthrough) { phrebejk@460: if (stop) stop(); phrebejk@460: return true; phrebejk@460: } phrebejk@460: var fallthrough = map.fallthrough; phrebejk@460: if (fallthrough == null) return false; phrebejk@460: if (Object.prototype.toString.call(fallthrough) != "[object Array]") phrebejk@460: return lookup(fallthrough); phrebejk@460: for (var i = 0, e = fallthrough.length; i < e; ++i) { phrebejk@460: if (lookup(fallthrough[i])) return true; phrebejk@460: } phrebejk@460: return false; phrebejk@460: } phrebejk@460: phrebejk@460: for (var i = 0; i < maps.length; ++i) phrebejk@460: if (lookup(maps[i])) return true; phrebejk@460: } phrebejk@460: function isModifierKey(event) { phrebejk@460: var name = keyNames[e_prop(event, "keyCode")]; phrebejk@460: return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; phrebejk@460: } phrebejk@460: CodeMirror.isModifierKey = isModifierKey; phrebejk@460: phrebejk@460: // FROMTEXTAREA phrebejk@460: phrebejk@460: CodeMirror.fromTextArea = function(textarea, options) { phrebejk@460: if (!options) options = {}; phrebejk@460: options.value = textarea.value; phrebejk@460: if (!options.tabindex && textarea.tabindex) phrebejk@460: options.tabindex = textarea.tabindex; phrebejk@460: // Set autofocus to true if this textarea is focused, or if it has phrebejk@460: // autofocus and no other element is focused. phrebejk@460: if (options.autofocus == null) { phrebejk@460: var hasFocus = document.body; phrebejk@460: // doc.activeElement occasionally throws on IE phrebejk@460: try { hasFocus = document.activeElement; } catch(e) {} phrebejk@460: options.autofocus = hasFocus == textarea || phrebejk@460: textarea.getAttribute("autofocus") != null && hasFocus == document.body; phrebejk@460: } phrebejk@460: phrebejk@460: function save() {textarea.value = cm.getValue();} phrebejk@460: if (textarea.form) { phrebejk@460: // Deplorable hack to make the submit method do the right thing. phrebejk@460: on(textarea.form, "submit", save); phrebejk@460: var form = textarea.form, realSubmit = form.submit; phrebejk@460: try { phrebejk@460: form.submit = function wrappedSubmit() { phrebejk@460: save(); phrebejk@460: form.submit = realSubmit; phrebejk@460: form.submit(); phrebejk@460: form.submit = wrappedSubmit; phrebejk@460: }; phrebejk@460: } catch(e) {} phrebejk@460: } phrebejk@460: phrebejk@460: textarea.style.display = "none"; phrebejk@460: var cm = CodeMirror(function(node) { phrebejk@460: textarea.parentNode.insertBefore(node, textarea.nextSibling); phrebejk@460: }, options); phrebejk@460: cm.save = save; phrebejk@460: cm.getTextArea = function() { return textarea; }; phrebejk@460: cm.toTextArea = function() { phrebejk@460: save(); phrebejk@460: textarea.parentNode.removeChild(cm.getWrapperElement()); phrebejk@460: textarea.style.display = ""; phrebejk@460: if (textarea.form) { phrebejk@460: off(textarea.form, "submit", save); phrebejk@460: if (typeof textarea.form.submit == "function") phrebejk@460: textarea.form.submit = realSubmit; phrebejk@460: } phrebejk@460: }; phrebejk@460: return cm; phrebejk@460: }; phrebejk@460: phrebejk@460: // STRING STREAM phrebejk@460: phrebejk@460: // Fed to the mode parsers, provides helper functions to make phrebejk@460: // parsers more succinct. phrebejk@460: phrebejk@460: // The character stream used by a mode's parser. phrebejk@460: function StringStream(string, tabSize) { phrebejk@460: this.pos = this.start = 0; phrebejk@460: this.string = string; phrebejk@460: this.tabSize = tabSize || 8; phrebejk@460: } phrebejk@460: phrebejk@460: StringStream.prototype = { phrebejk@460: eol: function() {return this.pos >= this.string.length;}, phrebejk@460: sol: function() {return this.pos == 0;}, phrebejk@460: peek: function() {return this.string.charAt(this.pos) || undefined;}, phrebejk@460: next: function() { phrebejk@460: if (this.pos < this.string.length) phrebejk@460: return this.string.charAt(this.pos++); phrebejk@460: }, phrebejk@460: eat: function(match) { phrebejk@460: var ch = this.string.charAt(this.pos); phrebejk@460: if (typeof match == "string") var ok = ch == match; phrebejk@460: else var ok = ch && (match.test ? match.test(ch) : match(ch)); phrebejk@460: if (ok) {++this.pos; return ch;} phrebejk@460: }, phrebejk@460: eatWhile: function(match) { phrebejk@460: var start = this.pos; phrebejk@460: while (this.eat(match)){} phrebejk@460: return this.pos > start; phrebejk@460: }, phrebejk@460: eatSpace: function() { phrebejk@460: var start = this.pos; phrebejk@460: while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; phrebejk@460: return this.pos > start; phrebejk@460: }, phrebejk@460: skipToEnd: function() {this.pos = this.string.length;}, phrebejk@460: skipTo: function(ch) { phrebejk@460: var found = this.string.indexOf(ch, this.pos); phrebejk@460: if (found > -1) {this.pos = found; return true;} phrebejk@460: }, phrebejk@460: backUp: function(n) {this.pos -= n;}, phrebejk@460: column: function() {return countColumn(this.string, this.start, this.tabSize);}, phrebejk@460: indentation: function() {return countColumn(this.string, null, this.tabSize);}, phrebejk@460: match: function(pattern, consume, caseInsensitive) { phrebejk@460: if (typeof pattern == "string") { phrebejk@460: var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; phrebejk@460: if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) { phrebejk@460: if (consume !== false) this.pos += pattern.length; phrebejk@460: return true; phrebejk@460: } phrebejk@460: } else { phrebejk@460: var match = this.string.slice(this.pos).match(pattern); phrebejk@460: if (match && match.index > 0) return null; phrebejk@460: if (match && consume !== false) this.pos += match[0].length; phrebejk@460: return match; phrebejk@460: } phrebejk@460: }, phrebejk@460: current: function(){return this.string.slice(this.start, this.pos);} phrebejk@460: }; phrebejk@460: CodeMirror.StringStream = StringStream; phrebejk@460: phrebejk@460: // TEXTMARKERS phrebejk@460: phrebejk@460: function TextMarker(cm, type) { phrebejk@460: this.lines = []; phrebejk@460: this.type = type; phrebejk@460: this.cm = cm; phrebejk@460: } phrebejk@460: phrebejk@460: TextMarker.prototype.clear = function() { phrebejk@460: if (this.explicitlyCleared) return; phrebejk@460: startOperation(this.cm); phrebejk@460: var min = null, max = null; phrebejk@460: for (var i = 0; i < this.lines.length; ++i) { phrebejk@460: var line = this.lines[i]; phrebejk@460: var span = getMarkedSpanFor(line.markedSpans, this); phrebejk@460: if (span.to != null) max = lineNo(line); phrebejk@460: line.markedSpans = removeMarkedSpan(line.markedSpans, span); phrebejk@460: if (span.from != null) phrebejk@460: min = lineNo(line); phrebejk@460: else if (this.collapsed && !lineIsHidden(line)) phrebejk@460: updateLineHeight(line, textHeight(this.cm.display)); phrebejk@460: } phrebejk@460: if (min != null) regChange(this.cm, min, max + 1); phrebejk@460: this.lines.length = 0; phrebejk@460: this.explicitlyCleared = true; phrebejk@460: if (this.collapsed && this.cm.view.cantEdit) { phrebejk@460: this.cm.view.cantEdit = false; phrebejk@460: reCheckSelection(this.cm); phrebejk@460: } phrebejk@460: endOperation(this.cm); phrebejk@460: signalLater(this.cm, this, "clear"); phrebejk@460: }; phrebejk@460: phrebejk@460: TextMarker.prototype.find = function() { phrebejk@460: var from, to; phrebejk@460: for (var i = 0; i < this.lines.length; ++i) { phrebejk@460: var line = this.lines[i]; phrebejk@460: var span = getMarkedSpanFor(line.markedSpans, this); phrebejk@460: if (span.from != null || span.to != null) { phrebejk@460: var found = lineNo(line); phrebejk@460: if (span.from != null) from = {line: found, ch: span.from}; phrebejk@460: if (span.to != null) to = {line: found, ch: span.to}; phrebejk@460: } phrebejk@460: } phrebejk@460: if (this.type == "bookmark") return from; phrebejk@460: return from && {from: from, to: to}; phrebejk@460: }; phrebejk@460: phrebejk@460: function markText(cm, from, to, options, type) { phrebejk@460: var doc = cm.view.doc; phrebejk@460: var marker = new TextMarker(cm, type); phrebejk@460: if (type == "range" && !posLess(from, to)) return marker; phrebejk@460: if (options) for (var opt in options) if (options.hasOwnProperty(opt)) phrebejk@460: marker[opt] = options[opt]; phrebejk@460: if (marker.replacedWith) { phrebejk@460: marker.collapsed = true; phrebejk@460: marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget"); phrebejk@460: } phrebejk@460: if (marker.collapsed) sawCollapsedSpans = true; phrebejk@460: phrebejk@460: var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd; phrebejk@460: doc.iter(curLine, to.line + 1, function(line) { phrebejk@460: var span = {from: null, to: null, marker: marker}; phrebejk@460: size += line.text.length; phrebejk@460: if (curLine == from.line) {span.from = from.ch; size -= from.ch;} phrebejk@460: if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;} phrebejk@460: if (marker.collapsed) { phrebejk@460: if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch); phrebejk@460: if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch); phrebejk@460: else updateLineHeight(line, 0); phrebejk@460: } phrebejk@460: addMarkedSpan(line, span); phrebejk@460: if (marker.collapsed && curLine == from.line && lineIsHidden(line)) phrebejk@460: updateLineHeight(line, 0); phrebejk@460: ++curLine; phrebejk@460: }); phrebejk@460: phrebejk@460: if (marker.readOnly) { phrebejk@460: sawReadOnlySpans = true; phrebejk@460: if (cm.view.history.done.length || cm.view.history.undone.length) phrebejk@460: cm.clearHistory(); phrebejk@460: } phrebejk@460: if (marker.collapsed) { phrebejk@460: if (collapsedAtStart != collapsedAtEnd) phrebejk@460: throw new Error("Inserting collapsed marker overlapping an existing one"); phrebejk@460: marker.size = size; phrebejk@460: marker.atomic = true; phrebejk@460: } phrebejk@460: if (marker.className || marker.startStyle || marker.endStyle || marker.collapsed) phrebejk@460: regChange(cm, from.line, to.line + 1); phrebejk@460: if (marker.atomic) reCheckSelection(cm); phrebejk@460: return marker; phrebejk@460: } phrebejk@460: phrebejk@460: // TEXTMARKER SPANS phrebejk@460: phrebejk@460: function getMarkedSpanFor(spans, marker) { phrebejk@460: if (spans) for (var i = 0; i < spans.length; ++i) { phrebejk@460: var span = spans[i]; phrebejk@460: if (span.marker == marker) return span; phrebejk@460: } phrebejk@460: } phrebejk@460: function removeMarkedSpan(spans, span) { phrebejk@460: for (var r, i = 0; i < spans.length; ++i) phrebejk@460: if (spans[i] != span) (r || (r = [])).push(spans[i]); phrebejk@460: return r; phrebejk@460: } phrebejk@460: function addMarkedSpan(line, span) { phrebejk@460: line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; phrebejk@460: span.marker.lines.push(line); phrebejk@460: } phrebejk@460: phrebejk@460: function markedSpansBefore(old, startCh) { phrebejk@460: if (old) for (var i = 0, nw; i < old.length; ++i) { phrebejk@460: var span = old[i], marker = span.marker; phrebejk@460: var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); phrebejk@460: if (startsBefore || marker.type == "bookmark" && span.from == startCh) { phrebejk@460: var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); phrebejk@460: (nw || (nw = [])).push({from: span.from, phrebejk@460: to: endsAfter ? null : span.to, phrebejk@460: marker: marker}); phrebejk@460: } phrebejk@460: } phrebejk@460: return nw; phrebejk@460: } phrebejk@460: phrebejk@460: function markedSpansAfter(old, startCh, endCh) { phrebejk@460: if (old) for (var i = 0, nw; i < old.length; ++i) { phrebejk@460: var span = old[i], marker = span.marker; phrebejk@460: var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); phrebejk@460: if (endsAfter || marker.type == "bookmark" && span.from == endCh && span.from != startCh) { phrebejk@460: var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); phrebejk@460: (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh, phrebejk@460: to: span.to == null ? null : span.to - endCh, phrebejk@460: marker: marker}); phrebejk@460: } phrebejk@460: } phrebejk@460: return nw; phrebejk@460: } phrebejk@460: phrebejk@460: function updateMarkedSpans(oldFirst, oldLast, startCh, endCh, newText) { phrebejk@460: if (!oldFirst && !oldLast) return newText; phrebejk@460: // Get the spans that 'stick out' on both sides phrebejk@460: var first = markedSpansBefore(oldFirst, startCh); phrebejk@460: var last = markedSpansAfter(oldLast, startCh, endCh); phrebejk@460: phrebejk@460: // Next, merge those two ends phrebejk@460: var sameLine = newText.length == 1, offset = lst(newText).length + (sameLine ? startCh : 0); phrebejk@460: if (first) { phrebejk@460: // Fix up .to properties of first phrebejk@460: for (var i = 0; i < first.length; ++i) { phrebejk@460: var span = first[i]; phrebejk@460: if (span.to == null) { phrebejk@460: var found = getMarkedSpanFor(last, span.marker); phrebejk@460: if (!found) span.to = startCh; phrebejk@460: else if (sameLine) span.to = found.to == null ? null : found.to + offset; phrebejk@460: } phrebejk@460: } phrebejk@460: } phrebejk@460: if (last) { phrebejk@460: // Fix up .from in last (or move them into first in case of sameLine) phrebejk@460: for (var i = 0; i < last.length; ++i) { phrebejk@460: var span = last[i]; phrebejk@460: if (span.to != null) span.to += offset; phrebejk@460: if (span.from == null) { phrebejk@460: var found = getMarkedSpanFor(first, span.marker); phrebejk@460: if (!found) { phrebejk@460: span.from = offset; phrebejk@460: if (sameLine) (first || (first = [])).push(span); phrebejk@460: } phrebejk@460: } else { phrebejk@460: span.from += offset; phrebejk@460: if (sameLine) (first || (first = [])).push(span); phrebejk@460: } phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: var newMarkers = [newHL(newText[0], first)]; phrebejk@460: if (!sameLine) { phrebejk@460: // Fill gap with whole-line-spans phrebejk@460: var gap = newText.length - 2, gapMarkers; phrebejk@460: if (gap > 0 && first) phrebejk@460: for (var i = 0; i < first.length; ++i) phrebejk@460: if (first[i].to == null) phrebejk@460: (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker}); phrebejk@460: for (var i = 0; i < gap; ++i) phrebejk@460: newMarkers.push(newHL(newText[i+1], gapMarkers)); phrebejk@460: newMarkers.push(newHL(lst(newText), last)); phrebejk@460: } phrebejk@460: return newMarkers; phrebejk@460: } phrebejk@460: phrebejk@460: function removeReadOnlyRanges(doc, from, to) { phrebejk@460: var markers = null; phrebejk@460: doc.iter(from.line, to.line + 1, function(line) { phrebejk@460: if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { phrebejk@460: var mark = line.markedSpans[i].marker; phrebejk@460: if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) phrebejk@460: (markers || (markers = [])).push(mark); phrebejk@460: } phrebejk@460: }); phrebejk@460: if (!markers) return null; phrebejk@460: var parts = [{from: from, to: to}]; phrebejk@460: for (var i = 0; i < markers.length; ++i) { phrebejk@460: var m = markers[i].find(); phrebejk@460: for (var j = 0; j < parts.length; ++j) { phrebejk@460: var p = parts[j]; phrebejk@460: if (!posLess(m.from, p.to) || posLess(m.to, p.from)) continue; phrebejk@460: var newParts = [j, 1]; phrebejk@460: if (posLess(p.from, m.from)) newParts.push({from: p.from, to: m.from}); phrebejk@460: if (posLess(m.to, p.to)) newParts.push({from: m.to, to: p.to}); phrebejk@460: parts.splice.apply(parts, newParts); phrebejk@460: j += newParts.length - 1; phrebejk@460: } phrebejk@460: } phrebejk@460: return parts; phrebejk@460: } phrebejk@460: phrebejk@460: function collapsedSpanAt(line, ch) { phrebejk@460: var sps = sawCollapsedSpans && line.markedSpans, found; phrebejk@460: if (sps) for (var sp, i = 0; i < sps.length; ++i) { phrebejk@460: sp = sps[i]; phrebejk@460: if (!sp.marker.collapsed) continue; phrebejk@460: if ((sp.from == null || sp.from < ch) && phrebejk@460: (sp.to == null || sp.to > ch) && phrebejk@460: (!found || found.width < sp.marker.width)) phrebejk@460: found = sp.marker; phrebejk@460: } phrebejk@460: return found; phrebejk@460: } phrebejk@460: function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); } phrebejk@460: function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); } phrebejk@460: phrebejk@460: function visualLine(doc, line) { phrebejk@460: var merged; phrebejk@460: while (merged = collapsedSpanAtStart(line)) phrebejk@460: line = getLine(doc, merged.find().from.line); phrebejk@460: return line; phrebejk@460: } phrebejk@460: phrebejk@460: function lineIsHidden(line) { phrebejk@460: var sps = sawCollapsedSpans && line.markedSpans; phrebejk@460: if (sps) for (var sp, i = 0; i < sps.length; ++i) { phrebejk@460: sp = sps[i]; phrebejk@460: if (!sp.marker.collapsed) continue; phrebejk@460: if (sp.from == null) return true; phrebejk@460: if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(line, sp)) phrebejk@460: return true; phrebejk@460: } phrebejk@460: } phrebejk@460: window.lineIsHidden = lineIsHidden; phrebejk@460: function lineIsHiddenInner(line, span) { phrebejk@460: if (span.to == null || span.marker.inclusiveRight && span.to == line.text.length) phrebejk@460: return true; phrebejk@460: for (var sp, i = 0; i < line.markedSpans.length; ++i) { phrebejk@460: sp = line.markedSpans[i]; phrebejk@460: if (sp.marker.collapsed && sp.from == span.to && phrebejk@460: (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && phrebejk@460: lineIsHiddenInner(line, sp)) return true; phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: // hl stands for history-line, a data structure that can be either a phrebejk@460: // string (line without markers) or a {text, markedSpans} object. phrebejk@460: function hlText(val) { return typeof val == "string" ? val : val.text; } phrebejk@460: function hlSpans(val) { phrebejk@460: if (typeof val == "string") return null; phrebejk@460: var spans = val.markedSpans, out = null; phrebejk@460: for (var i = 0; i < spans.length; ++i) { phrebejk@460: if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } phrebejk@460: else if (out) out.push(spans[i]); phrebejk@460: } phrebejk@460: return !out ? spans : out.length ? out : null; phrebejk@460: } phrebejk@460: function newHL(text, spans) { return spans ? {text: text, markedSpans: spans} : text; } phrebejk@460: phrebejk@460: function detachMarkedSpans(line) { phrebejk@460: var spans = line.markedSpans; phrebejk@460: if (!spans) return; phrebejk@460: for (var i = 0; i < spans.length; ++i) { phrebejk@460: var lines = spans[i].marker.lines; phrebejk@460: var ix = indexOf(lines, line); phrebejk@460: lines.splice(ix, 1); phrebejk@460: } phrebejk@460: line.markedSpans = null; phrebejk@460: } phrebejk@460: phrebejk@460: function attachMarkedSpans(line, spans) { phrebejk@460: if (!spans) return; phrebejk@460: for (var i = 0; i < spans.length; ++i) phrebejk@460: spans[i].marker.lines.push(line); phrebejk@460: line.markedSpans = spans; phrebejk@460: } phrebejk@460: phrebejk@460: // LINE DATA STRUCTURE phrebejk@460: phrebejk@460: // Line objects. These hold state related to a line, including phrebejk@460: // highlighting info (the styles array). phrebejk@460: function makeLine(text, markedSpans, height) { phrebejk@460: var line = {text: text, height: height}; phrebejk@460: attachMarkedSpans(line, markedSpans); phrebejk@460: if (lineIsHidden(line)) line.height = 0; phrebejk@460: return line; phrebejk@460: } phrebejk@460: phrebejk@460: function updateLine(cm, line, text, markedSpans) { phrebejk@460: line.text = text; phrebejk@460: line.stateAfter = line.styles = null; phrebejk@460: if (line.order != null) line.order = null; phrebejk@460: detachMarkedSpans(line); phrebejk@460: attachMarkedSpans(line, markedSpans); phrebejk@460: if (lineIsHidden(line)) line.height = 0; phrebejk@460: else if (!line.height) line.height = textHeight(cm.display); phrebejk@460: signalLater(cm, line, "change"); phrebejk@460: } phrebejk@460: phrebejk@460: function cleanUpLine(line) { phrebejk@460: line.parent = null; phrebejk@460: detachMarkedSpans(line); phrebejk@460: } phrebejk@460: phrebejk@460: // Run the given mode's parser over a line, update the styles phrebejk@460: // array, which contains alternating fragments of text and CSS phrebejk@460: // classes. phrebejk@460: function highlightLine(cm, line, state) { phrebejk@460: var mode = cm.view.mode, flattenSpans = cm.options.flattenSpans; phrebejk@460: var changed = !line.styles, pos = 0, curText = "", curStyle = null; phrebejk@460: var stream = new StringStream(line.text, cm.options.tabSize), st = line.styles || (line.styles = []); phrebejk@460: if (line.text == "" && mode.blankLine) mode.blankLine(state); phrebejk@460: while (!stream.eol()) { phrebejk@460: var style = mode.token(stream, state), substr = stream.current(); phrebejk@460: stream.start = stream.pos; phrebejk@460: if (!flattenSpans || curStyle != style) { phrebejk@460: if (curText) { phrebejk@460: changed = changed || pos >= st.length || curText != st[pos] || curStyle != st[pos+1]; phrebejk@460: st[pos++] = curText; st[pos++] = curStyle; phrebejk@460: } phrebejk@460: curText = substr; curStyle = style; phrebejk@460: } else curText = curText + substr; phrebejk@460: // Give up when line is ridiculously long phrebejk@460: if (stream.pos > 5000) break; phrebejk@460: } phrebejk@460: if (curText) { phrebejk@460: changed = changed || pos >= st.length || curText != st[pos] || curStyle != st[pos+1]; phrebejk@460: st[pos++] = curText; st[pos++] = curStyle; phrebejk@460: } phrebejk@460: if (stream.pos > 5000) { st[pos++] = line.text.slice(stream.pos); st[pos++] = null; } phrebejk@460: if (pos != st.length) { st.length = pos; changed = true; } phrebejk@460: return changed; phrebejk@460: } phrebejk@460: phrebejk@460: // Lightweight form of highlight -- proceed over this line and phrebejk@460: // update state, but don't save a style array. phrebejk@460: function processLine(cm, line, state) { phrebejk@460: var mode = cm.view.mode; phrebejk@460: var stream = new StringStream(line.text, cm.options.tabSize); phrebejk@460: if (line.text == "" && mode.blankLine) mode.blankLine(state); phrebejk@460: while (!stream.eol() && stream.pos <= 5000) { phrebejk@460: mode.token(stream, state); phrebejk@460: stream.start = stream.pos; phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: var styleToClassCache = {}; phrebejk@460: function styleToClass(style) { phrebejk@460: if (!style) return null; phrebejk@460: return styleToClassCache[style] || phrebejk@460: (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-")); phrebejk@460: } phrebejk@460: phrebejk@460: function lineContent(cm, realLine, measure) { phrebejk@460: var merged, line = realLine, lineBefore, sawBefore, simple = true; phrebejk@460: while (merged = collapsedSpanAtStart(line)) { phrebejk@460: simple = false; phrebejk@460: line = getLine(cm.view.doc, merged.find().from.line); phrebejk@460: if (!lineBefore) lineBefore = line; phrebejk@460: } phrebejk@460: phrebejk@460: var builder = {pre: elt("pre"), col: 0, pos: 0, display: !measure, phrebejk@460: measure: null, addedOne: false, cm: cm}; phrebejk@460: if (line.textClass) builder.pre.className = line.textClass; phrebejk@460: phrebejk@460: do { phrebejk@460: if (!line.styles) phrebejk@460: highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line))); phrebejk@460: builder.measure = line == realLine && measure; phrebejk@460: builder.pos = 0; phrebejk@460: builder.addToken = builder.measure ? buildTokenMeasure : buildToken; phrebejk@460: if (measure && sawBefore && line != realLine && !builder.addedOne) { phrebejk@460: measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure)); phrebejk@460: builder.addedOne = true; phrebejk@460: } phrebejk@460: var next = insertLineContent(line, builder); phrebejk@460: sawBefore = line == lineBefore; phrebejk@460: if (next) { phrebejk@460: line = getLine(cm.view.doc, next.to.line); phrebejk@460: simple = false; phrebejk@460: } phrebejk@460: } while (next); phrebejk@460: phrebejk@460: if (measure && !builder.addedOne) phrebejk@460: measure[0] = builder.pre.appendChild(simple ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure)); phrebejk@460: if (!builder.pre.firstChild && !lineIsHidden(realLine)) phrebejk@460: builder.pre.appendChild(document.createTextNode("\u00a0")); phrebejk@460: phrebejk@460: return builder.pre; phrebejk@460: } phrebejk@460: phrebejk@460: var tokenSpecialChars = /[\t\u0000-\u0019\u200b\u2028\u2029\uFEFF]/g; phrebejk@460: function buildToken(builder, text, style, startStyle, endStyle) { phrebejk@460: if (!text) return; phrebejk@460: if (!tokenSpecialChars.test(text)) { phrebejk@460: builder.col += text.length; phrebejk@460: var content = document.createTextNode(text); phrebejk@460: } else { phrebejk@460: var content = document.createDocumentFragment(), pos = 0; phrebejk@460: while (true) { phrebejk@460: tokenSpecialChars.lastIndex = pos; phrebejk@460: var m = tokenSpecialChars.exec(text); phrebejk@460: var skipped = m ? m.index - pos : text.length - pos; phrebejk@460: if (skipped) { phrebejk@460: content.appendChild(document.createTextNode(text.slice(pos, pos + skipped))); phrebejk@460: builder.col += skipped; phrebejk@460: } phrebejk@460: if (!m) break; phrebejk@460: pos += skipped + 1; phrebejk@460: if (m[0] == "\t") { phrebejk@460: var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; phrebejk@460: content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); phrebejk@460: builder.col += tabWidth; phrebejk@460: } else { phrebejk@460: var token = elt("span", "\u2022", "cm-invalidchar"); phrebejk@460: token.title = "\\u" + m[0].charCodeAt(0).toString(16); phrebejk@460: content.appendChild(token); phrebejk@460: builder.col += 1; phrebejk@460: } phrebejk@460: } phrebejk@460: } phrebejk@460: if (style || startStyle || endStyle || builder.measure) { phrebejk@460: var fullStyle = style || ""; phrebejk@460: if (startStyle) fullStyle += startStyle; phrebejk@460: if (endStyle) fullStyle += endStyle; phrebejk@460: return builder.pre.appendChild(elt("span", [content], fullStyle)); phrebejk@460: } phrebejk@460: builder.pre.appendChild(content); phrebejk@460: } phrebejk@460: phrebejk@460: function buildTokenMeasure(builder, text, style, startStyle, endStyle) { phrebejk@460: for (var i = 0; i < text.length; ++i) { phrebejk@460: if (i && i < text.length - 1 && phrebejk@460: builder.cm.options.lineWrapping && phrebejk@460: spanAffectsWrapping.test(text.slice(i - 1, i + 1))) phrebejk@460: builder.pre.appendChild(elt("wbr")); phrebejk@460: builder.measure[builder.pos++] = phrebejk@460: buildToken(builder, text.charAt(i), style, phrebejk@460: i == 0 && startStyle, i == text.length - 1 && endStyle); phrebejk@460: } phrebejk@460: if (text.length) builder.addedOne = true; phrebejk@460: } phrebejk@460: phrebejk@460: function buildCollapsedSpan(builder, size, widget) { phrebejk@460: if (widget) { phrebejk@460: if (!builder.display) widget = widget.cloneNode(true); phrebejk@460: builder.pre.appendChild(widget); phrebejk@460: if (builder.measure && size) { phrebejk@460: builder.measure[builder.pos] = widget; phrebejk@460: builder.addedOne = true; phrebejk@460: } phrebejk@460: } phrebejk@460: builder.pos += size; phrebejk@460: } phrebejk@460: phrebejk@460: // Outputs a number of spans to make up a line, taking highlighting phrebejk@460: // and marked text into account. phrebejk@460: function insertLineContent(line, builder) { phrebejk@460: var st = line.styles, spans = line.markedSpans; phrebejk@460: if (!spans) { phrebejk@460: for (var i = 0; i < st.length; i+=2) phrebejk@460: builder.addToken(builder, st[i], styleToClass(st[i+1])); phrebejk@460: return; phrebejk@460: } phrebejk@460: phrebejk@460: var allText = line.text, len = allText.length; phrebejk@460: var pos = 0, i = 0, text = "", style; phrebejk@460: var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed; phrebejk@460: for (;;) { phrebejk@460: if (nextChange == pos) { // Update current marker set phrebejk@460: spanStyle = spanEndStyle = spanStartStyle = ""; phrebejk@460: collapsed = null; nextChange = Infinity; phrebejk@460: var foundBookmark = null; phrebejk@460: for (var j = 0; j < spans.length; ++j) { phrebejk@460: var sp = spans[j], m = sp.marker; phrebejk@460: if (sp.from <= pos && (sp.to == null || sp.to > pos)) { phrebejk@460: if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; } phrebejk@460: if (m.className) spanStyle += " " + m.className; phrebejk@460: if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; phrebejk@460: if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; phrebejk@460: if (m.collapsed && (!collapsed || collapsed.marker.width < m.width)) phrebejk@460: collapsed = sp; phrebejk@460: } else if (sp.from > pos && nextChange > sp.from) { phrebejk@460: nextChange = sp.from; phrebejk@460: } phrebejk@460: if (m.type == "bookmark" && sp.from == pos && m.replacedWith) phrebejk@460: foundBookmark = m.replacedWith; phrebejk@460: } phrebejk@460: if (collapsed && (collapsed.from || 0) == pos) { phrebejk@460: buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos, phrebejk@460: collapsed.from != null && collapsed.marker.replacedWith); phrebejk@460: if (collapsed.to == null) return collapsed.marker.find(); phrebejk@460: } phrebejk@460: if (foundBookmark && !collapsed) buildCollapsedSpan(builder, 0, foundBookmark); phrebejk@460: } phrebejk@460: if (pos >= len) break; phrebejk@460: phrebejk@460: var upto = Math.min(len, nextChange); phrebejk@460: while (true) { phrebejk@460: if (text) { phrebejk@460: var end = pos + text.length; phrebejk@460: if (!collapsed) { phrebejk@460: var tokenText = end > upto ? text.slice(0, upto - pos) : text; phrebejk@460: builder.addToken(builder, tokenText, style + spanStyle, phrebejk@460: spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : ""); phrebejk@460: } phrebejk@460: if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} phrebejk@460: pos = end; phrebejk@460: spanStartStyle = ""; phrebejk@460: } phrebejk@460: text = st[i++]; style = styleToClass(st[i++]); phrebejk@460: } phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: // DOCUMENT DATA STRUCTURE phrebejk@460: phrebejk@460: function LeafChunk(lines) { phrebejk@460: this.lines = lines; phrebejk@460: this.parent = null; phrebejk@460: for (var i = 0, e = lines.length, height = 0; i < e; ++i) { phrebejk@460: lines[i].parent = this; phrebejk@460: height += lines[i].height; phrebejk@460: } phrebejk@460: this.height = height; phrebejk@460: } phrebejk@460: phrebejk@460: LeafChunk.prototype = { phrebejk@460: chunkSize: function() { return this.lines.length; }, phrebejk@460: remove: function(at, n, cm) { phrebejk@460: for (var i = at, e = at + n; i < e; ++i) { phrebejk@460: var line = this.lines[i]; phrebejk@460: this.height -= line.height; phrebejk@460: cleanUpLine(line); phrebejk@460: signalLater(cm, line, "delete"); phrebejk@460: } phrebejk@460: this.lines.splice(at, n); phrebejk@460: }, phrebejk@460: collapse: function(lines) { phrebejk@460: lines.splice.apply(lines, [lines.length, 0].concat(this.lines)); phrebejk@460: }, phrebejk@460: insertHeight: function(at, lines, height) { phrebejk@460: this.height += height; phrebejk@460: this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); phrebejk@460: for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this; phrebejk@460: }, phrebejk@460: iterN: function(at, n, op) { phrebejk@460: for (var e = at + n; at < e; ++at) phrebejk@460: if (op(this.lines[at])) return true; phrebejk@460: } phrebejk@460: }; phrebejk@460: phrebejk@460: function BranchChunk(children) { phrebejk@460: this.children = children; phrebejk@460: var size = 0, height = 0; phrebejk@460: for (var i = 0, e = children.length; i < e; ++i) { phrebejk@460: var ch = children[i]; phrebejk@460: size += ch.chunkSize(); height += ch.height; phrebejk@460: ch.parent = this; phrebejk@460: } phrebejk@460: this.size = size; phrebejk@460: this.height = height; phrebejk@460: this.parent = null; phrebejk@460: } phrebejk@460: phrebejk@460: BranchChunk.prototype = { phrebejk@460: chunkSize: function() { return this.size; }, phrebejk@460: remove: function(at, n, callbacks) { phrebejk@460: this.size -= n; phrebejk@460: for (var i = 0; i < this.children.length; ++i) { phrebejk@460: var child = this.children[i], sz = child.chunkSize(); phrebejk@460: if (at < sz) { phrebejk@460: var rm = Math.min(n, sz - at), oldHeight = child.height; phrebejk@460: child.remove(at, rm, callbacks); phrebejk@460: this.height -= oldHeight - child.height; phrebejk@460: if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } phrebejk@460: if ((n -= rm) == 0) break; phrebejk@460: at = 0; phrebejk@460: } else at -= sz; phrebejk@460: } phrebejk@460: if (this.size - n < 25) { phrebejk@460: var lines = []; phrebejk@460: this.collapse(lines); phrebejk@460: this.children = [new LeafChunk(lines)]; phrebejk@460: this.children[0].parent = this; phrebejk@460: } phrebejk@460: }, phrebejk@460: collapse: function(lines) { phrebejk@460: for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines); phrebejk@460: }, phrebejk@460: insert: function(at, lines) { phrebejk@460: var height = 0; phrebejk@460: for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height; phrebejk@460: this.insertHeight(at, lines, height); phrebejk@460: }, phrebejk@460: insertHeight: function(at, lines, height) { phrebejk@460: this.size += lines.length; phrebejk@460: this.height += height; phrebejk@460: for (var i = 0, e = this.children.length; i < e; ++i) { phrebejk@460: var child = this.children[i], sz = child.chunkSize(); phrebejk@460: if (at <= sz) { phrebejk@460: child.insertHeight(at, lines, height); phrebejk@460: if (child.lines && child.lines.length > 50) { phrebejk@460: while (child.lines.length > 50) { phrebejk@460: var spilled = child.lines.splice(child.lines.length - 25, 25); phrebejk@460: var newleaf = new LeafChunk(spilled); phrebejk@460: child.height -= newleaf.height; phrebejk@460: this.children.splice(i + 1, 0, newleaf); phrebejk@460: newleaf.parent = this; phrebejk@460: } phrebejk@460: this.maybeSpill(); phrebejk@460: } phrebejk@460: break; phrebejk@460: } phrebejk@460: at -= sz; phrebejk@460: } phrebejk@460: }, phrebejk@460: maybeSpill: function() { phrebejk@460: if (this.children.length <= 10) return; phrebejk@460: var me = this; phrebejk@460: do { phrebejk@460: var spilled = me.children.splice(me.children.length - 5, 5); phrebejk@460: var sibling = new BranchChunk(spilled); phrebejk@460: if (!me.parent) { // Become the parent node phrebejk@460: var copy = new BranchChunk(me.children); phrebejk@460: copy.parent = me; phrebejk@460: me.children = [copy, sibling]; phrebejk@460: me = copy; phrebejk@460: } else { phrebejk@460: me.size -= sibling.size; phrebejk@460: me.height -= sibling.height; phrebejk@460: var myIndex = indexOf(me.parent.children, me); phrebejk@460: me.parent.children.splice(myIndex + 1, 0, sibling); phrebejk@460: } phrebejk@460: sibling.parent = me.parent; phrebejk@460: } while (me.children.length > 10); phrebejk@460: me.parent.maybeSpill(); phrebejk@460: }, phrebejk@460: iter: function(from, to, op) { this.iterN(from, to - from, op); }, phrebejk@460: iterN: function(at, n, op) { phrebejk@460: for (var i = 0, e = this.children.length; i < e; ++i) { phrebejk@460: var child = this.children[i], sz = child.chunkSize(); phrebejk@460: if (at < sz) { phrebejk@460: var used = Math.min(n, sz - at); phrebejk@460: if (child.iterN(at, used, op)) return true; phrebejk@460: if ((n -= used) == 0) break; phrebejk@460: at = 0; phrebejk@460: } else at -= sz; phrebejk@460: } phrebejk@460: } phrebejk@460: }; phrebejk@460: phrebejk@460: // LINE UTILITIES phrebejk@460: phrebejk@460: function getLine(chunk, n) { phrebejk@460: while (!chunk.lines) { phrebejk@460: for (var i = 0;; ++i) { phrebejk@460: var child = chunk.children[i], sz = child.chunkSize(); phrebejk@460: if (n < sz) { chunk = child; break; } phrebejk@460: n -= sz; phrebejk@460: } phrebejk@460: } phrebejk@460: return chunk.lines[n]; phrebejk@460: } phrebejk@460: phrebejk@460: function updateLineHeight(line, height) { phrebejk@460: var diff = height - line.height; phrebejk@460: for (var n = line; n; n = n.parent) n.height += diff; phrebejk@460: } phrebejk@460: phrebejk@460: function lineNo(line) { phrebejk@460: if (line.parent == null) return null; phrebejk@460: var cur = line.parent, no = indexOf(cur.lines, line); phrebejk@460: for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { phrebejk@460: for (var i = 0;; ++i) { phrebejk@460: if (chunk.children[i] == cur) break; phrebejk@460: no += chunk.children[i].chunkSize(); phrebejk@460: } phrebejk@460: } phrebejk@460: return no; phrebejk@460: } phrebejk@460: phrebejk@460: function lineAtHeight(chunk, h) { phrebejk@460: var n = 0; phrebejk@460: outer: do { phrebejk@460: for (var i = 0, e = chunk.children.length; i < e; ++i) { phrebejk@460: var child = chunk.children[i], ch = child.height; phrebejk@460: if (h < ch) { chunk = child; continue outer; } phrebejk@460: h -= ch; phrebejk@460: n += child.chunkSize(); phrebejk@460: } phrebejk@460: return n; phrebejk@460: } while (!chunk.lines); phrebejk@460: for (var i = 0, e = chunk.lines.length; i < e; ++i) { phrebejk@460: var line = chunk.lines[i], lh = line.height; phrebejk@460: if (h < lh) break; phrebejk@460: h -= lh; phrebejk@460: } phrebejk@460: return n + i; phrebejk@460: } phrebejk@460: phrebejk@460: function heightAtLine(cm, lineObj) { phrebejk@460: lineObj = visualLine(cm.view.doc, lineObj); phrebejk@460: phrebejk@460: var h = 0, chunk = lineObj.parent; phrebejk@460: for (var i = 0; i < chunk.lines.length; ++i) { phrebejk@460: var line = chunk.lines[i]; phrebejk@460: if (line == lineObj) break; phrebejk@460: else h += line.height; phrebejk@460: } phrebejk@460: for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { phrebejk@460: for (var i = 0; i < p.children.length; ++i) { phrebejk@460: var cur = p.children[i]; phrebejk@460: if (cur == chunk) break; phrebejk@460: else h += cur.height; phrebejk@460: } phrebejk@460: } phrebejk@460: return h; phrebejk@460: } phrebejk@460: phrebejk@460: function getOrder(line) { phrebejk@460: var order = line.order; phrebejk@460: if (order == null) order = line.order = bidiOrdering(line.text); phrebejk@460: return order; phrebejk@460: } phrebejk@460: phrebejk@460: // HISTORY phrebejk@460: phrebejk@460: function makeHistory() { phrebejk@460: return { phrebejk@460: // Arrays of history events. Doing something adds an event to phrebejk@460: // done and clears undo. Undoing moves events from done to phrebejk@460: // undone, redoing moves them in the other direction. phrebejk@460: done: [], undone: [], phrebejk@460: // Used to track when changes can be merged into a single undo phrebejk@460: // event phrebejk@460: lastTime: 0, lastOp: null, lastOrigin: null, phrebejk@460: // Used by the isClean() method phrebejk@460: dirtyCounter: 0 phrebejk@460: }; phrebejk@460: } phrebejk@460: phrebejk@460: function addChange(cm, start, added, old, origin, fromBefore, toBefore, fromAfter, toAfter) { phrebejk@460: var history = cm.view.history; phrebejk@460: history.undone.length = 0; phrebejk@460: var time = +new Date, cur = lst(history.done); phrebejk@460: phrebejk@460: if (cur && phrebejk@460: (history.lastOp == cm.curOp.id || phrebejk@460: history.lastOrigin == origin && (origin == "input" || origin == "delete") && phrebejk@460: history.lastTime > time - 600)) { phrebejk@460: // Merge this change into the last event phrebejk@460: var last = lst(cur.events); phrebejk@460: if (last.start > start + old.length || last.start + last.added < start) { phrebejk@460: // Doesn't intersect with last sub-event, add new sub-event phrebejk@460: cur.events.push({start: start, added: added, old: old}); phrebejk@460: } else { phrebejk@460: // Patch up the last sub-event phrebejk@460: var startBefore = Math.max(0, last.start - start), phrebejk@460: endAfter = Math.max(0, (start + old.length) - (last.start + last.added)); phrebejk@460: for (var i = startBefore; i > 0; --i) last.old.unshift(old[i - 1]); phrebejk@460: for (var i = endAfter; i > 0; --i) last.old.push(old[old.length - i]); phrebejk@460: if (startBefore) last.start = start; phrebejk@460: last.added += added - (old.length - startBefore - endAfter); phrebejk@460: } phrebejk@460: cur.fromAfter = fromAfter; cur.toAfter = toAfter; phrebejk@460: } else { phrebejk@460: // Can not be merged, start a new event. phrebejk@460: cur = {events: [{start: start, added: added, old: old}], phrebejk@460: fromBefore: fromBefore, toBefore: toBefore, fromAfter: fromAfter, toAfter: toAfter}; phrebejk@460: history.done.push(cur); phrebejk@460: while (history.done.length > cm.options.undoDepth) phrebejk@460: history.done.shift(); phrebejk@460: if (history.dirtyCounter < 0) phrebejk@460: // The user has made a change after undoing past the last clean state. phrebejk@460: // We can never get back to a clean state now until markClean() is called. phrebejk@460: history.dirtyCounter = NaN; phrebejk@460: else phrebejk@460: history.dirtyCounter++; phrebejk@460: } phrebejk@460: history.lastTime = time; phrebejk@460: history.lastOp = cm.curOp.id; phrebejk@460: history.lastOrigin = origin; phrebejk@460: } phrebejk@460: phrebejk@460: // EVENT OPERATORS phrebejk@460: phrebejk@460: function stopMethod() {e_stop(this);} phrebejk@460: // Ensure an event has a stop method. phrebejk@460: function addStop(event) { phrebejk@460: if (!event.stop) event.stop = stopMethod; phrebejk@460: return event; phrebejk@460: } phrebejk@460: phrebejk@460: function e_preventDefault(e) { phrebejk@460: if (e.preventDefault) e.preventDefault(); phrebejk@460: else e.returnValue = false; phrebejk@460: } phrebejk@460: function e_stopPropagation(e) { phrebejk@460: if (e.stopPropagation) e.stopPropagation(); phrebejk@460: else e.cancelBubble = true; phrebejk@460: } phrebejk@460: function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} phrebejk@460: CodeMirror.e_stop = e_stop; phrebejk@460: CodeMirror.e_preventDefault = e_preventDefault; phrebejk@460: CodeMirror.e_stopPropagation = e_stopPropagation; phrebejk@460: phrebejk@460: function e_target(e) {return e.target || e.srcElement;} phrebejk@460: function e_button(e) { phrebejk@460: var b = e.which; phrebejk@460: if (b == null) { phrebejk@460: if (e.button & 1) b = 1; phrebejk@460: else if (e.button & 2) b = 3; phrebejk@460: else if (e.button & 4) b = 2; phrebejk@460: } phrebejk@460: if (mac && e.ctrlKey && b == 1) b = 3; phrebejk@460: return b; phrebejk@460: } phrebejk@460: phrebejk@460: // Allow 3rd-party code to override event properties by adding an override phrebejk@460: // object to an event object. phrebejk@460: function e_prop(e, prop) { phrebejk@460: var overridden = e.override && e.override.hasOwnProperty(prop); phrebejk@460: return overridden ? e.override[prop] : e[prop]; phrebejk@460: } phrebejk@460: phrebejk@460: // EVENT HANDLING phrebejk@460: phrebejk@460: function on(emitter, type, f) { phrebejk@460: if (emitter.addEventListener) phrebejk@460: emitter.addEventListener(type, f, false); phrebejk@460: else if (emitter.attachEvent) phrebejk@460: emitter.attachEvent("on" + type, f); phrebejk@460: else { phrebejk@460: var map = emitter._handlers || (emitter._handlers = {}); phrebejk@460: var arr = map[type] || (map[type] = []); phrebejk@460: arr.push(f); phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: function off(emitter, type, f) { phrebejk@460: if (emitter.removeEventListener) phrebejk@460: emitter.removeEventListener(type, f, false); phrebejk@460: else if (emitter.detachEvent) phrebejk@460: emitter.detachEvent("on" + type, f); phrebejk@460: else { phrebejk@460: var arr = emitter._handlers && emitter._handlers[type]; phrebejk@460: if (!arr) return; phrebejk@460: for (var i = 0; i < arr.length; ++i) phrebejk@460: if (arr[i] == f) { arr.splice(i, 1); break; } phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: function signal(emitter, type /*, values...*/) { phrebejk@460: var arr = emitter._handlers && emitter._handlers[type]; phrebejk@460: if (!arr) return; phrebejk@460: var args = Array.prototype.slice.call(arguments, 2); phrebejk@460: for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); phrebejk@460: } phrebejk@460: phrebejk@460: function signalLater(cm, emitter, type /*, values...*/) { phrebejk@460: var arr = emitter._handlers && emitter._handlers[type]; phrebejk@460: if (!arr) return; phrebejk@460: var args = Array.prototype.slice.call(arguments, 3), flist = cm.curOp && cm.curOp.delayedCallbacks; phrebejk@460: function bnd(f) {return function(){f.apply(null, args);};}; phrebejk@460: for (var i = 0; i < arr.length; ++i) phrebejk@460: if (flist) flist.push(bnd(arr[i])); phrebejk@460: else arr[i].apply(null, args); phrebejk@460: } phrebejk@460: phrebejk@460: function hasHandler(emitter, type) { phrebejk@460: var arr = emitter._handlers && emitter._handlers[type]; phrebejk@460: return arr && arr.length > 0; phrebejk@460: } phrebejk@460: phrebejk@460: CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal; phrebejk@460: phrebejk@460: // MISC UTILITIES phrebejk@460: phrebejk@460: // Number of pixels added to scroller and sizer to hide scrollbar phrebejk@460: var scrollerCutOff = 30; phrebejk@460: phrebejk@460: // Returned or thrown by various protocols to signal 'I'm not phrebejk@460: // handling this'. phrebejk@460: var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; phrebejk@460: phrebejk@460: function Delayed() {this.id = null;} phrebejk@460: Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}}; phrebejk@460: phrebejk@460: // Counts the column offset in a string, taking tabs into account. phrebejk@460: // Used mostly to find indentation. phrebejk@460: function countColumn(string, end, tabSize) { phrebejk@460: if (end == null) { phrebejk@460: end = string.search(/[^\s\u00a0]/); phrebejk@460: if (end == -1) end = string.length; phrebejk@460: } phrebejk@460: for (var i = 0, n = 0; i < end; ++i) { phrebejk@460: if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); phrebejk@460: else ++n; phrebejk@460: } phrebejk@460: return n; phrebejk@460: } phrebejk@460: CodeMirror.countColumn = countColumn; phrebejk@460: phrebejk@460: var spaceStrs = [""]; phrebejk@460: function spaceStr(n) { phrebejk@460: while (spaceStrs.length <= n) phrebejk@460: spaceStrs.push(lst(spaceStrs) + " "); phrebejk@460: return spaceStrs[n]; phrebejk@460: } phrebejk@460: phrebejk@460: function lst(arr) { return arr[arr.length-1]; } phrebejk@460: phrebejk@460: function selectInput(node) { phrebejk@460: if (ios) { // Mobile Safari apparently has a bug where select() is broken. phrebejk@460: node.selectionStart = 0; phrebejk@460: node.selectionEnd = node.value.length; phrebejk@460: } else node.select(); phrebejk@460: } phrebejk@460: phrebejk@460: function indexOf(collection, elt) { phrebejk@460: if (collection.indexOf) return collection.indexOf(elt); phrebejk@460: for (var i = 0, e = collection.length; i < e; ++i) phrebejk@460: if (collection[i] == elt) return i; phrebejk@460: return -1; phrebejk@460: } phrebejk@460: phrebejk@460: function emptyArray(size) { phrebejk@460: for (var a = [], i = 0; i < size; ++i) a.push(undefined); phrebejk@460: return a; phrebejk@460: } phrebejk@460: phrebejk@460: function bind(f) { phrebejk@460: var args = Array.prototype.slice.call(arguments, 1); phrebejk@460: return function(){return f.apply(null, args);}; phrebejk@460: } phrebejk@460: phrebejk@460: var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc]/; phrebejk@460: function isWordChar(ch) { phrebejk@460: return /\w/.test(ch) || ch > "\x80" && phrebejk@460: (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); phrebejk@460: } phrebejk@460: phrebejk@460: function isEmpty(obj) { phrebejk@460: var c = 0; phrebejk@460: for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) ++c; phrebejk@460: return !c; phrebejk@460: } phrebejk@460: phrebejk@460: var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F]/; phrebejk@460: phrebejk@460: // DOM UTILITIES phrebejk@460: phrebejk@460: function elt(tag, content, className, style) { phrebejk@460: var e = document.createElement(tag); phrebejk@460: if (className) e.className = className; phrebejk@460: if (style) e.style.cssText = style; phrebejk@460: if (typeof content == "string") setTextContent(e, content); phrebejk@460: else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); phrebejk@460: return e; phrebejk@460: } phrebejk@460: phrebejk@460: function removeChildren(e) { phrebejk@460: e.innerHTML = ""; phrebejk@460: return e; phrebejk@460: } phrebejk@460: phrebejk@460: function removeChildrenAndAdd(parent, e) { phrebejk@460: return removeChildren(parent).appendChild(e); phrebejk@460: } phrebejk@460: phrebejk@460: function setTextContent(e, str) { phrebejk@460: if (ie_lt9) { phrebejk@460: e.innerHTML = ""; phrebejk@460: e.appendChild(document.createTextNode(str)); phrebejk@460: } else e.textContent = str; phrebejk@460: } phrebejk@460: phrebejk@460: // FEATURE DETECTION phrebejk@460: phrebejk@460: // Detect drag-and-drop phrebejk@460: var dragAndDrop = function() { phrebejk@460: // There is *some* kind of drag-and-drop support in IE6-8, but I phrebejk@460: // couldn't get it to work yet. phrebejk@460: if (ie_lt9) return false; phrebejk@460: var div = elt('div'); phrebejk@460: return "draggable" in div || "dragDrop" in div; phrebejk@460: }(); phrebejk@460: phrebejk@460: // For a reason I have yet to figure out, some browsers disallow phrebejk@460: // word wrapping between certain characters *only* if a new inline phrebejk@460: // element is started between them. This makes it hard to reliably phrebejk@460: // measure the position of things, since that requires inserting an phrebejk@460: // extra span. This terribly fragile set of regexps matches the phrebejk@460: // character combinations that suffer from this phenomenon on the phrebejk@460: // various browsers. phrebejk@460: var spanAffectsWrapping = /^$/; // Won't match any two-character string phrebejk@460: if (gecko) spanAffectsWrapping = /$'/; phrebejk@460: else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/; phrebejk@460: else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/; phrebejk@460: phrebejk@460: var knownScrollbarWidth; phrebejk@460: function scrollbarWidth(measure) { phrebejk@460: if (knownScrollbarWidth != null) return knownScrollbarWidth; phrebejk@460: var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll"); phrebejk@460: removeChildrenAndAdd(measure, test); phrebejk@460: if (test.offsetWidth) phrebejk@460: knownScrollbarWidth = test.offsetHeight - test.clientHeight; phrebejk@460: return knownScrollbarWidth || 0; phrebejk@460: } phrebejk@460: phrebejk@460: var zwspSupported; phrebejk@460: function zeroWidthElement(measure) { phrebejk@460: if (zwspSupported == null) { phrebejk@460: var test = elt("span", "\u200b"); phrebejk@460: removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); phrebejk@460: if (measure.firstChild.offsetHeight != 0) phrebejk@460: zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_lt8; phrebejk@460: } phrebejk@460: if (zwspSupported) return elt("span", "\u200b"); phrebejk@460: else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); phrebejk@460: } phrebejk@460: phrebejk@460: // See if "".split is the broken IE version, if so, provide an phrebejk@460: // alternative way to split lines. phrebejk@460: var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { phrebejk@460: var pos = 0, result = [], l = string.length; phrebejk@460: while (pos <= l) { phrebejk@460: var nl = string.indexOf("\n", pos); phrebejk@460: if (nl == -1) nl = string.length; phrebejk@460: var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); phrebejk@460: var rt = line.indexOf("\r"); phrebejk@460: if (rt != -1) { phrebejk@460: result.push(line.slice(0, rt)); phrebejk@460: pos += rt + 1; phrebejk@460: } else { phrebejk@460: result.push(line); phrebejk@460: pos = nl + 1; phrebejk@460: } phrebejk@460: } phrebejk@460: return result; phrebejk@460: } : function(string){return string.split(/\r\n?|\n/);}; phrebejk@460: CodeMirror.splitLines = splitLines; phrebejk@460: phrebejk@460: var hasSelection = window.getSelection ? function(te) { phrebejk@460: try { return te.selectionStart != te.selectionEnd; } phrebejk@460: catch(e) { return false; } phrebejk@460: } : function(te) { phrebejk@460: try {var range = te.ownerDocument.selection.createRange();} phrebejk@460: catch(e) {} phrebejk@460: if (!range || range.parentElement() != te) return false; phrebejk@460: return range.compareEndPoints("StartToEnd", range) != 0; phrebejk@460: }; phrebejk@460: phrebejk@460: var hasCopyEvent = (function() { phrebejk@460: var e = elt("div"); phrebejk@460: if ("oncopy" in e) return true; phrebejk@460: e.setAttribute("oncopy", "return;"); phrebejk@460: return typeof e.oncopy == 'function'; phrebejk@460: })(); phrebejk@460: phrebejk@460: // KEY NAMING phrebejk@460: phrebejk@460: var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", phrebejk@460: 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", phrebejk@460: 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", phrebejk@460: 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete", phrebejk@460: 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", phrebejk@460: 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home", phrebejk@460: 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"}; phrebejk@460: CodeMirror.keyNames = keyNames; phrebejk@460: (function() { phrebejk@460: // Number keys phrebejk@460: for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i); phrebejk@460: // Alphabetic keys phrebejk@460: for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); phrebejk@460: // Function keys phrebejk@460: for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; phrebejk@460: })(); phrebejk@460: phrebejk@460: // BIDI HELPERS phrebejk@460: phrebejk@460: function iterateBidiSections(order, from, to, f) { phrebejk@460: if (!order) return f(from, to, "ltr"); phrebejk@460: for (var i = 0; i < order.length; ++i) { phrebejk@460: var part = order[i]; phrebejk@460: if (part.from < to && part.to > from) phrebejk@460: f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } phrebejk@460: function bidiRight(part) { return part.level % 2 ? part.from : part.to; } phrebejk@460: phrebejk@460: function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } phrebejk@460: function lineRight(line) { phrebejk@460: var order = getOrder(line); phrebejk@460: if (!order) return line.text.length; phrebejk@460: return bidiRight(lst(order)); phrebejk@460: } phrebejk@460: phrebejk@460: function lineStart(cm, lineN) { phrebejk@460: var line = getLine(cm.view.doc, lineN); phrebejk@460: var visual = visualLine(cm.view.doc, line); phrebejk@460: if (visual != line) lineN = lineNo(visual); phrebejk@460: var order = getOrder(visual); phrebejk@460: var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); phrebejk@460: return {line: lineN, ch: ch}; phrebejk@460: } phrebejk@460: function lineEnd(cm, lineNo) { phrebejk@460: var merged, line; phrebejk@460: while (merged = collapsedSpanAtEnd(line = getLine(cm.view.doc, lineNo))) phrebejk@460: lineNo = merged.find().to.line; phrebejk@460: var order = getOrder(line); phrebejk@460: var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); phrebejk@460: return {line: lineNo, ch: ch}; phrebejk@460: } phrebejk@460: phrebejk@460: // This is somewhat involved. It is needed in order to move phrebejk@460: // 'visually' through bi-directional text -- i.e., pressing left phrebejk@460: // should make the cursor go left, even when in RTL text. The phrebejk@460: // tricky part is the 'jumps', where RTL and LTR text touch each phrebejk@460: // other. This often requires the cursor offset to move more than phrebejk@460: // one unit, in order to visually move one unit. phrebejk@460: function moveVisually(line, start, dir, byUnit) { phrebejk@460: var bidi = getOrder(line); phrebejk@460: if (!bidi) return moveLogically(line, start, dir, byUnit); phrebejk@460: var moveOneUnit = byUnit ? function(pos, dir) { phrebejk@460: do pos += dir; phrebejk@460: while (pos > 0 && isExtendingChar.test(line.text.charAt(pos))); phrebejk@460: return pos; phrebejk@460: } : function(pos, dir) { return pos + dir; }; phrebejk@460: var linedir = bidi[0].level; phrebejk@460: for (var i = 0; i < bidi.length; ++i) { phrebejk@460: var part = bidi[i], sticky = part.level % 2 == linedir; phrebejk@460: if ((part.from < start && part.to > start) || phrebejk@460: (sticky && (part.from == start || part.to == start))) break; phrebejk@460: } phrebejk@460: var target = moveOneUnit(start, part.level % 2 ? -dir : dir); phrebejk@460: phrebejk@460: while (target != null) { phrebejk@460: if (part.level % 2 == linedir) { phrebejk@460: if (target < part.from || target > part.to) { phrebejk@460: part = bidi[i += dir]; phrebejk@460: target = part && (dir > 0 == part.level % 2 ? moveOneUnit(part.to, -1) : moveOneUnit(part.from, 1)); phrebejk@460: } else break; phrebejk@460: } else { phrebejk@460: if (target == bidiLeft(part)) { phrebejk@460: part = bidi[--i]; phrebejk@460: target = part && bidiRight(part); phrebejk@460: } else if (target == bidiRight(part)) { phrebejk@460: part = bidi[++i]; phrebejk@460: target = part && bidiLeft(part); phrebejk@460: } else break; phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: return target < 0 || target > line.text.length ? null : target; phrebejk@460: } phrebejk@460: phrebejk@460: function moveLogically(line, start, dir, byUnit) { phrebejk@460: var target = start + dir; phrebejk@460: if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir; phrebejk@460: return target < 0 || target > line.text.length ? null : target; phrebejk@460: } phrebejk@460: phrebejk@460: // Bidirectional ordering algorithm phrebejk@460: // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm phrebejk@460: // that this (partially) implements. phrebejk@460: phrebejk@460: // One-char codes used for character types: phrebejk@460: // L (L): Left-to-Right phrebejk@460: // R (R): Right-to-Left phrebejk@460: // r (AL): Right-to-Left Arabic phrebejk@460: // 1 (EN): European Number phrebejk@460: // + (ES): European Number Separator phrebejk@460: // % (ET): European Number Terminator phrebejk@460: // n (AN): Arabic Number phrebejk@460: // , (CS): Common Number Separator phrebejk@460: // m (NSM): Non-Spacing Mark phrebejk@460: // b (BN): Boundary Neutral phrebejk@460: // s (B): Paragraph Separator phrebejk@460: // t (S): Segment Separator phrebejk@460: // w (WS): Whitespace phrebejk@460: // N (ON): Other Neutrals phrebejk@460: phrebejk@460: // Returns null if characters are ordered as they appear phrebejk@460: // (left-to-right), or an array of sections ({from, to, level} phrebejk@460: // objects) in the order in which they occur visually. phrebejk@460: var bidiOrdering = (function() { phrebejk@460: // Character types for codepoints 0 to 0xff phrebejk@460: var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL"; phrebejk@460: // Character types for codepoints 0x600 to 0x6ff phrebejk@460: var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr"; phrebejk@460: function charType(code) { phrebejk@460: if (code <= 0xff) return lowTypes.charAt(code); phrebejk@460: else if (0x590 <= code && code <= 0x5f4) return "R"; phrebejk@460: else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600); phrebejk@460: else if (0x700 <= code && code <= 0x8ac) return "r"; phrebejk@460: else return "L"; phrebejk@460: } phrebejk@460: phrebejk@460: var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; phrebejk@460: var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; phrebejk@460: phrebejk@460: return function charOrdering(str) { phrebejk@460: if (!bidiRE.test(str)) return false; phrebejk@460: var len = str.length, types = [], startType = null; phrebejk@460: for (var i = 0, type; i < len; ++i) { phrebejk@460: types.push(type = charType(str.charCodeAt(i))); phrebejk@460: if (startType == null) { phrebejk@460: if (type == "L") startType = "L"; phrebejk@460: else if (type == "R" || type == "r") startType = "R"; phrebejk@460: } phrebejk@460: } phrebejk@460: if (startType == null) startType = "L"; phrebejk@460: phrebejk@460: // W1. Examine each non-spacing mark (NSM) in the level run, and phrebejk@460: // change the type of the NSM to the type of the previous phrebejk@460: // character. If the NSM is at the start of the level run, it will phrebejk@460: // get the type of sor. phrebejk@460: for (var i = 0, prev = startType; i < len; ++i) { phrebejk@460: var type = types[i]; phrebejk@460: if (type == "m") types[i] = prev; phrebejk@460: else prev = type; phrebejk@460: } phrebejk@460: phrebejk@460: // W2. Search backwards from each instance of a European number phrebejk@460: // until the first strong type (R, L, AL, or sor) is found. If an phrebejk@460: // AL is found, change the type of the European number to Arabic phrebejk@460: // number. phrebejk@460: // W3. Change all ALs to R. phrebejk@460: for (var i = 0, cur = startType; i < len; ++i) { phrebejk@460: var type = types[i]; phrebejk@460: if (type == "1" && cur == "r") types[i] = "n"; phrebejk@460: else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } phrebejk@460: } phrebejk@460: phrebejk@460: // W4. A single European separator between two European numbers phrebejk@460: // changes to a European number. A single common separator between phrebejk@460: // two numbers of the same type changes to that type. phrebejk@460: for (var i = 1, prev = types[0]; i < len - 1; ++i) { phrebejk@460: var type = types[i]; phrebejk@460: if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; phrebejk@460: else if (type == "," && prev == types[i+1] && phrebejk@460: (prev == "1" || prev == "n")) types[i] = prev; phrebejk@460: prev = type; phrebejk@460: } phrebejk@460: phrebejk@460: // W5. A sequence of European terminators adjacent to European phrebejk@460: // numbers changes to all European numbers. phrebejk@460: // W6. Otherwise, separators and terminators change to Other phrebejk@460: // Neutral. phrebejk@460: for (var i = 0; i < len; ++i) { phrebejk@460: var type = types[i]; phrebejk@460: if (type == ",") types[i] = "N"; phrebejk@460: else if (type == "%") { phrebejk@460: for (var end = i + 1; end < len && types[end] == "%"; ++end) {} phrebejk@460: var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N"; phrebejk@460: for (var j = i; j < end; ++j) types[j] = replace; phrebejk@460: i = end - 1; phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: // W7. Search backwards from each instance of a European number phrebejk@460: // until the first strong type (R, L, or sor) is found. If an L is phrebejk@460: // found, then change the type of the European number to L. phrebejk@460: for (var i = 0, cur = startType; i < len; ++i) { phrebejk@460: var type = types[i]; phrebejk@460: if (cur == "L" && type == "1") types[i] = "L"; phrebejk@460: else if (isStrong.test(type)) cur = type; phrebejk@460: } phrebejk@460: phrebejk@460: // N1. A sequence of neutrals takes the direction of the phrebejk@460: // surrounding strong text if the text on both sides has the same phrebejk@460: // direction. European and Arabic numbers act as if they were R in phrebejk@460: // terms of their influence on neutrals. Start-of-level-run (sor) phrebejk@460: // and end-of-level-run (eor) are used at level run boundaries. phrebejk@460: // N2. Any remaining neutrals take the embedding direction. phrebejk@460: for (var i = 0; i < len; ++i) { phrebejk@460: if (isNeutral.test(types[i])) { phrebejk@460: for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} phrebejk@460: var before = (i ? types[i-1] : startType) == "L"; phrebejk@460: var after = (end < len - 1 ? types[end] : startType) == "L"; phrebejk@460: var replace = before || after ? "L" : "R"; phrebejk@460: for (var j = i; j < end; ++j) types[j] = replace; phrebejk@460: i = end - 1; phrebejk@460: } phrebejk@460: } phrebejk@460: phrebejk@460: // Here we depart from the documented algorithm, in order to avoid phrebejk@460: // building up an actual levels array. Since there are only three phrebejk@460: // levels (0, 1, 2) in an implementation that doesn't take phrebejk@460: // explicit embedding into account, we can build up the order on phrebejk@460: // the fly, without following the level-based algorithm. phrebejk@460: var order = [], m; phrebejk@460: for (var i = 0; i < len;) { phrebejk@460: if (countsAsLeft.test(types[i])) { phrebejk@460: var start = i; phrebejk@460: for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} phrebejk@460: order.push({from: start, to: i, level: 0}); phrebejk@460: } else { phrebejk@460: var pos = i, at = order.length; phrebejk@460: for (++i; i < len && types[i] != "L"; ++i) {} phrebejk@460: for (var j = pos; j < i;) { phrebejk@460: if (countsAsNum.test(types[j])) { phrebejk@460: if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1}); phrebejk@460: var nstart = j; phrebejk@460: for (++j; j < i && countsAsNum.test(types[j]); ++j) {} phrebejk@460: order.splice(at, 0, {from: nstart, to: j, level: 2}); phrebejk@460: pos = j; phrebejk@460: } else ++j; phrebejk@460: } phrebejk@460: if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1}); phrebejk@460: } phrebejk@460: } phrebejk@460: if (order[0].level == 1 && (m = str.match(/^\s+/))) { phrebejk@460: order[0].from = m[0].length; phrebejk@460: order.unshift({from: 0, to: m[0].length, level: 0}); phrebejk@460: } phrebejk@460: if (lst(order).level == 1 && (m = str.match(/\s+$/))) { phrebejk@460: lst(order).to -= m[0].length; phrebejk@460: order.push({from: len - m[0].length, to: len, level: 0}); phrebejk@460: } phrebejk@460: if (order[0].level != lst(order).level) phrebejk@460: order.push({from: len, to: len, level: order[0].level}); phrebejk@460: phrebejk@460: return order; phrebejk@460: }; phrebejk@460: })(); phrebejk@460: phrebejk@460: // THE END phrebejk@460: phrebejk@460: CodeMirror.version = "3.0"; phrebejk@460: phrebejk@460: return CodeMirror; phrebejk@460: })();