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