michael@0: // This is CodeMirror (http://codemirror.net), a code editor michael@0: // implemented in JavaScript on top of the browser's DOM. michael@0: // michael@0: // You can find some technical background for some of the code below michael@0: // at http://marijnhaverbeke.nl/blog/#cm-internals . michael@0: michael@0: (function(mod) { michael@0: if (typeof exports == "object" && typeof module == "object") // CommonJS michael@0: module.exports = mod(); michael@0: else if (typeof define == "function" && define.amd) // AMD michael@0: return define([], mod); michael@0: else // Plain browser env michael@0: this.CodeMirror = mod(); michael@0: })(function() { michael@0: "use strict"; michael@0: michael@0: // BROWSER SNIFFING michael@0: michael@0: // Kludges for bugs and behavior differences that can't be feature michael@0: // detected are enabled based on userAgent etc sniffing. michael@0: michael@0: var gecko = /gecko\/\d/i.test(navigator.userAgent); michael@0: // ie_uptoN means Internet Explorer version N or lower michael@0: var ie_upto10 = /MSIE \d/.test(navigator.userAgent); michael@0: var ie_upto7 = ie_upto10 && (document.documentMode == null || document.documentMode < 8); michael@0: var ie_upto8 = ie_upto10 && (document.documentMode == null || document.documentMode < 9); michael@0: var ie_upto9 = ie_upto10 && (document.documentMode == null || document.documentMode < 10); michael@0: var ie_11up = /Trident\/([7-9]|\d{2,})\./.test(navigator.userAgent); michael@0: var ie = ie_upto10 || ie_11up; michael@0: var webkit = /WebKit\//.test(navigator.userAgent); michael@0: var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); michael@0: var chrome = /Chrome\//.test(navigator.userAgent); michael@0: var presto = /Opera\//.test(navigator.userAgent); michael@0: var safari = /Apple Computer/.test(navigator.vendor); michael@0: var khtml = /KHTML\//.test(navigator.userAgent); michael@0: var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent); michael@0: var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent); michael@0: var phantom = /PhantomJS/.test(navigator.userAgent); michael@0: michael@0: var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); michael@0: // This is woefully incomplete. Suggestions for alternative methods welcome. michael@0: var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent); michael@0: var mac = ios || /Mac/.test(navigator.platform); michael@0: var windows = /win/i.test(navigator.platform); michael@0: michael@0: var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/); michael@0: if (presto_version) presto_version = Number(presto_version[1]); michael@0: if (presto_version && presto_version >= 15) { presto = false; webkit = true; } michael@0: // Some browsers use the wrong event properties to signal cmd/ctrl on OS X michael@0: var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); michael@0: var captureRightClick = gecko || (ie && !ie_upto8); michael@0: michael@0: // Optimize some code when these features are not used. michael@0: var sawReadOnlySpans = false, sawCollapsedSpans = false; michael@0: michael@0: // EDITOR CONSTRUCTOR michael@0: michael@0: // A CodeMirror instance represents an editor. This is the object michael@0: // that user code is usually dealing with. michael@0: michael@0: function CodeMirror(place, options) { michael@0: if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); michael@0: michael@0: this.options = options = options || {}; michael@0: // Determine effective options based on given values and defaults. michael@0: for (var opt in defaults) if (!options.hasOwnProperty(opt)) michael@0: options[opt] = defaults[opt]; michael@0: setGuttersForLineNumbers(options); michael@0: michael@0: var doc = options.value; michael@0: if (typeof doc == "string") doc = new Doc(doc, options.mode); michael@0: this.doc = doc; michael@0: michael@0: var display = this.display = new Display(place, doc); michael@0: display.wrapper.CodeMirror = this; michael@0: updateGutters(this); michael@0: themeChanged(this); michael@0: if (options.lineWrapping) michael@0: this.display.wrapper.className += " CodeMirror-wrap"; michael@0: if (options.autofocus && !mobile) focusInput(this); michael@0: michael@0: this.state = { michael@0: keyMaps: [], // stores maps added by addKeyMap michael@0: overlays: [], // highlighting overlays, as added by addOverlay michael@0: modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info michael@0: overwrite: false, focused: false, michael@0: suppressEdits: false, // used to disable editing during key handlers when in readOnly mode michael@0: pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in readInput michael@0: draggingText: false, michael@0: highlight: new Delayed() // stores highlight worker timeout michael@0: }; michael@0: michael@0: // Override magic textarea content restore that IE sometimes does michael@0: // on our hidden textarea on reload michael@0: if (ie_upto10) setTimeout(bind(resetInput, this, true), 20); michael@0: michael@0: registerEventHandlers(this); michael@0: michael@0: var cm = this; michael@0: runInOp(this, function() { michael@0: cm.curOp.forceUpdate = true; michael@0: attachDoc(cm, doc); michael@0: michael@0: if ((options.autofocus && !mobile) || activeElt() == display.input) michael@0: setTimeout(bind(onFocus, cm), 20); michael@0: else michael@0: onBlur(cm); michael@0: michael@0: for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt)) michael@0: optionHandlers[opt](cm, options[opt], Init); michael@0: for (var i = 0; i < initHooks.length; ++i) initHooks[i](cm); michael@0: }); michael@0: } michael@0: michael@0: // DISPLAY CONSTRUCTOR michael@0: michael@0: // The display handles the DOM integration, both for input reading michael@0: // and content drawing. It holds references to DOM nodes and michael@0: // display-related state. michael@0: michael@0: function Display(place, doc) { michael@0: var d = this; michael@0: michael@0: // The semihidden textarea that is focused when the editor is michael@0: // focused, and receives input. michael@0: var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none"); michael@0: // The textarea is kept positioned near the cursor to prevent the michael@0: // fact that it'll be scrolled into view on input from scrolling michael@0: // our fake cursor out of view. On webkit, when wrap=off, paste is michael@0: // very slow. So make the area wide instead. michael@0: if (webkit) input.style.width = "1000px"; michael@0: else input.setAttribute("wrap", "off"); michael@0: // If border: 0; -- iOS fails to open keyboard (issue #1287) michael@0: if (ios) input.style.border = "1px solid black"; michael@0: input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false"); michael@0: michael@0: // Wraps and hides input textarea michael@0: d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); michael@0: // The fake scrollbar elements. michael@0: d.scrollbarH = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); michael@0: d.scrollbarV = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); michael@0: // Covers bottom-right square when both scrollbars are present. michael@0: d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); michael@0: // Covers bottom of gutter when coverGutterNextToScrollbar is on michael@0: // and h scrollbar is present. michael@0: d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); michael@0: // Will contain the actual code, positioned to cover the viewport. michael@0: d.lineDiv = elt("div", null, "CodeMirror-code"); michael@0: // Elements are added to these to represent selection and cursors. michael@0: d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); michael@0: d.cursorDiv = elt("div", null, "CodeMirror-cursors"); michael@0: // A visibility: hidden element used to find the size of things. michael@0: d.measure = elt("div", null, "CodeMirror-measure"); michael@0: // When lines outside of the viewport are measured, they are drawn in this. michael@0: d.lineMeasure = elt("div", null, "CodeMirror-measure"); michael@0: // Wraps everything that needs to exist inside the vertically-padded coordinate system michael@0: d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], michael@0: null, "position: relative; outline: none"); michael@0: // Moved around its parent to cover visible view. michael@0: d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); michael@0: // Set to the height of the document, allowing scrolling. michael@0: d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); michael@0: // Behavior of elts with overflow: auto and padding is michael@0: // inconsistent across browsers. This is used to ensure the michael@0: // scrollable area is big enough. michael@0: d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;"); michael@0: // Will contain the gutters, if any. michael@0: d.gutters = elt("div", null, "CodeMirror-gutters"); michael@0: d.lineGutter = null; michael@0: // Actual scrollable element. michael@0: d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); michael@0: d.scroller.setAttribute("tabIndex", "-1"); michael@0: // The element in which the editor lives. michael@0: d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV, michael@0: d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); michael@0: michael@0: // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) michael@0: if (ie_upto7) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } michael@0: // Needed to hide big blue blinking cursor on Mobile Safari michael@0: if (ios) input.style.width = "0px"; michael@0: if (!webkit) d.scroller.draggable = true; michael@0: // Needed to handle Tab key in KHTML michael@0: if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; } michael@0: // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). michael@0: if (ie_upto7) d.scrollbarH.style.minHeight = d.scrollbarV.style.minWidth = "18px"; michael@0: michael@0: if (place.appendChild) place.appendChild(d.wrapper); michael@0: else place(d.wrapper); michael@0: michael@0: // Current rendered range (may be bigger than the view window). michael@0: d.viewFrom = d.viewTo = doc.first; michael@0: // Information about the rendered lines. michael@0: d.view = []; michael@0: // Holds info about a single rendered line when it was rendered michael@0: // for measurement, while not in view. michael@0: d.externalMeasured = null; michael@0: // Empty space (in pixels) above the view michael@0: d.viewOffset = 0; michael@0: d.lastSizeC = 0; michael@0: d.updateLineNumbers = null; michael@0: michael@0: // Used to only resize the line number gutter when necessary (when michael@0: // the amount of lines crosses a boundary that makes its width change) michael@0: d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; michael@0: // See readInput and resetInput michael@0: d.prevInput = ""; michael@0: // Set to true when a non-horizontal-scrolling line widget is michael@0: // added. As an optimization, line widget aligning is skipped when michael@0: // this is false. michael@0: d.alignWidgets = false; michael@0: // Flag that indicates whether we expect input to appear real soon michael@0: // now (after some event like 'keypress' or 'input') and are michael@0: // polling intensively. michael@0: d.pollingFast = false; michael@0: // Self-resetting timeout for the poller michael@0: d.poll = new Delayed(); michael@0: michael@0: d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; michael@0: michael@0: // Tracks when resetInput has punted to just putting a short michael@0: // string into the textarea instead of the full selection. michael@0: d.inaccurateSelection = false; michael@0: michael@0: // Tracks the maximum line length so that the horizontal scrollbar michael@0: // can be kept static when scrolling. michael@0: d.maxLine = null; michael@0: d.maxLineLength = 0; michael@0: d.maxLineChanged = false; michael@0: michael@0: // Used for measuring wheel scrolling granularity michael@0: d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; michael@0: michael@0: // True when shift is held down. michael@0: d.shift = false; michael@0: } michael@0: michael@0: // STATE UPDATES michael@0: michael@0: // Used to get the editor into a consistent state again when options change. michael@0: michael@0: function loadMode(cm) { michael@0: cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); michael@0: resetModeState(cm); michael@0: } michael@0: michael@0: function resetModeState(cm) { michael@0: cm.doc.iter(function(line) { michael@0: if (line.stateAfter) line.stateAfter = null; michael@0: if (line.styles) line.styles = null; michael@0: }); michael@0: cm.doc.frontier = cm.doc.first; michael@0: startWorker(cm, 100); michael@0: cm.state.modeGen++; michael@0: if (cm.curOp) regChange(cm); michael@0: } michael@0: michael@0: function wrappingChanged(cm) { michael@0: if (cm.options.lineWrapping) { michael@0: cm.display.wrapper.className += " CodeMirror-wrap"; michael@0: cm.display.sizer.style.minWidth = ""; michael@0: } else { michael@0: cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", ""); michael@0: findMaxLine(cm); michael@0: } michael@0: estimateLineHeights(cm); michael@0: regChange(cm); michael@0: clearCaches(cm); michael@0: setTimeout(function(){updateScrollbars(cm);}, 100); michael@0: } michael@0: michael@0: // Returns a function that estimates the height of a line, to use as michael@0: // first approximation until the line becomes visible (and is thus michael@0: // properly measurable). michael@0: function estimateHeight(cm) { michael@0: var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; michael@0: var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); michael@0: return function(line) { michael@0: if (lineIsHidden(cm.doc, line)) return 0; michael@0: michael@0: var widgetsHeight = 0; michael@0: if (line.widgets) for (var i = 0; i < line.widgets.length; i++) { michael@0: if (line.widgets[i].height) widgetsHeight += line.widgets[i].height; michael@0: } michael@0: michael@0: if (wrapping) michael@0: return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th; michael@0: else michael@0: return widgetsHeight + th; michael@0: }; michael@0: } michael@0: michael@0: function estimateLineHeights(cm) { michael@0: var doc = cm.doc, est = estimateHeight(cm); michael@0: doc.iter(function(line) { michael@0: var estHeight = est(line); michael@0: if (estHeight != line.height) updateLineHeight(line, estHeight); michael@0: }); michael@0: } michael@0: michael@0: function keyMapChanged(cm) { michael@0: var map = keyMap[cm.options.keyMap], style = map.style; michael@0: cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") + michael@0: (style ? " cm-keymap-" + style : ""); michael@0: } michael@0: michael@0: function themeChanged(cm) { michael@0: cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + michael@0: cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); michael@0: clearCaches(cm); michael@0: } michael@0: michael@0: function guttersChanged(cm) { michael@0: updateGutters(cm); michael@0: regChange(cm); michael@0: setTimeout(function(){alignHorizontally(cm);}, 20); michael@0: } michael@0: michael@0: // Rebuild the gutter elements, ensure the margin to the left of the michael@0: // code matches their width. michael@0: function updateGutters(cm) { michael@0: var gutters = cm.display.gutters, specs = cm.options.gutters; michael@0: removeChildren(gutters); michael@0: for (var i = 0; i < specs.length; ++i) { michael@0: var gutterClass = specs[i]; michael@0: var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); michael@0: if (gutterClass == "CodeMirror-linenumbers") { michael@0: cm.display.lineGutter = gElt; michael@0: gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; michael@0: } michael@0: } michael@0: gutters.style.display = i ? "" : "none"; michael@0: var width = gutters.offsetWidth; michael@0: cm.display.sizer.style.marginLeft = width + "px"; michael@0: if (i) cm.display.scrollbarH.style.left = cm.options.fixedGutter ? width + "px" : 0; michael@0: } michael@0: michael@0: // Compute the character length of a line, taking into account michael@0: // collapsed ranges (see markText) that might hide parts, and join michael@0: // other lines onto it. michael@0: function lineLength(line) { michael@0: if (line.height == 0) return 0; michael@0: var len = line.text.length, merged, cur = line; michael@0: while (merged = collapsedSpanAtStart(cur)) { michael@0: var found = merged.find(0, true); michael@0: cur = found.from.line; michael@0: len += found.from.ch - found.to.ch; michael@0: } michael@0: cur = line; michael@0: while (merged = collapsedSpanAtEnd(cur)) { michael@0: var found = merged.find(0, true); michael@0: len -= cur.text.length - found.from.ch; michael@0: cur = found.to.line; michael@0: len += cur.text.length - found.to.ch; michael@0: } michael@0: return len; michael@0: } michael@0: michael@0: // Find the longest line in the document. michael@0: function findMaxLine(cm) { michael@0: var d = cm.display, doc = cm.doc; michael@0: d.maxLine = getLine(doc, doc.first); michael@0: d.maxLineLength = lineLength(d.maxLine); michael@0: d.maxLineChanged = true; michael@0: doc.iter(function(line) { michael@0: var len = lineLength(line); michael@0: if (len > d.maxLineLength) { michael@0: d.maxLineLength = len; michael@0: d.maxLine = line; michael@0: } michael@0: }); michael@0: } michael@0: michael@0: // Make sure the gutters options contains the element michael@0: // "CodeMirror-linenumbers" when the lineNumbers option is true. michael@0: function setGuttersForLineNumbers(options) { michael@0: var found = indexOf(options.gutters, "CodeMirror-linenumbers"); michael@0: if (found == -1 && options.lineNumbers) { michael@0: options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); michael@0: } else if (found > -1 && !options.lineNumbers) { michael@0: options.gutters = options.gutters.slice(0); michael@0: options.gutters.splice(found, 1); michael@0: } michael@0: } michael@0: michael@0: // SCROLLBARS michael@0: michael@0: // Prepare DOM reads needed to update the scrollbars. Done in one michael@0: // shot to minimize update/measure roundtrips. michael@0: function measureForScrollbars(cm) { michael@0: var scroll = cm.display.scroller; michael@0: return { michael@0: clientHeight: scroll.clientHeight, michael@0: barHeight: cm.display.scrollbarV.clientHeight, michael@0: scrollWidth: scroll.scrollWidth, clientWidth: scroll.clientWidth, michael@0: barWidth: cm.display.scrollbarH.clientWidth, michael@0: docHeight: Math.round(cm.doc.height + paddingVert(cm.display)) michael@0: }; michael@0: } michael@0: michael@0: // Re-synchronize the fake scrollbars with the actual size of the michael@0: // content. michael@0: function updateScrollbars(cm, measure) { michael@0: if (!measure) measure = measureForScrollbars(cm); michael@0: var d = cm.display; michael@0: var scrollHeight = measure.docHeight + scrollerCutOff; michael@0: var needsH = measure.scrollWidth > measure.clientWidth; michael@0: var needsV = scrollHeight > measure.clientHeight; michael@0: if (needsV) { michael@0: d.scrollbarV.style.display = "block"; michael@0: d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0"; michael@0: // A bug in IE8 can cause this value to be negative, so guard it. michael@0: d.scrollbarV.firstChild.style.height = michael@0: Math.max(0, scrollHeight - measure.clientHeight + (measure.barHeight || d.scrollbarV.clientHeight)) + "px"; michael@0: } else { michael@0: d.scrollbarV.style.display = ""; michael@0: d.scrollbarV.firstChild.style.height = "0"; michael@0: } michael@0: if (needsH) { michael@0: d.scrollbarH.style.display = "block"; michael@0: d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0"; michael@0: d.scrollbarH.firstChild.style.width = michael@0: (measure.scrollWidth - measure.clientWidth + (measure.barWidth || d.scrollbarH.clientWidth)) + "px"; michael@0: } else { michael@0: d.scrollbarH.style.display = ""; michael@0: d.scrollbarH.firstChild.style.width = "0"; michael@0: } michael@0: if (needsH && needsV) { michael@0: d.scrollbarFiller.style.display = "block"; michael@0: d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px"; michael@0: } else d.scrollbarFiller.style.display = ""; michael@0: if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { michael@0: d.gutterFiller.style.display = "block"; michael@0: d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px"; michael@0: d.gutterFiller.style.width = d.gutters.offsetWidth + "px"; michael@0: } else d.gutterFiller.style.display = ""; michael@0: michael@0: if (mac_geLion && scrollbarWidth(d.measure) === 0) { michael@0: d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px"; michael@0: var barMouseDown = function(e) { michael@0: if (e_target(e) != d.scrollbarV && e_target(e) != d.scrollbarH) michael@0: operation(cm, onMouseDown)(e); michael@0: }; michael@0: on(d.scrollbarV, "mousedown", barMouseDown); michael@0: on(d.scrollbarH, "mousedown", barMouseDown); michael@0: } michael@0: } michael@0: michael@0: // Compute the lines that are visible in a given viewport (defaults michael@0: // the the current scroll position). viewPort may contain top, michael@0: // height, and ensure (see op.scrollToPos) properties. michael@0: function visibleLines(display, doc, viewPort) { michael@0: var top = viewPort && viewPort.top != null ? viewPort.top : display.scroller.scrollTop; michael@0: top = Math.floor(top - paddingTop(display)); michael@0: var bottom = viewPort && viewPort.bottom != null ? viewPort.bottom : top + display.wrapper.clientHeight; michael@0: michael@0: var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); michael@0: // Ensure is a {from: {line, ch}, to: {line, ch}} object, and michael@0: // forces those lines into the viewport (if possible). michael@0: if (viewPort && viewPort.ensure) { michael@0: var ensureFrom = viewPort.ensure.from.line, ensureTo = viewPort.ensure.to.line; michael@0: if (ensureFrom < from) michael@0: return {from: ensureFrom, michael@0: to: lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)}; michael@0: if (Math.min(ensureTo, doc.lastLine()) >= to) michael@0: return {from: lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight), michael@0: to: ensureTo}; michael@0: } michael@0: return {from: from, to: to}; michael@0: } michael@0: michael@0: // LINE NUMBERS michael@0: michael@0: // Re-align line numbers and gutter marks to compensate for michael@0: // horizontal scrolling. michael@0: function alignHorizontally(cm) { michael@0: var display = cm.display, view = display.view; michael@0: if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; michael@0: var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; michael@0: var gutterW = display.gutters.offsetWidth, left = comp + "px"; michael@0: for (var i = 0; i < view.length; i++) if (!view[i].hidden) { michael@0: if (cm.options.fixedGutter && view[i].gutter) michael@0: view[i].gutter.style.left = left; michael@0: var align = view[i].alignable; michael@0: if (align) for (var j = 0; j < align.length; j++) michael@0: align[j].style.left = left; michael@0: } michael@0: if (cm.options.fixedGutter) michael@0: display.gutters.style.left = (comp + gutterW) + "px"; michael@0: } michael@0: michael@0: // Used to ensure that the line number gutter is still the right michael@0: // size for the current document size. Returns true when an update michael@0: // is needed. michael@0: function maybeUpdateLineNumberWidth(cm) { michael@0: if (!cm.options.lineNumbers) return false; michael@0: var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; michael@0: if (last.length != display.lineNumChars) { michael@0: var test = display.measure.appendChild(elt("div", [elt("div", last)], michael@0: "CodeMirror-linenumber CodeMirror-gutter-elt")); michael@0: var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; michael@0: display.lineGutter.style.width = ""; michael@0: display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding); michael@0: display.lineNumWidth = display.lineNumInnerWidth + padding; michael@0: display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; michael@0: display.lineGutter.style.width = display.lineNumWidth + "px"; michael@0: var width = display.gutters.offsetWidth; michael@0: display.scrollbarH.style.left = cm.options.fixedGutter ? width + "px" : 0; michael@0: display.sizer.style.marginLeft = width + "px"; michael@0: return true; michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: function lineNumberFor(options, i) { michael@0: return String(options.lineNumberFormatter(i + options.firstLineNumber)); michael@0: } michael@0: michael@0: // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, michael@0: // but using getBoundingClientRect to get a sub-pixel-accurate michael@0: // result. michael@0: function compensateForHScroll(display) { michael@0: return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; michael@0: } michael@0: michael@0: // DISPLAY DRAWING michael@0: michael@0: // Updates the display, selection, and scrollbars, using the michael@0: // information in display.view to find out which nodes are no longer michael@0: // up-to-date. Tries to bail out early when no changes are needed, michael@0: // unless forced is true. michael@0: // Returns true if an actual update happened, false otherwise. michael@0: function updateDisplay(cm, viewPort, forced) { michael@0: var oldFrom = cm.display.viewFrom, oldTo = cm.display.viewTo, updated; michael@0: var visible = visibleLines(cm.display, cm.doc, viewPort); michael@0: for (var first = true;; first = false) { michael@0: var oldWidth = cm.display.scroller.clientWidth; michael@0: if (!updateDisplayInner(cm, visible, forced)) break; michael@0: updated = true; michael@0: michael@0: // If the max line changed since it was last measured, measure it, michael@0: // and ensure the document's width matches it. michael@0: if (cm.display.maxLineChanged && !cm.options.lineWrapping) michael@0: adjustContentWidth(cm); michael@0: michael@0: var barMeasure = measureForScrollbars(cm); michael@0: updateSelection(cm); michael@0: setDocumentHeight(cm, barMeasure); michael@0: updateScrollbars(cm, barMeasure); michael@0: if (first && cm.options.lineWrapping && oldWidth != cm.display.scroller.clientWidth) { michael@0: forced = true; michael@0: continue; michael@0: } michael@0: forced = false; michael@0: michael@0: // Clip forced viewport to actual scrollable area. michael@0: if (viewPort && viewPort.top != null) michael@0: viewPort = {top: Math.min(barMeasure.docHeight - scrollerCutOff - barMeasure.clientHeight, viewPort.top)}; michael@0: // Updated line heights might result in the drawn area not michael@0: // actually covering the viewport. Keep looping until it does. michael@0: visible = visibleLines(cm.display, cm.doc, viewPort); michael@0: if (visible.from >= cm.display.viewFrom && visible.to <= cm.display.viewTo) michael@0: break; michael@0: } michael@0: michael@0: cm.display.updateLineNumbers = null; michael@0: if (updated) { michael@0: signalLater(cm, "update", cm); michael@0: if (cm.display.viewFrom != oldFrom || cm.display.viewTo != oldTo) michael@0: signalLater(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); michael@0: } michael@0: return updated; michael@0: } michael@0: michael@0: // Does the actual updating of the line display. Bails out michael@0: // (returning false) when there is nothing to be done and forced is michael@0: // false. michael@0: function updateDisplayInner(cm, visible, forced) { michael@0: var display = cm.display, doc = cm.doc; michael@0: if (!display.wrapper.offsetWidth) { michael@0: resetView(cm); michael@0: return; michael@0: } michael@0: michael@0: // Bail out if the visible area is already rendered and nothing changed. michael@0: if (!forced && visible.from >= display.viewFrom && visible.to <= display.viewTo && michael@0: countDirtyView(cm) == 0) michael@0: return; michael@0: michael@0: if (maybeUpdateLineNumberWidth(cm)) michael@0: resetView(cm); michael@0: var dims = getDimensions(cm); michael@0: michael@0: // Compute a suitable new viewport (from & to) michael@0: var end = doc.first + doc.size; michael@0: var from = Math.max(visible.from - cm.options.viewportMargin, doc.first); michael@0: var to = Math.min(end, visible.to + cm.options.viewportMargin); michael@0: if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom); michael@0: if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo); michael@0: if (sawCollapsedSpans) { michael@0: from = visualLineNo(cm.doc, from); michael@0: to = visualLineEndNo(cm.doc, to); michael@0: } michael@0: michael@0: var different = from != display.viewFrom || to != display.viewTo || michael@0: display.lastSizeC != display.wrapper.clientHeight; michael@0: adjustView(cm, from, to); michael@0: michael@0: display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); michael@0: // Position the mover div to align with the current scroll position michael@0: cm.display.mover.style.top = display.viewOffset + "px"; michael@0: michael@0: var toUpdate = countDirtyView(cm); michael@0: if (!different && toUpdate == 0 && !forced) return; michael@0: michael@0: // For big changes, we hide the enclosing element during the michael@0: // update, since that speeds up the operations on most browsers. michael@0: var focused = activeElt(); michael@0: if (toUpdate > 4) display.lineDiv.style.display = "none"; michael@0: patchDisplay(cm, display.updateLineNumbers, dims); michael@0: if (toUpdate > 4) display.lineDiv.style.display = ""; michael@0: // There might have been a widget with a focused element that got michael@0: // hidden or updated, if so re-focus it. michael@0: if (focused && activeElt() != focused && focused.offsetHeight) focused.focus(); michael@0: michael@0: // Prevent selection and cursors from interfering with the scroll michael@0: // width. michael@0: removeChildren(display.cursorDiv); michael@0: removeChildren(display.selectionDiv); michael@0: michael@0: if (different) { michael@0: display.lastSizeC = display.wrapper.clientHeight; michael@0: startWorker(cm, 400); michael@0: } michael@0: michael@0: updateHeightsInViewport(cm); michael@0: michael@0: return true; michael@0: } michael@0: michael@0: function adjustContentWidth(cm) { michael@0: var display = cm.display; michael@0: var width = measureChar(cm, display.maxLine, display.maxLine.text.length).left; michael@0: display.maxLineChanged = false; michael@0: var minWidth = Math.max(0, width + 3); michael@0: var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + minWidth + scrollerCutOff - display.scroller.clientWidth); michael@0: display.sizer.style.minWidth = minWidth + "px"; michael@0: if (maxScrollLeft < cm.doc.scrollLeft) michael@0: setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true); michael@0: } michael@0: michael@0: function setDocumentHeight(cm, measure) { michael@0: cm.display.sizer.style.minHeight = cm.display.heightForcer.style.top = measure.docHeight + "px"; michael@0: cm.display.gutters.style.height = Math.max(measure.docHeight, measure.clientHeight - scrollerCutOff) + "px"; michael@0: } michael@0: michael@0: // Read the actual heights of the rendered lines, and update their michael@0: // stored heights to match. michael@0: function updateHeightsInViewport(cm) { michael@0: var display = cm.display; michael@0: var prevBottom = display.lineDiv.offsetTop; michael@0: for (var i = 0; i < display.view.length; i++) { michael@0: var cur = display.view[i], height; michael@0: if (cur.hidden) continue; michael@0: if (ie_upto7) { michael@0: var bot = cur.node.offsetTop + cur.node.offsetHeight; michael@0: height = bot - prevBottom; michael@0: prevBottom = bot; michael@0: } else { michael@0: var box = cur.node.getBoundingClientRect(); michael@0: height = box.bottom - box.top; michael@0: } michael@0: var diff = cur.line.height - height; michael@0: if (height < 2) height = textHeight(display); michael@0: if (diff > .001 || diff < -.001) { michael@0: updateLineHeight(cur.line, height); michael@0: updateWidgetHeight(cur.line); michael@0: if (cur.rest) for (var j = 0; j < cur.rest.length; j++) michael@0: updateWidgetHeight(cur.rest[j]); michael@0: } michael@0: } michael@0: } michael@0: michael@0: // Read and store the height of line widgets associated with the michael@0: // given line. michael@0: function updateWidgetHeight(line) { michael@0: if (line.widgets) for (var i = 0; i < line.widgets.length; ++i) michael@0: line.widgets[i].height = line.widgets[i].node.offsetHeight; michael@0: } michael@0: michael@0: // Do a bulk-read of the DOM positions and sizes needed to draw the michael@0: // view, so that we don't interleave reading and writing to the DOM. michael@0: function getDimensions(cm) { michael@0: var d = cm.display, left = {}, width = {}; michael@0: for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { michael@0: left[cm.options.gutters[i]] = n.offsetLeft; michael@0: width[cm.options.gutters[i]] = n.offsetWidth; michael@0: } michael@0: return {fixedPos: compensateForHScroll(d), michael@0: gutterTotalWidth: d.gutters.offsetWidth, michael@0: gutterLeft: left, michael@0: gutterWidth: width, michael@0: wrapperWidth: d.wrapper.clientWidth}; michael@0: } michael@0: michael@0: // Sync the actual display DOM structure with display.view, removing michael@0: // nodes for lines that are no longer in view, and creating the ones michael@0: // that are not there yet, and updating the ones that are out of michael@0: // date. michael@0: function patchDisplay(cm, updateNumbersFrom, dims) { michael@0: var display = cm.display, lineNumbers = cm.options.lineNumbers; michael@0: var container = display.lineDiv, cur = container.firstChild; michael@0: michael@0: function rm(node) { michael@0: var next = node.nextSibling; michael@0: // Works around a throw-scroll bug in OS X Webkit michael@0: if (webkit && mac && cm.display.currentWheelTarget == node) michael@0: node.style.display = "none"; michael@0: else michael@0: node.parentNode.removeChild(node); michael@0: return next; michael@0: } michael@0: michael@0: var view = display.view, lineN = display.viewFrom; michael@0: // Loop over the elements in the view, syncing cur (the DOM nodes michael@0: // in display.lineDiv) with the view as we go. michael@0: for (var i = 0; i < view.length; i++) { michael@0: var lineView = view[i]; michael@0: if (lineView.hidden) { michael@0: } else if (!lineView.node) { // Not drawn yet michael@0: var node = buildLineElement(cm, lineView, lineN, dims); michael@0: container.insertBefore(node, cur); michael@0: } else { // Already drawn michael@0: while (cur != lineView.node) cur = rm(cur); michael@0: var updateNumber = lineNumbers && updateNumbersFrom != null && michael@0: updateNumbersFrom <= lineN && lineView.lineNumber; michael@0: if (lineView.changes) { michael@0: if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false; michael@0: updateLineForChanges(cm, lineView, lineN, dims); michael@0: } michael@0: if (updateNumber) { michael@0: removeChildren(lineView.lineNumber); michael@0: lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); michael@0: } michael@0: cur = lineView.node.nextSibling; michael@0: } michael@0: lineN += lineView.size; michael@0: } michael@0: while (cur) cur = rm(cur); michael@0: } michael@0: michael@0: // When an aspect of a line changes, a string is added to michael@0: // lineView.changes. This updates the relevant part of the line's michael@0: // DOM structure. michael@0: function updateLineForChanges(cm, lineView, lineN, dims) { michael@0: for (var j = 0; j < lineView.changes.length; j++) { michael@0: var type = lineView.changes[j]; michael@0: if (type == "text") updateLineText(cm, lineView); michael@0: else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims); michael@0: else if (type == "class") updateLineClasses(lineView); michael@0: else if (type == "widget") updateLineWidgets(lineView, dims); michael@0: } michael@0: lineView.changes = null; michael@0: } michael@0: michael@0: // Lines with gutter elements, widgets or a background class need to michael@0: // be wrapped, and have the extra elements added to the wrapper div michael@0: function ensureLineWrapped(lineView) { michael@0: if (lineView.node == lineView.text) { michael@0: lineView.node = elt("div", null, null, "position: relative"); michael@0: if (lineView.text.parentNode) michael@0: lineView.text.parentNode.replaceChild(lineView.node, lineView.text); michael@0: lineView.node.appendChild(lineView.text); michael@0: if (ie_upto7) lineView.node.style.zIndex = 2; michael@0: } michael@0: return lineView.node; michael@0: } michael@0: michael@0: function updateLineBackground(lineView) { michael@0: var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; michael@0: if (cls) cls += " CodeMirror-linebackground"; michael@0: if (lineView.background) { michael@0: if (cls) lineView.background.className = cls; michael@0: else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } michael@0: } else if (cls) { michael@0: var wrap = ensureLineWrapped(lineView); michael@0: lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); michael@0: } michael@0: } michael@0: michael@0: // Wrapper around buildLineContent which will reuse the structure michael@0: // in display.externalMeasured when possible. michael@0: function getLineContent(cm, lineView) { michael@0: var ext = cm.display.externalMeasured; michael@0: if (ext && ext.line == lineView.line) { michael@0: cm.display.externalMeasured = null; michael@0: lineView.measure = ext.measure; michael@0: return ext.built; michael@0: } michael@0: return buildLineContent(cm, lineView); michael@0: } michael@0: michael@0: // Redraw the line's text. Interacts with the background and text michael@0: // classes because the mode may output tokens that influence these michael@0: // classes. michael@0: function updateLineText(cm, lineView) { michael@0: var cls = lineView.text.className; michael@0: var built = getLineContent(cm, lineView); michael@0: if (lineView.text == lineView.node) lineView.node = built.pre; michael@0: lineView.text.parentNode.replaceChild(built.pre, lineView.text); michael@0: lineView.text = built.pre; michael@0: if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { michael@0: lineView.bgClass = built.bgClass; michael@0: lineView.textClass = built.textClass; michael@0: updateLineClasses(lineView); michael@0: } else if (cls) { michael@0: lineView.text.className = cls; michael@0: } michael@0: } michael@0: michael@0: function updateLineClasses(lineView) { michael@0: updateLineBackground(lineView); michael@0: if (lineView.line.wrapClass) michael@0: ensureLineWrapped(lineView).className = lineView.line.wrapClass; michael@0: else if (lineView.node != lineView.text) michael@0: lineView.node.className = ""; michael@0: var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; michael@0: lineView.text.className = textClass || ""; michael@0: } michael@0: michael@0: function updateLineGutter(cm, lineView, lineN, dims) { michael@0: if (lineView.gutter) { michael@0: lineView.node.removeChild(lineView.gutter); michael@0: lineView.gutter = null; michael@0: } michael@0: var markers = lineView.line.gutterMarkers; michael@0: if (cm.options.lineNumbers || markers) { michael@0: var wrap = ensureLineWrapped(lineView); michael@0: var gutterWrap = lineView.gutter = michael@0: wrap.insertBefore(elt("div", null, "CodeMirror-gutter-wrapper", "position: absolute; left: " + michael@0: (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"), michael@0: lineView.text); michael@0: if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) michael@0: lineView.lineNumber = gutterWrap.appendChild( michael@0: elt("div", lineNumberFor(cm.options, lineN), michael@0: "CodeMirror-linenumber CodeMirror-gutter-elt", michael@0: "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " michael@0: + cm.display.lineNumInnerWidth + "px")); michael@0: if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) { michael@0: var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; michael@0: if (found) michael@0: gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + michael@0: dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); michael@0: } michael@0: } michael@0: } michael@0: michael@0: function updateLineWidgets(lineView, dims) { michael@0: if (lineView.alignable) lineView.alignable = null; michael@0: for (var node = lineView.node.firstChild, next; node; node = next) { michael@0: var next = node.nextSibling; michael@0: if (node.className == "CodeMirror-linewidget") michael@0: lineView.node.removeChild(node); michael@0: } michael@0: insertLineWidgets(lineView, dims); michael@0: } michael@0: michael@0: // Build a line's DOM representation from scratch michael@0: function buildLineElement(cm, lineView, lineN, dims) { michael@0: var built = getLineContent(cm, lineView); michael@0: lineView.text = lineView.node = built.pre; michael@0: if (built.bgClass) lineView.bgClass = built.bgClass; michael@0: if (built.textClass) lineView.textClass = built.textClass; michael@0: michael@0: updateLineClasses(lineView); michael@0: updateLineGutter(cm, lineView, lineN, dims); michael@0: insertLineWidgets(lineView, dims); michael@0: return lineView.node; michael@0: } michael@0: michael@0: // A lineView may contain multiple logical lines (when merged by michael@0: // collapsed spans). The widgets for all of them need to be drawn. michael@0: function insertLineWidgets(lineView, dims) { michael@0: insertLineWidgetsFor(lineView.line, lineView, dims, true); michael@0: if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) michael@0: insertLineWidgetsFor(lineView.rest[i], lineView, dims, false); michael@0: } michael@0: michael@0: function insertLineWidgetsFor(line, lineView, dims, allowAbove) { michael@0: if (!line.widgets) return; michael@0: var wrap = ensureLineWrapped(lineView); michael@0: for (var i = 0, ws = line.widgets; i < ws.length; ++i) { michael@0: var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); michael@0: if (!widget.handleMouseEvents) node.ignoreEvents = true; michael@0: positionLineWidget(widget, node, lineView, dims); michael@0: if (allowAbove && widget.above) michael@0: wrap.insertBefore(node, lineView.gutter || lineView.text); michael@0: else michael@0: wrap.appendChild(node); michael@0: signalLater(widget, "redraw"); michael@0: } michael@0: } michael@0: michael@0: function positionLineWidget(widget, node, lineView, dims) { michael@0: if (widget.noHScroll) { michael@0: (lineView.alignable || (lineView.alignable = [])).push(node); michael@0: var width = dims.wrapperWidth; michael@0: node.style.left = dims.fixedPos + "px"; michael@0: if (!widget.coverGutter) { michael@0: width -= dims.gutterTotalWidth; michael@0: node.style.paddingLeft = dims.gutterTotalWidth + "px"; michael@0: } michael@0: node.style.width = width + "px"; michael@0: } michael@0: if (widget.coverGutter) { michael@0: node.style.zIndex = 5; michael@0: node.style.position = "relative"; michael@0: if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; michael@0: } michael@0: } michael@0: michael@0: // POSITION OBJECT michael@0: michael@0: // A Pos instance represents a position within the text. michael@0: var Pos = CodeMirror.Pos = function(line, ch) { michael@0: if (!(this instanceof Pos)) return new Pos(line, ch); michael@0: this.line = line; this.ch = ch; michael@0: }; michael@0: michael@0: // Compare two positions, return 0 if they are the same, a negative michael@0: // number when a is less, and a positive number otherwise. michael@0: var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; }; michael@0: michael@0: function copyPos(x) {return Pos(x.line, x.ch);} michael@0: function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; } michael@0: function minPos(a, b) { return cmp(a, b) < 0 ? a : b; } michael@0: michael@0: // SELECTION / CURSOR michael@0: michael@0: // Selection objects are immutable. A new one is created every time michael@0: // the selection changes. A selection is one or more non-overlapping michael@0: // (and non-touching) ranges, sorted, and an integer that indicates michael@0: // which one is the primary selection (the one that's scrolled into michael@0: // view, that getCursor returns, etc). michael@0: function Selection(ranges, primIndex) { michael@0: this.ranges = ranges; michael@0: this.primIndex = primIndex; michael@0: } michael@0: michael@0: Selection.prototype = { michael@0: primary: function() { return this.ranges[this.primIndex]; }, michael@0: equals: function(other) { michael@0: if (other == this) return true; michael@0: if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false; michael@0: for (var i = 0; i < this.ranges.length; i++) { michael@0: var here = this.ranges[i], there = other.ranges[i]; michael@0: if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false; michael@0: } michael@0: return true; michael@0: }, michael@0: deepCopy: function() { michael@0: for (var out = [], i = 0; i < this.ranges.length; i++) michael@0: out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); michael@0: return new Selection(out, this.primIndex); michael@0: }, michael@0: somethingSelected: function() { michael@0: for (var i = 0; i < this.ranges.length; i++) michael@0: if (!this.ranges[i].empty()) return true; michael@0: return false; michael@0: }, michael@0: contains: function(pos, end) { michael@0: if (!end) end = pos; michael@0: for (var i = 0; i < this.ranges.length; i++) { michael@0: var range = this.ranges[i]; michael@0: if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) michael@0: return i; michael@0: } michael@0: return -1; michael@0: } michael@0: }; michael@0: michael@0: function Range(anchor, head) { michael@0: this.anchor = anchor; this.head = head; michael@0: } michael@0: michael@0: Range.prototype = { michael@0: from: function() { return minPos(this.anchor, this.head); }, michael@0: to: function() { return maxPos(this.anchor, this.head); }, michael@0: empty: function() { michael@0: return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; michael@0: } michael@0: }; michael@0: michael@0: // Take an unsorted, potentially overlapping set of ranges, and michael@0: // build a selection out of it. 'Consumes' ranges array (modifying michael@0: // it). michael@0: function normalizeSelection(ranges, primIndex) { michael@0: var prim = ranges[primIndex]; michael@0: ranges.sort(function(a, b) { return cmp(a.from(), b.from()); }); michael@0: primIndex = indexOf(ranges, prim); michael@0: for (var i = 1; i < ranges.length; i++) { michael@0: var cur = ranges[i], prev = ranges[i - 1]; michael@0: if (cmp(prev.to(), cur.from()) >= 0) { michael@0: var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); michael@0: var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; michael@0: if (i <= primIndex) --primIndex; michael@0: ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); michael@0: } michael@0: } michael@0: return new Selection(ranges, primIndex); michael@0: } michael@0: michael@0: function simpleSelection(anchor, head) { michael@0: return new Selection([new Range(anchor, head || anchor)], 0); michael@0: } michael@0: michael@0: // Most of the external API clips given positions to make sure they michael@0: // actually exist within the document. michael@0: function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} michael@0: function clipPos(doc, pos) { michael@0: if (pos.line < doc.first) return Pos(doc.first, 0); michael@0: var last = doc.first + doc.size - 1; michael@0: if (pos.line > last) return Pos(last, getLine(doc, last).text.length); michael@0: return clipToLen(pos, getLine(doc, pos.line).text.length); michael@0: } michael@0: function clipToLen(pos, linelen) { michael@0: var ch = pos.ch; michael@0: if (ch == null || ch > linelen) return Pos(pos.line, linelen); michael@0: else if (ch < 0) return Pos(pos.line, 0); michael@0: else return pos; michael@0: } michael@0: function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} michael@0: function clipPosArray(doc, array) { michael@0: for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]); michael@0: return out; michael@0: } michael@0: michael@0: // SELECTION UPDATES michael@0: michael@0: // The 'scroll' parameter given to many of these indicated whether michael@0: // the new cursor position should be scrolled into view after michael@0: // modifying the selection. michael@0: michael@0: // If shift is held or the extend flag is set, extends a range to michael@0: // include a given position (and optionally a second position). michael@0: // Otherwise, simply returns the range between the given positions. michael@0: // Used for cursor motion and such. michael@0: function extendRange(doc, range, head, other) { michael@0: if (doc.cm && doc.cm.display.shift || doc.extend) { michael@0: var anchor = range.anchor; michael@0: if (other) { michael@0: var posBefore = cmp(head, anchor) < 0; michael@0: if (posBefore != (cmp(other, anchor) < 0)) { michael@0: anchor = head; michael@0: head = other; michael@0: } else if (posBefore != (cmp(head, other) < 0)) { michael@0: head = other; michael@0: } michael@0: } michael@0: return new Range(anchor, head); michael@0: } else { michael@0: return new Range(other || head, head); michael@0: } michael@0: } michael@0: michael@0: // Extend the primary selection range, discard the rest. michael@0: function extendSelection(doc, head, other, options) { michael@0: setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options); michael@0: } michael@0: michael@0: // Extend all selections (pos is an array of selections with length michael@0: // equal the number of selections) michael@0: function extendSelections(doc, heads, options) { michael@0: for (var out = [], i = 0; i < doc.sel.ranges.length; i++) michael@0: out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null); michael@0: var newSel = normalizeSelection(out, doc.sel.primIndex); michael@0: setSelection(doc, newSel, options); michael@0: } michael@0: michael@0: // Updates a single range in the selection. michael@0: function replaceOneSelection(doc, i, range, options) { michael@0: var ranges = doc.sel.ranges.slice(0); michael@0: ranges[i] = range; michael@0: setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); michael@0: } michael@0: michael@0: // Reset the selection to a single range. michael@0: function setSimpleSelection(doc, anchor, head, options) { michael@0: setSelection(doc, simpleSelection(anchor, head), options); michael@0: } michael@0: michael@0: // Give beforeSelectionChange handlers a change to influence a michael@0: // selection update. michael@0: function filterSelectionChange(doc, sel) { michael@0: var obj = { michael@0: ranges: sel.ranges, michael@0: update: function(ranges) { michael@0: this.ranges = []; michael@0: for (var i = 0; i < ranges.length; i++) michael@0: this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), michael@0: clipPos(doc, ranges[i].head)); michael@0: } michael@0: }; michael@0: signal(doc, "beforeSelectionChange", doc, obj); michael@0: if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); michael@0: if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1); michael@0: else return sel; michael@0: } michael@0: michael@0: function setSelectionReplaceHistory(doc, sel, options) { michael@0: var done = doc.history.done, last = lst(done); michael@0: if (last && last.ranges) { michael@0: done[done.length - 1] = sel; michael@0: setSelectionNoUndo(doc, sel, options); michael@0: } else { michael@0: setSelection(doc, sel, options); michael@0: } michael@0: } michael@0: michael@0: // Set a new selection. michael@0: function setSelection(doc, sel, options) { michael@0: setSelectionNoUndo(doc, sel, options); michael@0: addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); michael@0: } michael@0: michael@0: function setSelectionNoUndo(doc, sel, options) { michael@0: if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) michael@0: sel = filterSelectionChange(doc, sel); michael@0: michael@0: var bias = cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1; michael@0: setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); michael@0: michael@0: if (!(options && options.scroll === false) && doc.cm) michael@0: ensureCursorVisible(doc.cm); michael@0: } michael@0: michael@0: function setSelectionInner(doc, sel) { michael@0: if (sel.equals(doc.sel)) return; michael@0: michael@0: doc.sel = sel; michael@0: michael@0: if (doc.cm) michael@0: doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = michael@0: doc.cm.curOp.cursorActivity = true; michael@0: signalLater(doc, "cursorActivity", doc); michael@0: } michael@0: michael@0: // Verify that the selection does not partially select any atomic michael@0: // marked ranges. michael@0: function reCheckSelection(doc) { michael@0: setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll); michael@0: } michael@0: michael@0: // Return a selection that does not partially select any atomic michael@0: // ranges. michael@0: function skipAtomicInSelection(doc, sel, bias, mayClear) { michael@0: var out; michael@0: for (var i = 0; i < sel.ranges.length; i++) { michael@0: var range = sel.ranges[i]; michael@0: var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear); michael@0: var newHead = skipAtomic(doc, range.head, bias, mayClear); michael@0: if (out || newAnchor != range.anchor || newHead != range.head) { michael@0: if (!out) out = sel.ranges.slice(0, i); michael@0: out[i] = new Range(newAnchor, newHead); michael@0: } michael@0: } michael@0: return out ? normalizeSelection(out, sel.primIndex) : sel; michael@0: } michael@0: michael@0: // Ensure a given position is not inside an atomic range. michael@0: function skipAtomic(doc, pos, bias, mayClear) { michael@0: var flipped = false, curPos = pos; michael@0: var dir = bias || 1; michael@0: doc.cantEdit = false; michael@0: search: for (;;) { michael@0: var line = getLine(doc, curPos.line); michael@0: if (line.markedSpans) { michael@0: for (var i = 0; i < line.markedSpans.length; ++i) { michael@0: var sp = line.markedSpans[i], m = sp.marker; michael@0: if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) && michael@0: (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { michael@0: if (mayClear) { michael@0: signal(m, "beforeCursorEnter"); michael@0: if (m.explicitlyCleared) { michael@0: if (!line.markedSpans) break; michael@0: else {--i; continue;} michael@0: } michael@0: } michael@0: if (!m.atomic) continue; michael@0: var newPos = m.find(dir < 0 ? -1 : 1); michael@0: if (cmp(newPos, curPos) == 0) { michael@0: newPos.ch += dir; michael@0: if (newPos.ch < 0) { michael@0: if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1)); michael@0: else newPos = null; michael@0: } else if (newPos.ch > line.text.length) { michael@0: if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0); michael@0: else newPos = null; michael@0: } michael@0: if (!newPos) { michael@0: if (flipped) { michael@0: // Driven in a corner -- no valid cursor position found at all michael@0: // -- try again *with* clearing, if we didn't already michael@0: if (!mayClear) return skipAtomic(doc, pos, bias, true); michael@0: // Otherwise, turn off editing until further notice, and return the start of the doc michael@0: doc.cantEdit = true; michael@0: return Pos(doc.first, 0); michael@0: } michael@0: flipped = true; newPos = pos; dir = -dir; michael@0: } michael@0: } michael@0: curPos = newPos; michael@0: continue search; michael@0: } michael@0: } michael@0: } michael@0: return curPos; michael@0: } michael@0: } michael@0: michael@0: // SELECTION DRAWING michael@0: michael@0: // Redraw the selection and/or cursor michael@0: function updateSelection(cm) { michael@0: var display = cm.display, doc = cm.doc; michael@0: var curFragment = document.createDocumentFragment(); michael@0: var selFragment = document.createDocumentFragment(); michael@0: michael@0: for (var i = 0; i < doc.sel.ranges.length; i++) { michael@0: var range = doc.sel.ranges[i]; michael@0: var collapsed = range.empty(); michael@0: if (collapsed || cm.options.showCursorWhenSelecting) michael@0: updateSelectionCursor(cm, range, curFragment); michael@0: if (!collapsed) michael@0: updateSelectionRange(cm, range, selFragment); michael@0: } michael@0: michael@0: // Move the hidden textarea near the cursor to prevent scrolling artifacts michael@0: if (cm.options.moveInputWithCursor) { michael@0: var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); michael@0: var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); michael@0: var top = Math.max(0, Math.min(display.wrapper.clientHeight - 10, michael@0: headPos.top + lineOff.top - wrapOff.top)); michael@0: var left = Math.max(0, Math.min(display.wrapper.clientWidth - 10, michael@0: headPos.left + lineOff.left - wrapOff.left)); michael@0: display.inputDiv.style.top = top + "px"; michael@0: display.inputDiv.style.left = left + "px"; michael@0: } michael@0: michael@0: removeChildrenAndAdd(display.cursorDiv, curFragment); michael@0: removeChildrenAndAdd(display.selectionDiv, selFragment); michael@0: } michael@0: michael@0: // Draws a cursor for the given range michael@0: function updateSelectionCursor(cm, range, output) { michael@0: var pos = cursorCoords(cm, range.head, "div"); michael@0: michael@0: var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); michael@0: cursor.style.left = pos.left + "px"; michael@0: cursor.style.top = pos.top + "px"; michael@0: cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; michael@0: michael@0: if (pos.other) { michael@0: // Secondary cursor, shown when on a 'jump' in bi-directional text michael@0: var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); michael@0: otherCursor.style.display = ""; michael@0: otherCursor.style.left = pos.other.left + "px"; michael@0: otherCursor.style.top = pos.other.top + "px"; michael@0: otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; michael@0: } michael@0: } michael@0: michael@0: // Draws the given range as a highlighted selection michael@0: function updateSelectionRange(cm, range, output) { michael@0: var display = cm.display, doc = cm.doc; michael@0: var fragment = document.createDocumentFragment(); michael@0: var padding = paddingH(cm.display), leftSide = padding.left, rightSide = display.lineSpace.offsetWidth - padding.right; michael@0: michael@0: function add(left, top, width, bottom) { michael@0: if (top < 0) top = 0; michael@0: fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + michael@0: "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) + michael@0: "px; height: " + (bottom - top) + "px")); michael@0: } michael@0: michael@0: function drawForLine(line, fromArg, toArg) { michael@0: var lineObj = getLine(doc, line); michael@0: var lineLen = lineObj.text.length; michael@0: var start, end; michael@0: function coords(ch, bias) { michael@0: return charCoords(cm, Pos(line, ch), "div", lineObj, bias); michael@0: } michael@0: michael@0: iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { michael@0: var leftPos = coords(from, "left"), rightPos, left, right; michael@0: if (from == to) { michael@0: rightPos = leftPos; michael@0: left = right = leftPos.left; michael@0: } else { michael@0: rightPos = coords(to - 1, "right"); michael@0: if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } michael@0: left = leftPos.left; michael@0: right = rightPos.right; michael@0: } michael@0: if (fromArg == null && from == 0) left = leftSide; michael@0: if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part michael@0: add(left, leftPos.top, null, leftPos.bottom); michael@0: left = leftSide; michael@0: if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); michael@0: } michael@0: if (toArg == null && to == lineLen) right = rightSide; michael@0: if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) michael@0: start = leftPos; michael@0: if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) michael@0: end = rightPos; michael@0: if (left < leftSide + 1) left = leftSide; michael@0: add(left, rightPos.top, right - left, rightPos.bottom); michael@0: }); michael@0: return {start: start, end: end}; michael@0: } michael@0: michael@0: var sFrom = range.from(), sTo = range.to(); michael@0: if (sFrom.line == sTo.line) { michael@0: drawForLine(sFrom.line, sFrom.ch, sTo.ch); michael@0: } else { michael@0: var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); michael@0: var singleVLine = visualLine(fromLine) == visualLine(toLine); michael@0: var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; michael@0: var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; michael@0: if (singleVLine) { michael@0: if (leftEnd.top < rightStart.top - 2) { michael@0: add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); michael@0: add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); michael@0: } else { michael@0: add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); michael@0: } michael@0: } michael@0: if (leftEnd.bottom < rightStart.top) michael@0: add(leftSide, leftEnd.bottom, null, rightStart.top); michael@0: } michael@0: michael@0: output.appendChild(fragment); michael@0: } michael@0: michael@0: // Cursor-blinking michael@0: function restartBlink(cm) { michael@0: if (!cm.state.focused) return; michael@0: var display = cm.display; michael@0: clearInterval(display.blinker); michael@0: var on = true; michael@0: display.cursorDiv.style.visibility = ""; michael@0: if (cm.options.cursorBlinkRate > 0) michael@0: display.blinker = setInterval(function() { michael@0: display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; michael@0: }, cm.options.cursorBlinkRate); michael@0: } michael@0: michael@0: // HIGHLIGHT WORKER michael@0: michael@0: function startWorker(cm, time) { michael@0: if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) michael@0: cm.state.highlight.set(time, bind(highlightWorker, cm)); michael@0: } michael@0: michael@0: function highlightWorker(cm) { michael@0: var doc = cm.doc; michael@0: if (doc.frontier < doc.first) doc.frontier = doc.first; michael@0: if (doc.frontier >= cm.display.viewTo) return; michael@0: var end = +new Date + cm.options.workTime; michael@0: var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); michael@0: michael@0: runInOp(cm, function() { michael@0: doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) { michael@0: if (doc.frontier >= cm.display.viewFrom) { // Visible michael@0: var oldStyles = line.styles; michael@0: line.styles = highlightLine(cm, line, state, true); michael@0: var ischange = !oldStyles || oldStyles.length != line.styles.length; michael@0: for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; michael@0: if (ischange) regLineChange(cm, doc.frontier, "text"); michael@0: line.stateAfter = copyState(doc.mode, state); michael@0: } else { michael@0: processLine(cm, line.text, state); michael@0: line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; michael@0: } michael@0: ++doc.frontier; michael@0: if (+new Date > end) { michael@0: startWorker(cm, cm.options.workDelay); michael@0: return true; michael@0: } michael@0: }); michael@0: }); michael@0: } michael@0: michael@0: // Finds the line to start with when starting a parse. Tries to michael@0: // find a line with a stateAfter, so that it can start with a michael@0: // valid state. If that fails, it returns the line with the michael@0: // smallest indentation, which tends to need the least context to michael@0: // parse correctly. michael@0: function findStartLine(cm, n, precise) { michael@0: var minindent, minline, doc = cm.doc; michael@0: var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); michael@0: for (var search = n; search > lim; --search) { michael@0: if (search <= doc.first) return doc.first; michael@0: var line = getLine(doc, search - 1); michael@0: if (line.stateAfter && (!precise || search <= doc.frontier)) return search; michael@0: var indented = countColumn(line.text, null, cm.options.tabSize); michael@0: if (minline == null || minindent > indented) { michael@0: minline = search - 1; michael@0: minindent = indented; michael@0: } michael@0: } michael@0: return minline; michael@0: } michael@0: michael@0: function getStateBefore(cm, n, precise) { michael@0: var doc = cm.doc, display = cm.display; michael@0: if (!doc.mode.startState) return true; michael@0: var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter; michael@0: if (!state) state = startState(doc.mode); michael@0: else state = copyState(doc.mode, state); michael@0: doc.iter(pos, n, function(line) { michael@0: processLine(cm, line.text, state); michael@0: var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo; michael@0: line.stateAfter = save ? copyState(doc.mode, state) : null; michael@0: ++pos; michael@0: }); michael@0: if (precise) doc.frontier = pos; michael@0: return state; michael@0: } michael@0: michael@0: // POSITION MEASUREMENT michael@0: michael@0: function paddingTop(display) {return display.lineSpace.offsetTop;} michael@0: function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} michael@0: function paddingH(display) { michael@0: if (display.cachedPaddingH) return display.cachedPaddingH; michael@0: var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); michael@0: var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; michael@0: return display.cachedPaddingH = {left: parseInt(style.paddingLeft), michael@0: right: parseInt(style.paddingRight)}; michael@0: } michael@0: michael@0: // Ensure the lineView.wrapping.heights array is populated. This is michael@0: // an array of bottom offsets for the lines that make up a drawn michael@0: // line. When lineWrapping is on, there might be more than one michael@0: // height. michael@0: function ensureLineHeights(cm, lineView, rect) { michael@0: var wrapping = cm.options.lineWrapping; michael@0: var curWidth = wrapping && cm.display.scroller.clientWidth; michael@0: if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { michael@0: var heights = lineView.measure.heights = []; michael@0: if (wrapping) { michael@0: lineView.measure.width = curWidth; michael@0: var rects = lineView.text.firstChild.getClientRects(); michael@0: for (var i = 0; i < rects.length - 1; i++) { michael@0: var cur = rects[i], next = rects[i + 1]; michael@0: if (Math.abs(cur.bottom - next.bottom) > 2) michael@0: heights.push((cur.bottom + next.top) / 2 - rect.top); michael@0: } michael@0: } michael@0: heights.push(rect.bottom - rect.top); michael@0: } michael@0: } michael@0: michael@0: // Find a line map (mapping character offsets to text nodes) and a michael@0: // measurement cache for the given line number. (A line view might michael@0: // contain multiple lines when collapsed ranges are present.) michael@0: function mapFromLineView(lineView, line, lineN) { michael@0: if (lineView.line == line) michael@0: return {map: lineView.measure.map, cache: lineView.measure.cache}; michael@0: for (var i = 0; i < lineView.rest.length; i++) michael@0: if (lineView.rest[i] == line) michael@0: return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]}; michael@0: for (var i = 0; i < lineView.rest.length; i++) michael@0: if (lineNo(lineView.rest[i]) > lineN) michael@0: return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true}; michael@0: } michael@0: michael@0: // Render a line into the hidden node display.externalMeasured. Used michael@0: // when measurement is needed for a line that's not in the viewport. michael@0: function updateExternalMeasurement(cm, line) { michael@0: line = visualLine(line); michael@0: var lineN = lineNo(line); michael@0: var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); michael@0: view.lineN = lineN; michael@0: var built = view.built = buildLineContent(cm, view); michael@0: view.text = built.pre; michael@0: removeChildrenAndAdd(cm.display.lineMeasure, built.pre); michael@0: return view; michael@0: } michael@0: michael@0: // Get a {top, bottom, left, right} box (in line-local coordinates) michael@0: // for a given character. michael@0: function measureChar(cm, line, ch, bias) { michael@0: return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); michael@0: } michael@0: michael@0: // Find a line view that corresponds to the given line number. michael@0: function findViewForLine(cm, lineN) { michael@0: if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) michael@0: return cm.display.view[findViewIndex(cm, lineN)]; michael@0: var ext = cm.display.externalMeasured; michael@0: if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) michael@0: return ext; michael@0: } michael@0: michael@0: // Measurement can be split in two steps, the set-up work that michael@0: // applies to the whole line, and the measurement of the actual michael@0: // character. Functions like coordsChar, that need to do a lot of michael@0: // measurements in a row, can thus ensure that the set-up work is michael@0: // only done once. michael@0: function prepareMeasureForLine(cm, line) { michael@0: var lineN = lineNo(line); michael@0: var view = findViewForLine(cm, lineN); michael@0: if (view && !view.text) michael@0: view = null; michael@0: else if (view && view.changes) michael@0: updateLineForChanges(cm, view, lineN, getDimensions(cm)); michael@0: if (!view) michael@0: view = updateExternalMeasurement(cm, line); michael@0: michael@0: var info = mapFromLineView(view, line, lineN); michael@0: return { michael@0: line: line, view: view, rect: null, michael@0: map: info.map, cache: info.cache, before: info.before, michael@0: hasHeights: false michael@0: }; michael@0: } michael@0: michael@0: // Given a prepared measurement object, measures the position of an michael@0: // actual character (or fetches it from the cache). michael@0: function measureCharPrepared(cm, prepared, ch, bias) { michael@0: if (prepared.before) ch = -1; michael@0: var key = ch + (bias || ""), found; michael@0: if (prepared.cache.hasOwnProperty(key)) { michael@0: found = prepared.cache[key]; michael@0: } else { michael@0: if (!prepared.rect) michael@0: prepared.rect = prepared.view.text.getBoundingClientRect(); michael@0: if (!prepared.hasHeights) { michael@0: ensureLineHeights(cm, prepared.view, prepared.rect); michael@0: prepared.hasHeights = true; michael@0: } michael@0: found = measureCharInner(cm, prepared, ch, bias); michael@0: if (!found.bogus) prepared.cache[key] = found; michael@0: } michael@0: return {left: found.left, right: found.right, top: found.top, bottom: found.bottom}; michael@0: } michael@0: michael@0: var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; michael@0: michael@0: function measureCharInner(cm, prepared, ch, bias) { michael@0: var map = prepared.map; michael@0: michael@0: var node, start, end, collapse; michael@0: // First, search the line map for the text node corresponding to, michael@0: // or closest to, the target character. michael@0: for (var i = 0; i < map.length; i += 3) { michael@0: var mStart = map[i], mEnd = map[i + 1]; michael@0: if (ch < mStart) { michael@0: start = 0; end = 1; michael@0: collapse = "left"; michael@0: } else if (ch < mEnd) { michael@0: start = ch - mStart; michael@0: end = start + 1; michael@0: } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { michael@0: end = mEnd - mStart; michael@0: start = end - 1; michael@0: if (ch >= mEnd) collapse = "right"; michael@0: } michael@0: if (start != null) { michael@0: node = map[i + 2]; michael@0: if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) michael@0: collapse = bias; michael@0: if (bias == "left" && start == 0) michael@0: while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { michael@0: node = map[(i -= 3) + 2]; michael@0: collapse = "left"; michael@0: } michael@0: if (bias == "right" && start == mEnd - mStart) michael@0: while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { michael@0: node = map[(i += 3) + 2]; michael@0: collapse = "right"; michael@0: } michael@0: break; michael@0: } michael@0: } michael@0: michael@0: var rect; michael@0: if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. michael@0: while (start && isExtendingChar(prepared.line.text.charAt(mStart + start))) --start; michael@0: while (mStart + end < mEnd && isExtendingChar(prepared.line.text.charAt(mStart + end))) ++end; michael@0: if (ie_upto8 && start == 0 && end == mEnd - mStart) { michael@0: rect = node.parentNode.getBoundingClientRect(); michael@0: } else if (ie && cm.options.lineWrapping) { michael@0: var rects = range(node, start, end).getClientRects(); michael@0: if (rects.length) michael@0: rect = rects[bias == "right" ? rects.length - 1 : 0]; michael@0: else michael@0: rect = nullRect; michael@0: } else { michael@0: rect = range(node, start, end).getBoundingClientRect(); michael@0: } michael@0: } else { // If it is a widget, simply get the box for the whole widget. michael@0: if (start > 0) collapse = bias = "right"; michael@0: var rects; michael@0: if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) michael@0: rect = rects[bias == "right" ? rects.length - 1 : 0]; michael@0: else michael@0: rect = node.getBoundingClientRect(); michael@0: } michael@0: if (ie_upto8 && !start && (!rect || !rect.left && !rect.right)) { michael@0: var rSpan = node.parentNode.getClientRects()[0]; michael@0: if (rSpan) michael@0: rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; michael@0: else michael@0: rect = nullRect; michael@0: } michael@0: michael@0: var top, bot = (rect.bottom + rect.top) / 2 - prepared.rect.top; michael@0: var heights = prepared.view.measure.heights; michael@0: for (var i = 0; i < heights.length - 1; i++) michael@0: if (bot < heights[i]) break; michael@0: top = i ? heights[i - 1] : 0; bot = heights[i]; michael@0: var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, michael@0: right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, michael@0: top: top, bottom: bot}; michael@0: if (!rect.left && !rect.right) result.bogus = true; michael@0: return result; michael@0: } michael@0: michael@0: function clearLineMeasurementCacheFor(lineView) { michael@0: if (lineView.measure) { michael@0: lineView.measure.cache = {}; michael@0: lineView.measure.heights = null; michael@0: if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) michael@0: lineView.measure.caches[i] = {}; michael@0: } michael@0: } michael@0: michael@0: function clearLineMeasurementCache(cm) { michael@0: cm.display.externalMeasure = null; michael@0: removeChildren(cm.display.lineMeasure); michael@0: for (var i = 0; i < cm.display.view.length; i++) michael@0: clearLineMeasurementCacheFor(cm.display.view[i]); michael@0: } michael@0: michael@0: function clearCaches(cm) { michael@0: clearLineMeasurementCache(cm); michael@0: cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; michael@0: if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; michael@0: cm.display.lineNumChars = null; michael@0: } michael@0: michael@0: function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } michael@0: function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } michael@0: michael@0: // Converts a {top, bottom, left, right} box from line-local michael@0: // coordinates into another coordinate system. Context may be one of michael@0: // "line", "div" (display.lineDiv), "local"/null (editor), or "page". michael@0: function intoCoordSystem(cm, lineObj, rect, context) { michael@0: if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { michael@0: var size = widgetHeight(lineObj.widgets[i]); michael@0: rect.top += size; rect.bottom += size; michael@0: } michael@0: if (context == "line") return rect; michael@0: if (!context) context = "local"; michael@0: var yOff = heightAtLine(lineObj); michael@0: if (context == "local") yOff += paddingTop(cm.display); michael@0: else yOff -= cm.display.viewOffset; michael@0: if (context == "page" || context == "window") { michael@0: var lOff = cm.display.lineSpace.getBoundingClientRect(); michael@0: yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); michael@0: var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); michael@0: rect.left += xOff; rect.right += xOff; michael@0: } michael@0: rect.top += yOff; rect.bottom += yOff; michael@0: return rect; michael@0: } michael@0: michael@0: // Coverts a box from "div" coords to another coordinate system. michael@0: // Context may be "window", "page", "div", or "local"/null. michael@0: function fromCoordSystem(cm, coords, context) { michael@0: if (context == "div") return coords; michael@0: var left = coords.left, top = coords.top; michael@0: // First move into "page" coordinate system michael@0: if (context == "page") { michael@0: left -= pageScrollX(); michael@0: top -= pageScrollY(); michael@0: } else if (context == "local" || !context) { michael@0: var localBox = cm.display.sizer.getBoundingClientRect(); michael@0: left += localBox.left; michael@0: top += localBox.top; michael@0: } michael@0: michael@0: var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); michael@0: return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; michael@0: } michael@0: michael@0: function charCoords(cm, pos, context, lineObj, bias) { michael@0: if (!lineObj) lineObj = getLine(cm.doc, pos.line); michael@0: return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); michael@0: } michael@0: michael@0: // Returns a box for a given cursor position, which may have an michael@0: // 'other' property containing the position of the secondary cursor michael@0: // on a bidi boundary. michael@0: function cursorCoords(cm, pos, context, lineObj, preparedMeasure) { michael@0: lineObj = lineObj || getLine(cm.doc, pos.line); michael@0: if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj); michael@0: function get(ch, right) { michael@0: var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left"); michael@0: if (right) m.left = m.right; else m.right = m.left; michael@0: return intoCoordSystem(cm, lineObj, m, context); michael@0: } michael@0: function getBidi(ch, partPos) { michael@0: var part = order[partPos], right = part.level % 2; michael@0: if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { michael@0: part = order[--partPos]; michael@0: ch = bidiRight(part) - (part.level % 2 ? 0 : 1); michael@0: right = true; michael@0: } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { michael@0: part = order[++partPos]; michael@0: ch = bidiLeft(part) - part.level % 2; michael@0: right = false; michael@0: } michael@0: if (right && ch == part.to && ch > part.from) return get(ch - 1); michael@0: return get(ch, right); michael@0: } michael@0: var order = getOrder(lineObj), ch = pos.ch; michael@0: if (!order) return get(ch); michael@0: var partPos = getBidiPartAt(order, ch); michael@0: var val = getBidi(ch, partPos); michael@0: if (bidiOther != null) val.other = getBidi(ch, bidiOther); michael@0: return val; michael@0: } michael@0: michael@0: // Used to cheaply estimate the coordinates for a position. Used for michael@0: // intermediate scroll updates. michael@0: function estimateCoords(cm, pos) { michael@0: var left = 0, pos = clipPos(cm.doc, pos); michael@0: if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch; michael@0: var lineObj = getLine(cm.doc, pos.line); michael@0: var top = heightAtLine(lineObj) + paddingTop(cm.display); michael@0: return {left: left, right: left, top: top, bottom: top + lineObj.height}; michael@0: } michael@0: michael@0: // Positions returned by coordsChar contain some extra information. michael@0: // xRel is the relative x position of the input coordinates compared michael@0: // to the found position (so xRel > 0 means the coordinates are to michael@0: // the right of the character position, for example). When outside michael@0: // is true, that means the coordinates lie outside the line's michael@0: // vertical range. michael@0: function PosWithInfo(line, ch, outside, xRel) { michael@0: var pos = Pos(line, ch); michael@0: pos.xRel = xRel; michael@0: if (outside) pos.outside = true; michael@0: return pos; michael@0: } michael@0: michael@0: // Compute the character position closest to the given coordinates. michael@0: // Input must be lineSpace-local ("div" coordinate system). michael@0: function coordsChar(cm, x, y) { michael@0: var doc = cm.doc; michael@0: y += cm.display.viewOffset; michael@0: if (y < 0) return PosWithInfo(doc.first, 0, true, -1); michael@0: var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; michael@0: if (lineN > last) michael@0: return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1); michael@0: if (x < 0) x = 0; michael@0: michael@0: var lineObj = getLine(doc, lineN); michael@0: for (;;) { michael@0: var found = coordsCharInner(cm, lineObj, lineN, x, y); michael@0: var merged = collapsedSpanAtEnd(lineObj); michael@0: var mergedPos = merged && merged.find(0, true); michael@0: if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) michael@0: lineN = lineNo(lineObj = mergedPos.to.line); michael@0: else michael@0: return found; michael@0: } michael@0: } michael@0: michael@0: function coordsCharInner(cm, lineObj, lineNo, x, y) { michael@0: var innerOff = y - heightAtLine(lineObj); michael@0: var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; michael@0: var preparedMeasure = prepareMeasureForLine(cm, lineObj); michael@0: michael@0: function getX(ch) { michael@0: var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure); michael@0: wrongLine = true; michael@0: if (innerOff > sp.bottom) return sp.left - adjust; michael@0: else if (innerOff < sp.top) return sp.left + adjust; michael@0: else wrongLine = false; michael@0: return sp.left; michael@0: } michael@0: michael@0: var bidi = getOrder(lineObj), dist = lineObj.text.length; michael@0: var from = lineLeft(lineObj), to = lineRight(lineObj); michael@0: var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; michael@0: michael@0: if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); michael@0: // Do a binary search between these bounds. michael@0: for (;;) { michael@0: if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { michael@0: var ch = x < fromX || x - fromX <= toX - x ? from : to; michael@0: var xDiff = x - (ch == from ? fromX : toX); michael@0: while (isExtendingChar(lineObj.text.charAt(ch))) ++ch; michael@0: var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, michael@0: xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0); michael@0: return pos; michael@0: } michael@0: var step = Math.ceil(dist / 2), middle = from + step; michael@0: if (bidi) { michael@0: middle = from; michael@0: for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); michael@0: } michael@0: var middleX = getX(middle); michael@0: if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} michael@0: else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} michael@0: } michael@0: } michael@0: michael@0: var measureText; michael@0: // Compute the default text height. michael@0: function textHeight(display) { michael@0: if (display.cachedTextHeight != null) return display.cachedTextHeight; michael@0: if (measureText == null) { michael@0: measureText = elt("pre"); michael@0: // Measure a bunch of lines, for browsers that compute michael@0: // fractional heights. michael@0: for (var i = 0; i < 49; ++i) { michael@0: measureText.appendChild(document.createTextNode("x")); michael@0: measureText.appendChild(elt("br")); michael@0: } michael@0: measureText.appendChild(document.createTextNode("x")); michael@0: } michael@0: removeChildrenAndAdd(display.measure, measureText); michael@0: var height = measureText.offsetHeight / 50; michael@0: if (height > 3) display.cachedTextHeight = height; michael@0: removeChildren(display.measure); michael@0: return height || 1; michael@0: } michael@0: michael@0: // Compute the default character width. michael@0: function charWidth(display) { michael@0: if (display.cachedCharWidth != null) return display.cachedCharWidth; michael@0: var anchor = elt("span", "xxxxxxxxxx"); michael@0: var pre = elt("pre", [anchor]); michael@0: removeChildrenAndAdd(display.measure, pre); michael@0: var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; michael@0: if (width > 2) display.cachedCharWidth = width; michael@0: return width || 10; michael@0: } michael@0: michael@0: // OPERATIONS michael@0: michael@0: // Operations are used to wrap a series of changes to the editor michael@0: // state in such a way that each change won't have to update the michael@0: // cursor and display (which would be awkward, slow, and michael@0: // error-prone). Instead, display updates are batched and then all michael@0: // combined and executed at once. michael@0: michael@0: var nextOpId = 0; michael@0: // Start a new operation. michael@0: function startOperation(cm) { michael@0: cm.curOp = { michael@0: viewChanged: false, // Flag that indicates that lines might need to be redrawn michael@0: startHeight: cm.doc.height, // Used to detect need to update scrollbar michael@0: forceUpdate: false, // Used to force a redraw michael@0: updateInput: null, // Whether to reset the input textarea michael@0: typing: false, // Whether this reset should be careful to leave existing text (for compositing) michael@0: changeObjs: null, // Accumulated changes, for firing change events michael@0: cursorActivity: false, // Whether to fire a cursorActivity event michael@0: selectionChanged: false, // Whether the selection needs to be redrawn michael@0: updateMaxLine: false, // Set when the widest line needs to be determined anew michael@0: scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet michael@0: scrollToPos: null, // Used to scroll to a specific position michael@0: id: ++nextOpId // Unique ID michael@0: }; michael@0: if (!delayedCallbackDepth++) delayedCallbacks = []; michael@0: } michael@0: michael@0: // Finish an operation, updating the display and signalling delayed events michael@0: function endOperation(cm) { michael@0: var op = cm.curOp, doc = cm.doc, display = cm.display; michael@0: cm.curOp = null; michael@0: michael@0: if (op.updateMaxLine) findMaxLine(cm); michael@0: michael@0: // If it looks like an update might be needed, call updateDisplay michael@0: if (op.viewChanged || op.forceUpdate || op.scrollTop != null || michael@0: op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || michael@0: op.scrollToPos.to.line >= display.viewTo) || michael@0: display.maxLineChanged && cm.options.lineWrapping) { michael@0: var updated = updateDisplay(cm, {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); michael@0: if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop; michael@0: } michael@0: // If no update was run, but the selection changed, redraw that. michael@0: if (!updated && op.selectionChanged) updateSelection(cm); michael@0: if (!updated && op.startHeight != cm.doc.height) updateScrollbars(cm); michael@0: michael@0: // Propagate the scroll position to the actual DOM scroller michael@0: if (op.scrollTop != null && display.scroller.scrollTop != op.scrollTop) { michael@0: var top = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)); michael@0: display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = top; michael@0: } michael@0: if (op.scrollLeft != null && display.scroller.scrollLeft != op.scrollLeft) { michael@0: var left = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft)); michael@0: display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = left; michael@0: alignHorizontally(cm); michael@0: } michael@0: // If we need to scroll a specific position into view, do so. michael@0: if (op.scrollToPos) { michael@0: var coords = scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos.from), michael@0: clipPos(cm.doc, op.scrollToPos.to), op.scrollToPos.margin); michael@0: if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords); michael@0: } michael@0: michael@0: if (op.selectionChanged) restartBlink(cm); michael@0: michael@0: if (cm.state.focused && op.updateInput) michael@0: resetInput(cm, op.typing); michael@0: michael@0: // Fire events for markers that are hidden/unidden by editing or michael@0: // undoing michael@0: var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; michael@0: if (hidden) for (var i = 0; i < hidden.length; ++i) michael@0: if (!hidden[i].lines.length) signal(hidden[i], "hide"); michael@0: if (unhidden) for (var i = 0; i < unhidden.length; ++i) michael@0: if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); michael@0: michael@0: var delayed; michael@0: if (!--delayedCallbackDepth) { michael@0: delayed = delayedCallbacks; michael@0: delayedCallbacks = null; michael@0: } michael@0: // Fire change events, and delayed event handlers michael@0: if (op.changeObjs) { michael@0: for (var i = 0; i < op.changeObjs.length; i++) michael@0: signal(cm, "change", cm, op.changeObjs[i]); michael@0: signal(cm, "changes", cm, op.changeObjs); michael@0: } michael@0: if (op.cursorActivity) signal(cm, "cursorActivity", cm); michael@0: if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i](); michael@0: } michael@0: michael@0: // Run the given function in an operation michael@0: function runInOp(cm, f) { michael@0: if (cm.curOp) return f(); michael@0: startOperation(cm); michael@0: try { return f(); } michael@0: finally { endOperation(cm); } michael@0: } michael@0: // Wraps a function in an operation. Returns the wrapped function. michael@0: function operation(cm, f) { michael@0: return function() { michael@0: if (cm.curOp) return f.apply(cm, arguments); michael@0: startOperation(cm); michael@0: try { return f.apply(cm, arguments); } michael@0: finally { endOperation(cm); } michael@0: }; michael@0: } michael@0: // Used to add methods to editor and doc instances, wrapping them in michael@0: // operations. michael@0: function methodOp(f) { michael@0: return function() { michael@0: if (this.curOp) return f.apply(this, arguments); michael@0: startOperation(this); michael@0: try { return f.apply(this, arguments); } michael@0: finally { endOperation(this); } michael@0: }; michael@0: } michael@0: function docMethodOp(f) { michael@0: return function() { michael@0: var cm = this.cm; michael@0: if (!cm || cm.curOp) return f.apply(this, arguments); michael@0: startOperation(cm); michael@0: try { return f.apply(this, arguments); } michael@0: finally { endOperation(cm); } michael@0: }; michael@0: } michael@0: michael@0: // VIEW TRACKING michael@0: michael@0: // These objects are used to represent the visible (currently drawn) michael@0: // part of the document. A LineView may correspond to multiple michael@0: // logical lines, if those are connected by collapsed ranges. michael@0: function LineView(doc, line, lineN) { michael@0: // The starting line michael@0: this.line = line; michael@0: // Continuing lines, if any michael@0: this.rest = visualLineContinued(line); michael@0: // Number of logical lines in this visual line michael@0: this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; michael@0: this.node = this.text = null; michael@0: this.hidden = lineIsHidden(doc, line); michael@0: } michael@0: michael@0: // Create a range of LineView objects for the given lines. michael@0: function buildViewArray(cm, from, to) { michael@0: var array = [], nextPos; michael@0: for (var pos = from; pos < to; pos = nextPos) { michael@0: var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); michael@0: nextPos = pos + view.size; michael@0: array.push(view); michael@0: } michael@0: return array; michael@0: } michael@0: michael@0: // Updates the display.view data structure for a given change to the michael@0: // document. From and to are in pre-change coordinates. Lendiff is michael@0: // the amount of lines added or subtracted by the change. This is michael@0: // used for changes that span multiple lines, or change the way michael@0: // lines are divided into visual lines. regLineChange (below) michael@0: // registers single-line changes. michael@0: function regChange(cm, from, to, lendiff) { michael@0: if (from == null) from = cm.doc.first; michael@0: if (to == null) to = cm.doc.first + cm.doc.size; michael@0: if (!lendiff) lendiff = 0; michael@0: michael@0: var display = cm.display; michael@0: if (lendiff && to < display.viewTo && michael@0: (display.updateLineNumbers == null || display.updateLineNumbers > from)) michael@0: display.updateLineNumbers = from; michael@0: michael@0: cm.curOp.viewChanged = true; michael@0: michael@0: if (from >= display.viewTo) { // Change after michael@0: if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) michael@0: resetView(cm); michael@0: } else if (to <= display.viewFrom) { // Change before michael@0: if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { michael@0: resetView(cm); michael@0: } else { michael@0: display.viewFrom += lendiff; michael@0: display.viewTo += lendiff; michael@0: } michael@0: } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap michael@0: resetView(cm); michael@0: } else if (from <= display.viewFrom) { // Top overlap michael@0: var cut = viewCuttingPoint(cm, to, to + lendiff, 1); michael@0: if (cut) { michael@0: display.view = display.view.slice(cut.index); michael@0: display.viewFrom = cut.lineN; michael@0: display.viewTo += lendiff; michael@0: } else { michael@0: resetView(cm); michael@0: } michael@0: } else if (to >= display.viewTo) { // Bottom overlap michael@0: var cut = viewCuttingPoint(cm, from, from, -1); michael@0: if (cut) { michael@0: display.view = display.view.slice(0, cut.index); michael@0: display.viewTo = cut.lineN; michael@0: } else { michael@0: resetView(cm); michael@0: } michael@0: } else { // Gap in the middle michael@0: var cutTop = viewCuttingPoint(cm, from, from, -1); michael@0: var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); michael@0: if (cutTop && cutBot) { michael@0: display.view = display.view.slice(0, cutTop.index) michael@0: .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) michael@0: .concat(display.view.slice(cutBot.index)); michael@0: display.viewTo += lendiff; michael@0: } else { michael@0: resetView(cm); michael@0: } michael@0: } michael@0: michael@0: var ext = display.externalMeasured; michael@0: if (ext) { michael@0: if (to < ext.lineN) michael@0: ext.lineN += lendiff; michael@0: else if (from < ext.lineN + ext.size) michael@0: display.externalMeasured = null; michael@0: } michael@0: } michael@0: michael@0: // Register a change to a single line. Type must be one of "text", michael@0: // "gutter", "class", "widget" michael@0: function regLineChange(cm, line, type) { michael@0: cm.curOp.viewChanged = true; michael@0: var display = cm.display, ext = cm.display.externalMeasured; michael@0: if (ext && line >= ext.lineN && line < ext.lineN + ext.size) michael@0: display.externalMeasured = null; michael@0: michael@0: if (line < display.viewFrom || line >= display.viewTo) return; michael@0: var lineView = display.view[findViewIndex(cm, line)]; michael@0: if (lineView.node == null) return; michael@0: var arr = lineView.changes || (lineView.changes = []); michael@0: if (indexOf(arr, type) == -1) arr.push(type); michael@0: } michael@0: michael@0: // Clear the view. michael@0: function resetView(cm) { michael@0: cm.display.viewFrom = cm.display.viewTo = cm.doc.first; michael@0: cm.display.view = []; michael@0: cm.display.viewOffset = 0; michael@0: } michael@0: michael@0: // Find the view element corresponding to a given line. Return null michael@0: // when the line isn't visible. michael@0: function findViewIndex(cm, n) { michael@0: if (n >= cm.display.viewTo) return null; michael@0: n -= cm.display.viewFrom; michael@0: if (n < 0) return null; michael@0: var view = cm.display.view; michael@0: for (var i = 0; i < view.length; i++) { michael@0: n -= view[i].size; michael@0: if (n < 0) return i; michael@0: } michael@0: } michael@0: michael@0: function viewCuttingPoint(cm, oldN, newN, dir) { michael@0: var index = findViewIndex(cm, oldN), diff, view = cm.display.view; michael@0: if (!sawCollapsedSpans) return {index: index, lineN: newN}; michael@0: for (var i = 0, n = cm.display.viewFrom; i < index; i++) michael@0: n += view[i].size; michael@0: if (n != oldN) { michael@0: if (dir > 0) { michael@0: if (index == view.length - 1) return null; michael@0: diff = (n + view[index].size) - oldN; michael@0: index++; michael@0: } else { michael@0: diff = n - oldN; michael@0: } michael@0: oldN += diff; newN += diff; michael@0: } michael@0: while (visualLineNo(cm.doc, newN) != newN) { michael@0: if (index == (dir < 0 ? 0 : view.length - 1)) return null; michael@0: newN += dir * view[index - (dir < 0 ? 1 : 0)].size; michael@0: index += dir; michael@0: } michael@0: return {index: index, lineN: newN}; michael@0: } michael@0: michael@0: // Force the view to cover a given range, adding empty view element michael@0: // or clipping off existing ones as needed. michael@0: function adjustView(cm, from, to) { michael@0: var display = cm.display, view = display.view; michael@0: if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { michael@0: display.view = buildViewArray(cm, from, to); michael@0: display.viewFrom = from; michael@0: } else { michael@0: if (display.viewFrom > from) michael@0: display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); michael@0: else if (display.viewFrom < from) michael@0: display.view = display.view.slice(findViewIndex(cm, from)); michael@0: display.viewFrom = from; michael@0: if (display.viewTo < to) michael@0: display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); michael@0: else if (display.viewTo > to) michael@0: display.view = display.view.slice(0, findViewIndex(cm, to)); michael@0: } michael@0: display.viewTo = to; michael@0: } michael@0: michael@0: // Count the number of lines in the view whose DOM representation is michael@0: // out of date (or nonexistent). michael@0: function countDirtyView(cm) { michael@0: var view = cm.display.view, dirty = 0; michael@0: for (var i = 0; i < view.length; i++) { michael@0: var lineView = view[i]; michael@0: if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty; michael@0: } michael@0: return dirty; michael@0: } michael@0: michael@0: // INPUT HANDLING michael@0: michael@0: // Poll for input changes, using the normal rate of polling. This michael@0: // runs as long as the editor is focused. michael@0: function slowPoll(cm) { michael@0: if (cm.display.pollingFast) return; michael@0: cm.display.poll.set(cm.options.pollInterval, function() { michael@0: readInput(cm); michael@0: if (cm.state.focused) slowPoll(cm); michael@0: }); michael@0: } michael@0: michael@0: // When an event has just come in that is likely to add or change michael@0: // something in the input textarea, we poll faster, to ensure that michael@0: // the change appears on the screen quickly. michael@0: function fastPoll(cm) { michael@0: var missed = false; michael@0: cm.display.pollingFast = true; michael@0: function p() { michael@0: var changed = readInput(cm); michael@0: if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);} michael@0: else {cm.display.pollingFast = false; slowPoll(cm);} michael@0: } michael@0: cm.display.poll.set(20, p); michael@0: } michael@0: michael@0: // Read input from the textarea, and update the document to match. michael@0: // When something is selected, it is present in the textarea, and michael@0: // selected (unless it is huge, in which case a placeholder is michael@0: // used). When nothing is selected, the cursor sits after previously michael@0: // seen text (can be empty), which is stored in prevInput (we must michael@0: // not reset the textarea when typing, because that breaks IME). michael@0: function readInput(cm) { michael@0: var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc; michael@0: // Since this is called a *lot*, try to bail out as cheaply as michael@0: // possible when it is clear that nothing happened. hasSelection michael@0: // will be the case when there is a lot of text in the textarea, michael@0: // in which case reading its value would be expensive. michael@0: if (!cm.state.focused || hasSelection(input) || isReadOnly(cm) || cm.options.disableInput) return false; michael@0: var text = input.value; michael@0: // If nothing changed, bail. michael@0: if (text == prevInput && !cm.somethingSelected()) return false; michael@0: // Work around nonsensical selection resetting in IE9/10 michael@0: if (ie && !ie_upto8 && cm.display.inputHasSelection === text) { michael@0: resetInput(cm); michael@0: return false; michael@0: } michael@0: michael@0: var withOp = !cm.curOp; michael@0: if (withOp) startOperation(cm); michael@0: cm.display.shift = false; michael@0: michael@0: // Find the part of the input that is actually new michael@0: var same = 0, l = Math.min(prevInput.length, text.length); michael@0: while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; michael@0: var inserted = text.slice(same), textLines = splitLines(inserted); michael@0: michael@0: // When pasing N lines into N selections, insert one line per selection michael@0: var multiPaste = cm.state.pasteIncoming && textLines.length > 1 && doc.sel.ranges.length == textLines.length; michael@0: michael@0: // Normal behavior is to insert the new text into every selection michael@0: for (var i = doc.sel.ranges.length - 1; i >= 0; i--) { michael@0: var range = doc.sel.ranges[i]; michael@0: var from = range.from(), to = range.to(); michael@0: // Handle deletion michael@0: if (same < prevInput.length) michael@0: from = Pos(from.line, from.ch - (prevInput.length - same)); michael@0: // Handle overwrite michael@0: else if (cm.state.overwrite && range.empty() && !cm.state.pasteIncoming) michael@0: to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); michael@0: var updateInput = cm.curOp.updateInput; michael@0: var changeEvent = {from: from, to: to, text: multiPaste ? [textLines[i]] : textLines, michael@0: origin: cm.state.pasteIncoming ? "paste" : cm.state.cutIncoming ? "cut" : "+input"}; michael@0: makeChange(cm.doc, changeEvent); michael@0: signalLater(cm, "inputRead", cm, changeEvent); michael@0: // When an 'electric' character is inserted, immediately trigger a reindent michael@0: if (inserted && !cm.state.pasteIncoming && cm.options.electricChars && michael@0: cm.options.smartIndent && range.head.ch < 100 && michael@0: (!i || doc.sel.ranges[i - 1].head.line != range.head.line)) { michael@0: var electric = cm.getModeAt(range.head).electricChars; michael@0: if (electric) for (var j = 0; j < electric.length; j++) michael@0: if (inserted.indexOf(electric.charAt(j)) > -1) { michael@0: indentLine(cm, range.head.line, "smart"); michael@0: break; michael@0: } michael@0: } michael@0: } michael@0: ensureCursorVisible(cm); michael@0: cm.curOp.updateInput = updateInput; michael@0: cm.curOp.typing = true; michael@0: michael@0: // Don't leave long text in the textarea, since it makes further polling slow michael@0: if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = ""; michael@0: else cm.display.prevInput = text; michael@0: if (withOp) endOperation(cm); michael@0: cm.state.pasteIncoming = cm.state.cutIncoming = false; michael@0: return true; michael@0: } michael@0: michael@0: // Reset the input to correspond to the selection (or to be empty, michael@0: // when not typing and nothing is selected) michael@0: function resetInput(cm, typing) { michael@0: var minimal, selected, doc = cm.doc; michael@0: if (cm.somethingSelected()) { michael@0: cm.display.prevInput = ""; michael@0: var range = doc.sel.primary(); michael@0: minimal = hasCopyEvent && michael@0: (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000); michael@0: var content = minimal ? "-" : selected || cm.getSelection(); michael@0: cm.display.input.value = content; michael@0: if (cm.state.focused) selectInput(cm.display.input); michael@0: if (ie && !ie_upto8) cm.display.inputHasSelection = content; michael@0: } else if (!typing) { michael@0: cm.display.prevInput = cm.display.input.value = ""; michael@0: if (ie && !ie_upto8) cm.display.inputHasSelection = null; michael@0: } michael@0: cm.display.inaccurateSelection = minimal; michael@0: } michael@0: michael@0: function focusInput(cm) { michael@0: if (cm.options.readOnly != "nocursor" && (!mobile || activeElt() != cm.display.input)) michael@0: cm.display.input.focus(); michael@0: } michael@0: michael@0: function ensureFocus(cm) { michael@0: if (!cm.state.focused) { focusInput(cm); onFocus(cm); } michael@0: } michael@0: michael@0: function isReadOnly(cm) { michael@0: return cm.options.readOnly || cm.doc.cantEdit; michael@0: } michael@0: michael@0: // EVENT HANDLERS michael@0: michael@0: // Attach the necessary event handlers when initializing the editor michael@0: function registerEventHandlers(cm) { michael@0: var d = cm.display; michael@0: on(d.scroller, "mousedown", operation(cm, onMouseDown)); michael@0: // Older IE's will not fire a second mousedown for a double click michael@0: if (ie_upto10) michael@0: on(d.scroller, "dblclick", operation(cm, function(e) { michael@0: if (signalDOMEvent(cm, e)) return; michael@0: var pos = posFromMouse(cm, e); michael@0: if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; michael@0: e_preventDefault(e); michael@0: var word = findWordAt(cm.doc, pos); michael@0: extendSelection(cm.doc, word.anchor, word.head); michael@0: })); michael@0: else michael@0: on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); }); michael@0: // Prevent normal selection in the editor (we handle our own) michael@0: on(d.lineSpace, "selectstart", function(e) { michael@0: if (!eventInWidget(d, e)) e_preventDefault(e); michael@0: }); michael@0: // Some browsers fire contextmenu *after* opening the menu, at michael@0: // which point we can't mess with it anymore. Context menu is michael@0: // handled in onMouseDown for these browsers. michael@0: if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); michael@0: michael@0: // Sync scrolling between fake scrollbars and real scrollable michael@0: // area, ensure viewport is updated when scrolling. michael@0: on(d.scroller, "scroll", function() { michael@0: if (d.scroller.clientHeight) { michael@0: setScrollTop(cm, d.scroller.scrollTop); michael@0: setScrollLeft(cm, d.scroller.scrollLeft, true); michael@0: signal(cm, "scroll", cm); michael@0: } michael@0: }); michael@0: on(d.scrollbarV, "scroll", function() { michael@0: if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop); michael@0: }); michael@0: on(d.scrollbarH, "scroll", function() { michael@0: if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft); michael@0: }); michael@0: michael@0: // Listen to wheel events in order to try and update the viewport on time. michael@0: on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); michael@0: on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); michael@0: michael@0: // Prevent clicks in the scrollbars from killing focus michael@0: function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); } michael@0: on(d.scrollbarH, "mousedown", reFocus); michael@0: on(d.scrollbarV, "mousedown", reFocus); michael@0: // Prevent wrapper from ever scrolling michael@0: on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); michael@0: michael@0: // When the window resizes, we need to refresh active editors. michael@0: var resizeTimer; michael@0: function onResize() { michael@0: if (resizeTimer == null) resizeTimer = setTimeout(function() { michael@0: resizeTimer = null; michael@0: // Might be a text scaling operation, clear size caches. michael@0: d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = knownScrollbarWidth = null; michael@0: cm.setSize(); michael@0: }, 100); michael@0: } michael@0: on(window, "resize", onResize); michael@0: // The above handler holds on to the editor and its data michael@0: // structures. Here we poll to unregister it when the editor is no michael@0: // longer in the document, so that it can be garbage-collected. michael@0: function unregister() { michael@0: if (contains(document.body, d.wrapper)) setTimeout(unregister, 5000); michael@0: else off(window, "resize", onResize); michael@0: } michael@0: setTimeout(unregister, 5000); michael@0: michael@0: on(d.input, "keyup", operation(cm, onKeyUp)); michael@0: on(d.input, "input", function() { michael@0: if (ie && !ie_upto8 && cm.display.inputHasSelection) cm.display.inputHasSelection = null; michael@0: fastPoll(cm); michael@0: }); michael@0: on(d.input, "keydown", operation(cm, onKeyDown)); michael@0: on(d.input, "keypress", operation(cm, onKeyPress)); michael@0: on(d.input, "focus", bind(onFocus, cm)); michael@0: on(d.input, "blur", bind(onBlur, cm)); michael@0: michael@0: function drag_(e) { michael@0: if (!signalDOMEvent(cm, e)) e_stop(e); michael@0: } michael@0: if (cm.options.dragDrop) { michael@0: on(d.scroller, "dragstart", function(e){onDragStart(cm, e);}); michael@0: on(d.scroller, "dragenter", drag_); michael@0: on(d.scroller, "dragover", drag_); michael@0: on(d.scroller, "drop", operation(cm, onDrop)); michael@0: } michael@0: on(d.scroller, "paste", function(e) { michael@0: if (eventInWidget(d, e)) return; michael@0: cm.state.pasteIncoming = true; michael@0: focusInput(cm); michael@0: fastPoll(cm); michael@0: }); michael@0: on(d.input, "paste", function() { michael@0: cm.state.pasteIncoming = true; michael@0: fastPoll(cm); michael@0: }); michael@0: michael@0: function prepareCopy(e) { michael@0: if (d.inaccurateSelection) { michael@0: d.prevInput = ""; michael@0: d.inaccurateSelection = false; michael@0: d.input.value = cm.getSelection(); michael@0: selectInput(d.input); michael@0: } michael@0: if (e.type == "cut") cm.state.cutIncoming = true; michael@0: } michael@0: on(d.input, "cut", prepareCopy); michael@0: on(d.input, "copy", prepareCopy); michael@0: michael@0: // Needed to handle Tab key in KHTML michael@0: if (khtml) on(d.sizer, "mouseup", function() { michael@0: if (activeElt() == d.input) d.input.blur(); michael@0: focusInput(cm); michael@0: }); michael@0: } michael@0: michael@0: // MOUSE EVENTS michael@0: michael@0: // Return true when the given mouse event happened in a widget michael@0: function eventInWidget(display, e) { michael@0: for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { michael@0: if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true; michael@0: } michael@0: } michael@0: michael@0: // Given a mouse event, find the corresponding position. If liberal michael@0: // is false, it checks whether a gutter or scrollbar was clicked, michael@0: // and returns null if it was. forRect is used by rectangular michael@0: // selections, and tries to estimate a character position even for michael@0: // coordinates beyond the right of the text. michael@0: function posFromMouse(cm, e, liberal, forRect) { michael@0: var display = cm.display; michael@0: if (!liberal) { michael@0: var target = e_target(e); michael@0: if (target == display.scrollbarH || target == display.scrollbarV || michael@0: target == display.scrollbarFiller || target == display.gutterFiller) return null; michael@0: } michael@0: var x, y, space = display.lineSpace.getBoundingClientRect(); michael@0: // Fails unpredictably on IE[67] when mouse is dragged around quickly. michael@0: try { x = e.clientX - space.left; y = e.clientY - space.top; } michael@0: catch (e) { return null; } michael@0: var coords = coordsChar(cm, x, y), line; michael@0: if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { michael@0: var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; michael@0: coords = Pos(coords.line, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff); michael@0: } michael@0: return coords; michael@0: } michael@0: michael@0: // A mouse down can be a single click, double click, triple click, michael@0: // start of selection drag, start of text drag, new cursor michael@0: // (ctrl-click), rectangle drag (alt-drag), or xwin michael@0: // middle-click-paste. Or it might be a click on something we should michael@0: // not interfere with, such as a scrollbar or widget. michael@0: function onMouseDown(e) { michael@0: if (signalDOMEvent(this, e)) return; michael@0: var cm = this, display = cm.display; michael@0: display.shift = e.shiftKey; michael@0: michael@0: if (eventInWidget(display, e)) { michael@0: if (!webkit) { michael@0: // Briefly turn off draggability, to allow widgets to do michael@0: // normal dragging things. michael@0: display.scroller.draggable = false; michael@0: setTimeout(function(){display.scroller.draggable = true;}, 100); michael@0: } michael@0: return; michael@0: } michael@0: if (clickInGutter(cm, e)) return; michael@0: var start = posFromMouse(cm, e); michael@0: window.focus(); michael@0: michael@0: switch (e_button(e)) { michael@0: case 1: michael@0: if (start) michael@0: leftButtonDown(cm, e, start); michael@0: else if (e_target(e) == display.scroller) michael@0: e_preventDefault(e); michael@0: break; michael@0: case 2: michael@0: if (webkit) cm.state.lastMiddleDown = +new Date; michael@0: if (start) extendSelection(cm.doc, start); michael@0: setTimeout(bind(focusInput, cm), 20); michael@0: e_preventDefault(e); michael@0: break; michael@0: case 3: michael@0: if (captureRightClick) onContextMenu(cm, e); michael@0: break; michael@0: } michael@0: } michael@0: michael@0: var lastClick, lastDoubleClick; michael@0: function leftButtonDown(cm, e, start) { michael@0: setTimeout(bind(ensureFocus, cm), 0); michael@0: michael@0: var now = +new Date, type; michael@0: if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { michael@0: type = "triple"; michael@0: } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { michael@0: type = "double"; michael@0: lastDoubleClick = {time: now, pos: start}; michael@0: } else { michael@0: type = "single"; michael@0: lastClick = {time: now, pos: start}; michael@0: } michael@0: michael@0: var sel = cm.doc.sel, addNew = mac ? e.metaKey : e.ctrlKey; michael@0: if (cm.options.dragDrop && dragAndDrop && !addNew && !isReadOnly(cm) && michael@0: type == "single" && sel.contains(start) > -1 && sel.somethingSelected()) michael@0: leftButtonStartDrag(cm, e, start); michael@0: else michael@0: leftButtonSelect(cm, e, start, type, addNew); michael@0: } michael@0: michael@0: // Start a text drag. When it ends, see if any dragging actually michael@0: // happen, and treat as a click if it didn't. michael@0: function leftButtonStartDrag(cm, e, start) { michael@0: var display = cm.display; michael@0: var dragEnd = operation(cm, function(e2) { michael@0: if (webkit) display.scroller.draggable = false; michael@0: cm.state.draggingText = false; michael@0: off(document, "mouseup", dragEnd); michael@0: off(display.scroller, "drop", dragEnd); michael@0: if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { michael@0: e_preventDefault(e2); michael@0: extendSelection(cm.doc, start); michael@0: focusInput(cm); michael@0: // Work around unexplainable focus problem in IE9 (#2127) michael@0: if (ie_upto10 && !ie_upto8) michael@0: setTimeout(function() {document.body.focus(); focusInput(cm);}, 20); michael@0: } michael@0: }); michael@0: // Let the drag handler handle this. michael@0: if (webkit) display.scroller.draggable = true; michael@0: cm.state.draggingText = dragEnd; michael@0: // IE's approach to draggable michael@0: if (display.scroller.dragDrop) display.scroller.dragDrop(); michael@0: on(document, "mouseup", dragEnd); michael@0: on(display.scroller, "drop", dragEnd); michael@0: } michael@0: michael@0: // Normal selection, as opposed to text dragging. michael@0: function leftButtonSelect(cm, e, start, type, addNew) { michael@0: var display = cm.display, doc = cm.doc; michael@0: e_preventDefault(e); michael@0: michael@0: var ourRange, ourIndex, startSel = doc.sel; michael@0: if (addNew) { michael@0: ourIndex = doc.sel.contains(start); michael@0: if (ourIndex > -1) michael@0: ourRange = doc.sel.ranges[ourIndex]; michael@0: else michael@0: ourRange = new Range(start, start); michael@0: } else { michael@0: ourRange = doc.sel.primary(); michael@0: } michael@0: michael@0: if (e.altKey) { michael@0: type = "rect"; michael@0: if (!addNew) ourRange = new Range(start, start); michael@0: start = posFromMouse(cm, e, true, true); michael@0: ourIndex = -1; michael@0: } else if (type == "double") { michael@0: var word = findWordAt(doc, start); michael@0: if (cm.display.shift || doc.extend) michael@0: ourRange = extendRange(doc, ourRange, word.anchor, word.head); michael@0: else michael@0: ourRange = word; michael@0: } else if (type == "triple") { michael@0: var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))); michael@0: if (cm.display.shift || doc.extend) michael@0: ourRange = extendRange(doc, ourRange, line.anchor, line.head); michael@0: else michael@0: ourRange = line; michael@0: } else { michael@0: ourRange = extendRange(doc, ourRange, start); michael@0: } michael@0: michael@0: if (!addNew) { michael@0: ourIndex = 0; michael@0: setSelection(doc, new Selection([ourRange], 0), sel_mouse); michael@0: } else if (ourIndex > -1) { michael@0: replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); michael@0: } else { michael@0: ourIndex = doc.sel.ranges.length; michael@0: setSelection(doc, normalizeSelection(doc.sel.ranges.concat([ourRange]), ourIndex), michael@0: {scroll: false, origin: "*mouse"}); michael@0: } michael@0: michael@0: var lastPos = start; michael@0: function extendTo(pos) { michael@0: if (cmp(lastPos, pos) == 0) return; michael@0: lastPos = pos; michael@0: michael@0: if (type == "rect") { michael@0: var ranges = [], tabSize = cm.options.tabSize; michael@0: var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); michael@0: var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); michael@0: var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); michael@0: for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); michael@0: line <= end; line++) { michael@0: var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); michael@0: if (left == right) michael@0: ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); michael@0: else if (text.length > leftPos) michael@0: ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); michael@0: } michael@0: if (!ranges.length) ranges.push(new Range(start, start)); michael@0: setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), sel_mouse); michael@0: } else { michael@0: var oldRange = ourRange; michael@0: var anchor = oldRange.anchor, head = pos; michael@0: if (type != "single") { michael@0: if (type == "double") michael@0: var range = findWordAt(doc, pos); michael@0: else michael@0: var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))); michael@0: if (cmp(range.anchor, anchor) > 0) { michael@0: head = range.head; michael@0: anchor = minPos(oldRange.from(), range.anchor); michael@0: } else { michael@0: head = range.anchor; michael@0: anchor = maxPos(oldRange.to(), range.head); michael@0: } michael@0: } michael@0: var ranges = startSel.ranges.slice(0); michael@0: ranges[ourIndex] = new Range(clipPos(doc, anchor), head); michael@0: setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse); michael@0: } michael@0: } michael@0: michael@0: var editorSize = display.wrapper.getBoundingClientRect(); michael@0: // Used to ensure timeout re-tries don't fire when another extend michael@0: // happened in the meantime (clearTimeout isn't reliable -- at michael@0: // least on Chrome, the timeouts still happen even when cleared, michael@0: // if the clear happens after their scheduled firing time). michael@0: var counter = 0; michael@0: michael@0: function extend(e) { michael@0: var curCount = ++counter; michael@0: var cur = posFromMouse(cm, e, true, type == "rect"); michael@0: if (!cur) return; michael@0: if (cmp(cur, lastPos) != 0) { michael@0: ensureFocus(cm); michael@0: extendTo(cur); michael@0: var visible = visibleLines(display, doc); michael@0: if (cur.line >= visible.to || cur.line < visible.from) michael@0: setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); michael@0: } else { michael@0: var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; michael@0: if (outside) setTimeout(operation(cm, function() { michael@0: if (counter != curCount) return; michael@0: display.scroller.scrollTop += outside; michael@0: extend(e); michael@0: }), 50); michael@0: } michael@0: } michael@0: michael@0: function done(e) { michael@0: counter = Infinity; michael@0: e_preventDefault(e); michael@0: focusInput(cm); michael@0: off(document, "mousemove", move); michael@0: off(document, "mouseup", up); michael@0: doc.history.lastSelOrigin = null; michael@0: } michael@0: michael@0: var move = operation(cm, function(e) { michael@0: if ((ie && !ie_upto9) ? !e.buttons : !e_button(e)) done(e); michael@0: else extend(e); michael@0: }); michael@0: var up = operation(cm, done); michael@0: on(document, "mousemove", move); michael@0: on(document, "mouseup", up); michael@0: } michael@0: michael@0: // Determines whether an event happened in the gutter, and fires the michael@0: // handlers for the corresponding event. michael@0: function gutterEvent(cm, e, type, prevent, signalfn) { michael@0: try { var mX = e.clientX, mY = e.clientY; } michael@0: catch(e) { return false; } michael@0: if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false; michael@0: if (prevent) e_preventDefault(e); michael@0: michael@0: var display = cm.display; michael@0: var lineBox = display.lineDiv.getBoundingClientRect(); michael@0: michael@0: if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e); michael@0: mY -= lineBox.top - display.viewOffset; michael@0: michael@0: for (var i = 0; i < cm.options.gutters.length; ++i) { michael@0: var g = display.gutters.childNodes[i]; michael@0: if (g && g.getBoundingClientRect().right >= mX) { michael@0: var line = lineAtHeight(cm.doc, mY); michael@0: var gutter = cm.options.gutters[i]; michael@0: signalfn(cm, type, cm, line, gutter, e); michael@0: return e_defaultPrevented(e); michael@0: } michael@0: } michael@0: } michael@0: michael@0: function clickInGutter(cm, e) { michael@0: return gutterEvent(cm, e, "gutterClick", true, signalLater); michael@0: } michael@0: michael@0: // Kludge to work around strange IE behavior where it'll sometimes michael@0: // re-fire a series of drag-related events right after the drop (#1551) michael@0: var lastDrop = 0; michael@0: michael@0: function onDrop(e) { michael@0: var cm = this; michael@0: if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) michael@0: return; michael@0: e_preventDefault(e); michael@0: if (ie_upto10) lastDrop = +new Date; michael@0: var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; michael@0: if (!pos || isReadOnly(cm)) return; michael@0: // Might be a file drop, in which case we simply extract the text michael@0: // and insert it. michael@0: if (files && files.length && window.FileReader && window.File) { michael@0: var n = files.length, text = Array(n), read = 0; michael@0: var loadFile = function(file, i) { michael@0: var reader = new FileReader; michael@0: reader.onload = function() { michael@0: text[i] = reader.result; michael@0: if (++read == n) { michael@0: pos = clipPos(cm.doc, pos); michael@0: var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}; michael@0: makeChange(cm.doc, change); michael@0: setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); michael@0: } michael@0: }; michael@0: reader.readAsText(file); michael@0: }; michael@0: for (var i = 0; i < n; ++i) loadFile(files[i], i); michael@0: } else { // Normal drop michael@0: // Don't do a replace if the drop happened inside of the selected text. michael@0: if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { michael@0: cm.state.draggingText(e); michael@0: // Ensure the editor is re-focused michael@0: setTimeout(bind(focusInput, cm), 20); michael@0: return; michael@0: } michael@0: try { michael@0: var text = e.dataTransfer.getData("Text"); michael@0: if (text) { michael@0: var selected = cm.state.draggingText && cm.listSelections(); michael@0: setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); michael@0: if (selected) for (var i = 0; i < selected.length; ++i) michael@0: replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag"); michael@0: cm.replaceSelection(text, "around", "paste"); michael@0: focusInput(cm); michael@0: } michael@0: } michael@0: catch(e){} michael@0: } michael@0: } michael@0: michael@0: function onDragStart(cm, e) { michael@0: if (ie_upto10 && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } michael@0: if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; michael@0: michael@0: e.dataTransfer.setData("Text", cm.getSelection()); michael@0: michael@0: // Use dummy image instead of default browsers image. michael@0: // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. michael@0: if (e.dataTransfer.setDragImage && !safari) { michael@0: var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); michael@0: img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; michael@0: if (presto) { michael@0: img.width = img.height = 1; michael@0: cm.display.wrapper.appendChild(img); michael@0: // Force a relayout, or Opera won't use our image for some obscure reason michael@0: img._top = img.offsetTop; michael@0: } michael@0: e.dataTransfer.setDragImage(img, 0, 0); michael@0: if (presto) img.parentNode.removeChild(img); michael@0: } michael@0: } michael@0: michael@0: // SCROLL EVENTS michael@0: michael@0: // Sync the scrollable area and scrollbars, ensure the viewport michael@0: // covers the visible area. michael@0: function setScrollTop(cm, val) { michael@0: if (Math.abs(cm.doc.scrollTop - val) < 2) return; michael@0: cm.doc.scrollTop = val; michael@0: if (!gecko) updateDisplay(cm, {top: val}); michael@0: if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; michael@0: if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val; michael@0: if (gecko) updateDisplay(cm); michael@0: startWorker(cm, 100); michael@0: } michael@0: // Sync scroller and scrollbar, ensure the gutter elements are michael@0: // aligned. michael@0: function setScrollLeft(cm, val, isScroller) { michael@0: if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; michael@0: val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); michael@0: cm.doc.scrollLeft = val; michael@0: alignHorizontally(cm); michael@0: if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; michael@0: if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val; michael@0: } michael@0: michael@0: // Since the delta values reported on mouse wheel events are michael@0: // unstandardized between browsers and even browser versions, and michael@0: // generally horribly unpredictable, this code starts by measuring michael@0: // the scroll effect that the first few mouse wheel events have, michael@0: // and, from that, detects the way it can convert deltas to pixel michael@0: // offsets afterwards. michael@0: // michael@0: // The reason we want to know the amount a wheel event will scroll michael@0: // is that it gives us a chance to update the display before the michael@0: // actual scrolling happens, reducing flickering. michael@0: michael@0: var wheelSamples = 0, wheelPixelsPerUnit = null; michael@0: // Fill in a browser-detected starting value on browsers where we michael@0: // know one. These don't have to be accurate -- the result of them michael@0: // being wrong would just be a slight flicker on the first wheel michael@0: // scroll (if it is large enough). michael@0: if (ie) wheelPixelsPerUnit = -.53; michael@0: else if (gecko) wheelPixelsPerUnit = 15; michael@0: else if (chrome) wheelPixelsPerUnit = -.7; michael@0: else if (safari) wheelPixelsPerUnit = -1/3; michael@0: michael@0: function onScrollWheel(cm, e) { michael@0: var dx = e.wheelDeltaX, dy = e.wheelDeltaY; michael@0: if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; michael@0: if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; michael@0: else if (dy == null) dy = e.wheelDelta; michael@0: michael@0: var display = cm.display, scroll = display.scroller; michael@0: // Quit if there's nothing to scroll here michael@0: if (!(dx && scroll.scrollWidth > scroll.clientWidth || michael@0: dy && scroll.scrollHeight > scroll.clientHeight)) return; michael@0: michael@0: // Webkit browsers on OS X abort momentum scrolls when the target michael@0: // of the scroll event is removed from the scrollable element. michael@0: // This hack (see related code in patchDisplay) makes sure the michael@0: // element is kept around. michael@0: if (dy && mac && webkit) { michael@0: outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { michael@0: for (var i = 0; i < view.length; i++) { michael@0: if (view[i].node == cur) { michael@0: cm.display.currentWheelTarget = cur; michael@0: break outer; michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: // On some browsers, horizontal scrolling will cause redraws to michael@0: // happen before the gutter has been realigned, causing it to michael@0: // wriggle around in a most unseemly way. When we have an michael@0: // estimated pixels/delta value, we just handle horizontal michael@0: // scrolling entirely here. It'll be slightly off from native, but michael@0: // better than glitching out. michael@0: if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { michael@0: if (dy) michael@0: setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); michael@0: setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); michael@0: e_preventDefault(e); michael@0: display.wheelStartX = null; // Abort measurement, if in progress michael@0: return; michael@0: } michael@0: michael@0: // 'Project' the visible viewport to cover the area that is being michael@0: // scrolled into view (if we know enough to estimate it). michael@0: if (dy && wheelPixelsPerUnit != null) { michael@0: var pixels = dy * wheelPixelsPerUnit; michael@0: var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; michael@0: if (pixels < 0) top = Math.max(0, top + pixels - 50); michael@0: else bot = Math.min(cm.doc.height, bot + pixels + 50); michael@0: updateDisplay(cm, {top: top, bottom: bot}); michael@0: } michael@0: michael@0: if (wheelSamples < 20) { michael@0: if (display.wheelStartX == null) { michael@0: display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; michael@0: display.wheelDX = dx; display.wheelDY = dy; michael@0: setTimeout(function() { michael@0: if (display.wheelStartX == null) return; michael@0: var movedX = scroll.scrollLeft - display.wheelStartX; michael@0: var movedY = scroll.scrollTop - display.wheelStartY; michael@0: var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || michael@0: (movedX && display.wheelDX && movedX / display.wheelDX); michael@0: display.wheelStartX = display.wheelStartY = null; michael@0: if (!sample) return; michael@0: wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); michael@0: ++wheelSamples; michael@0: }, 200); michael@0: } else { michael@0: display.wheelDX += dx; display.wheelDY += dy; michael@0: } michael@0: } michael@0: } michael@0: michael@0: // KEY EVENTS michael@0: michael@0: // Run a handler that was bound to a key. michael@0: function doHandleBinding(cm, bound, dropShift) { michael@0: if (typeof bound == "string") { michael@0: bound = commands[bound]; michael@0: if (!bound) return false; michael@0: } michael@0: // Ensure previous input has been read, so that the handler sees a michael@0: // consistent view of the document michael@0: if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false; michael@0: var prevShift = cm.display.shift, done = false; michael@0: try { michael@0: if (isReadOnly(cm)) cm.state.suppressEdits = true; michael@0: if (dropShift) cm.display.shift = false; michael@0: done = bound(cm) != Pass; michael@0: } finally { michael@0: cm.display.shift = prevShift; michael@0: cm.state.suppressEdits = false; michael@0: } michael@0: return done; michael@0: } michael@0: michael@0: // Collect the currently active keymaps. michael@0: function allKeyMaps(cm) { michael@0: var maps = cm.state.keyMaps.slice(0); michael@0: if (cm.options.extraKeys) maps.push(cm.options.extraKeys); michael@0: maps.push(cm.options.keyMap); michael@0: return maps; michael@0: } michael@0: michael@0: var maybeTransition; michael@0: // Handle a key from the keydown event. michael@0: function handleKeyBinding(cm, e) { michael@0: // Handle automatic keymap transitions michael@0: var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto; michael@0: clearTimeout(maybeTransition); michael@0: if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() { michael@0: if (getKeyMap(cm.options.keyMap) == startMap) { michael@0: cm.options.keyMap = (next.call ? next.call(null, cm) : next); michael@0: keyMapChanged(cm); michael@0: } michael@0: }, 50); michael@0: michael@0: var name = keyName(e, true), handled = false; michael@0: if (!name) return false; michael@0: var keymaps = allKeyMaps(cm); michael@0: michael@0: if (e.shiftKey) { michael@0: // First try to resolve full name (including 'Shift-'). Failing michael@0: // that, see if there is a cursor-motion command (starting with michael@0: // 'go') bound to the keyname without 'Shift-'. michael@0: handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);}) michael@0: || lookupKey(name, keymaps, function(b) { michael@0: if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) michael@0: return doHandleBinding(cm, b); michael@0: }); michael@0: } else { michael@0: handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); }); michael@0: } michael@0: michael@0: if (handled) { michael@0: e_preventDefault(e); michael@0: restartBlink(cm); michael@0: signalLater(cm, "keyHandled", cm, name, e); michael@0: } michael@0: return handled; michael@0: } michael@0: michael@0: // Handle a key from the keypress event michael@0: function handleCharBinding(cm, e, ch) { michael@0: var handled = lookupKey("'" + ch + "'", allKeyMaps(cm), michael@0: function(b) { return doHandleBinding(cm, b, true); }); michael@0: if (handled) { michael@0: e_preventDefault(e); michael@0: restartBlink(cm); michael@0: signalLater(cm, "keyHandled", cm, "'" + ch + "'", e); michael@0: } michael@0: return handled; michael@0: } michael@0: michael@0: var lastStoppedKey = null; michael@0: function onKeyDown(e) { michael@0: var cm = this; michael@0: ensureFocus(cm); michael@0: if (signalDOMEvent(cm, e)) return; michael@0: // IE does strange things with escape. michael@0: if (ie_upto10 && e.keyCode == 27) e.returnValue = false; michael@0: var code = e.keyCode; michael@0: cm.display.shift = code == 16 || e.shiftKey; michael@0: var handled = handleKeyBinding(cm, e); michael@0: if (presto) { michael@0: lastStoppedKey = handled ? code : null; michael@0: // Opera has no cut event... we try to at least catch the key combo michael@0: if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) michael@0: cm.replaceSelection("", null, "cut"); michael@0: } michael@0: } michael@0: michael@0: function onKeyUp(e) { michael@0: if (signalDOMEvent(this, e)) return; michael@0: if (e.keyCode == 16) this.doc.sel.shift = false; michael@0: } michael@0: michael@0: function onKeyPress(e) { michael@0: var cm = this; michael@0: if (signalDOMEvent(cm, e)) return; michael@0: var keyCode = e.keyCode, charCode = e.charCode; michael@0: if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} michael@0: if (((presto && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return; michael@0: var ch = String.fromCharCode(charCode == null ? keyCode : charCode); michael@0: if (handleCharBinding(cm, e, ch)) return; michael@0: if (ie && !ie_upto8) cm.display.inputHasSelection = null; michael@0: fastPoll(cm); michael@0: } michael@0: michael@0: // FOCUS/BLUR EVENTS michael@0: michael@0: function onFocus(cm) { michael@0: if (cm.options.readOnly == "nocursor") return; michael@0: if (!cm.state.focused) { michael@0: signal(cm, "focus", cm); michael@0: cm.state.focused = true; michael@0: if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1) michael@0: cm.display.wrapper.className += " CodeMirror-focused"; michael@0: if (!cm.curOp) { michael@0: resetInput(cm); michael@0: if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #1730 michael@0: } michael@0: } michael@0: slowPoll(cm); michael@0: restartBlink(cm); michael@0: } michael@0: function onBlur(cm) { michael@0: if (cm.state.focused) { michael@0: signal(cm, "blur", cm); michael@0: cm.state.focused = false; michael@0: cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-focused", ""); michael@0: } michael@0: clearInterval(cm.display.blinker); michael@0: setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150); michael@0: } michael@0: michael@0: // CONTEXT MENU HANDLING michael@0: michael@0: var detectingSelectAll; michael@0: // To make the context menu work, we need to briefly unhide the michael@0: // textarea (making it as unobtrusive as possible) to let the michael@0: // right-click take effect on it. michael@0: function onContextMenu(cm, e) { michael@0: if (signalDOMEvent(cm, e, "contextmenu")) return; michael@0: var display = cm.display; michael@0: if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return; michael@0: michael@0: var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; michael@0: if (!pos || presto) return; // Opera is difficult. michael@0: michael@0: // Reset the current text selection only if the click is done outside of the selection michael@0: // and 'resetSelectionOnContextMenu' option is true. michael@0: var reset = cm.options.resetSelectionOnContextMenu; michael@0: if (reset && cm.doc.sel.contains(pos) == -1) michael@0: operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); michael@0: michael@0: var oldCSS = display.input.style.cssText; michael@0: display.inputDiv.style.position = "absolute"; michael@0: display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + michael@0: "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " + michael@0: (ie ? "rgba(255, 255, 255, .05)" : "transparent") + michael@0: "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; michael@0: focusInput(cm); michael@0: resetInput(cm); michael@0: // Adds "Select all" to context menu in FF michael@0: if (!cm.somethingSelected()) display.input.value = display.prevInput = " "; michael@0: michael@0: // Select-all will be greyed out if there's nothing to select, so michael@0: // this adds a zero-width space so that we can later check whether michael@0: // it got selected. michael@0: function prepareSelectAllHack() { michael@0: if (display.input.selectionStart != null) { michael@0: var extval = display.input.value = "\u200b" + (cm.somethingSelected() ? display.input.value : ""); michael@0: display.prevInput = "\u200b"; michael@0: display.input.selectionStart = 1; display.input.selectionEnd = extval.length; michael@0: } michael@0: } michael@0: function rehide() { michael@0: display.inputDiv.style.position = "relative"; michael@0: display.input.style.cssText = oldCSS; michael@0: if (ie_upto8) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos; michael@0: slowPoll(cm); michael@0: michael@0: // Try to detect the user choosing select-all michael@0: if (display.input.selectionStart != null) { michael@0: if (!ie || ie_upto8) prepareSelectAllHack(); michael@0: clearTimeout(detectingSelectAll); michael@0: var i = 0, poll = function(){ michael@0: if (display.prevInput == "\u200b" && display.input.selectionStart == 0) michael@0: operation(cm, commands.selectAll)(cm); michael@0: else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500); michael@0: else resetInput(cm); michael@0: }; michael@0: detectingSelectAll = setTimeout(poll, 200); michael@0: } michael@0: } michael@0: michael@0: if (ie && !ie_upto8) prepareSelectAllHack(); michael@0: if (captureRightClick) { michael@0: e_stop(e); michael@0: var mouseup = function() { michael@0: off(window, "mouseup", mouseup); michael@0: setTimeout(rehide, 20); michael@0: }; michael@0: on(window, "mouseup", mouseup); michael@0: } else { michael@0: setTimeout(rehide, 50); michael@0: } michael@0: } michael@0: michael@0: function contextMenuInGutter(cm, e) { michael@0: if (!hasHandler(cm, "gutterContextMenu")) return false; michael@0: return gutterEvent(cm, e, "gutterContextMenu", false, signal); michael@0: } michael@0: michael@0: // UPDATING michael@0: michael@0: // Compute the position of the end of a change (its 'to' property michael@0: // refers to the pre-change end). michael@0: var changeEnd = CodeMirror.changeEnd = function(change) { michael@0: if (!change.text) return change.to; michael@0: return Pos(change.from.line + change.text.length - 1, michael@0: lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); michael@0: }; michael@0: michael@0: // Adjust a position to refer to the post-change position of the michael@0: // same text, or the end of the change if the change covers it. michael@0: function adjustForChange(pos, change) { michael@0: if (cmp(pos, change.from) < 0) return pos; michael@0: if (cmp(pos, change.to) <= 0) return changeEnd(change); michael@0: michael@0: var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; michael@0: if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch; michael@0: return Pos(line, ch); michael@0: } michael@0: michael@0: function computeSelAfterChange(doc, change) { michael@0: var out = []; michael@0: for (var i = 0; i < doc.sel.ranges.length; i++) { michael@0: var range = doc.sel.ranges[i]; michael@0: out.push(new Range(adjustForChange(range.anchor, change), michael@0: adjustForChange(range.head, change))); michael@0: } michael@0: return normalizeSelection(out, doc.sel.primIndex); michael@0: } michael@0: michael@0: function offsetPos(pos, old, nw) { michael@0: if (pos.line == old.line) michael@0: return Pos(nw.line, pos.ch - old.ch + nw.ch); michael@0: else michael@0: return Pos(nw.line + (pos.line - old.line), pos.ch); michael@0: } michael@0: michael@0: // Used by replaceSelections to allow moving the selection to the michael@0: // start or around the replaced test. Hint may be "start" or "around". michael@0: function computeReplacedSel(doc, changes, hint) { michael@0: var out = []; michael@0: var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; michael@0: for (var i = 0; i < changes.length; i++) { michael@0: var change = changes[i]; michael@0: var from = offsetPos(change.from, oldPrev, newPrev); michael@0: var to = offsetPos(changeEnd(change), oldPrev, newPrev); michael@0: oldPrev = change.to; michael@0: newPrev = to; michael@0: if (hint == "around") { michael@0: var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; michael@0: out[i] = new Range(inv ? to : from, inv ? from : to); michael@0: } else { michael@0: out[i] = new Range(from, from); michael@0: } michael@0: } michael@0: return new Selection(out, doc.sel.primIndex); michael@0: } michael@0: michael@0: // Allow "beforeChange" event handlers to influence a change michael@0: function filterChange(doc, change, update) { michael@0: var obj = { michael@0: canceled: false, michael@0: from: change.from, michael@0: to: change.to, michael@0: text: change.text, michael@0: origin: change.origin, michael@0: cancel: function() { this.canceled = true; } michael@0: }; michael@0: if (update) obj.update = function(from, to, text, origin) { michael@0: if (from) this.from = clipPos(doc, from); michael@0: if (to) this.to = clipPos(doc, to); michael@0: if (text) this.text = text; michael@0: if (origin !== undefined) this.origin = origin; michael@0: }; michael@0: signal(doc, "beforeChange", doc, obj); michael@0: if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); michael@0: michael@0: if (obj.canceled) return null; michael@0: return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; michael@0: } michael@0: michael@0: // Apply a change to a document, and add it to the document's michael@0: // history, and propagating it to all linked documents. michael@0: function makeChange(doc, change, ignoreReadOnly) { michael@0: if (doc.cm) { michael@0: if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); michael@0: if (doc.cm.state.suppressEdits) return; michael@0: } michael@0: michael@0: if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { michael@0: change = filterChange(doc, change, true); michael@0: if (!change) return; michael@0: } michael@0: michael@0: // Possibly split or suppress the update based on the presence michael@0: // of read-only spans in its range. michael@0: var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); michael@0: if (split) { michael@0: for (var i = split.length - 1; i >= 0; --i) michael@0: makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}); michael@0: } else { michael@0: makeChangeInner(doc, change); michael@0: } michael@0: } michael@0: michael@0: function makeChangeInner(doc, change) { michael@0: if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return; michael@0: var selAfter = computeSelAfterChange(doc, change); michael@0: addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); michael@0: michael@0: makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); michael@0: var rebased = []; michael@0: michael@0: linkedDocs(doc, function(doc, sharedHist) { michael@0: if (!sharedHist && indexOf(rebased, doc.history) == -1) { michael@0: rebaseHist(doc.history, change); michael@0: rebased.push(doc.history); michael@0: } michael@0: makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); michael@0: }); michael@0: } michael@0: michael@0: // Revert a change stored in a document's history. michael@0: function makeChangeFromHistory(doc, type, allowSelectionOnly) { michael@0: if (doc.cm && doc.cm.state.suppressEdits) return; michael@0: michael@0: var hist = doc.history, event, selAfter = doc.sel; michael@0: var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; michael@0: michael@0: // Verify that there is a useable event (so that ctrl-z won't michael@0: // needlessly clear selection events) michael@0: for (var i = 0; i < source.length; i++) { michael@0: event = source[i]; michael@0: if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) michael@0: break; michael@0: } michael@0: if (i == source.length) return; michael@0: hist.lastOrigin = hist.lastSelOrigin = null; michael@0: michael@0: for (;;) { michael@0: event = source.pop(); michael@0: if (event.ranges) { michael@0: pushSelectionToHistory(event, dest); michael@0: if (allowSelectionOnly && !event.equals(doc.sel)) { michael@0: setSelection(doc, event, {clearRedo: false}); michael@0: return; michael@0: } michael@0: selAfter = event; michael@0: } michael@0: else break; michael@0: } michael@0: michael@0: // Build up a reverse change object to add to the opposite history michael@0: // stack (redo when undoing, and vice versa). michael@0: var antiChanges = []; michael@0: pushSelectionToHistory(selAfter, dest); michael@0: dest.push({changes: antiChanges, generation: hist.generation}); michael@0: hist.generation = event.generation || ++hist.maxGeneration; michael@0: michael@0: var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); michael@0: michael@0: for (var i = event.changes.length - 1; i >= 0; --i) { michael@0: var change = event.changes[i]; michael@0: change.origin = type; michael@0: if (filter && !filterChange(doc, change, false)) { michael@0: source.length = 0; michael@0: return; michael@0: } michael@0: michael@0: antiChanges.push(historyChangeFromChange(doc, change)); michael@0: michael@0: var after = i ? computeSelAfterChange(doc, change, null) : lst(source); michael@0: makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); michael@0: if (doc.cm) ensureCursorVisible(doc.cm); michael@0: var rebased = []; michael@0: michael@0: // Propagate to the linked documents michael@0: linkedDocs(doc, function(doc, sharedHist) { michael@0: if (!sharedHist && indexOf(rebased, doc.history) == -1) { michael@0: rebaseHist(doc.history, change); michael@0: rebased.push(doc.history); michael@0: } michael@0: makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); michael@0: }); michael@0: } michael@0: } michael@0: michael@0: // Sub-views need their line numbers shifted when text is added michael@0: // above or below them in the parent document. michael@0: function shiftDoc(doc, distance) { michael@0: doc.first += distance; michael@0: doc.sel = new Selection(map(doc.sel.ranges, function(range) { michael@0: return new Range(Pos(range.anchor.line + distance, range.anchor.ch), michael@0: Pos(range.head.line + distance, range.head.ch)); michael@0: }), doc.sel.primIndex); michael@0: if (doc.cm) regChange(doc.cm, doc.first, doc.first - distance, distance); michael@0: } michael@0: michael@0: // More lower-level change function, handling only a single document michael@0: // (not linked ones). michael@0: function makeChangeSingleDoc(doc, change, selAfter, spans) { michael@0: if (doc.cm && !doc.cm.curOp) michael@0: return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); michael@0: michael@0: if (change.to.line < doc.first) { michael@0: shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); michael@0: return; michael@0: } michael@0: if (change.from.line > doc.lastLine()) return; michael@0: michael@0: // Clip the change to the size of this doc michael@0: if (change.from.line < doc.first) { michael@0: var shift = change.text.length - 1 - (doc.first - change.from.line); michael@0: shiftDoc(doc, shift); michael@0: change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), michael@0: text: [lst(change.text)], origin: change.origin}; michael@0: } michael@0: var last = doc.lastLine(); michael@0: if (change.to.line > last) { michael@0: change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), michael@0: text: [change.text[0]], origin: change.origin}; michael@0: } michael@0: michael@0: change.removed = getBetween(doc, change.from, change.to); michael@0: michael@0: if (!selAfter) selAfter = computeSelAfterChange(doc, change, null); michael@0: if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans); michael@0: else updateDoc(doc, change, spans); michael@0: setSelectionNoUndo(doc, selAfter, sel_dontScroll); michael@0: } michael@0: michael@0: // Handle the interaction of a change to a document with the editor michael@0: // that this document is part of. michael@0: function makeChangeSingleDocInEditor(cm, change, spans) { michael@0: var doc = cm.doc, display = cm.display, from = change.from, to = change.to; michael@0: michael@0: var recomputeMaxLength = false, checkWidthStart = from.line; michael@0: if (!cm.options.lineWrapping) { michael@0: checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); michael@0: doc.iter(checkWidthStart, to.line + 1, function(line) { michael@0: if (line == display.maxLine) { michael@0: recomputeMaxLength = true; michael@0: return true; michael@0: } michael@0: }); michael@0: } michael@0: michael@0: if (doc.sel.contains(change.from, change.to) > -1) michael@0: cm.curOp.cursorActivity = true; michael@0: michael@0: updateDoc(doc, change, spans, estimateHeight(cm)); michael@0: michael@0: if (!cm.options.lineWrapping) { michael@0: doc.iter(checkWidthStart, from.line + change.text.length, function(line) { michael@0: var len = lineLength(line); michael@0: if (len > display.maxLineLength) { michael@0: display.maxLine = line; michael@0: display.maxLineLength = len; michael@0: display.maxLineChanged = true; michael@0: recomputeMaxLength = false; michael@0: } michael@0: }); michael@0: if (recomputeMaxLength) cm.curOp.updateMaxLine = true; michael@0: } michael@0: michael@0: // Adjust frontier, schedule worker michael@0: doc.frontier = Math.min(doc.frontier, from.line); michael@0: startWorker(cm, 400); michael@0: michael@0: var lendiff = change.text.length - (to.line - from.line) - 1; michael@0: // Remember that these lines changed, for updating the display michael@0: if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) michael@0: regLineChange(cm, from.line, "text"); michael@0: else michael@0: regChange(cm, from.line, to.line + 1, lendiff); michael@0: michael@0: if (hasHandler(cm, "change") || hasHandler(cm, "changes")) michael@0: (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push({ michael@0: from: from, to: to, michael@0: text: change.text, michael@0: removed: change.removed, michael@0: origin: change.origin michael@0: }); michael@0: } michael@0: michael@0: function replaceRange(doc, code, from, to, origin) { michael@0: if (!to) to = from; michael@0: if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } michael@0: if (typeof code == "string") code = splitLines(code); michael@0: makeChange(doc, {from: from, to: to, text: code, origin: origin}); michael@0: } michael@0: michael@0: // SCROLLING THINGS INTO VIEW michael@0: michael@0: // If an editor sits on the top or bottom of the window, partially michael@0: // scrolled out of view, this ensures that the cursor is visible. michael@0: function maybeScrollWindow(cm, coords) { michael@0: var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; michael@0: if (coords.top + box.top < 0) doScroll = true; michael@0: else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; michael@0: if (doScroll != null && !phantom) { michael@0: var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " + michael@0: (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " + michael@0: (coords.bottom - coords.top + scrollerCutOff) + "px; left: " + michael@0: coords.left + "px; width: 2px;"); michael@0: cm.display.lineSpace.appendChild(scrollNode); michael@0: scrollNode.scrollIntoView(doScroll); michael@0: cm.display.lineSpace.removeChild(scrollNode); michael@0: } michael@0: } michael@0: michael@0: // Scroll a given position into view (immediately), verifying that michael@0: // it actually became visible (as line heights are accurately michael@0: // measured, the position of something may 'drift' during drawing). michael@0: function scrollPosIntoView(cm, pos, end, margin) { michael@0: if (margin == null) margin = 0; michael@0: for (;;) { michael@0: var changed = false, coords = cursorCoords(cm, pos); michael@0: var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); michael@0: var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), michael@0: Math.min(coords.top, endCoords.top) - margin, michael@0: Math.max(coords.left, endCoords.left), michael@0: Math.max(coords.bottom, endCoords.bottom) + margin); michael@0: var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; michael@0: if (scrollPos.scrollTop != null) { michael@0: setScrollTop(cm, scrollPos.scrollTop); michael@0: if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; michael@0: } michael@0: if (scrollPos.scrollLeft != null) { michael@0: setScrollLeft(cm, scrollPos.scrollLeft); michael@0: if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; michael@0: } michael@0: if (!changed) return coords; michael@0: } michael@0: } michael@0: michael@0: // Scroll a given set of coordinates into view (immediately). michael@0: function scrollIntoView(cm, x1, y1, x2, y2) { michael@0: var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); michael@0: if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); michael@0: if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); michael@0: } michael@0: michael@0: // Calculate a new scroll position needed to scroll the given michael@0: // rectangle into view. Returns an object with scrollTop and michael@0: // scrollLeft properties. When these are undefined, the michael@0: // vertical/horizontal position does not need to be adjusted. michael@0: function calculateScrollPos(cm, x1, y1, x2, y2) { michael@0: var display = cm.display, snapMargin = textHeight(cm.display); michael@0: if (y1 < 0) y1 = 0; michael@0: var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; michael@0: var screen = display.scroller.clientHeight - scrollerCutOff, result = {}; michael@0: var docBottom = cm.doc.height + paddingVert(display); michael@0: var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; michael@0: if (y1 < screentop) { michael@0: result.scrollTop = atTop ? 0 : y1; michael@0: } else if (y2 > screentop + screen) { michael@0: var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); michael@0: if (newTop != screentop) result.scrollTop = newTop; michael@0: } michael@0: michael@0: var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; michael@0: var screenw = display.scroller.clientWidth - scrollerCutOff; michael@0: x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth; michael@0: var gutterw = display.gutters.offsetWidth; michael@0: var atLeft = x1 < gutterw + 10; michael@0: if (x1 < screenleft + gutterw || atLeft) { michael@0: if (atLeft) x1 = 0; michael@0: result.scrollLeft = Math.max(0, x1 - 10 - gutterw); michael@0: } else if (x2 > screenw + screenleft - 3) { michael@0: result.scrollLeft = x2 + 10 - screenw; michael@0: } michael@0: return result; michael@0: } michael@0: michael@0: // Store a relative adjustment to the scroll position in the current michael@0: // operation (to be applied when the operation finishes). michael@0: function addToScrollPos(cm, left, top) { michael@0: if (left != null || top != null) resolveScrollToPos(cm); michael@0: if (left != null) michael@0: cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left; michael@0: if (top != null) michael@0: cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; michael@0: } michael@0: michael@0: // Make sure that at the end of the operation the current cursor is michael@0: // shown. michael@0: function ensureCursorVisible(cm) { michael@0: resolveScrollToPos(cm); michael@0: var cur = cm.getCursor(), from = cur, to = cur; michael@0: if (!cm.options.lineWrapping) { michael@0: from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; michael@0: to = Pos(cur.line, cur.ch + 1); michael@0: } michael@0: cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}; michael@0: } michael@0: michael@0: // When an operation has its scrollToPos property set, and another michael@0: // scroll action is applied before the end of the operation, this michael@0: // 'simulates' scrolling that position into view in a cheap way, so michael@0: // that the effect of intermediate scroll commands is not ignored. michael@0: function resolveScrollToPos(cm) { michael@0: var range = cm.curOp.scrollToPos; michael@0: if (range) { michael@0: cm.curOp.scrollToPos = null; michael@0: var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); michael@0: var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), michael@0: Math.min(from.top, to.top) - range.margin, michael@0: Math.max(from.right, to.right), michael@0: Math.max(from.bottom, to.bottom) + range.margin); michael@0: cm.scrollTo(sPos.scrollLeft, sPos.scrollTop); michael@0: } michael@0: } michael@0: michael@0: // API UTILITIES michael@0: michael@0: // Indent the given line. The how parameter can be "smart", michael@0: // "add"/null, "subtract", or "prev". When aggressive is false michael@0: // (typically set to true for forced single-line indents), empty michael@0: // lines are not indented, and places where the mode returns Pass michael@0: // are left alone. michael@0: function indentLine(cm, n, how, aggressive) { michael@0: var doc = cm.doc, state; michael@0: if (how == null) how = "add"; michael@0: if (how == "smart") { michael@0: // Fall back to "prev" when the mode doesn't have an indentation michael@0: // method. michael@0: if (!cm.doc.mode.indent) how = "prev"; michael@0: else state = getStateBefore(cm, n); michael@0: } michael@0: michael@0: var tabSize = cm.options.tabSize; michael@0: var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); michael@0: if (line.stateAfter) line.stateAfter = null; michael@0: var curSpaceString = line.text.match(/^\s*/)[0], indentation; michael@0: if (!aggressive && !/\S/.test(line.text)) { michael@0: indentation = 0; michael@0: how = "not"; michael@0: } else if (how == "smart") { michael@0: indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); michael@0: if (indentation == Pass) { michael@0: if (!aggressive) return; michael@0: how = "prev"; michael@0: } michael@0: } michael@0: if (how == "prev") { michael@0: if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); michael@0: else indentation = 0; michael@0: } else if (how == "add") { michael@0: indentation = curSpace + cm.options.indentUnit; michael@0: } else if (how == "subtract") { michael@0: indentation = curSpace - cm.options.indentUnit; michael@0: } else if (typeof how == "number") { michael@0: indentation = curSpace + how; michael@0: } michael@0: indentation = Math.max(0, indentation); michael@0: michael@0: var indentString = "", pos = 0; michael@0: if (cm.options.indentWithTabs) michael@0: for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} michael@0: if (pos < indentation) indentString += spaceStr(indentation - pos); michael@0: michael@0: if (indentString != curSpaceString) { michael@0: replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); michael@0: } else { michael@0: // Ensure that, if the cursor was in the whitespace at the start michael@0: // of the line, it is moved to the end of that space. michael@0: for (var i = 0; i < doc.sel.ranges.length; i++) { michael@0: var range = doc.sel.ranges[i]; michael@0: if (range.head.line == n && range.head.ch < curSpaceString.length) { michael@0: var pos = Pos(n, curSpaceString.length); michael@0: replaceOneSelection(doc, i, new Range(pos, pos)); michael@0: break; michael@0: } michael@0: } michael@0: } michael@0: line.stateAfter = null; michael@0: } michael@0: michael@0: // Utility for applying a change to a line by handle or number, michael@0: // returning the number and optionally registering the line as michael@0: // changed. michael@0: function changeLine(cm, handle, changeType, op) { michael@0: var no = handle, line = handle, doc = cm.doc; michael@0: if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); michael@0: else no = lineNo(handle); michael@0: if (no == null) return null; michael@0: if (op(line, no)) regLineChange(cm, no, changeType); michael@0: else return null; michael@0: return line; michael@0: } michael@0: michael@0: // Helper for deleting text near the selection(s), used to implement michael@0: // backspace, delete, and similar functionality. michael@0: function deleteNearSelection(cm, compute) { michael@0: var ranges = cm.doc.sel.ranges, kill = []; michael@0: // Build up a set of ranges to kill first, merging overlapping michael@0: // ranges. michael@0: for (var i = 0; i < ranges.length; i++) { michael@0: var toKill = compute(ranges[i]); michael@0: while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { michael@0: var replaced = kill.pop(); michael@0: if (cmp(replaced.from, toKill.from) < 0) { michael@0: toKill.from = replaced.from; michael@0: break; michael@0: } michael@0: } michael@0: kill.push(toKill); michael@0: } michael@0: // Next, remove those actual ranges. michael@0: runInOp(cm, function() { michael@0: for (var i = kill.length - 1; i >= 0; i--) michael@0: replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); michael@0: ensureCursorVisible(cm); michael@0: }); michael@0: } michael@0: michael@0: // Used for horizontal relative motion. Dir is -1 or 1 (left or michael@0: // right), unit can be "char", "column" (like char, but doesn't michael@0: // cross line boundaries), "word" (across next word), or "group" (to michael@0: // the start of next group of word or non-word-non-whitespace michael@0: // chars). The visually param controls whether, in right-to-left michael@0: // text, direction 1 means to move towards the next index in the michael@0: // string, or towards the character to the right of the current michael@0: // position. The resulting position will have a hitSide=true michael@0: // property if it reached the end of the document. michael@0: function findPosH(doc, pos, dir, unit, visually) { michael@0: var line = pos.line, ch = pos.ch, origDir = dir; michael@0: var lineObj = getLine(doc, line); michael@0: var possible = true; michael@0: function findNextLine() { michael@0: var l = line + dir; michael@0: if (l < doc.first || l >= doc.first + doc.size) return (possible = false); michael@0: line = l; michael@0: return lineObj = getLine(doc, l); michael@0: } michael@0: function moveOnce(boundToLine) { michael@0: var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); michael@0: if (next == null) { michael@0: if (!boundToLine && findNextLine()) { michael@0: if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); michael@0: else ch = dir < 0 ? lineObj.text.length : 0; michael@0: } else return (possible = false); michael@0: } else ch = next; michael@0: return true; michael@0: } michael@0: michael@0: if (unit == "char") moveOnce(); michael@0: else if (unit == "column") moveOnce(true); michael@0: else if (unit == "word" || unit == "group") { michael@0: var sawType = null, group = unit == "group"; michael@0: for (var first = true;; first = false) { michael@0: if (dir < 0 && !moveOnce(!first)) break; michael@0: var cur = lineObj.text.charAt(ch) || "\n"; michael@0: var type = isWordChar(cur) ? "w" michael@0: : group && cur == "\n" ? "n" michael@0: : !group || /\s/.test(cur) ? null michael@0: : "p"; michael@0: if (group && !first && !type) type = "s"; michael@0: if (sawType && sawType != type) { michael@0: if (dir < 0) {dir = 1; moveOnce();} michael@0: break; michael@0: } michael@0: michael@0: if (type) sawType = type; michael@0: if (dir > 0 && !moveOnce(!first)) break; michael@0: } michael@0: } michael@0: var result = skipAtomic(doc, Pos(line, ch), origDir, true); michael@0: if (!possible) result.hitSide = true; michael@0: return result; michael@0: } michael@0: michael@0: // For relative vertical movement. Dir may be -1 or 1. Unit can be michael@0: // "page" or "line". The resulting position will have a hitSide=true michael@0: // property if it reached the end of the document. michael@0: function findPosV(cm, pos, dir, unit) { michael@0: var doc = cm.doc, x = pos.left, y; michael@0: if (unit == "page") { michael@0: var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); michael@0: y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display)); michael@0: } else if (unit == "line") { michael@0: y = dir > 0 ? pos.bottom + 3 : pos.top - 3; michael@0: } michael@0: for (;;) { michael@0: var target = coordsChar(cm, x, y); michael@0: if (!target.outside) break; michael@0: if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } michael@0: y += dir * 5; michael@0: } michael@0: return target; michael@0: } michael@0: michael@0: // Find the word at the given position (as returned by coordsChar). michael@0: function findWordAt(doc, pos) { michael@0: var line = getLine(doc, pos.line).text; michael@0: var start = pos.ch, end = pos.ch; michael@0: if (line) { michael@0: if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; michael@0: var startChar = line.charAt(start); michael@0: var check = isWordChar(startChar) ? isWordChar michael@0: : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} michael@0: : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; michael@0: while (start > 0 && check(line.charAt(start - 1))) --start; michael@0: while (end < line.length && check(line.charAt(end))) ++end; michael@0: } michael@0: return new Range(Pos(pos.line, start), Pos(pos.line, end)); michael@0: } michael@0: michael@0: // EDITOR METHODS michael@0: michael@0: // The publicly visible API. Note that methodOp(f) means michael@0: // 'wrap f in an operation, performed on its `this` parameter'. michael@0: michael@0: // This is not the complete set of editor methods. Most of the michael@0: // methods defined on the Doc type are also injected into michael@0: // CodeMirror.prototype, for backwards compatibility and michael@0: // convenience. michael@0: michael@0: CodeMirror.prototype = { michael@0: constructor: CodeMirror, michael@0: focus: function(){window.focus(); focusInput(this); fastPoll(this);}, michael@0: michael@0: setOption: function(option, value) { michael@0: var options = this.options, old = options[option]; michael@0: if (options[option] == value && option != "mode") return; michael@0: options[option] = value; michael@0: if (optionHandlers.hasOwnProperty(option)) michael@0: operation(this, optionHandlers[option])(this, value, old); michael@0: }, michael@0: michael@0: getOption: function(option) {return this.options[option];}, michael@0: getDoc: function() {return this.doc;}, michael@0: michael@0: addKeyMap: function(map, bottom) { michael@0: this.state.keyMaps[bottom ? "push" : "unshift"](map); michael@0: }, michael@0: removeKeyMap: function(map) { michael@0: var maps = this.state.keyMaps; michael@0: for (var i = 0; i < maps.length; ++i) michael@0: if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map)) { michael@0: maps.splice(i, 1); michael@0: return true; michael@0: } michael@0: }, michael@0: michael@0: addOverlay: methodOp(function(spec, options) { michael@0: var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); michael@0: if (mode.startState) throw new Error("Overlays may not be stateful."); michael@0: this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); michael@0: this.state.modeGen++; michael@0: regChange(this); michael@0: }), michael@0: removeOverlay: methodOp(function(spec) { michael@0: var overlays = this.state.overlays; michael@0: for (var i = 0; i < overlays.length; ++i) { michael@0: var cur = overlays[i].modeSpec; michael@0: if (cur == spec || typeof spec == "string" && cur.name == spec) { michael@0: overlays.splice(i, 1); michael@0: this.state.modeGen++; michael@0: regChange(this); michael@0: return; michael@0: } michael@0: } michael@0: }), michael@0: michael@0: indentLine: methodOp(function(n, dir, aggressive) { michael@0: if (typeof dir != "string" && typeof dir != "number") { michael@0: if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; michael@0: else dir = dir ? "add" : "subtract"; michael@0: } michael@0: if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); michael@0: }), michael@0: indentSelection: methodOp(function(how) { michael@0: var ranges = this.doc.sel.ranges, end = -1; michael@0: for (var i = 0; i < ranges.length; i++) { michael@0: var range = ranges[i]; michael@0: if (!range.empty()) { michael@0: var start = Math.max(end, range.from().line); michael@0: var to = range.to(); michael@0: end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; michael@0: for (var j = start; j < end; ++j) michael@0: indentLine(this, j, how); michael@0: } else if (range.head.line > end) { michael@0: indentLine(this, range.head.line, how, true); michael@0: end = range.head.line; michael@0: if (i == this.doc.sel.primIndex) ensureCursorVisible(this); michael@0: } michael@0: } michael@0: }), michael@0: michael@0: // Fetch the parser token for a given character. Useful for hacks michael@0: // that want to inspect the mode state (say, for completion). michael@0: getTokenAt: function(pos, precise) { michael@0: var doc = this.doc; michael@0: pos = clipPos(doc, pos); michael@0: var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode; michael@0: var line = getLine(doc, pos.line); michael@0: var stream = new StringStream(line.text, this.options.tabSize); michael@0: while (stream.pos < pos.ch && !stream.eol()) { michael@0: stream.start = stream.pos; michael@0: var style = mode.token(stream, state); michael@0: } michael@0: return {start: stream.start, michael@0: end: stream.pos, michael@0: string: stream.current(), michael@0: type: style || null, michael@0: state: state}; michael@0: }, michael@0: michael@0: getTokenTypeAt: function(pos) { michael@0: pos = clipPos(this.doc, pos); michael@0: var styles = getLineStyles(this, getLine(this.doc, pos.line)); michael@0: var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; michael@0: if (ch == 0) return styles[2]; michael@0: for (;;) { michael@0: var mid = (before + after) >> 1; michael@0: if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; michael@0: else if (styles[mid * 2 + 1] < ch) before = mid + 1; michael@0: else return styles[mid * 2 + 2]; michael@0: } michael@0: }, michael@0: michael@0: getModeAt: function(pos) { michael@0: var mode = this.doc.mode; michael@0: if (!mode.innerMode) return mode; michael@0: return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; michael@0: }, michael@0: michael@0: getHelper: function(pos, type) { michael@0: return this.getHelpers(pos, type)[0]; michael@0: }, michael@0: michael@0: getHelpers: function(pos, type) { michael@0: var found = []; michael@0: if (!helpers.hasOwnProperty(type)) return helpers; michael@0: var help = helpers[type], mode = this.getModeAt(pos); michael@0: if (typeof mode[type] == "string") { michael@0: if (help[mode[type]]) found.push(help[mode[type]]); michael@0: } else if (mode[type]) { michael@0: for (var i = 0; i < mode[type].length; i++) { michael@0: var val = help[mode[type][i]]; michael@0: if (val) found.push(val); michael@0: } michael@0: } else if (mode.helperType && help[mode.helperType]) { michael@0: found.push(help[mode.helperType]); michael@0: } else if (help[mode.name]) { michael@0: found.push(help[mode.name]); michael@0: } michael@0: for (var i = 0; i < help._global.length; i++) { michael@0: var cur = help._global[i]; michael@0: if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) michael@0: found.push(cur.val); michael@0: } michael@0: return found; michael@0: }, michael@0: michael@0: getStateAfter: function(line, precise) { michael@0: var doc = this.doc; michael@0: line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); michael@0: return getStateBefore(this, line + 1, precise); michael@0: }, michael@0: michael@0: cursorCoords: function(start, mode) { michael@0: var pos, range = this.doc.sel.primary(); michael@0: if (start == null) pos = range.head; michael@0: else if (typeof start == "object") pos = clipPos(this.doc, start); michael@0: else pos = start ? range.from() : range.to(); michael@0: return cursorCoords(this, pos, mode || "page"); michael@0: }, michael@0: michael@0: charCoords: function(pos, mode) { michael@0: return charCoords(this, clipPos(this.doc, pos), mode || "page"); michael@0: }, michael@0: michael@0: coordsChar: function(coords, mode) { michael@0: coords = fromCoordSystem(this, coords, mode || "page"); michael@0: return coordsChar(this, coords.left, coords.top); michael@0: }, michael@0: michael@0: lineAtHeight: function(height, mode) { michael@0: height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; michael@0: return lineAtHeight(this.doc, height + this.display.viewOffset); michael@0: }, michael@0: heightAtLine: function(line, mode) { michael@0: var end = false, last = this.doc.first + this.doc.size - 1; michael@0: if (line < this.doc.first) line = this.doc.first; michael@0: else if (line > last) { line = last; end = true; } michael@0: var lineObj = getLine(this.doc, line); michael@0: return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top + michael@0: (end ? this.doc.height - heightAtLine(lineObj) : 0); michael@0: }, michael@0: michael@0: defaultTextHeight: function() { return textHeight(this.display); }, michael@0: defaultCharWidth: function() { return charWidth(this.display); }, michael@0: michael@0: setGutterMarker: methodOp(function(line, gutterID, value) { michael@0: return changeLine(this, line, "gutter", function(line) { michael@0: var markers = line.gutterMarkers || (line.gutterMarkers = {}); michael@0: markers[gutterID] = value; michael@0: if (!value && isEmpty(markers)) line.gutterMarkers = null; michael@0: return true; michael@0: }); michael@0: }), michael@0: michael@0: clearGutter: methodOp(function(gutterID) { michael@0: var cm = this, doc = cm.doc, i = doc.first; michael@0: doc.iter(function(line) { michael@0: if (line.gutterMarkers && line.gutterMarkers[gutterID]) { michael@0: line.gutterMarkers[gutterID] = null; michael@0: regLineChange(cm, i, "gutter"); michael@0: if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; michael@0: } michael@0: ++i; michael@0: }); michael@0: }), michael@0: michael@0: addLineClass: methodOp(function(handle, where, cls) { michael@0: return changeLine(this, handle, "class", function(line) { michael@0: var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; michael@0: if (!line[prop]) line[prop] = cls; michael@0: else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false; michael@0: else line[prop] += " " + cls; michael@0: return true; michael@0: }); michael@0: }), michael@0: michael@0: removeLineClass: methodOp(function(handle, where, cls) { michael@0: return changeLine(this, handle, "class", function(line) { michael@0: var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; michael@0: var cur = line[prop]; michael@0: if (!cur) return false; michael@0: else if (cls == null) line[prop] = null; michael@0: else { michael@0: var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)")); michael@0: if (!found) return false; michael@0: var end = found.index + found[0].length; michael@0: line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; michael@0: } michael@0: return true; michael@0: }); michael@0: }), michael@0: michael@0: addLineWidget: methodOp(function(handle, node, options) { michael@0: return addLineWidget(this, handle, node, options); michael@0: }), michael@0: michael@0: removeLineWidget: function(widget) { widget.clear(); }, michael@0: michael@0: lineInfo: function(line) { michael@0: if (typeof line == "number") { michael@0: if (!isLine(this.doc, line)) return null; michael@0: var n = line; michael@0: line = getLine(this.doc, line); michael@0: if (!line) return null; michael@0: } else { michael@0: var n = lineNo(line); michael@0: if (n == null) return null; michael@0: } michael@0: return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, michael@0: textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, michael@0: widgets: line.widgets}; michael@0: }, michael@0: michael@0: getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};}, michael@0: michael@0: addWidget: function(pos, node, scroll, vert, horiz) { michael@0: var display = this.display; michael@0: pos = cursorCoords(this, clipPos(this.doc, pos)); michael@0: var top = pos.bottom, left = pos.left; michael@0: node.style.position = "absolute"; michael@0: display.sizer.appendChild(node); michael@0: if (vert == "over") { michael@0: top = pos.top; michael@0: } else if (vert == "above" || vert == "near") { michael@0: var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), michael@0: hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); michael@0: // Default to positioning above (if specified and possible); otherwise default to positioning below michael@0: if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) michael@0: top = pos.top - node.offsetHeight; michael@0: else if (pos.bottom + node.offsetHeight <= vspace) michael@0: top = pos.bottom; michael@0: if (left + node.offsetWidth > hspace) michael@0: left = hspace - node.offsetWidth; michael@0: } michael@0: node.style.top = top + "px"; michael@0: node.style.left = node.style.right = ""; michael@0: if (horiz == "right") { michael@0: left = display.sizer.clientWidth - node.offsetWidth; michael@0: node.style.right = "0px"; michael@0: } else { michael@0: if (horiz == "left") left = 0; michael@0: else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; michael@0: node.style.left = left + "px"; michael@0: } michael@0: if (scroll) michael@0: scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight); michael@0: }, michael@0: michael@0: triggerOnKeyDown: methodOp(onKeyDown), michael@0: triggerOnKeyPress: methodOp(onKeyPress), michael@0: triggerOnKeyUp: methodOp(onKeyUp), michael@0: michael@0: execCommand: function(cmd) { michael@0: if (commands.hasOwnProperty(cmd)) michael@0: return commands[cmd](this); michael@0: }, michael@0: michael@0: findPosH: function(from, amount, unit, visually) { michael@0: var dir = 1; michael@0: if (amount < 0) { dir = -1; amount = -amount; } michael@0: for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { michael@0: cur = findPosH(this.doc, cur, dir, unit, visually); michael@0: if (cur.hitSide) break; michael@0: } michael@0: return cur; michael@0: }, michael@0: michael@0: moveH: methodOp(function(dir, unit) { michael@0: var cm = this; michael@0: cm.extendSelectionsBy(function(range) { michael@0: if (cm.display.shift || cm.doc.extend || range.empty()) michael@0: return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually); michael@0: else michael@0: return dir < 0 ? range.from() : range.to(); michael@0: }, sel_move); michael@0: }), michael@0: michael@0: deleteH: methodOp(function(dir, unit) { michael@0: var sel = this.doc.sel, doc = this.doc; michael@0: if (sel.somethingSelected()) michael@0: doc.replaceSelection("", null, "+delete"); michael@0: else michael@0: deleteNearSelection(this, function(range) { michael@0: var other = findPosH(doc, range.head, dir, unit, false); michael@0: return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}; michael@0: }); michael@0: }), michael@0: michael@0: findPosV: function(from, amount, unit, goalColumn) { michael@0: var dir = 1, x = goalColumn; michael@0: if (amount < 0) { dir = -1; amount = -amount; } michael@0: for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { michael@0: var coords = cursorCoords(this, cur, "div"); michael@0: if (x == null) x = coords.left; michael@0: else coords.left = x; michael@0: cur = findPosV(this, coords, dir, unit); michael@0: if (cur.hitSide) break; michael@0: } michael@0: return cur; michael@0: }, michael@0: michael@0: moveV: methodOp(function(dir, unit) { michael@0: var cm = this, doc = this.doc, goals = []; michael@0: var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected(); michael@0: doc.extendSelectionsBy(function(range) { michael@0: if (collapse) michael@0: return dir < 0 ? range.from() : range.to(); michael@0: var headPos = cursorCoords(cm, range.head, "div"); michael@0: if (range.goalColumn != null) headPos.left = range.goalColumn; michael@0: goals.push(headPos.left); michael@0: var pos = findPosV(cm, headPos, dir, unit); michael@0: if (unit == "page" && range == doc.sel.primary()) michael@0: addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top); michael@0: return pos; michael@0: }, sel_move); michael@0: if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++) michael@0: doc.sel.ranges[i].goalColumn = goals[i]; michael@0: }), michael@0: michael@0: toggleOverwrite: function(value) { michael@0: if (value != null && value == this.state.overwrite) return; michael@0: if (this.state.overwrite = !this.state.overwrite) michael@0: this.display.cursorDiv.className += " CodeMirror-overwrite"; michael@0: else michael@0: this.display.cursorDiv.className = this.display.cursorDiv.className.replace(" CodeMirror-overwrite", ""); michael@0: michael@0: signal(this, "overwriteToggle", this, this.state.overwrite); michael@0: }, michael@0: hasFocus: function() { return activeElt() == this.display.input; }, michael@0: michael@0: scrollTo: methodOp(function(x, y) { michael@0: if (x != null || y != null) resolveScrollToPos(this); michael@0: if (x != null) this.curOp.scrollLeft = x; michael@0: if (y != null) this.curOp.scrollTop = y; michael@0: }), michael@0: getScrollInfo: function() { michael@0: var scroller = this.display.scroller, co = scrollerCutOff; michael@0: return {left: scroller.scrollLeft, top: scroller.scrollTop, michael@0: height: scroller.scrollHeight - co, width: scroller.scrollWidth - co, michael@0: clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co}; michael@0: }, michael@0: michael@0: scrollIntoView: methodOp(function(range, margin) { michael@0: if (range == null) { michael@0: range = {from: this.doc.sel.primary().head, to: null}; michael@0: if (margin == null) margin = this.options.cursorScrollMargin; michael@0: } else if (typeof range == "number") { michael@0: range = {from: Pos(range, 0), to: null}; michael@0: } else if (range.from == null) { michael@0: range = {from: range, to: null}; michael@0: } michael@0: if (!range.to) range.to = range.from; michael@0: range.margin = margin || 0; michael@0: michael@0: if (range.from.line != null) { michael@0: resolveScrollToPos(this); michael@0: this.curOp.scrollToPos = range; michael@0: } else { michael@0: var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left), michael@0: Math.min(range.from.top, range.to.top) - range.margin, michael@0: Math.max(range.from.right, range.to.right), michael@0: Math.max(range.from.bottom, range.to.bottom) + range.margin); michael@0: this.scrollTo(sPos.scrollLeft, sPos.scrollTop); michael@0: } michael@0: }), michael@0: michael@0: setSize: methodOp(function(width, height) { michael@0: function interpret(val) { michael@0: return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; michael@0: } michael@0: if (width != null) this.display.wrapper.style.width = interpret(width); michael@0: if (height != null) this.display.wrapper.style.height = interpret(height); michael@0: if (this.options.lineWrapping) clearLineMeasurementCache(this); michael@0: this.curOp.forceUpdate = true; michael@0: signal(this, "refresh", this); michael@0: }), michael@0: michael@0: operation: function(f){return runInOp(this, f);}, michael@0: michael@0: refresh: methodOp(function() { michael@0: var oldHeight = this.display.cachedTextHeight; michael@0: regChange(this); michael@0: clearCaches(this); michael@0: this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop); michael@0: if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) michael@0: estimateLineHeights(this); michael@0: signal(this, "refresh", this); michael@0: }), michael@0: michael@0: swapDoc: methodOp(function(doc) { michael@0: var old = this.doc; michael@0: old.cm = null; michael@0: attachDoc(this, doc); michael@0: clearCaches(this); michael@0: resetInput(this); michael@0: this.scrollTo(doc.scrollLeft, doc.scrollTop); michael@0: signalLater(this, "swapDoc", this, old); michael@0: return old; michael@0: }), michael@0: michael@0: getInputField: function(){return this.display.input;}, michael@0: getWrapperElement: function(){return this.display.wrapper;}, michael@0: getScrollerElement: function(){return this.display.scroller;}, michael@0: getGutterElement: function(){return this.display.gutters;} michael@0: }; michael@0: eventMixin(CodeMirror); michael@0: michael@0: // OPTION DEFAULTS michael@0: michael@0: // The default configuration options. michael@0: var defaults = CodeMirror.defaults = {}; michael@0: // Functions to run when options are changed. michael@0: var optionHandlers = CodeMirror.optionHandlers = {}; michael@0: michael@0: function option(name, deflt, handle, notOnInit) { michael@0: CodeMirror.defaults[name] = deflt; michael@0: if (handle) optionHandlers[name] = michael@0: notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; michael@0: } michael@0: michael@0: // Passed to option handlers when there is no old value. michael@0: var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; michael@0: michael@0: // These two are, on init, called from the constructor because they michael@0: // have to be initialized before the editor can start at all. michael@0: option("value", "", function(cm, val) { michael@0: cm.setValue(val); michael@0: }, true); michael@0: option("mode", null, function(cm, val) { michael@0: cm.doc.modeOption = val; michael@0: loadMode(cm); michael@0: }, true); michael@0: michael@0: option("indentUnit", 2, loadMode, true); michael@0: option("indentWithTabs", false); michael@0: option("smartIndent", true); michael@0: option("tabSize", 4, function(cm) { michael@0: resetModeState(cm); michael@0: clearCaches(cm); michael@0: regChange(cm); michael@0: }, true); michael@0: option("specialChars", /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\ufeff]/g, function(cm, val) { michael@0: cm.options.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); michael@0: cm.refresh(); michael@0: }, true); michael@0: option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true); michael@0: option("electricChars", true); michael@0: option("rtlMoveVisually", !windows); michael@0: option("wholeLineUpdateBefore", true); michael@0: michael@0: option("theme", "default", function(cm) { michael@0: themeChanged(cm); michael@0: guttersChanged(cm); michael@0: }, true); michael@0: option("keyMap", "default", keyMapChanged); michael@0: option("extraKeys", null); michael@0: michael@0: option("lineWrapping", false, wrappingChanged, true); michael@0: option("gutters", [], function(cm) { michael@0: setGuttersForLineNumbers(cm.options); michael@0: guttersChanged(cm); michael@0: }, true); michael@0: option("fixedGutter", true, function(cm, val) { michael@0: cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; michael@0: cm.refresh(); michael@0: }, true); michael@0: option("coverGutterNextToScrollbar", false, updateScrollbars, true); michael@0: option("lineNumbers", false, function(cm) { michael@0: setGuttersForLineNumbers(cm.options); michael@0: guttersChanged(cm); michael@0: }, true); michael@0: option("firstLineNumber", 1, guttersChanged, true); michael@0: option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true); michael@0: option("showCursorWhenSelecting", false, updateSelection, true); michael@0: michael@0: option("resetSelectionOnContextMenu", true); michael@0: michael@0: option("readOnly", false, function(cm, val) { michael@0: if (val == "nocursor") { michael@0: onBlur(cm); michael@0: cm.display.input.blur(); michael@0: cm.display.disabled = true; michael@0: } else { michael@0: cm.display.disabled = false; michael@0: if (!val) resetInput(cm); michael@0: } michael@0: }); michael@0: option("disableInput", false, function(cm, val) {if (!val) resetInput(cm);}, true); michael@0: option("dragDrop", true); michael@0: michael@0: option("cursorBlinkRate", 530); michael@0: option("cursorScrollMargin", 0); michael@0: option("cursorHeight", 1); michael@0: option("workTime", 100); michael@0: option("workDelay", 100); michael@0: option("flattenSpans", true, resetModeState, true); michael@0: option("addModeClass", false, resetModeState, true); michael@0: option("pollInterval", 100); michael@0: option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;}); michael@0: option("historyEventDelay", 1250); michael@0: option("viewportMargin", 10, function(cm){cm.refresh();}, true); michael@0: option("maxHighlightLength", 10000, resetModeState, true); michael@0: option("moveInputWithCursor", true, function(cm, val) { michael@0: if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0; michael@0: }); michael@0: michael@0: option("tabindex", null, function(cm, val) { michael@0: cm.display.input.tabIndex = val || ""; michael@0: }); michael@0: option("autofocus", null); michael@0: michael@0: // MODE DEFINITION AND QUERYING michael@0: michael@0: // Known modes, by name and by MIME michael@0: var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; michael@0: michael@0: // Extra arguments are stored as the mode's dependencies, which is michael@0: // used by (legacy) mechanisms like loadmode.js to automatically michael@0: // load a mode. (Preferred mechanism is the require/define calls.) michael@0: CodeMirror.defineMode = function(name, mode) { michael@0: if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; michael@0: if (arguments.length > 2) { michael@0: mode.dependencies = []; michael@0: for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]); michael@0: } michael@0: modes[name] = mode; michael@0: }; michael@0: michael@0: CodeMirror.defineMIME = function(mime, spec) { michael@0: mimeModes[mime] = spec; michael@0: }; michael@0: michael@0: // Given a MIME type, a {name, ...options} config object, or a name michael@0: // string, return a mode config object. michael@0: CodeMirror.resolveMode = function(spec) { michael@0: if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { michael@0: spec = mimeModes[spec]; michael@0: } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { michael@0: var found = mimeModes[spec.name]; michael@0: if (typeof found == "string") found = {name: found}; michael@0: spec = createObj(found, spec); michael@0: spec.name = found.name; michael@0: } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { michael@0: return CodeMirror.resolveMode("application/xml"); michael@0: } michael@0: if (typeof spec == "string") return {name: spec}; michael@0: else return spec || {name: "null"}; michael@0: }; michael@0: michael@0: // Given a mode spec (anything that resolveMode accepts), find and michael@0: // initialize an actual mode object. michael@0: CodeMirror.getMode = function(options, spec) { michael@0: var spec = CodeMirror.resolveMode(spec); michael@0: var mfactory = modes[spec.name]; michael@0: if (!mfactory) return CodeMirror.getMode(options, "text/plain"); michael@0: var modeObj = mfactory(options, spec); michael@0: if (modeExtensions.hasOwnProperty(spec.name)) { michael@0: var exts = modeExtensions[spec.name]; michael@0: for (var prop in exts) { michael@0: if (!exts.hasOwnProperty(prop)) continue; michael@0: if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; michael@0: modeObj[prop] = exts[prop]; michael@0: } michael@0: } michael@0: modeObj.name = spec.name; michael@0: if (spec.helperType) modeObj.helperType = spec.helperType; michael@0: if (spec.modeProps) for (var prop in spec.modeProps) michael@0: modeObj[prop] = spec.modeProps[prop]; michael@0: michael@0: return modeObj; michael@0: }; michael@0: michael@0: // Minimal default mode. michael@0: CodeMirror.defineMode("null", function() { michael@0: return {token: function(stream) {stream.skipToEnd();}}; michael@0: }); michael@0: CodeMirror.defineMIME("text/plain", "null"); michael@0: michael@0: // This can be used to attach properties to mode objects from michael@0: // outside the actual mode definition. michael@0: var modeExtensions = CodeMirror.modeExtensions = {}; michael@0: CodeMirror.extendMode = function(mode, properties) { michael@0: var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); michael@0: copyObj(properties, exts); michael@0: }; michael@0: michael@0: // EXTENSIONS michael@0: michael@0: CodeMirror.defineExtension = function(name, func) { michael@0: CodeMirror.prototype[name] = func; michael@0: }; michael@0: CodeMirror.defineDocExtension = function(name, func) { michael@0: Doc.prototype[name] = func; michael@0: }; michael@0: CodeMirror.defineOption = option; michael@0: michael@0: var initHooks = []; michael@0: CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; michael@0: michael@0: var helpers = CodeMirror.helpers = {}; michael@0: CodeMirror.registerHelper = function(type, name, value) { michael@0: if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []}; michael@0: helpers[type][name] = value; michael@0: }; michael@0: CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { michael@0: CodeMirror.registerHelper(type, name, value); michael@0: helpers[type]._global.push({pred: predicate, val: value}); michael@0: }; michael@0: michael@0: // MODE STATE HANDLING michael@0: michael@0: // Utility functions for working with state. Exported because nested michael@0: // modes need to do this for their inner modes. michael@0: michael@0: var copyState = CodeMirror.copyState = function(mode, state) { michael@0: if (state === true) return state; michael@0: if (mode.copyState) return mode.copyState(state); michael@0: var nstate = {}; michael@0: for (var n in state) { michael@0: var val = state[n]; michael@0: if (val instanceof Array) val = val.concat([]); michael@0: nstate[n] = val; michael@0: } michael@0: return nstate; michael@0: }; michael@0: michael@0: var startState = CodeMirror.startState = function(mode, a1, a2) { michael@0: return mode.startState ? mode.startState(a1, a2) : true; michael@0: }; michael@0: michael@0: // Given a mode and a state (for that mode), find the inner mode and michael@0: // state at the position that the state refers to. michael@0: CodeMirror.innerMode = function(mode, state) { michael@0: while (mode.innerMode) { michael@0: var info = mode.innerMode(state); michael@0: if (!info || info.mode == mode) break; michael@0: state = info.state; michael@0: mode = info.mode; michael@0: } michael@0: return info || {mode: mode, state: state}; michael@0: }; michael@0: michael@0: // STANDARD COMMANDS michael@0: michael@0: // Commands are parameter-less actions that can be performed on an michael@0: // editor, mostly used for keybindings. michael@0: var commands = CodeMirror.commands = { michael@0: selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);}, michael@0: singleSelection: function(cm) { michael@0: cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); michael@0: }, michael@0: killLine: function(cm) { michael@0: deleteNearSelection(cm, function(range) { michael@0: if (range.empty()) { michael@0: var len = getLine(cm.doc, range.head.line).text.length; michael@0: if (range.head.ch == len && range.head.line < cm.lastLine()) michael@0: return {from: range.head, to: Pos(range.head.line + 1, 0)}; michael@0: else michael@0: return {from: range.head, to: Pos(range.head.line, len)}; michael@0: } else { michael@0: return {from: range.from(), to: range.to()}; michael@0: } michael@0: }); michael@0: }, michael@0: deleteLine: function(cm) { michael@0: deleteNearSelection(cm, function(range) { michael@0: return {from: Pos(range.from().line, 0), michael@0: to: clipPos(cm.doc, Pos(range.to().line + 1, 0))}; michael@0: }); michael@0: }, michael@0: delLineLeft: function(cm) { michael@0: deleteNearSelection(cm, function(range) { michael@0: return {from: Pos(range.from().line, 0), to: range.from()}; michael@0: }); michael@0: }, michael@0: undo: function(cm) {cm.undo();}, michael@0: redo: function(cm) {cm.redo();}, michael@0: undoSelection: function(cm) {cm.undoSelection();}, michael@0: redoSelection: function(cm) {cm.redoSelection();}, michael@0: goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, michael@0: goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, michael@0: goLineStart: function(cm) { michael@0: cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); }, sel_move); michael@0: }, michael@0: goLineStartSmart: function(cm) { michael@0: cm.extendSelectionsBy(function(range) { michael@0: var start = lineStart(cm, range.head.line); michael@0: var line = cm.getLineHandle(start.line); michael@0: var order = getOrder(line); michael@0: if (!order || order[0].level == 0) { michael@0: var firstNonWS = Math.max(0, line.text.search(/\S/)); michael@0: var inWS = range.head.line == start.line && range.head.ch <= firstNonWS && range.head.ch; michael@0: return Pos(start.line, inWS ? 0 : firstNonWS); michael@0: } michael@0: return start; michael@0: }, sel_move); michael@0: }, michael@0: goLineEnd: function(cm) { michael@0: cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); }, sel_move); michael@0: }, michael@0: goLineRight: function(cm) { michael@0: cm.extendSelectionsBy(function(range) { michael@0: var top = cm.charCoords(range.head, "div").top + 5; michael@0: return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); michael@0: }, sel_move); michael@0: }, michael@0: goLineLeft: function(cm) { michael@0: cm.extendSelectionsBy(function(range) { michael@0: var top = cm.charCoords(range.head, "div").top + 5; michael@0: return cm.coordsChar({left: 0, top: top}, "div"); michael@0: }, sel_move); michael@0: }, michael@0: goLineUp: function(cm) {cm.moveV(-1, "line");}, michael@0: goLineDown: function(cm) {cm.moveV(1, "line");}, michael@0: goPageUp: function(cm) {cm.moveV(-1, "page");}, michael@0: goPageDown: function(cm) {cm.moveV(1, "page");}, michael@0: goCharLeft: function(cm) {cm.moveH(-1, "char");}, michael@0: goCharRight: function(cm) {cm.moveH(1, "char");}, michael@0: goColumnLeft: function(cm) {cm.moveH(-1, "column");}, michael@0: goColumnRight: function(cm) {cm.moveH(1, "column");}, michael@0: goWordLeft: function(cm) {cm.moveH(-1, "word");}, michael@0: goGroupRight: function(cm) {cm.moveH(1, "group");}, michael@0: goGroupLeft: function(cm) {cm.moveH(-1, "group");}, michael@0: goWordRight: function(cm) {cm.moveH(1, "word");}, michael@0: delCharBefore: function(cm) {cm.deleteH(-1, "char");}, michael@0: delCharAfter: function(cm) {cm.deleteH(1, "char");}, michael@0: delWordBefore: function(cm) {cm.deleteH(-1, "word");}, michael@0: delWordAfter: function(cm) {cm.deleteH(1, "word");}, michael@0: delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, michael@0: delGroupAfter: function(cm) {cm.deleteH(1, "group");}, michael@0: indentAuto: function(cm) {cm.indentSelection("smart");}, michael@0: indentMore: function(cm) {cm.indentSelection("add");}, michael@0: indentLess: function(cm) {cm.indentSelection("subtract");}, michael@0: insertTab: function(cm) {cm.replaceSelection("\t");}, michael@0: defaultTab: function(cm) { michael@0: if (cm.somethingSelected()) cm.indentSelection("add"); michael@0: else cm.execCommand("insertTab"); michael@0: }, michael@0: transposeChars: function(cm) { michael@0: runInOp(cm, function() { michael@0: var ranges = cm.listSelections(); michael@0: for (var i = 0; i < ranges.length; i++) { michael@0: var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; michael@0: if (cur.ch > 0 && cur.ch < line.length - 1) michael@0: cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1), michael@0: Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1)); michael@0: } michael@0: }); michael@0: }, michael@0: newlineAndIndent: function(cm) { michael@0: runInOp(cm, function() { michael@0: var len = cm.listSelections().length; michael@0: for (var i = 0; i < len; i++) { michael@0: var range = cm.listSelections()[i]; michael@0: cm.replaceRange("\n", range.anchor, range.head, "+input"); michael@0: cm.indentLine(range.from().line + 1, null, true); michael@0: ensureCursorVisible(cm); michael@0: } michael@0: }); michael@0: }, michael@0: toggleOverwrite: function(cm) {cm.toggleOverwrite();} michael@0: }; michael@0: michael@0: // STANDARD KEYMAPS michael@0: michael@0: var keyMap = CodeMirror.keyMap = {}; michael@0: keyMap.basic = { michael@0: "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", michael@0: "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", michael@0: "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", michael@0: "Tab": "defaultTab", "Shift-Tab": "indentAuto", michael@0: "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", michael@0: "Esc": "singleSelection" michael@0: }; michael@0: // Note that the save and find-related commands aren't defined by michael@0: // default. User code or addons can define them. Unknown commands michael@0: // are simply ignored. michael@0: keyMap.pcDefault = { michael@0: "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", michael@0: "Ctrl-Home": "goDocStart", "Ctrl-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd", michael@0: "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", michael@0: "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", michael@0: "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", michael@0: "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", michael@0: "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", michael@0: fallthrough: "basic" michael@0: }; michael@0: keyMap.macDefault = { michael@0: "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", michael@0: "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", michael@0: "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delGroupBefore", michael@0: "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", michael@0: "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", michael@0: "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft", michael@0: "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", michael@0: fallthrough: ["basic", "emacsy"] michael@0: }; michael@0: // Very basic readline/emacs-style bindings, which are standard on Mac. michael@0: keyMap.emacsy = { michael@0: "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", michael@0: "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", michael@0: "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", michael@0: "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" michael@0: }; michael@0: keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; michael@0: michael@0: // KEYMAP DISPATCH michael@0: michael@0: function getKeyMap(val) { michael@0: if (typeof val == "string") return keyMap[val]; michael@0: else return val; michael@0: } michael@0: michael@0: // Given an array of keymaps and a key name, call handle on any michael@0: // bindings found, until that returns a truthy value, at which point michael@0: // we consider the key handled. Implements things like binding a key michael@0: // to false stopping further handling and keymap fallthrough. michael@0: var lookupKey = CodeMirror.lookupKey = function(name, maps, handle) { michael@0: function lookup(map) { michael@0: map = getKeyMap(map); michael@0: var found = map[name]; michael@0: if (found === false) return "stop"; michael@0: if (found != null && handle(found)) return true; michael@0: if (map.nofallthrough) return "stop"; michael@0: michael@0: var fallthrough = map.fallthrough; michael@0: if (fallthrough == null) return false; michael@0: if (Object.prototype.toString.call(fallthrough) != "[object Array]") michael@0: return lookup(fallthrough); michael@0: for (var i = 0; i < fallthrough.length; ++i) { michael@0: var done = lookup(fallthrough[i]); michael@0: if (done) return done; michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: for (var i = 0; i < maps.length; ++i) { michael@0: var done = lookup(maps[i]); michael@0: if (done) return done != "stop"; michael@0: } michael@0: }; michael@0: michael@0: // Modifier key presses don't count as 'real' key presses for the michael@0: // purpose of keymap fallthrough. michael@0: var isModifierKey = CodeMirror.isModifierKey = function(event) { michael@0: var name = keyNames[event.keyCode]; michael@0: return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; michael@0: }; michael@0: michael@0: // Look up the name of a key as indicated by an event object. michael@0: var keyName = CodeMirror.keyName = function(event, noShift) { michael@0: if (presto && event.keyCode == 34 && event["char"]) return false; michael@0: var name = keyNames[event.keyCode]; michael@0: if (name == null || event.altGraphKey) return false; michael@0: if (event.altKey) name = "Alt-" + name; michael@0: if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name; michael@0: if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name; michael@0: if (!noShift && event.shiftKey) name = "Shift-" + name; michael@0: return name; michael@0: }; michael@0: michael@0: // FROMTEXTAREA michael@0: michael@0: CodeMirror.fromTextArea = function(textarea, options) { michael@0: if (!options) options = {}; michael@0: options.value = textarea.value; michael@0: if (!options.tabindex && textarea.tabindex) michael@0: options.tabindex = textarea.tabindex; michael@0: if (!options.placeholder && textarea.placeholder) michael@0: options.placeholder = textarea.placeholder; michael@0: // Set autofocus to true if this textarea is focused, or if it has michael@0: // autofocus and no other element is focused. michael@0: if (options.autofocus == null) { michael@0: var hasFocus = activeElt(); michael@0: options.autofocus = hasFocus == textarea || michael@0: textarea.getAttribute("autofocus") != null && hasFocus == document.body; michael@0: } michael@0: michael@0: function save() {textarea.value = cm.getValue();} michael@0: if (textarea.form) { michael@0: on(textarea.form, "submit", save); michael@0: // Deplorable hack to make the submit method do the right thing. michael@0: if (!options.leaveSubmitMethodAlone) { michael@0: var form = textarea.form, realSubmit = form.submit; michael@0: try { michael@0: var wrappedSubmit = form.submit = function() { michael@0: save(); michael@0: form.submit = realSubmit; michael@0: form.submit(); michael@0: form.submit = wrappedSubmit; michael@0: }; michael@0: } catch(e) {} michael@0: } michael@0: } michael@0: michael@0: textarea.style.display = "none"; michael@0: var cm = CodeMirror(function(node) { michael@0: textarea.parentNode.insertBefore(node, textarea.nextSibling); michael@0: }, options); michael@0: cm.save = save; michael@0: cm.getTextArea = function() { return textarea; }; michael@0: cm.toTextArea = function() { michael@0: save(); michael@0: textarea.parentNode.removeChild(cm.getWrapperElement()); michael@0: textarea.style.display = ""; michael@0: if (textarea.form) { michael@0: off(textarea.form, "submit", save); michael@0: if (typeof textarea.form.submit == "function") michael@0: textarea.form.submit = realSubmit; michael@0: } michael@0: }; michael@0: return cm; michael@0: }; michael@0: michael@0: // STRING STREAM michael@0: michael@0: // Fed to the mode parsers, provides helper functions to make michael@0: // parsers more succinct. michael@0: michael@0: var StringStream = CodeMirror.StringStream = function(string, tabSize) { michael@0: this.pos = this.start = 0; michael@0: this.string = string; michael@0: this.tabSize = tabSize || 8; michael@0: this.lastColumnPos = this.lastColumnValue = 0; michael@0: this.lineStart = 0; michael@0: }; michael@0: michael@0: StringStream.prototype = { michael@0: eol: function() {return this.pos >= this.string.length;}, michael@0: sol: function() {return this.pos == this.lineStart;}, michael@0: peek: function() {return this.string.charAt(this.pos) || undefined;}, michael@0: next: function() { michael@0: if (this.pos < this.string.length) michael@0: return this.string.charAt(this.pos++); michael@0: }, michael@0: eat: function(match) { michael@0: var ch = this.string.charAt(this.pos); michael@0: if (typeof match == "string") var ok = ch == match; michael@0: else var ok = ch && (match.test ? match.test(ch) : match(ch)); michael@0: if (ok) {++this.pos; return ch;} michael@0: }, michael@0: eatWhile: function(match) { michael@0: var start = this.pos; michael@0: while (this.eat(match)){} michael@0: return this.pos > start; michael@0: }, michael@0: eatSpace: function() { michael@0: var start = this.pos; michael@0: while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; michael@0: return this.pos > start; michael@0: }, michael@0: skipToEnd: function() {this.pos = this.string.length;}, michael@0: skipTo: function(ch) { michael@0: var found = this.string.indexOf(ch, this.pos); michael@0: if (found > -1) {this.pos = found; return true;} michael@0: }, michael@0: backUp: function(n) {this.pos -= n;}, michael@0: column: function() { michael@0: if (this.lastColumnPos < this.start) { michael@0: this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); michael@0: this.lastColumnPos = this.start; michael@0: } michael@0: return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); michael@0: }, michael@0: indentation: function() { michael@0: return countColumn(this.string, null, this.tabSize) - michael@0: (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); michael@0: }, michael@0: match: function(pattern, consume, caseInsensitive) { michael@0: if (typeof pattern == "string") { michael@0: var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; michael@0: var substr = this.string.substr(this.pos, pattern.length); michael@0: if (cased(substr) == cased(pattern)) { michael@0: if (consume !== false) this.pos += pattern.length; michael@0: return true; michael@0: } michael@0: } else { michael@0: var match = this.string.slice(this.pos).match(pattern); michael@0: if (match && match.index > 0) return null; michael@0: if (match && consume !== false) this.pos += match[0].length; michael@0: return match; michael@0: } michael@0: }, michael@0: current: function(){return this.string.slice(this.start, this.pos);}, michael@0: hideFirstChars: function(n, inner) { michael@0: this.lineStart += n; michael@0: try { return inner(); } michael@0: finally { this.lineStart -= n; } michael@0: } michael@0: }; michael@0: michael@0: // TEXTMARKERS michael@0: michael@0: // Created with markText and setBookmark methods. A TextMarker is a michael@0: // handle that can be used to clear or find a marked position in the michael@0: // document. Line objects hold arrays (markedSpans) containing michael@0: // {from, to, marker} object pointing to such marker objects, and michael@0: // indicating that such a marker is present on that line. Multiple michael@0: // lines may point to the same marker when it spans across lines. michael@0: // The spans will have null for their from/to properties when the michael@0: // marker continues beyond the start/end of the line. Markers have michael@0: // links back to the lines they currently touch. michael@0: michael@0: var TextMarker = CodeMirror.TextMarker = function(doc, type) { michael@0: this.lines = []; michael@0: this.type = type; michael@0: this.doc = doc; michael@0: }; michael@0: eventMixin(TextMarker); michael@0: michael@0: // Clear the marker. michael@0: TextMarker.prototype.clear = function() { michael@0: if (this.explicitlyCleared) return; michael@0: var cm = this.doc.cm, withOp = cm && !cm.curOp; michael@0: if (withOp) startOperation(cm); michael@0: if (hasHandler(this, "clear")) { michael@0: var found = this.find(); michael@0: if (found) signalLater(this, "clear", found.from, found.to); michael@0: } michael@0: var min = null, max = null; michael@0: for (var i = 0; i < this.lines.length; ++i) { michael@0: var line = this.lines[i]; michael@0: var span = getMarkedSpanFor(line.markedSpans, this); michael@0: if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text"); michael@0: else if (cm) { michael@0: if (span.to != null) max = lineNo(line); michael@0: if (span.from != null) min = lineNo(line); michael@0: } michael@0: line.markedSpans = removeMarkedSpan(line.markedSpans, span); michael@0: if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) michael@0: updateLineHeight(line, textHeight(cm.display)); michael@0: } michael@0: if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) { michael@0: var visual = visualLine(this.lines[i]), len = lineLength(visual); michael@0: if (len > cm.display.maxLineLength) { michael@0: cm.display.maxLine = visual; michael@0: cm.display.maxLineLength = len; michael@0: cm.display.maxLineChanged = true; michael@0: } michael@0: } michael@0: michael@0: if (min != null && cm && this.collapsed) regChange(cm, min, max + 1); michael@0: this.lines.length = 0; michael@0: this.explicitlyCleared = true; michael@0: if (this.atomic && this.doc.cantEdit) { michael@0: this.doc.cantEdit = false; michael@0: if (cm) reCheckSelection(cm.doc); michael@0: } michael@0: if (cm) signalLater(cm, "markerCleared", cm, this); michael@0: if (withOp) endOperation(cm); michael@0: }; michael@0: michael@0: // Find the position of the marker in the document. Returns a {from, michael@0: // to} object by default. Side can be passed to get a specific side michael@0: // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the michael@0: // Pos objects returned contain a line object, rather than a line michael@0: // number (used to prevent looking up the same line twice). michael@0: TextMarker.prototype.find = function(side, lineObj) { michael@0: if (side == null && this.type == "bookmark") side = 1; michael@0: var from, to; michael@0: for (var i = 0; i < this.lines.length; ++i) { michael@0: var line = this.lines[i]; michael@0: var span = getMarkedSpanFor(line.markedSpans, this); michael@0: if (span.from != null) { michael@0: from = Pos(lineObj ? line : lineNo(line), span.from); michael@0: if (side == -1) return from; michael@0: } michael@0: if (span.to != null) { michael@0: to = Pos(lineObj ? line : lineNo(line), span.to); michael@0: if (side == 1) return to; michael@0: } michael@0: } michael@0: return from && {from: from, to: to}; michael@0: }; michael@0: michael@0: // Signals that the marker's widget changed, and surrounding layout michael@0: // should be recomputed. michael@0: TextMarker.prototype.changed = function() { michael@0: var pos = this.find(-1, true), widget = this, cm = this.doc.cm; michael@0: if (!pos || !cm) return; michael@0: runInOp(cm, function() { michael@0: var line = pos.line, lineN = lineNo(pos.line); michael@0: var view = findViewForLine(cm, lineN); michael@0: if (view) { michael@0: clearLineMeasurementCacheFor(view); michael@0: cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; michael@0: } michael@0: cm.curOp.updateMaxLine = true; michael@0: if (!lineIsHidden(widget.doc, line) && widget.height != null) { michael@0: var oldHeight = widget.height; michael@0: widget.height = null; michael@0: var dHeight = widgetHeight(widget) - oldHeight; michael@0: if (dHeight) michael@0: updateLineHeight(line, line.height + dHeight); michael@0: } michael@0: }); michael@0: }; michael@0: michael@0: TextMarker.prototype.attachLine = function(line) { michael@0: if (!this.lines.length && this.doc.cm) { michael@0: var op = this.doc.cm.curOp; michael@0: if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) michael@0: (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); michael@0: } michael@0: this.lines.push(line); michael@0: }; michael@0: TextMarker.prototype.detachLine = function(line) { michael@0: this.lines.splice(indexOf(this.lines, line), 1); michael@0: if (!this.lines.length && this.doc.cm) { michael@0: var op = this.doc.cm.curOp; michael@0: (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); michael@0: } michael@0: }; michael@0: michael@0: // Collapsed markers have unique ids, in order to be able to order michael@0: // them, which is needed for uniquely determining an outer marker michael@0: // when they overlap (they may nest, but not partially overlap). michael@0: var nextMarkerId = 0; michael@0: michael@0: // Create a marker, wire it up to the right lines, and michael@0: function markText(doc, from, to, options, type) { michael@0: // Shared markers (across linked documents) are handled separately michael@0: // (markTextShared will call out to this again, once per michael@0: // document). michael@0: if (options && options.shared) return markTextShared(doc, from, to, options, type); michael@0: // Ensure we are in an operation. michael@0: if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); michael@0: michael@0: var marker = new TextMarker(doc, type), diff = cmp(from, to); michael@0: if (options) copyObj(options, marker); michael@0: // Don't connect empty markers unless clearWhenEmpty is false michael@0: if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) michael@0: return marker; michael@0: if (marker.replacedWith) { michael@0: // Showing up as a widget implies collapsed (widget replaces text) michael@0: marker.collapsed = true; michael@0: marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget"); michael@0: if (!options.handleMouseEvents) marker.widgetNode.ignoreEvents = true; michael@0: if (options.insertLeft) marker.widgetNode.insertLeft = true; michael@0: } michael@0: if (marker.collapsed) { michael@0: if (conflictingCollapsedRange(doc, from.line, from, to, marker) || michael@0: from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) michael@0: throw new Error("Inserting collapsed marker partially overlapping an existing one"); michael@0: sawCollapsedSpans = true; michael@0: } michael@0: michael@0: if (marker.addToHistory) michael@0: addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); michael@0: michael@0: var curLine = from.line, cm = doc.cm, updateMaxLine; michael@0: doc.iter(curLine, to.line + 1, function(line) { michael@0: if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) michael@0: updateMaxLine = true; michael@0: if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0); michael@0: addMarkedSpan(line, new MarkedSpan(marker, michael@0: curLine == from.line ? from.ch : null, michael@0: curLine == to.line ? to.ch : null)); michael@0: ++curLine; michael@0: }); michael@0: // lineIsHidden depends on the presence of the spans, so needs a second pass michael@0: if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { michael@0: if (lineIsHidden(doc, line)) updateLineHeight(line, 0); michael@0: }); michael@0: michael@0: if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); }); michael@0: michael@0: if (marker.readOnly) { michael@0: sawReadOnlySpans = true; michael@0: if (doc.history.done.length || doc.history.undone.length) michael@0: doc.clearHistory(); michael@0: } michael@0: if (marker.collapsed) { michael@0: marker.id = ++nextMarkerId; michael@0: marker.atomic = true; michael@0: } michael@0: if (cm) { michael@0: // Sync editor state michael@0: if (updateMaxLine) cm.curOp.updateMaxLine = true; michael@0: if (marker.collapsed) michael@0: regChange(cm, from.line, to.line + 1); michael@0: else if (marker.className || marker.title || marker.startStyle || marker.endStyle) michael@0: for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text"); michael@0: if (marker.atomic) reCheckSelection(cm.doc); michael@0: signalLater(cm, "markerAdded", cm, marker); michael@0: } michael@0: return marker; michael@0: } michael@0: michael@0: // SHARED TEXTMARKERS michael@0: michael@0: // A shared marker spans multiple linked documents. It is michael@0: // implemented as a meta-marker-object controlling multiple normal michael@0: // markers. michael@0: var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) { michael@0: this.markers = markers; michael@0: this.primary = primary; michael@0: for (var i = 0, me = this; i < markers.length; ++i) { michael@0: markers[i].parent = this; michael@0: on(markers[i], "clear", function(){me.clear();}); michael@0: } michael@0: }; michael@0: eventMixin(SharedTextMarker); michael@0: michael@0: SharedTextMarker.prototype.clear = function() { michael@0: if (this.explicitlyCleared) return; michael@0: this.explicitlyCleared = true; michael@0: for (var i = 0; i < this.markers.length; ++i) michael@0: this.markers[i].clear(); michael@0: signalLater(this, "clear"); michael@0: }; michael@0: SharedTextMarker.prototype.find = function(side, lineObj) { michael@0: return this.primary.find(side, lineObj); michael@0: }; michael@0: michael@0: function markTextShared(doc, from, to, options, type) { michael@0: options = copyObj(options); michael@0: options.shared = false; michael@0: var markers = [markText(doc, from, to, options, type)], primary = markers[0]; michael@0: var widget = options.widgetNode; michael@0: linkedDocs(doc, function(doc) { michael@0: if (widget) options.widgetNode = widget.cloneNode(true); michael@0: markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); michael@0: for (var i = 0; i < doc.linked.length; ++i) michael@0: if (doc.linked[i].isParent) return; michael@0: primary = lst(markers); michael@0: }); michael@0: return new SharedTextMarker(markers, primary); michael@0: } michael@0: michael@0: // TEXTMARKER SPANS michael@0: michael@0: function MarkedSpan(marker, from, to) { michael@0: this.marker = marker; michael@0: this.from = from; this.to = to; michael@0: } michael@0: michael@0: // Search an array of spans for a span matching the given marker. michael@0: function getMarkedSpanFor(spans, marker) { michael@0: if (spans) for (var i = 0; i < spans.length; ++i) { michael@0: var span = spans[i]; michael@0: if (span.marker == marker) return span; michael@0: } michael@0: } michael@0: // Remove a span from an array, returning undefined if no spans are michael@0: // left (we don't store arrays for lines without spans). michael@0: function removeMarkedSpan(spans, span) { michael@0: for (var r, i = 0; i < spans.length; ++i) michael@0: if (spans[i] != span) (r || (r = [])).push(spans[i]); michael@0: return r; michael@0: } michael@0: // Add a span to a line. michael@0: function addMarkedSpan(line, span) { michael@0: line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; michael@0: span.marker.attachLine(line); michael@0: } michael@0: michael@0: // Used for the algorithm that adjusts markers for a change in the michael@0: // document. These functions cut an array of spans at a given michael@0: // character position, returning an array of remaining chunks (or michael@0: // undefined if nothing remains). michael@0: function markedSpansBefore(old, startCh, isInsert) { michael@0: if (old) for (var i = 0, nw; i < old.length; ++i) { michael@0: var span = old[i], marker = span.marker; michael@0: var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); michael@0: if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { michael@0: var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); michael@0: (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); michael@0: } michael@0: } michael@0: return nw; michael@0: } michael@0: function markedSpansAfter(old, endCh, isInsert) { michael@0: if (old) for (var i = 0, nw; i < old.length; ++i) { michael@0: var span = old[i], marker = span.marker; michael@0: var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); michael@0: if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { michael@0: var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); michael@0: (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, michael@0: span.to == null ? null : span.to - endCh)); michael@0: } michael@0: } michael@0: return nw; michael@0: } michael@0: michael@0: // Given a change object, compute the new set of marker spans that michael@0: // cover the line in which the change took place. Removes spans michael@0: // entirely within the change, reconnects spans belonging to the michael@0: // same marker that appear on both sides of the change, and cuts off michael@0: // spans partially within the change. Returns an array of span michael@0: // arrays with one element for each line in (after) the change. michael@0: function stretchSpansOverChange(doc, change) { michael@0: var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; michael@0: var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; michael@0: if (!oldFirst && !oldLast) return null; michael@0: michael@0: var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; michael@0: // Get the spans that 'stick out' on both sides michael@0: var first = markedSpansBefore(oldFirst, startCh, isInsert); michael@0: var last = markedSpansAfter(oldLast, endCh, isInsert); michael@0: michael@0: // Next, merge those two ends michael@0: var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); michael@0: if (first) { michael@0: // Fix up .to properties of first michael@0: for (var i = 0; i < first.length; ++i) { michael@0: var span = first[i]; michael@0: if (span.to == null) { michael@0: var found = getMarkedSpanFor(last, span.marker); michael@0: if (!found) span.to = startCh; michael@0: else if (sameLine) span.to = found.to == null ? null : found.to + offset; michael@0: } michael@0: } michael@0: } michael@0: if (last) { michael@0: // Fix up .from in last (or move them into first in case of sameLine) michael@0: for (var i = 0; i < last.length; ++i) { michael@0: var span = last[i]; michael@0: if (span.to != null) span.to += offset; michael@0: if (span.from == null) { michael@0: var found = getMarkedSpanFor(first, span.marker); michael@0: if (!found) { michael@0: span.from = offset; michael@0: if (sameLine) (first || (first = [])).push(span); michael@0: } michael@0: } else { michael@0: span.from += offset; michael@0: if (sameLine) (first || (first = [])).push(span); michael@0: } michael@0: } michael@0: } michael@0: // Make sure we didn't create any zero-length spans michael@0: if (first) first = clearEmptySpans(first); michael@0: if (last && last != first) last = clearEmptySpans(last); michael@0: michael@0: var newMarkers = [first]; michael@0: if (!sameLine) { michael@0: // Fill gap with whole-line-spans michael@0: var gap = change.text.length - 2, gapMarkers; michael@0: if (gap > 0 && first) michael@0: for (var i = 0; i < first.length; ++i) michael@0: if (first[i].to == null) michael@0: (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null)); michael@0: for (var i = 0; i < gap; ++i) michael@0: newMarkers.push(gapMarkers); michael@0: newMarkers.push(last); michael@0: } michael@0: return newMarkers; michael@0: } michael@0: michael@0: // Remove spans that are empty and don't have a clearWhenEmpty michael@0: // option of false. michael@0: function clearEmptySpans(spans) { michael@0: for (var i = 0; i < spans.length; ++i) { michael@0: var span = spans[i]; michael@0: if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) michael@0: spans.splice(i--, 1); michael@0: } michael@0: if (!spans.length) return null; michael@0: return spans; michael@0: } michael@0: michael@0: // Used for un/re-doing changes from the history. Combines the michael@0: // result of computing the existing spans with the set of spans that michael@0: // existed in the history (so that deleting around a span and then michael@0: // undoing brings back the span). michael@0: function mergeOldSpans(doc, change) { michael@0: var old = getOldSpans(doc, change); michael@0: var stretched = stretchSpansOverChange(doc, change); michael@0: if (!old) return stretched; michael@0: if (!stretched) return old; michael@0: michael@0: for (var i = 0; i < old.length; ++i) { michael@0: var oldCur = old[i], stretchCur = stretched[i]; michael@0: if (oldCur && stretchCur) { michael@0: spans: for (var j = 0; j < stretchCur.length; ++j) { michael@0: var span = stretchCur[j]; michael@0: for (var k = 0; k < oldCur.length; ++k) michael@0: if (oldCur[k].marker == span.marker) continue spans; michael@0: oldCur.push(span); michael@0: } michael@0: } else if (stretchCur) { michael@0: old[i] = stretchCur; michael@0: } michael@0: } michael@0: return old; michael@0: } michael@0: michael@0: // Used to 'clip' out readOnly ranges when making a change. michael@0: function removeReadOnlyRanges(doc, from, to) { michael@0: var markers = null; michael@0: doc.iter(from.line, to.line + 1, function(line) { michael@0: if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { michael@0: var mark = line.markedSpans[i].marker; michael@0: if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) michael@0: (markers || (markers = [])).push(mark); michael@0: } michael@0: }); michael@0: if (!markers) return null; michael@0: var parts = [{from: from, to: to}]; michael@0: for (var i = 0; i < markers.length; ++i) { michael@0: var mk = markers[i], m = mk.find(0); michael@0: for (var j = 0; j < parts.length; ++j) { michael@0: var p = parts[j]; michael@0: if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue; michael@0: var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); michael@0: if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) michael@0: newParts.push({from: p.from, to: m.from}); michael@0: if (dto > 0 || !mk.inclusiveRight && !dto) michael@0: newParts.push({from: m.to, to: p.to}); michael@0: parts.splice.apply(parts, newParts); michael@0: j += newParts.length - 1; michael@0: } michael@0: } michael@0: return parts; michael@0: } michael@0: michael@0: // Connect or disconnect spans from a line. michael@0: function detachMarkedSpans(line) { michael@0: var spans = line.markedSpans; michael@0: if (!spans) return; michael@0: for (var i = 0; i < spans.length; ++i) michael@0: spans[i].marker.detachLine(line); michael@0: line.markedSpans = null; michael@0: } michael@0: function attachMarkedSpans(line, spans) { michael@0: if (!spans) return; michael@0: for (var i = 0; i < spans.length; ++i) michael@0: spans[i].marker.attachLine(line); michael@0: line.markedSpans = spans; michael@0: } michael@0: michael@0: // Helpers used when computing which overlapping collapsed span michael@0: // counts as the larger one. michael@0: function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; } michael@0: function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; } michael@0: michael@0: // Returns a number indicating which of two overlapping collapsed michael@0: // spans is larger (and thus includes the other). Falls back to michael@0: // comparing ids when the spans cover exactly the same range. michael@0: function compareCollapsedMarkers(a, b) { michael@0: var lenDiff = a.lines.length - b.lines.length; michael@0: if (lenDiff != 0) return lenDiff; michael@0: var aPos = a.find(), bPos = b.find(); michael@0: var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); michael@0: if (fromCmp) return -fromCmp; michael@0: var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); michael@0: if (toCmp) return toCmp; michael@0: return b.id - a.id; michael@0: } michael@0: michael@0: // Find out whether a line ends or starts in a collapsed span. If michael@0: // so, return the marker for that span. michael@0: function collapsedSpanAtSide(line, start) { michael@0: var sps = sawCollapsedSpans && line.markedSpans, found; michael@0: if (sps) for (var sp, i = 0; i < sps.length; ++i) { michael@0: sp = sps[i]; michael@0: if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && michael@0: (!found || compareCollapsedMarkers(found, sp.marker) < 0)) michael@0: found = sp.marker; michael@0: } michael@0: return found; michael@0: } michael@0: function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); } michael@0: function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); } michael@0: michael@0: // Test whether there exists a collapsed span that partially michael@0: // overlaps (covers the start or end, but not both) of a new span. michael@0: // Such overlap is not allowed. michael@0: function conflictingCollapsedRange(doc, lineNo, from, to, marker) { michael@0: var line = getLine(doc, lineNo); michael@0: var sps = sawCollapsedSpans && line.markedSpans; michael@0: if (sps) for (var i = 0; i < sps.length; ++i) { michael@0: var sp = sps[i]; michael@0: if (!sp.marker.collapsed) continue; michael@0: var found = sp.marker.find(0); michael@0: var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); michael@0: var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); michael@0: if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue; michael@0: if (fromCmp <= 0 && (cmp(found.to, from) || extraRight(sp.marker) - extraLeft(marker)) > 0 || michael@0: fromCmp >= 0 && (cmp(found.from, to) || extraLeft(sp.marker) - extraRight(marker)) < 0) michael@0: return true; michael@0: } michael@0: } michael@0: michael@0: // A visual line is a line as drawn on the screen. Folding, for michael@0: // example, can cause multiple logical lines to appear on the same michael@0: // visual line. This finds the start of the visual line that the michael@0: // given line is part of (usually that is the line itself). michael@0: function visualLine(line) { michael@0: var merged; michael@0: while (merged = collapsedSpanAtStart(line)) michael@0: line = merged.find(-1, true).line; michael@0: return line; michael@0: } michael@0: michael@0: // Returns an array of logical lines that continue the visual line michael@0: // started by the argument, or undefined if there are no such lines. michael@0: function visualLineContinued(line) { michael@0: var merged, lines; michael@0: while (merged = collapsedSpanAtEnd(line)) { michael@0: line = merged.find(1, true).line; michael@0: (lines || (lines = [])).push(line); michael@0: } michael@0: return lines; michael@0: } michael@0: michael@0: // Get the line number of the start of the visual line that the michael@0: // given line number is part of. michael@0: function visualLineNo(doc, lineN) { michael@0: var line = getLine(doc, lineN), vis = visualLine(line); michael@0: if (line == vis) return lineN; michael@0: return lineNo(vis); michael@0: } michael@0: // Get the line number of the start of the next visual line after michael@0: // the given line. michael@0: function visualLineEndNo(doc, lineN) { michael@0: if (lineN > doc.lastLine()) return lineN; michael@0: var line = getLine(doc, lineN), merged; michael@0: if (!lineIsHidden(doc, line)) return lineN; michael@0: while (merged = collapsedSpanAtEnd(line)) michael@0: line = merged.find(1, true).line; michael@0: return lineNo(line) + 1; michael@0: } michael@0: michael@0: // Compute whether a line is hidden. Lines count as hidden when they michael@0: // are part of a visual line that starts with another line, or when michael@0: // they are entirely covered by collapsed, non-widget span. michael@0: function lineIsHidden(doc, line) { michael@0: var sps = sawCollapsedSpans && line.markedSpans; michael@0: if (sps) for (var sp, i = 0; i < sps.length; ++i) { michael@0: sp = sps[i]; michael@0: if (!sp.marker.collapsed) continue; michael@0: if (sp.from == null) return true; michael@0: if (sp.marker.widgetNode) continue; michael@0: if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) michael@0: return true; michael@0: } michael@0: } michael@0: function lineIsHiddenInner(doc, line, span) { michael@0: if (span.to == null) { michael@0: var end = span.marker.find(1, true); michael@0: return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); michael@0: } michael@0: if (span.marker.inclusiveRight && span.to == line.text.length) michael@0: return true; michael@0: for (var sp, i = 0; i < line.markedSpans.length; ++i) { michael@0: sp = line.markedSpans[i]; michael@0: if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && michael@0: (sp.to == null || sp.to != span.from) && michael@0: (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && michael@0: lineIsHiddenInner(doc, line, sp)) return true; michael@0: } michael@0: } michael@0: michael@0: // LINE WIDGETS michael@0: michael@0: // Line widgets are block elements displayed above or below a line. michael@0: michael@0: var LineWidget = CodeMirror.LineWidget = function(cm, node, options) { michael@0: if (options) for (var opt in options) if (options.hasOwnProperty(opt)) michael@0: this[opt] = options[opt]; michael@0: this.cm = cm; michael@0: this.node = node; michael@0: }; michael@0: eventMixin(LineWidget); michael@0: michael@0: function adjustScrollWhenAboveVisible(cm, line, diff) { michael@0: if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) michael@0: addToScrollPos(cm, null, diff); michael@0: } michael@0: michael@0: LineWidget.prototype.clear = function() { michael@0: var cm = this.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); michael@0: if (no == null || !ws) return; michael@0: for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); michael@0: if (!ws.length) line.widgets = null; michael@0: var height = widgetHeight(this); michael@0: runInOp(cm, function() { michael@0: adjustScrollWhenAboveVisible(cm, line, -height); michael@0: regLineChange(cm, no, "widget"); michael@0: updateLineHeight(line, Math.max(0, line.height - height)); michael@0: }); michael@0: }; michael@0: LineWidget.prototype.changed = function() { michael@0: var oldH = this.height, cm = this.cm, line = this.line; michael@0: this.height = null; michael@0: var diff = widgetHeight(this) - oldH; michael@0: if (!diff) return; michael@0: runInOp(cm, function() { michael@0: cm.curOp.forceUpdate = true; michael@0: adjustScrollWhenAboveVisible(cm, line, diff); michael@0: updateLineHeight(line, line.height + diff); michael@0: }); michael@0: }; michael@0: michael@0: function widgetHeight(widget) { michael@0: if (widget.height != null) return widget.height; michael@0: if (!contains(document.body, widget.node)) michael@0: removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative")); michael@0: return widget.height = widget.node.offsetHeight; michael@0: } michael@0: michael@0: function addLineWidget(cm, handle, node, options) { michael@0: var widget = new LineWidget(cm, node, options); michael@0: if (widget.noHScroll) cm.display.alignWidgets = true; michael@0: changeLine(cm, handle, "widget", function(line) { michael@0: var widgets = line.widgets || (line.widgets = []); michael@0: if (widget.insertAt == null) widgets.push(widget); michael@0: else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); michael@0: widget.line = line; michael@0: if (!lineIsHidden(cm.doc, line)) { michael@0: var aboveVisible = heightAtLine(line) < cm.doc.scrollTop; michael@0: updateLineHeight(line, line.height + widgetHeight(widget)); michael@0: if (aboveVisible) addToScrollPos(cm, null, widget.height); michael@0: cm.curOp.forceUpdate = true; michael@0: } michael@0: return true; michael@0: }); michael@0: return widget; michael@0: } michael@0: michael@0: // LINE DATA STRUCTURE michael@0: michael@0: // Line objects. These hold state related to a line, including michael@0: // highlighting info (the styles array). michael@0: var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) { michael@0: this.text = text; michael@0: attachMarkedSpans(this, markedSpans); michael@0: this.height = estimateHeight ? estimateHeight(this) : 1; michael@0: }; michael@0: eventMixin(Line); michael@0: Line.prototype.lineNo = function() { return lineNo(this); }; michael@0: michael@0: // Change the content (text, markers) of a line. Automatically michael@0: // invalidates cached information and tries to re-estimate the michael@0: // line's height. michael@0: function updateLine(line, text, markedSpans, estimateHeight) { michael@0: line.text = text; michael@0: if (line.stateAfter) line.stateAfter = null; michael@0: if (line.styles) line.styles = null; michael@0: if (line.order != null) line.order = null; michael@0: detachMarkedSpans(line); michael@0: attachMarkedSpans(line, markedSpans); michael@0: var estHeight = estimateHeight ? estimateHeight(line) : 1; michael@0: if (estHeight != line.height) updateLineHeight(line, estHeight); michael@0: } michael@0: michael@0: // Detach a line from the document tree and its markers. michael@0: function cleanUpLine(line) { michael@0: line.parent = null; michael@0: detachMarkedSpans(line); michael@0: } michael@0: michael@0: // Run the given mode's parser over a line, calling f for each token. michael@0: function runMode(cm, text, mode, state, f, forceToEnd) { michael@0: var flattenSpans = mode.flattenSpans; michael@0: if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; michael@0: var curStart = 0, curStyle = null; michael@0: var stream = new StringStream(text, cm.options.tabSize), style; michael@0: if (text == "" && mode.blankLine) mode.blankLine(state); michael@0: while (!stream.eol()) { michael@0: if (stream.pos > cm.options.maxHighlightLength) { michael@0: flattenSpans = false; michael@0: if (forceToEnd) processLine(cm, text, state, stream.pos); michael@0: stream.pos = text.length; michael@0: style = null; michael@0: } else { michael@0: style = mode.token(stream, state); michael@0: } michael@0: if (cm.options.addModeClass) { michael@0: var mName = CodeMirror.innerMode(mode, state).mode.name; michael@0: if (mName) style = "m-" + (style ? mName + " " + style : mName); michael@0: } michael@0: if (!flattenSpans || curStyle != style) { michael@0: if (curStart < stream.start) f(stream.start, curStyle); michael@0: curStart = stream.start; curStyle = style; michael@0: } michael@0: stream.start = stream.pos; michael@0: } michael@0: while (curStart < stream.pos) { michael@0: // Webkit seems to refuse to render text nodes longer than 57444 characters michael@0: var pos = Math.min(stream.pos, curStart + 50000); michael@0: f(pos, curStyle); michael@0: curStart = pos; michael@0: } michael@0: } michael@0: michael@0: // Compute a style array (an array starting with a mode generation michael@0: // -- for invalidation -- followed by pairs of end positions and michael@0: // style strings), which is used to highlight the tokens on the michael@0: // line. michael@0: function highlightLine(cm, line, state, forceToEnd) { michael@0: // A styles array always starts with a number identifying the michael@0: // mode/overlays that it is based on (for easy invalidation). michael@0: var st = [cm.state.modeGen]; michael@0: // Compute the base array of styles michael@0: runMode(cm, line.text, cm.doc.mode, state, function(end, style) { michael@0: st.push(end, style); michael@0: }, forceToEnd); michael@0: michael@0: // Run overlays, adjust style array. michael@0: for (var o = 0; o < cm.state.overlays.length; ++o) { michael@0: var overlay = cm.state.overlays[o], i = 1, at = 0; michael@0: runMode(cm, line.text, overlay.mode, true, function(end, style) { michael@0: var start = i; michael@0: // Ensure there's a token end at the current position, and that i points at it michael@0: while (at < end) { michael@0: var i_end = st[i]; michael@0: if (i_end > end) michael@0: st.splice(i, 1, end, st[i+1], i_end); michael@0: i += 2; michael@0: at = Math.min(end, i_end); michael@0: } michael@0: if (!style) return; michael@0: if (overlay.opaque) { michael@0: st.splice(start, i - start, end, style); michael@0: i = start + 2; michael@0: } else { michael@0: for (; start < i; start += 2) { michael@0: var cur = st[start+1]; michael@0: st[start+1] = cur ? cur + " " + style : style; michael@0: } michael@0: } michael@0: }); michael@0: } michael@0: michael@0: return st; michael@0: } michael@0: michael@0: function getLineStyles(cm, line) { michael@0: if (!line.styles || line.styles[0] != cm.state.modeGen) michael@0: line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line))); michael@0: return line.styles; michael@0: } michael@0: michael@0: // Lightweight form of highlight -- proceed over this line and michael@0: // update state, but don't save a style array. Used for lines that michael@0: // aren't currently visible. michael@0: function processLine(cm, text, state, startAt) { michael@0: var mode = cm.doc.mode; michael@0: var stream = new StringStream(text, cm.options.tabSize); michael@0: stream.start = stream.pos = startAt || 0; michael@0: if (text == "" && mode.blankLine) mode.blankLine(state); michael@0: while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) { michael@0: mode.token(stream, state); michael@0: stream.start = stream.pos; michael@0: } michael@0: } michael@0: michael@0: // Convert a style as returned by a mode (either null, or a string michael@0: // containing one or more styles) to a CSS style. This is cached, michael@0: // and also looks for line-wide styles. michael@0: var styleToClassCache = {}, styleToClassCacheWithMode = {}; michael@0: function interpretTokenStyle(style, builder) { michael@0: if (!style) return null; michael@0: for (;;) { michael@0: var lineClass = style.match(/(?:^|\s+)line-(background-)?(\S+)/); michael@0: if (!lineClass) break; michael@0: style = style.slice(0, lineClass.index) + style.slice(lineClass.index + lineClass[0].length); michael@0: var prop = lineClass[1] ? "bgClass" : "textClass"; michael@0: if (builder[prop] == null) michael@0: builder[prop] = lineClass[2]; michael@0: else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(builder[prop])) michael@0: builder[prop] += " " + lineClass[2]; michael@0: } michael@0: if (/^\s*$/.test(style)) return null; michael@0: var cache = builder.cm.options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; michael@0: return cache[style] || michael@0: (cache[style] = style.replace(/\S+/g, "cm-$&")); michael@0: } michael@0: michael@0: // Render the DOM representation of the text of a line. Also builds michael@0: // up a 'line map', which points at the DOM nodes that represent michael@0: // specific stretches of text, and is used by the measuring code. michael@0: // The returned object contains the DOM node, this map, and michael@0: // information about line-wide styles that were set by the mode. michael@0: function buildLineContent(cm, lineView) { michael@0: // The padding-right forces the element to have a 'border', which michael@0: // is needed on Webkit to be able to get line-level bounding michael@0: // rectangles for it (in measureChar). michael@0: var content = elt("span", null, null, webkit ? "padding-right: .1px" : null); michael@0: var builder = {pre: elt("pre", [content]), content: content, col: 0, pos: 0, cm: cm}; michael@0: lineView.measure = {}; michael@0: michael@0: // Iterate over the logical lines that make up this visual line. michael@0: for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { michael@0: var line = i ? lineView.rest[i - 1] : lineView.line, order; michael@0: builder.pos = 0; michael@0: builder.addToken = buildToken; michael@0: // Optionally wire in some hacks into the token-rendering michael@0: // algorithm, to deal with browser quirks. michael@0: if ((ie || webkit) && cm.getOption("lineWrapping")) michael@0: builder.addToken = buildTokenSplitSpaces(builder.addToken); michael@0: if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) michael@0: builder.addToken = buildTokenBadBidi(builder.addToken, order); michael@0: builder.map = []; michael@0: insertLineContent(line, builder, getLineStyles(cm, line)); michael@0: michael@0: // Ensure at least a single node is present, for measuring. michael@0: if (builder.map.length == 0) michael@0: builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); michael@0: michael@0: // Store the map and a cache object for the current logical line michael@0: if (i == 0) { michael@0: lineView.measure.map = builder.map; michael@0: lineView.measure.cache = {}; michael@0: } else { michael@0: (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); michael@0: (lineView.measure.caches || (lineView.measure.caches = [])).push({}); michael@0: } michael@0: } michael@0: michael@0: signal(cm, "renderLine", cm, lineView.line, builder.pre); michael@0: return builder; michael@0: } michael@0: michael@0: function defaultSpecialCharPlaceholder(ch) { michael@0: var token = elt("span", "\u2022", "cm-invalidchar"); michael@0: token.title = "\\u" + ch.charCodeAt(0).toString(16); michael@0: return token; michael@0: } michael@0: michael@0: // Build up the DOM representation for a single token, and add it to michael@0: // the line map. Takes care to render special characters separately. michael@0: function buildToken(builder, text, style, startStyle, endStyle, title) { michael@0: if (!text) return; michael@0: var special = builder.cm.options.specialChars, mustWrap = false; michael@0: if (!special.test(text)) { michael@0: builder.col += text.length; michael@0: var content = document.createTextNode(text); michael@0: builder.map.push(builder.pos, builder.pos + text.length, content); michael@0: if (ie_upto8) mustWrap = true; michael@0: builder.pos += text.length; michael@0: } else { michael@0: var content = document.createDocumentFragment(), pos = 0; michael@0: while (true) { michael@0: special.lastIndex = pos; michael@0: var m = special.exec(text); michael@0: var skipped = m ? m.index - pos : text.length - pos; michael@0: if (skipped) { michael@0: var txt = document.createTextNode(text.slice(pos, pos + skipped)); michael@0: if (ie_upto8) content.appendChild(elt("span", [txt])); michael@0: else content.appendChild(txt); michael@0: builder.map.push(builder.pos, builder.pos + skipped, txt); michael@0: builder.col += skipped; michael@0: builder.pos += skipped; michael@0: } michael@0: if (!m) break; michael@0: pos += skipped + 1; michael@0: if (m[0] == "\t") { michael@0: var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; michael@0: var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); michael@0: builder.col += tabWidth; michael@0: } else { michael@0: var txt = builder.cm.options.specialCharPlaceholder(m[0]); michael@0: if (ie_upto8) content.appendChild(elt("span", [txt])); michael@0: else content.appendChild(txt); michael@0: builder.col += 1; michael@0: } michael@0: builder.map.push(builder.pos, builder.pos + 1, txt); michael@0: builder.pos++; michael@0: } michael@0: } michael@0: if (style || startStyle || endStyle || mustWrap) { michael@0: var fullStyle = style || ""; michael@0: if (startStyle) fullStyle += startStyle; michael@0: if (endStyle) fullStyle += endStyle; michael@0: var token = elt("span", [content], fullStyle); michael@0: if (title) token.title = title; michael@0: return builder.content.appendChild(token); michael@0: } michael@0: builder.content.appendChild(content); michael@0: } michael@0: michael@0: function buildTokenSplitSpaces(inner) { michael@0: function split(old) { michael@0: var out = " "; michael@0: for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; michael@0: out += " "; michael@0: return out; michael@0: } michael@0: return function(builder, text, style, startStyle, endStyle, title) { michael@0: inner(builder, text.replace(/ {3,}/g, split), style, startStyle, endStyle, title); michael@0: }; michael@0: } michael@0: michael@0: // Work around nonsense dimensions being reported for stretches of michael@0: // right-to-left text. michael@0: function buildTokenBadBidi(inner, order) { michael@0: return function(builder, text, style, startStyle, endStyle, title) { michael@0: style = style ? style + " cm-force-border" : "cm-force-border"; michael@0: var start = builder.pos, end = start + text.length; michael@0: for (;;) { michael@0: // Find the part that overlaps with the start of this text michael@0: for (var i = 0; i < order.length; i++) { michael@0: var part = order[i]; michael@0: if (part.to > start && part.from <= start) break; michael@0: } michael@0: if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title); michael@0: inner(builder, text.slice(0, part.to - start), style, startStyle, null, title); michael@0: startStyle = null; michael@0: text = text.slice(part.to - start); michael@0: start = part.to; michael@0: } michael@0: }; michael@0: } michael@0: michael@0: function buildCollapsedSpan(builder, size, marker, ignoreWidget) { michael@0: var widget = !ignoreWidget && marker.widgetNode; michael@0: if (widget) { michael@0: builder.map.push(builder.pos, builder.pos + size, widget); michael@0: builder.content.appendChild(widget); michael@0: } michael@0: builder.pos += size; michael@0: } michael@0: michael@0: // Outputs a number of spans to make up a line, taking highlighting michael@0: // and marked text into account. michael@0: function insertLineContent(line, builder, styles) { michael@0: var spans = line.markedSpans, allText = line.text, at = 0; michael@0: if (!spans) { michael@0: for (var i = 1; i < styles.length; i+=2) michael@0: builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder)); michael@0: return; michael@0: } michael@0: michael@0: var len = allText.length, pos = 0, i = 1, text = "", style; michael@0: var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; michael@0: for (;;) { michael@0: if (nextChange == pos) { // Update current marker set michael@0: spanStyle = spanEndStyle = spanStartStyle = title = ""; michael@0: collapsed = null; nextChange = Infinity; michael@0: var foundBookmarks = []; michael@0: for (var j = 0; j < spans.length; ++j) { michael@0: var sp = spans[j], m = sp.marker; michael@0: if (sp.from <= pos && (sp.to == null || sp.to > pos)) { michael@0: if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; } michael@0: if (m.className) spanStyle += " " + m.className; michael@0: if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; michael@0: if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; michael@0: if (m.title && !title) title = m.title; michael@0: if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) michael@0: collapsed = sp; michael@0: } else if (sp.from > pos && nextChange > sp.from) { michael@0: nextChange = sp.from; michael@0: } michael@0: if (m.type == "bookmark" && sp.from == pos && m.widgetNode) foundBookmarks.push(m); michael@0: } michael@0: if (collapsed && (collapsed.from || 0) == pos) { michael@0: buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, michael@0: collapsed.marker, collapsed.from == null); michael@0: if (collapsed.to == null) return; michael@0: } michael@0: if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j) michael@0: buildCollapsedSpan(builder, 0, foundBookmarks[j]); michael@0: } michael@0: if (pos >= len) break; michael@0: michael@0: var upto = Math.min(len, nextChange); michael@0: while (true) { michael@0: if (text) { michael@0: var end = pos + text.length; michael@0: if (!collapsed) { michael@0: var tokenText = end > upto ? text.slice(0, upto - pos) : text; michael@0: builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, michael@0: spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title); michael@0: } michael@0: if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} michael@0: pos = end; michael@0: spanStartStyle = ""; michael@0: } michael@0: text = allText.slice(at, at = styles[i++]); michael@0: style = interpretTokenStyle(styles[i++], builder); michael@0: } michael@0: } michael@0: } michael@0: michael@0: // DOCUMENT DATA STRUCTURE michael@0: michael@0: // By default, updates that start and end at the beginning of a line michael@0: // are treated specially, in order to make the association of line michael@0: // widgets and marker elements with the text behave more intuitive. michael@0: function isWholeLineUpdate(doc, change) { michael@0: return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && michael@0: (!doc.cm || doc.cm.options.wholeLineUpdateBefore); michael@0: } michael@0: michael@0: // Perform a change on the document data structure. michael@0: function updateDoc(doc, change, markedSpans, estimateHeight) { michael@0: function spansFor(n) {return markedSpans ? markedSpans[n] : null;} michael@0: function update(line, text, spans) { michael@0: updateLine(line, text, spans, estimateHeight); michael@0: signalLater(line, "change", line, change); michael@0: } michael@0: michael@0: var from = change.from, to = change.to, text = change.text; michael@0: var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); michael@0: var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; michael@0: michael@0: // Adjust the line structure michael@0: if (isWholeLineUpdate(doc, change)) { michael@0: // This is a whole-line replace. Treated specially to make michael@0: // sure line objects move the way they are supposed to. michael@0: for (var i = 0, added = []; i < text.length - 1; ++i) michael@0: added.push(new Line(text[i], spansFor(i), estimateHeight)); michael@0: update(lastLine, lastLine.text, lastSpans); michael@0: if (nlines) doc.remove(from.line, nlines); michael@0: if (added.length) doc.insert(from.line, added); michael@0: } else if (firstLine == lastLine) { michael@0: if (text.length == 1) { michael@0: update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); michael@0: } else { michael@0: for (var added = [], i = 1; i < text.length - 1; ++i) michael@0: added.push(new Line(text[i], spansFor(i), estimateHeight)); michael@0: added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); michael@0: update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); michael@0: doc.insert(from.line + 1, added); michael@0: } michael@0: } else if (text.length == 1) { michael@0: update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); michael@0: doc.remove(from.line + 1, nlines); michael@0: } else { michael@0: update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); michael@0: update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); michael@0: for (var i = 1, added = []; i < text.length - 1; ++i) michael@0: added.push(new Line(text[i], spansFor(i), estimateHeight)); michael@0: if (nlines > 1) doc.remove(from.line + 1, nlines - 1); michael@0: doc.insert(from.line + 1, added); michael@0: } michael@0: michael@0: signalLater(doc, "change", doc, change); michael@0: } michael@0: michael@0: // The document is represented as a BTree consisting of leaves, with michael@0: // chunk of lines in them, and branches, with up to ten leaves or michael@0: // other branch nodes below them. The top node is always a branch michael@0: // node, and is the document object itself (meaning it has michael@0: // additional methods and properties). michael@0: // michael@0: // All nodes have parent links. The tree is used both to go from michael@0: // line numbers to line objects, and to go from objects to numbers. michael@0: // It also indexes by height, and is used to convert between height michael@0: // and line object, and to find the total height of the document. michael@0: // michael@0: // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html michael@0: michael@0: function LeafChunk(lines) { michael@0: this.lines = lines; michael@0: this.parent = null; michael@0: for (var i = 0, height = 0; i < lines.length; ++i) { michael@0: lines[i].parent = this; michael@0: height += lines[i].height; michael@0: } michael@0: this.height = height; michael@0: } michael@0: michael@0: LeafChunk.prototype = { michael@0: chunkSize: function() { return this.lines.length; }, michael@0: // Remove the n lines at offset 'at'. michael@0: removeInner: function(at, n) { michael@0: for (var i = at, e = at + n; i < e; ++i) { michael@0: var line = this.lines[i]; michael@0: this.height -= line.height; michael@0: cleanUpLine(line); michael@0: signalLater(line, "delete"); michael@0: } michael@0: this.lines.splice(at, n); michael@0: }, michael@0: // Helper used to collapse a small branch into a single leaf. michael@0: collapse: function(lines) { michael@0: lines.push.apply(lines, this.lines); michael@0: }, michael@0: // Insert the given array of lines at offset 'at', count them as michael@0: // having the given height. michael@0: insertInner: function(at, lines, height) { michael@0: this.height += height; michael@0: this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); michael@0: for (var i = 0; i < lines.length; ++i) lines[i].parent = this; michael@0: }, michael@0: // Used to iterate over a part of the tree. michael@0: iterN: function(at, n, op) { michael@0: for (var e = at + n; at < e; ++at) michael@0: if (op(this.lines[at])) return true; michael@0: } michael@0: }; michael@0: michael@0: function BranchChunk(children) { michael@0: this.children = children; michael@0: var size = 0, height = 0; michael@0: for (var i = 0; i < children.length; ++i) { michael@0: var ch = children[i]; michael@0: size += ch.chunkSize(); height += ch.height; michael@0: ch.parent = this; michael@0: } michael@0: this.size = size; michael@0: this.height = height; michael@0: this.parent = null; michael@0: } michael@0: michael@0: BranchChunk.prototype = { michael@0: chunkSize: function() { return this.size; }, michael@0: removeInner: function(at, n) { michael@0: this.size -= n; michael@0: for (var i = 0; i < this.children.length; ++i) { michael@0: var child = this.children[i], sz = child.chunkSize(); michael@0: if (at < sz) { michael@0: var rm = Math.min(n, sz - at), oldHeight = child.height; michael@0: child.removeInner(at, rm); michael@0: this.height -= oldHeight - child.height; michael@0: if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } michael@0: if ((n -= rm) == 0) break; michael@0: at = 0; michael@0: } else at -= sz; michael@0: } michael@0: // If the result is smaller than 25 lines, ensure that it is a michael@0: // single leaf node. michael@0: if (this.size - n < 25 && michael@0: (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { michael@0: var lines = []; michael@0: this.collapse(lines); michael@0: this.children = [new LeafChunk(lines)]; michael@0: this.children[0].parent = this; michael@0: } michael@0: }, michael@0: collapse: function(lines) { michael@0: for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines); michael@0: }, michael@0: insertInner: function(at, lines, height) { michael@0: this.size += lines.length; michael@0: this.height += height; michael@0: for (var i = 0; i < this.children.length; ++i) { michael@0: var child = this.children[i], sz = child.chunkSize(); michael@0: if (at <= sz) { michael@0: child.insertInner(at, lines, height); michael@0: if (child.lines && child.lines.length > 50) { michael@0: while (child.lines.length > 50) { michael@0: var spilled = child.lines.splice(child.lines.length - 25, 25); michael@0: var newleaf = new LeafChunk(spilled); michael@0: child.height -= newleaf.height; michael@0: this.children.splice(i + 1, 0, newleaf); michael@0: newleaf.parent = this; michael@0: } michael@0: this.maybeSpill(); michael@0: } michael@0: break; michael@0: } michael@0: at -= sz; michael@0: } michael@0: }, michael@0: // When a node has grown, check whether it should be split. michael@0: maybeSpill: function() { michael@0: if (this.children.length <= 10) return; michael@0: var me = this; michael@0: do { michael@0: var spilled = me.children.splice(me.children.length - 5, 5); michael@0: var sibling = new BranchChunk(spilled); michael@0: if (!me.parent) { // Become the parent node michael@0: var copy = new BranchChunk(me.children); michael@0: copy.parent = me; michael@0: me.children = [copy, sibling]; michael@0: me = copy; michael@0: } else { michael@0: me.size -= sibling.size; michael@0: me.height -= sibling.height; michael@0: var myIndex = indexOf(me.parent.children, me); michael@0: me.parent.children.splice(myIndex + 1, 0, sibling); michael@0: } michael@0: sibling.parent = me.parent; michael@0: } while (me.children.length > 10); michael@0: me.parent.maybeSpill(); michael@0: }, michael@0: iterN: function(at, n, op) { michael@0: for (var i = 0; i < this.children.length; ++i) { michael@0: var child = this.children[i], sz = child.chunkSize(); michael@0: if (at < sz) { michael@0: var used = Math.min(n, sz - at); michael@0: if (child.iterN(at, used, op)) return true; michael@0: if ((n -= used) == 0) break; michael@0: at = 0; michael@0: } else at -= sz; michael@0: } michael@0: } michael@0: }; michael@0: michael@0: var nextDocId = 0; michael@0: var Doc = CodeMirror.Doc = function(text, mode, firstLine) { michael@0: if (!(this instanceof Doc)) return new Doc(text, mode, firstLine); michael@0: if (firstLine == null) firstLine = 0; michael@0: michael@0: BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); michael@0: this.first = firstLine; michael@0: this.scrollTop = this.scrollLeft = 0; michael@0: this.cantEdit = false; michael@0: this.cleanGeneration = 1; michael@0: this.frontier = firstLine; michael@0: var start = Pos(firstLine, 0); michael@0: this.sel = simpleSelection(start); michael@0: this.history = new History(null); michael@0: this.id = ++nextDocId; michael@0: this.modeOption = mode; michael@0: michael@0: if (typeof text == "string") text = splitLines(text); michael@0: updateDoc(this, {from: start, to: start, text: text}); michael@0: setSelection(this, simpleSelection(start), sel_dontScroll); michael@0: }; michael@0: michael@0: Doc.prototype = createObj(BranchChunk.prototype, { michael@0: constructor: Doc, michael@0: // Iterate over the document. Supports two forms -- with only one michael@0: // argument, it calls that for each line in the document. With michael@0: // three, it iterates over the range given by the first two (with michael@0: // the second being non-inclusive). michael@0: iter: function(from, to, op) { michael@0: if (op) this.iterN(from - this.first, to - from, op); michael@0: else this.iterN(this.first, this.first + this.size, from); michael@0: }, michael@0: michael@0: // Non-public interface for adding and removing lines. michael@0: insert: function(at, lines) { michael@0: var height = 0; michael@0: for (var i = 0; i < lines.length; ++i) height += lines[i].height; michael@0: this.insertInner(at - this.first, lines, height); michael@0: }, michael@0: remove: function(at, n) { this.removeInner(at - this.first, n); }, michael@0: michael@0: // From here, the methods are part of the public interface. Most michael@0: // are also available from CodeMirror (editor) instances. michael@0: michael@0: getValue: function(lineSep) { michael@0: var lines = getLines(this, this.first, this.first + this.size); michael@0: if (lineSep === false) return lines; michael@0: return lines.join(lineSep || "\n"); michael@0: }, michael@0: setValue: docMethodOp(function(code) { michael@0: var top = Pos(this.first, 0), last = this.first + this.size - 1; michael@0: makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), michael@0: text: splitLines(code), origin: "setValue"}, true); michael@0: setSelection(this, simpleSelection(top)); michael@0: }), michael@0: replaceRange: function(code, from, to, origin) { michael@0: from = clipPos(this, from); michael@0: to = to ? clipPos(this, to) : from; michael@0: replaceRange(this, code, from, to, origin); michael@0: }, michael@0: getRange: function(from, to, lineSep) { michael@0: var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); michael@0: if (lineSep === false) return lines; michael@0: return lines.join(lineSep || "\n"); michael@0: }, michael@0: michael@0: getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, michael@0: michael@0: getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);}, michael@0: getLineNumber: function(line) {return lineNo(line);}, michael@0: michael@0: getLineHandleVisualStart: function(line) { michael@0: if (typeof line == "number") line = getLine(this, line); michael@0: return visualLine(line); michael@0: }, michael@0: michael@0: lineCount: function() {return this.size;}, michael@0: firstLine: function() {return this.first;}, michael@0: lastLine: function() {return this.first + this.size - 1;}, michael@0: michael@0: clipPos: function(pos) {return clipPos(this, pos);}, michael@0: michael@0: getCursor: function(start) { michael@0: var range = this.sel.primary(), pos; michael@0: if (start == null || start == "head") pos = range.head; michael@0: else if (start == "anchor") pos = range.anchor; michael@0: else if (start == "end" || start == "to" || start === false) pos = range.to(); michael@0: else pos = range.from(); michael@0: return pos; michael@0: }, michael@0: listSelections: function() { return this.sel.ranges; }, michael@0: somethingSelected: function() {return this.sel.somethingSelected();}, michael@0: michael@0: setCursor: docMethodOp(function(line, ch, options) { michael@0: setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); michael@0: }), michael@0: setSelection: docMethodOp(function(anchor, head, options) { michael@0: setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); michael@0: }), michael@0: extendSelection: docMethodOp(function(head, other, options) { michael@0: extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); michael@0: }), michael@0: extendSelections: docMethodOp(function(heads, options) { michael@0: extendSelections(this, clipPosArray(this, heads, options)); michael@0: }), michael@0: extendSelectionsBy: docMethodOp(function(f, options) { michael@0: extendSelections(this, map(this.sel.ranges, f), options); michael@0: }), michael@0: setSelections: docMethodOp(function(ranges, primary, options) { michael@0: if (!ranges.length) return; michael@0: for (var i = 0, out = []; i < ranges.length; i++) michael@0: out[i] = new Range(clipPos(this, ranges[i].anchor), michael@0: clipPos(this, ranges[i].head)); michael@0: if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex); michael@0: setSelection(this, normalizeSelection(out, primary), options); michael@0: }), michael@0: addSelection: docMethodOp(function(anchor, head, options) { michael@0: var ranges = this.sel.ranges.slice(0); michael@0: ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); michael@0: setSelection(this, normalizeSelection(ranges, ranges.length - 1), options); michael@0: }), michael@0: michael@0: getSelection: function(lineSep) { michael@0: var ranges = this.sel.ranges, lines; michael@0: for (var i = 0; i < ranges.length; i++) { michael@0: var sel = getBetween(this, ranges[i].from(), ranges[i].to()); michael@0: lines = lines ? lines.concat(sel) : sel; michael@0: } michael@0: if (lineSep === false) return lines; michael@0: else return lines.join(lineSep || "\n"); michael@0: }, michael@0: getSelections: function(lineSep) { michael@0: var parts = [], ranges = this.sel.ranges; michael@0: for (var i = 0; i < ranges.length; i++) { michael@0: var sel = getBetween(this, ranges[i].from(), ranges[i].to()); michael@0: if (lineSep !== false) sel = sel.join(lineSep || "\n"); michael@0: parts[i] = sel; michael@0: } michael@0: return parts; michael@0: }, michael@0: replaceSelection: docMethodOp(function(code, collapse, origin) { michael@0: var dup = []; michael@0: for (var i = 0; i < this.sel.ranges.length; i++) michael@0: dup[i] = code; michael@0: this.replaceSelections(dup, collapse, origin || "+input"); michael@0: }), michael@0: replaceSelections: function(code, collapse, origin) { michael@0: var changes = [], sel = this.sel; michael@0: for (var i = 0; i < sel.ranges.length; i++) { michael@0: var range = sel.ranges[i]; michael@0: changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin}; michael@0: } michael@0: var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); michael@0: for (var i = changes.length - 1; i >= 0; i--) michael@0: makeChange(this, changes[i]); michael@0: if (newSel) setSelectionReplaceHistory(this, newSel); michael@0: else if (this.cm) ensureCursorVisible(this.cm); michael@0: }, michael@0: undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), michael@0: redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), michael@0: undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), michael@0: redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), michael@0: michael@0: setExtending: function(val) {this.extend = val;}, michael@0: getExtending: function() {return this.extend;}, michael@0: michael@0: historySize: function() { michael@0: var hist = this.history, done = 0, undone = 0; michael@0: for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done; michael@0: for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone; michael@0: return {undo: done, redo: undone}; michael@0: }, michael@0: clearHistory: function() {this.history = new History(this.history.maxGeneration);}, michael@0: michael@0: markClean: function() { michael@0: this.cleanGeneration = this.changeGeneration(true); michael@0: }, michael@0: changeGeneration: function(forceSplit) { michael@0: if (forceSplit) michael@0: this.history.lastOp = this.history.lastOrigin = null; michael@0: return this.history.generation; michael@0: }, michael@0: isClean: function (gen) { michael@0: return this.history.generation == (gen || this.cleanGeneration); michael@0: }, michael@0: michael@0: getHistory: function() { michael@0: return {done: copyHistoryArray(this.history.done), michael@0: undone: copyHistoryArray(this.history.undone)}; michael@0: }, michael@0: setHistory: function(histData) { michael@0: var hist = this.history = new History(this.history.maxGeneration); michael@0: hist.done = copyHistoryArray(histData.done.slice(0), null, true); michael@0: hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); michael@0: }, michael@0: michael@0: markText: function(from, to, options) { michael@0: return markText(this, clipPos(this, from), clipPos(this, to), options, "range"); michael@0: }, michael@0: setBookmark: function(pos, options) { michael@0: var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), michael@0: insertLeft: options && options.insertLeft, michael@0: clearWhenEmpty: false, shared: options && options.shared}; michael@0: pos = clipPos(this, pos); michael@0: return markText(this, pos, pos, realOpts, "bookmark"); michael@0: }, michael@0: findMarksAt: function(pos) { michael@0: pos = clipPos(this, pos); michael@0: var markers = [], spans = getLine(this, pos.line).markedSpans; michael@0: if (spans) for (var i = 0; i < spans.length; ++i) { michael@0: var span = spans[i]; michael@0: if ((span.from == null || span.from <= pos.ch) && michael@0: (span.to == null || span.to >= pos.ch)) michael@0: markers.push(span.marker.parent || span.marker); michael@0: } michael@0: return markers; michael@0: }, michael@0: findMarks: function(from, to) { michael@0: from = clipPos(this, from); to = clipPos(this, to); michael@0: var found = [], lineNo = from.line; michael@0: this.iter(from.line, to.line + 1, function(line) { michael@0: var spans = line.markedSpans; michael@0: if (spans) for (var i = 0; i < spans.length; i++) { michael@0: var span = spans[i]; michael@0: if (!(lineNo == from.line && from.ch > span.to || michael@0: span.from == null && lineNo != from.line|| michael@0: lineNo == to.line && span.from > to.ch)) michael@0: found.push(span.marker.parent || span.marker); michael@0: } michael@0: ++lineNo; michael@0: }); michael@0: return found; michael@0: }, michael@0: getAllMarks: function() { michael@0: var markers = []; michael@0: this.iter(function(line) { michael@0: var sps = line.markedSpans; michael@0: if (sps) for (var i = 0; i < sps.length; ++i) michael@0: if (sps[i].from != null) markers.push(sps[i].marker); michael@0: }); michael@0: return markers; michael@0: }, michael@0: michael@0: posFromIndex: function(off) { michael@0: var ch, lineNo = this.first; michael@0: this.iter(function(line) { michael@0: var sz = line.text.length + 1; michael@0: if (sz > off) { ch = off; return true; } michael@0: off -= sz; michael@0: ++lineNo; michael@0: }); michael@0: return clipPos(this, Pos(lineNo, ch)); michael@0: }, michael@0: indexFromPos: function (coords) { michael@0: coords = clipPos(this, coords); michael@0: var index = coords.ch; michael@0: if (coords.line < this.first || coords.ch < 0) return 0; michael@0: this.iter(this.first, coords.line, function (line) { michael@0: index += line.text.length + 1; michael@0: }); michael@0: return index; michael@0: }, michael@0: michael@0: copy: function(copyHistory) { michael@0: var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first); michael@0: doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; michael@0: doc.sel = this.sel; michael@0: doc.extend = false; michael@0: if (copyHistory) { michael@0: doc.history.undoDepth = this.history.undoDepth; michael@0: doc.setHistory(this.getHistory()); michael@0: } michael@0: return doc; michael@0: }, michael@0: michael@0: linkedDoc: function(options) { michael@0: if (!options) options = {}; michael@0: var from = this.first, to = this.first + this.size; michael@0: if (options.from != null && options.from > from) from = options.from; michael@0: if (options.to != null && options.to < to) to = options.to; michael@0: var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from); michael@0: if (options.sharedHist) copy.history = this.history; michael@0: (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); michael@0: copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; michael@0: return copy; michael@0: }, michael@0: unlinkDoc: function(other) { michael@0: if (other instanceof CodeMirror) other = other.doc; michael@0: if (this.linked) for (var i = 0; i < this.linked.length; ++i) { michael@0: var link = this.linked[i]; michael@0: if (link.doc != other) continue; michael@0: this.linked.splice(i, 1); michael@0: other.unlinkDoc(this); michael@0: break; michael@0: } michael@0: // If the histories were shared, split them again michael@0: if (other.history == this.history) { michael@0: var splitIds = [other.id]; michael@0: linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); michael@0: other.history = new History(null); michael@0: other.history.done = copyHistoryArray(this.history.done, splitIds); michael@0: other.history.undone = copyHistoryArray(this.history.undone, splitIds); michael@0: } michael@0: }, michael@0: iterLinkedDocs: function(f) {linkedDocs(this, f);}, michael@0: michael@0: getMode: function() {return this.mode;}, michael@0: getEditor: function() {return this.cm;} michael@0: }); michael@0: michael@0: // Public alias. michael@0: Doc.prototype.eachLine = Doc.prototype.iter; michael@0: michael@0: // Set up methods on CodeMirror's prototype to redirect to the editor's document. michael@0: var dontDelegate = "iter insert remove copy getEditor".split(" "); michael@0: for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) michael@0: CodeMirror.prototype[prop] = (function(method) { michael@0: return function() {return method.apply(this.doc, arguments);}; michael@0: })(Doc.prototype[prop]); michael@0: michael@0: eventMixin(Doc); michael@0: michael@0: // Call f for all linked documents. michael@0: function linkedDocs(doc, f, sharedHistOnly) { michael@0: function propagate(doc, skip, sharedHist) { michael@0: if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { michael@0: var rel = doc.linked[i]; michael@0: if (rel.doc == skip) continue; michael@0: var shared = sharedHist && rel.sharedHist; michael@0: if (sharedHistOnly && !shared) continue; michael@0: f(rel.doc, shared); michael@0: propagate(rel.doc, doc, shared); michael@0: } michael@0: } michael@0: propagate(doc, null, true); michael@0: } michael@0: michael@0: // Attach a document to an editor. michael@0: function attachDoc(cm, doc) { michael@0: if (doc.cm) throw new Error("This document is already in use."); michael@0: cm.doc = doc; michael@0: doc.cm = cm; michael@0: estimateLineHeights(cm); michael@0: loadMode(cm); michael@0: if (!cm.options.lineWrapping) findMaxLine(cm); michael@0: cm.options.mode = doc.modeOption; michael@0: regChange(cm); michael@0: } michael@0: michael@0: // LINE UTILITIES michael@0: michael@0: // Find the line object corresponding to the given line number. michael@0: function getLine(doc, n) { michael@0: n -= doc.first; michael@0: if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document."); michael@0: for (var chunk = doc; !chunk.lines;) { michael@0: for (var i = 0;; ++i) { michael@0: var child = chunk.children[i], sz = child.chunkSize(); michael@0: if (n < sz) { chunk = child; break; } michael@0: n -= sz; michael@0: } michael@0: } michael@0: return chunk.lines[n]; michael@0: } michael@0: michael@0: // Get the part of a document between two positions, as an array of michael@0: // strings. michael@0: function getBetween(doc, start, end) { michael@0: var out = [], n = start.line; michael@0: doc.iter(start.line, end.line + 1, function(line) { michael@0: var text = line.text; michael@0: if (n == end.line) text = text.slice(0, end.ch); michael@0: if (n == start.line) text = text.slice(start.ch); michael@0: out.push(text); michael@0: ++n; michael@0: }); michael@0: return out; michael@0: } michael@0: // Get the lines between from and to, as array of strings. michael@0: function getLines(doc, from, to) { michael@0: var out = []; michael@0: doc.iter(from, to, function(line) { out.push(line.text); }); michael@0: return out; michael@0: } michael@0: michael@0: // Update the height of a line, propagating the height change michael@0: // upwards to parent nodes. michael@0: function updateLineHeight(line, height) { michael@0: var diff = height - line.height; michael@0: if (diff) for (var n = line; n; n = n.parent) n.height += diff; michael@0: } michael@0: michael@0: // Given a line object, find its line number by walking up through michael@0: // its parent links. michael@0: function lineNo(line) { michael@0: if (line.parent == null) return null; michael@0: var cur = line.parent, no = indexOf(cur.lines, line); michael@0: for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { michael@0: for (var i = 0;; ++i) { michael@0: if (chunk.children[i] == cur) break; michael@0: no += chunk.children[i].chunkSize(); michael@0: } michael@0: } michael@0: return no + cur.first; michael@0: } michael@0: michael@0: // Find the line at the given vertical position, using the height michael@0: // information in the document tree. michael@0: function lineAtHeight(chunk, h) { michael@0: var n = chunk.first; michael@0: outer: do { michael@0: for (var i = 0; i < chunk.children.length; ++i) { michael@0: var child = chunk.children[i], ch = child.height; michael@0: if (h < ch) { chunk = child; continue outer; } michael@0: h -= ch; michael@0: n += child.chunkSize(); michael@0: } michael@0: return n; michael@0: } while (!chunk.lines); michael@0: for (var i = 0; i < chunk.lines.length; ++i) { michael@0: var line = chunk.lines[i], lh = line.height; michael@0: if (h < lh) break; michael@0: h -= lh; michael@0: } michael@0: return n + i; michael@0: } michael@0: michael@0: michael@0: // Find the height above the given line. michael@0: function heightAtLine(lineObj) { michael@0: lineObj = visualLine(lineObj); michael@0: michael@0: var h = 0, chunk = lineObj.parent; michael@0: for (var i = 0; i < chunk.lines.length; ++i) { michael@0: var line = chunk.lines[i]; michael@0: if (line == lineObj) break; michael@0: else h += line.height; michael@0: } michael@0: for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { michael@0: for (var i = 0; i < p.children.length; ++i) { michael@0: var cur = p.children[i]; michael@0: if (cur == chunk) break; michael@0: else h += cur.height; michael@0: } michael@0: } michael@0: return h; michael@0: } michael@0: michael@0: // Get the bidi ordering for the given line (and cache it). Returns michael@0: // false for lines that are fully left-to-right, and an array of michael@0: // BidiSpan objects otherwise. michael@0: function getOrder(line) { michael@0: var order = line.order; michael@0: if (order == null) order = line.order = bidiOrdering(line.text); michael@0: return order; michael@0: } michael@0: michael@0: // HISTORY michael@0: michael@0: function History(startGen) { michael@0: // Arrays of change events and selections. Doing something adds an michael@0: // event to done and clears undo. Undoing moves events from done michael@0: // to undone, redoing moves them in the other direction. michael@0: this.done = []; this.undone = []; michael@0: this.undoDepth = Infinity; michael@0: // Used to track when changes can be merged into a single undo michael@0: // event michael@0: this.lastModTime = this.lastSelTime = 0; michael@0: this.lastOp = null; michael@0: this.lastOrigin = this.lastSelOrigin = null; michael@0: // Used by the isClean() method michael@0: this.generation = this.maxGeneration = startGen || 1; michael@0: } michael@0: michael@0: // Create a history change event from an updateDoc-style change michael@0: // object. michael@0: function historyChangeFromChange(doc, change) { michael@0: var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; michael@0: attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); michael@0: linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); michael@0: return histChange; michael@0: } michael@0: michael@0: // Pop all selection events off the end of a history array. Stop at michael@0: // a change event. michael@0: function clearSelectionEvents(array) { michael@0: while (array.length) { michael@0: var last = lst(array); michael@0: if (last.ranges) array.pop(); michael@0: else break; michael@0: } michael@0: } michael@0: michael@0: // Find the top change event in the history. Pop off selection michael@0: // events that are in the way. michael@0: function lastChangeEvent(hist, force) { michael@0: if (force) { michael@0: clearSelectionEvents(hist.done); michael@0: return lst(hist.done); michael@0: } else if (hist.done.length && !lst(hist.done).ranges) { michael@0: return lst(hist.done); michael@0: } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { michael@0: hist.done.pop(); michael@0: return lst(hist.done); michael@0: } michael@0: } michael@0: michael@0: // Register a change in the history. Merges changes that are within michael@0: // a single operation, ore are close together with an origin that michael@0: // allows merging (starting with "+") into a single event. michael@0: function addChangeToHistory(doc, change, selAfter, opId) { michael@0: var hist = doc.history; michael@0: hist.undone.length = 0; michael@0: var time = +new Date, cur; michael@0: michael@0: if ((hist.lastOp == opId || michael@0: hist.lastOrigin == change.origin && change.origin && michael@0: ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || michael@0: change.origin.charAt(0) == "*")) && michael@0: (cur = lastChangeEvent(hist, hist.lastOp == opId))) { michael@0: // Merge this change into the last event michael@0: var last = lst(cur.changes); michael@0: if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { michael@0: // Optimized case for simple insertion -- don't want to add michael@0: // new changesets for every character typed michael@0: last.to = changeEnd(change); michael@0: } else { michael@0: // Add new sub-event michael@0: cur.changes.push(historyChangeFromChange(doc, change)); michael@0: } michael@0: } else { michael@0: // Can not be merged, start a new event. michael@0: var before = lst(hist.done); michael@0: if (!before || !before.ranges) michael@0: pushSelectionToHistory(doc.sel, hist.done); michael@0: cur = {changes: [historyChangeFromChange(doc, change)], michael@0: generation: hist.generation}; michael@0: hist.done.push(cur); michael@0: while (hist.done.length > hist.undoDepth) { michael@0: hist.done.shift(); michael@0: if (!hist.done[0].ranges) hist.done.shift(); michael@0: } michael@0: } michael@0: hist.done.push(selAfter); michael@0: hist.generation = ++hist.maxGeneration; michael@0: hist.lastModTime = hist.lastSelTime = time; michael@0: hist.lastOp = opId; michael@0: hist.lastOrigin = hist.lastSelOrigin = change.origin; michael@0: michael@0: if (!last) signal(doc, "historyAdded"); michael@0: } michael@0: michael@0: function selectionEventCanBeMerged(doc, origin, prev, sel) { michael@0: var ch = origin.charAt(0); michael@0: return ch == "*" || michael@0: ch == "+" && michael@0: prev.ranges.length == sel.ranges.length && michael@0: prev.somethingSelected() == sel.somethingSelected() && michael@0: new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); michael@0: } michael@0: michael@0: // Called whenever the selection changes, sets the new selection as michael@0: // the pending selection in the history, and pushes the old pending michael@0: // selection into the 'done' array when it was significantly michael@0: // different (in number of selected ranges, emptiness, or time). michael@0: function addSelectionToHistory(doc, sel, opId, options) { michael@0: var hist = doc.history, origin = options && options.origin; michael@0: michael@0: // A new event is started when the previous origin does not match michael@0: // the current, or the origins don't allow matching. Origins michael@0: // starting with * are always merged, those starting with + are michael@0: // merged when similar and close together in time. michael@0: if (opId == hist.lastOp || michael@0: (origin && hist.lastSelOrigin == origin && michael@0: (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || michael@0: selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) michael@0: hist.done[hist.done.length - 1] = sel; michael@0: else michael@0: pushSelectionToHistory(sel, hist.done); michael@0: michael@0: hist.lastSelTime = +new Date; michael@0: hist.lastSelOrigin = origin; michael@0: hist.lastOp = opId; michael@0: if (options && options.clearRedo !== false) michael@0: clearSelectionEvents(hist.undone); michael@0: } michael@0: michael@0: function pushSelectionToHistory(sel, dest) { michael@0: var top = lst(dest); michael@0: if (!(top && top.ranges && top.equals(sel))) michael@0: dest.push(sel); michael@0: } michael@0: michael@0: // Used to store marked span information in the history. michael@0: function attachLocalSpans(doc, change, from, to) { michael@0: var existing = change["spans_" + doc.id], n = 0; michael@0: doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) { michael@0: if (line.markedSpans) michael@0: (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; michael@0: ++n; michael@0: }); michael@0: } michael@0: michael@0: // When un/re-doing restores text containing marked spans, those michael@0: // that have been explicitly cleared should not be restored. michael@0: function removeClearedSpans(spans) { michael@0: if (!spans) return null; michael@0: for (var i = 0, out; i < spans.length; ++i) { michael@0: if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } michael@0: else if (out) out.push(spans[i]); michael@0: } michael@0: return !out ? spans : out.length ? out : null; michael@0: } michael@0: michael@0: // Retrieve and filter the old marked spans stored in a change event. michael@0: function getOldSpans(doc, change) { michael@0: var found = change["spans_" + doc.id]; michael@0: if (!found) return null; michael@0: for (var i = 0, nw = []; i < change.text.length; ++i) michael@0: nw.push(removeClearedSpans(found[i])); michael@0: return nw; michael@0: } michael@0: michael@0: // Used both to provide a JSON-safe object in .getHistory, and, when michael@0: // detaching a document, to split the history in two michael@0: function copyHistoryArray(events, newGroup, instantiateSel) { michael@0: for (var i = 0, copy = []; i < events.length; ++i) { michael@0: var event = events[i]; michael@0: if (event.ranges) { michael@0: copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); michael@0: continue; michael@0: } michael@0: var changes = event.changes, newChanges = []; michael@0: copy.push({changes: newChanges}); michael@0: for (var j = 0; j < changes.length; ++j) { michael@0: var change = changes[j], m; michael@0: newChanges.push({from: change.from, to: change.to, text: change.text}); michael@0: if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { michael@0: if (indexOf(newGroup, Number(m[1])) > -1) { michael@0: lst(newChanges)[prop] = change[prop]; michael@0: delete change[prop]; michael@0: } michael@0: } michael@0: } michael@0: } michael@0: return copy; michael@0: } michael@0: michael@0: // Rebasing/resetting history to deal with externally-sourced changes michael@0: michael@0: function rebaseHistSelSingle(pos, from, to, diff) { michael@0: if (to < pos.line) { michael@0: pos.line += diff; michael@0: } else if (from < pos.line) { michael@0: pos.line = from; michael@0: pos.ch = 0; michael@0: } michael@0: } michael@0: michael@0: // Tries to rebase an array of history events given a change in the michael@0: // document. If the change touches the same lines as the event, the michael@0: // event, and everything 'behind' it, is discarded. If the change is michael@0: // before the event, the event's positions are updated. Uses a michael@0: // copy-on-write scheme for the positions, to avoid having to michael@0: // reallocate them all on every rebase, but also avoid problems with michael@0: // shared position objects being unsafely updated. michael@0: function rebaseHistArray(array, from, to, diff) { michael@0: for (var i = 0; i < array.length; ++i) { michael@0: var sub = array[i], ok = true; michael@0: if (sub.ranges) { michael@0: if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } michael@0: for (var j = 0; j < sub.ranges.length; j++) { michael@0: rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); michael@0: rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); michael@0: } michael@0: continue; michael@0: } michael@0: for (var j = 0; j < sub.changes.length; ++j) { michael@0: var cur = sub.changes[j]; michael@0: if (to < cur.from.line) { michael@0: cur.from = Pos(cur.from.line + diff, cur.from.ch); michael@0: cur.to = Pos(cur.to.line + diff, cur.to.ch); michael@0: } else if (from <= cur.to.line) { michael@0: ok = false; michael@0: break; michael@0: } michael@0: } michael@0: if (!ok) { michael@0: array.splice(0, i + 1); michael@0: i = 0; michael@0: } michael@0: } michael@0: } michael@0: michael@0: function rebaseHist(hist, change) { michael@0: var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; michael@0: rebaseHistArray(hist.done, from, to, diff); michael@0: rebaseHistArray(hist.undone, from, to, diff); michael@0: } michael@0: michael@0: // EVENT UTILITIES michael@0: michael@0: // Due to the fact that we still support jurassic IE versions, some michael@0: // compatibility wrappers are needed. michael@0: michael@0: var e_preventDefault = CodeMirror.e_preventDefault = function(e) { michael@0: if (e.preventDefault) e.preventDefault(); michael@0: else e.returnValue = false; michael@0: }; michael@0: var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) { michael@0: if (e.stopPropagation) e.stopPropagation(); michael@0: else e.cancelBubble = true; michael@0: }; michael@0: function e_defaultPrevented(e) { michael@0: return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; michael@0: } michael@0: var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);}; michael@0: michael@0: function e_target(e) {return e.target || e.srcElement;} michael@0: function e_button(e) { michael@0: var b = e.which; michael@0: if (b == null) { michael@0: if (e.button & 1) b = 1; michael@0: else if (e.button & 2) b = 3; michael@0: else if (e.button & 4) b = 2; michael@0: } michael@0: if (mac && e.ctrlKey && b == 1) b = 3; michael@0: return b; michael@0: } michael@0: michael@0: // EVENT HANDLING michael@0: michael@0: // Lightweight event framework. on/off also work on DOM nodes, michael@0: // registering native DOM handlers. michael@0: michael@0: var on = CodeMirror.on = function(emitter, type, f) { michael@0: if (emitter.addEventListener) michael@0: emitter.addEventListener(type, f, false); michael@0: else if (emitter.attachEvent) michael@0: emitter.attachEvent("on" + type, f); michael@0: else { michael@0: var map = emitter._handlers || (emitter._handlers = {}); michael@0: var arr = map[type] || (map[type] = []); michael@0: arr.push(f); michael@0: } michael@0: }; michael@0: michael@0: var off = CodeMirror.off = function(emitter, type, f) { michael@0: if (emitter.removeEventListener) michael@0: emitter.removeEventListener(type, f, false); michael@0: else if (emitter.detachEvent) michael@0: emitter.detachEvent("on" + type, f); michael@0: else { michael@0: var arr = emitter._handlers && emitter._handlers[type]; michael@0: if (!arr) return; michael@0: for (var i = 0; i < arr.length; ++i) michael@0: if (arr[i] == f) { arr.splice(i, 1); break; } michael@0: } michael@0: }; michael@0: michael@0: var signal = CodeMirror.signal = function(emitter, type /*, values...*/) { michael@0: var arr = emitter._handlers && emitter._handlers[type]; michael@0: if (!arr) return; michael@0: var args = Array.prototype.slice.call(arguments, 2); michael@0: for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); michael@0: }; michael@0: michael@0: // Often, we want to signal events at a point where we are in the michael@0: // middle of some work, but don't want the handler to start calling michael@0: // other methods on the editor, which might be in an inconsistent michael@0: // state or simply not expect any other events to happen. michael@0: // signalLater looks whether there are any handlers, and schedules michael@0: // them to be executed when the last operation ends, or, if no michael@0: // operation is active, when a timeout fires. michael@0: var delayedCallbacks, delayedCallbackDepth = 0; michael@0: function signalLater(emitter, type /*, values...*/) { michael@0: var arr = emitter._handlers && emitter._handlers[type]; michael@0: if (!arr) return; michael@0: var args = Array.prototype.slice.call(arguments, 2); michael@0: if (!delayedCallbacks) { michael@0: ++delayedCallbackDepth; michael@0: delayedCallbacks = []; michael@0: setTimeout(fireDelayed, 0); michael@0: } michael@0: function bnd(f) {return function(){f.apply(null, args);};}; michael@0: for (var i = 0; i < arr.length; ++i) michael@0: delayedCallbacks.push(bnd(arr[i])); michael@0: } michael@0: michael@0: function fireDelayed() { michael@0: --delayedCallbackDepth; michael@0: var delayed = delayedCallbacks; michael@0: delayedCallbacks = null; michael@0: for (var i = 0; i < delayed.length; ++i) delayed[i](); michael@0: } michael@0: michael@0: // The DOM events that CodeMirror handles can be overridden by michael@0: // registering a (non-DOM) handler on the editor for the event name, michael@0: // and preventDefault-ing the event in that handler. michael@0: function signalDOMEvent(cm, e, override) { michael@0: signal(cm, override || e.type, cm, e); michael@0: return e_defaultPrevented(e) || e.codemirrorIgnore; michael@0: } michael@0: michael@0: function hasHandler(emitter, type) { michael@0: var arr = emitter._handlers && emitter._handlers[type]; michael@0: return arr && arr.length > 0; michael@0: } michael@0: michael@0: // Add on and off methods to a constructor's prototype, to make michael@0: // registering events on such objects more convenient. michael@0: function eventMixin(ctor) { michael@0: ctor.prototype.on = function(type, f) {on(this, type, f);}; michael@0: ctor.prototype.off = function(type, f) {off(this, type, f);}; michael@0: } michael@0: michael@0: // MISC UTILITIES michael@0: michael@0: // Number of pixels added to scroller and sizer to hide scrollbar michael@0: var scrollerCutOff = 30; michael@0: michael@0: // Returned or thrown by various protocols to signal 'I'm not michael@0: // handling this'. michael@0: var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; michael@0: michael@0: // Reused option objects for setSelection & friends michael@0: var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; michael@0: michael@0: function Delayed() {this.id = null;} michael@0: Delayed.prototype.set = function(ms, f) { michael@0: clearTimeout(this.id); michael@0: this.id = setTimeout(f, ms); michael@0: }; michael@0: michael@0: // Counts the column offset in a string, taking tabs into account. michael@0: // Used mostly to find indentation. michael@0: var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) { michael@0: if (end == null) { michael@0: end = string.search(/[^\s\u00a0]/); michael@0: if (end == -1) end = string.length; michael@0: } michael@0: for (var i = startIndex || 0, n = startValue || 0;;) { michael@0: var nextTab = string.indexOf("\t", i); michael@0: if (nextTab < 0 || nextTab >= end) michael@0: return n + (end - i); michael@0: n += nextTab - i; michael@0: n += tabSize - (n % tabSize); michael@0: i = nextTab + 1; michael@0: } michael@0: }; michael@0: michael@0: // The inverse of countColumn -- find the offset that corresponds to michael@0: // a particular column. michael@0: function findColumn(string, goal, tabSize) { michael@0: for (var pos = 0, col = 0;;) { michael@0: var nextTab = string.indexOf("\t", pos); michael@0: if (nextTab == -1) nextTab = string.length; michael@0: var skipped = nextTab - pos; michael@0: if (nextTab == string.length || col + skipped >= goal) michael@0: return pos + Math.min(skipped, goal - col); michael@0: col += nextTab - pos; michael@0: col += tabSize - (col % tabSize); michael@0: pos = nextTab + 1; michael@0: if (col >= goal) return pos; michael@0: } michael@0: } michael@0: michael@0: var spaceStrs = [""]; michael@0: function spaceStr(n) { michael@0: while (spaceStrs.length <= n) michael@0: spaceStrs.push(lst(spaceStrs) + " "); michael@0: return spaceStrs[n]; michael@0: } michael@0: michael@0: function lst(arr) { return arr[arr.length-1]; } michael@0: michael@0: var selectInput = function(node) { node.select(); }; michael@0: if (ios) // Mobile Safari apparently has a bug where select() is broken. michael@0: selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; michael@0: else if (ie) // Suppress mysterious IE10 errors michael@0: selectInput = function(node) { try { node.select(); } catch(_e) {} }; michael@0: michael@0: function indexOf(array, elt) { michael@0: for (var i = 0; i < array.length; ++i) michael@0: if (array[i] == elt) return i; michael@0: return -1; michael@0: } michael@0: if ([].indexOf) indexOf = function(array, elt) { return array.indexOf(elt); }; michael@0: function map(array, f) { michael@0: var out = []; michael@0: for (var i = 0; i < array.length; i++) out[i] = f(array[i], i); michael@0: return out; michael@0: } michael@0: if ([].map) map = function(array, f) { return array.map(f); }; michael@0: michael@0: function createObj(base, props) { michael@0: var inst; michael@0: if (Object.create) { michael@0: inst = Object.create(base); michael@0: } else { michael@0: var ctor = function() {}; michael@0: ctor.prototype = base; michael@0: inst = new ctor(); michael@0: } michael@0: if (props) copyObj(props, inst); michael@0: return inst; michael@0: }; michael@0: michael@0: function copyObj(obj, target) { michael@0: if (!target) target = {}; michael@0: for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop]; michael@0: return target; michael@0: } michael@0: michael@0: function bind(f) { michael@0: var args = Array.prototype.slice.call(arguments, 1); michael@0: return function(){return f.apply(null, args);}; michael@0: } michael@0: michael@0: var nonASCIISingleCaseWordChar = /[\u00df\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; michael@0: var isWordChar = CodeMirror.isWordChar = function(ch) { michael@0: return /\w/.test(ch) || ch > "\x80" && michael@0: (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); michael@0: }; michael@0: michael@0: function isEmpty(obj) { michael@0: for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; michael@0: return true; michael@0: } michael@0: michael@0: // Extending unicode characters. A series of a non-extending char + michael@0: // any number of extending chars is treated as a single unit as far michael@0: // as editing and measuring is concerned. This is not fully correct, michael@0: // since some scripts/fonts/browsers also treat other configurations michael@0: // of code points as a group. michael@0: var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; michael@0: function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); } michael@0: michael@0: // DOM UTILITIES michael@0: michael@0: function elt(tag, content, className, style) { michael@0: var e = document.createElement(tag); michael@0: if (className) e.className = className; michael@0: if (style) e.style.cssText = style; michael@0: if (typeof content == "string") e.appendChild(document.createTextNode(content)); michael@0: else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); michael@0: return e; michael@0: } michael@0: michael@0: var range; michael@0: if (document.createRange) range = function(node, start, end) { michael@0: var r = document.createRange(); michael@0: r.setEnd(node, end); michael@0: r.setStart(node, start); michael@0: return r; michael@0: }; michael@0: else range = function(node, start, end) { michael@0: var r = document.body.createTextRange(); michael@0: r.moveToElementText(node.parentNode); michael@0: r.collapse(true); michael@0: r.moveEnd("character", end); michael@0: r.moveStart("character", start); michael@0: return r; michael@0: }; michael@0: michael@0: function removeChildren(e) { michael@0: for (var count = e.childNodes.length; count > 0; --count) michael@0: e.removeChild(e.firstChild); michael@0: return e; michael@0: } michael@0: michael@0: function removeChildrenAndAdd(parent, e) { michael@0: return removeChildren(parent).appendChild(e); michael@0: } michael@0: michael@0: function contains(parent, child) { michael@0: if (parent.contains) michael@0: return parent.contains(child); michael@0: while (child = child.parentNode) michael@0: if (child == parent) return true; michael@0: } michael@0: michael@0: function activeElt() { return document.activeElement; } michael@0: // Older versions of IE throws unspecified error when touching michael@0: // document.activeElement in some cases (during loading, in iframe) michael@0: if (ie_upto10) activeElt = function() { michael@0: try { return document.activeElement; } michael@0: catch(e) { return document.body; } michael@0: }; michael@0: michael@0: // FEATURE DETECTION michael@0: michael@0: // Detect drag-and-drop michael@0: var dragAndDrop = function() { michael@0: // There is *some* kind of drag-and-drop support in IE6-8, but I michael@0: // couldn't get it to work yet. michael@0: if (ie_upto8) return false; michael@0: var div = elt('div'); michael@0: return "draggable" in div || "dragDrop" in div; michael@0: }(); michael@0: michael@0: var knownScrollbarWidth; michael@0: function scrollbarWidth(measure) { michael@0: if (knownScrollbarWidth != null) return knownScrollbarWidth; michael@0: var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll"); michael@0: removeChildrenAndAdd(measure, test); michael@0: if (test.offsetWidth) michael@0: knownScrollbarWidth = test.offsetHeight - test.clientHeight; michael@0: return knownScrollbarWidth || 0; michael@0: } michael@0: michael@0: var zwspSupported; michael@0: function zeroWidthElement(measure) { michael@0: if (zwspSupported == null) { michael@0: var test = elt("span", "\u200b"); michael@0: removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); michael@0: if (measure.firstChild.offsetHeight != 0) michael@0: zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_upto7; michael@0: } michael@0: if (zwspSupported) return elt("span", "\u200b"); michael@0: else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); michael@0: } michael@0: michael@0: // Feature-detect IE's crummy client rect reporting for bidi text michael@0: var badBidiRects; michael@0: function hasBadBidiRects(measure) { michael@0: if (badBidiRects != null) return badBidiRects; michael@0: var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); michael@0: var r0 = range(txt, 0, 1).getBoundingClientRect(); michael@0: if (r0.left == r0.right) return false; michael@0: var r1 = range(txt, 1, 2).getBoundingClientRect(); michael@0: return badBidiRects = (r1.right - r0.right < 3); michael@0: } michael@0: michael@0: // See if "".split is the broken IE version, if so, provide an michael@0: // alternative way to split lines. michael@0: var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { michael@0: var pos = 0, result = [], l = string.length; michael@0: while (pos <= l) { michael@0: var nl = string.indexOf("\n", pos); michael@0: if (nl == -1) nl = string.length; michael@0: var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); michael@0: var rt = line.indexOf("\r"); michael@0: if (rt != -1) { michael@0: result.push(line.slice(0, rt)); michael@0: pos += rt + 1; michael@0: } else { michael@0: result.push(line); michael@0: pos = nl + 1; michael@0: } michael@0: } michael@0: return result; michael@0: } : function(string){return string.split(/\r\n?|\n/);}; michael@0: michael@0: var hasSelection = window.getSelection ? function(te) { michael@0: try { return te.selectionStart != te.selectionEnd; } michael@0: catch(e) { return false; } michael@0: } : function(te) { michael@0: try {var range = te.ownerDocument.selection.createRange();} michael@0: catch(e) {} michael@0: if (!range || range.parentElement() != te) return false; michael@0: return range.compareEndPoints("StartToEnd", range) != 0; michael@0: }; michael@0: michael@0: var hasCopyEvent = (function() { michael@0: var e = elt("div"); michael@0: if ("oncopy" in e) return true; michael@0: e.setAttribute("oncopy", "return;"); michael@0: return typeof e.oncopy == "function"; michael@0: })(); michael@0: michael@0: // KEY NAMES michael@0: michael@0: var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", michael@0: 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", michael@0: 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", michael@0: 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete", michael@0: 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", michael@0: 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", michael@0: 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"}; michael@0: CodeMirror.keyNames = keyNames; michael@0: (function() { michael@0: // Number keys michael@0: for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i); michael@0: // Alphabetic keys michael@0: for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); michael@0: // Function keys michael@0: for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; michael@0: })(); michael@0: michael@0: // BIDI HELPERS michael@0: michael@0: function iterateBidiSections(order, from, to, f) { michael@0: if (!order) return f(from, to, "ltr"); michael@0: var found = false; michael@0: for (var i = 0; i < order.length; ++i) { michael@0: var part = order[i]; michael@0: if (part.from < to && part.to > from || from == to && part.to == from) { michael@0: f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); michael@0: found = true; michael@0: } michael@0: } michael@0: if (!found) f(from, to, "ltr"); michael@0: } michael@0: michael@0: function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } michael@0: function bidiRight(part) { return part.level % 2 ? part.from : part.to; } michael@0: michael@0: function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } michael@0: function lineRight(line) { michael@0: var order = getOrder(line); michael@0: if (!order) return line.text.length; michael@0: return bidiRight(lst(order)); michael@0: } michael@0: michael@0: function lineStart(cm, lineN) { michael@0: var line = getLine(cm.doc, lineN); michael@0: var visual = visualLine(line); michael@0: if (visual != line) lineN = lineNo(visual); michael@0: var order = getOrder(visual); michael@0: var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); michael@0: return Pos(lineN, ch); michael@0: } michael@0: function lineEnd(cm, lineN) { michael@0: var merged, line = getLine(cm.doc, lineN); michael@0: while (merged = collapsedSpanAtEnd(line)) { michael@0: line = merged.find(1, true).line; michael@0: lineN = null; michael@0: } michael@0: var order = getOrder(line); michael@0: var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); michael@0: return Pos(lineN == null ? lineNo(line) : lineN, ch); michael@0: } michael@0: michael@0: function compareBidiLevel(order, a, b) { michael@0: var linedir = order[0].level; michael@0: if (a == linedir) return true; michael@0: if (b == linedir) return false; michael@0: return a < b; michael@0: } michael@0: var bidiOther; michael@0: function getBidiPartAt(order, pos) { michael@0: bidiOther = null; michael@0: for (var i = 0, found; i < order.length; ++i) { michael@0: var cur = order[i]; michael@0: if (cur.from < pos && cur.to > pos) return i; michael@0: if ((cur.from == pos || cur.to == pos)) { michael@0: if (found == null) { michael@0: found = i; michael@0: } else if (compareBidiLevel(order, cur.level, order[found].level)) { michael@0: if (cur.from != cur.to) bidiOther = found; michael@0: return i; michael@0: } else { michael@0: if (cur.from != cur.to) bidiOther = i; michael@0: return found; michael@0: } michael@0: } michael@0: } michael@0: return found; michael@0: } michael@0: michael@0: function moveInLine(line, pos, dir, byUnit) { michael@0: if (!byUnit) return pos + dir; michael@0: do pos += dir; michael@0: while (pos > 0 && isExtendingChar(line.text.charAt(pos))); michael@0: return pos; michael@0: } michael@0: michael@0: // This is needed in order to move 'visually' through bi-directional michael@0: // text -- i.e., pressing left should make the cursor go left, even michael@0: // when in RTL text. The tricky part is the 'jumps', where RTL and michael@0: // LTR text touch each other. This often requires the cursor offset michael@0: // to move more than one unit, in order to visually move one unit. michael@0: function moveVisually(line, start, dir, byUnit) { michael@0: var bidi = getOrder(line); michael@0: if (!bidi) return moveLogically(line, start, dir, byUnit); michael@0: var pos = getBidiPartAt(bidi, start), part = bidi[pos]; michael@0: var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); michael@0: michael@0: for (;;) { michael@0: if (target > part.from && target < part.to) return target; michael@0: if (target == part.from || target == part.to) { michael@0: if (getBidiPartAt(bidi, target) == pos) return target; michael@0: part = bidi[pos += dir]; michael@0: return (dir > 0) == part.level % 2 ? part.to : part.from; michael@0: } else { michael@0: part = bidi[pos += dir]; michael@0: if (!part) return null; michael@0: if ((dir > 0) == part.level % 2) michael@0: target = moveInLine(line, part.to, -1, byUnit); michael@0: else michael@0: target = moveInLine(line, part.from, 1, byUnit); michael@0: } michael@0: } michael@0: } michael@0: michael@0: function moveLogically(line, start, dir, byUnit) { michael@0: var target = start + dir; michael@0: if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir; michael@0: return target < 0 || target > line.text.length ? null : target; michael@0: } michael@0: michael@0: // Bidirectional ordering algorithm michael@0: // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm michael@0: // that this (partially) implements. michael@0: michael@0: // One-char codes used for character types: michael@0: // L (L): Left-to-Right michael@0: // R (R): Right-to-Left michael@0: // r (AL): Right-to-Left Arabic michael@0: // 1 (EN): European Number michael@0: // + (ES): European Number Separator michael@0: // % (ET): European Number Terminator michael@0: // n (AN): Arabic Number michael@0: // , (CS): Common Number Separator michael@0: // m (NSM): Non-Spacing Mark michael@0: // b (BN): Boundary Neutral michael@0: // s (B): Paragraph Separator michael@0: // t (S): Segment Separator michael@0: // w (WS): Whitespace michael@0: // N (ON): Other Neutrals michael@0: michael@0: // Returns null if characters are ordered as they appear michael@0: // (left-to-right), or an array of sections ({from, to, level} michael@0: // objects) in the order in which they occur visually. michael@0: var bidiOrdering = (function() { michael@0: // Character types for codepoints 0 to 0xff michael@0: var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; michael@0: // Character types for codepoints 0x600 to 0x6ff michael@0: var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm"; michael@0: function charType(code) { michael@0: if (code <= 0xf7) return lowTypes.charAt(code); michael@0: else if (0x590 <= code && code <= 0x5f4) return "R"; michael@0: else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600); michael@0: else if (0x6ee <= code && code <= 0x8ac) return "r"; michael@0: else if (0x2000 <= code && code <= 0x200b) return "w"; michael@0: else if (code == 0x200c) return "b"; michael@0: else return "L"; michael@0: } michael@0: michael@0: var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; michael@0: var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; michael@0: // Browsers seem to always treat the boundaries of block elements as being L. michael@0: var outerType = "L"; michael@0: michael@0: function BidiSpan(level, from, to) { michael@0: this.level = level; michael@0: this.from = from; this.to = to; michael@0: } michael@0: michael@0: return function(str) { michael@0: if (!bidiRE.test(str)) return false; michael@0: var len = str.length, types = []; michael@0: for (var i = 0, type; i < len; ++i) michael@0: types.push(type = charType(str.charCodeAt(i))); michael@0: michael@0: // W1. Examine each non-spacing mark (NSM) in the level run, and michael@0: // change the type of the NSM to the type of the previous michael@0: // character. If the NSM is at the start of the level run, it will michael@0: // get the type of sor. michael@0: for (var i = 0, prev = outerType; i < len; ++i) { michael@0: var type = types[i]; michael@0: if (type == "m") types[i] = prev; michael@0: else prev = type; michael@0: } michael@0: michael@0: // W2. Search backwards from each instance of a European number michael@0: // until the first strong type (R, L, AL, or sor) is found. If an michael@0: // AL is found, change the type of the European number to Arabic michael@0: // number. michael@0: // W3. Change all ALs to R. michael@0: for (var i = 0, cur = outerType; i < len; ++i) { michael@0: var type = types[i]; michael@0: if (type == "1" && cur == "r") types[i] = "n"; michael@0: else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } michael@0: } michael@0: michael@0: // W4. A single European separator between two European numbers michael@0: // changes to a European number. A single common separator between michael@0: // two numbers of the same type changes to that type. michael@0: for (var i = 1, prev = types[0]; i < len - 1; ++i) { michael@0: var type = types[i]; michael@0: if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; michael@0: else if (type == "," && prev == types[i+1] && michael@0: (prev == "1" || prev == "n")) types[i] = prev; michael@0: prev = type; michael@0: } michael@0: michael@0: // W5. A sequence of European terminators adjacent to European michael@0: // numbers changes to all European numbers. michael@0: // W6. Otherwise, separators and terminators change to Other michael@0: // Neutral. michael@0: for (var i = 0; i < len; ++i) { michael@0: var type = types[i]; michael@0: if (type == ",") types[i] = "N"; michael@0: else if (type == "%") { michael@0: for (var end = i + 1; end < len && types[end] == "%"; ++end) {} michael@0: var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; michael@0: for (var j = i; j < end; ++j) types[j] = replace; michael@0: i = end - 1; michael@0: } michael@0: } michael@0: michael@0: // W7. Search backwards from each instance of a European number michael@0: // until the first strong type (R, L, or sor) is found. If an L is michael@0: // found, then change the type of the European number to L. michael@0: for (var i = 0, cur = outerType; i < len; ++i) { michael@0: var type = types[i]; michael@0: if (cur == "L" && type == "1") types[i] = "L"; michael@0: else if (isStrong.test(type)) cur = type; michael@0: } michael@0: michael@0: // N1. A sequence of neutrals takes the direction of the michael@0: // surrounding strong text if the text on both sides has the same michael@0: // direction. European and Arabic numbers act as if they were R in michael@0: // terms of their influence on neutrals. Start-of-level-run (sor) michael@0: // and end-of-level-run (eor) are used at level run boundaries. michael@0: // N2. Any remaining neutrals take the embedding direction. michael@0: for (var i = 0; i < len; ++i) { michael@0: if (isNeutral.test(types[i])) { michael@0: for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} michael@0: var before = (i ? types[i-1] : outerType) == "L"; michael@0: var after = (end < len ? types[end] : outerType) == "L"; michael@0: var replace = before || after ? "L" : "R"; michael@0: for (var j = i; j < end; ++j) types[j] = replace; michael@0: i = end - 1; michael@0: } michael@0: } michael@0: michael@0: // Here we depart from the documented algorithm, in order to avoid michael@0: // building up an actual levels array. Since there are only three michael@0: // levels (0, 1, 2) in an implementation that doesn't take michael@0: // explicit embedding into account, we can build up the order on michael@0: // the fly, without following the level-based algorithm. michael@0: var order = [], m; michael@0: for (var i = 0; i < len;) { michael@0: if (countsAsLeft.test(types[i])) { michael@0: var start = i; michael@0: for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} michael@0: order.push(new BidiSpan(0, start, i)); michael@0: } else { michael@0: var pos = i, at = order.length; michael@0: for (++i; i < len && types[i] != "L"; ++i) {} michael@0: for (var j = pos; j < i;) { michael@0: if (countsAsNum.test(types[j])) { michael@0: if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j)); michael@0: var nstart = j; michael@0: for (++j; j < i && countsAsNum.test(types[j]); ++j) {} michael@0: order.splice(at, 0, new BidiSpan(2, nstart, j)); michael@0: pos = j; michael@0: } else ++j; michael@0: } michael@0: if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i)); michael@0: } michael@0: } michael@0: if (order[0].level == 1 && (m = str.match(/^\s+/))) { michael@0: order[0].from = m[0].length; michael@0: order.unshift(new BidiSpan(0, 0, m[0].length)); michael@0: } michael@0: if (lst(order).level == 1 && (m = str.match(/\s+$/))) { michael@0: lst(order).to -= m[0].length; michael@0: order.push(new BidiSpan(0, len - m[0].length, len)); michael@0: } michael@0: if (order[0].level != lst(order).level) michael@0: order.push(new BidiSpan(order[0].level, len, len)); michael@0: michael@0: return order; michael@0: }; michael@0: })(); michael@0: michael@0: // THE END michael@0: michael@0: CodeMirror.version = "4.0.3"; michael@0: michael@0: return CodeMirror; michael@0: });