Path: blob/main/website/GAUSS/js/codemirror.js
2941 views
// CodeMirror, copyright (c) by Marijn Haverbeke and others1// Distributed under an MIT license: http://codemirror.net/LICENSE23// This is CodeMirror (http://codemirror.net), a code editor4// implemented in JavaScript on top of the browser's DOM.5//6// You can find some technical background for some of the code below7// at http://marijnhaverbeke.nl/blog/#cm-internals .89(function(mod) {10if (typeof exports == "object" && typeof module == "object") // CommonJS11module.exports = mod();12else if (typeof define == "function" && define.amd) // AMD13return define([], mod);14else // Plain browser env15this.CodeMirror = mod();16})(function() {17"use strict";1819// BROWSER SNIFFING2021// Kludges for bugs and behavior differences that can't be feature22// detected are enabled based on userAgent etc sniffing.2324var gecko = /gecko\/\d/i.test(navigator.userAgent);25// ie_uptoN means Internet Explorer version N or lower26var ie_upto10 = /MSIE \d/.test(navigator.userAgent);27var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);28var ie = ie_upto10 || ie_11up;29var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);30var webkit = /WebKit\//.test(navigator.userAgent);31var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);32var chrome = /Chrome\//.test(navigator.userAgent);33var presto = /Opera\//.test(navigator.userAgent);34var safari = /Apple Computer/.test(navigator.vendor);35var khtml = /KHTML\//.test(navigator.userAgent);36var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);37var phantom = /PhantomJS/.test(navigator.userAgent);3839var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);40// This is woefully incomplete. Suggestions for alternative methods welcome.41var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);42var mac = ios || /Mac/.test(navigator.platform);43var windows = /win/i.test(navigator.platform);4445var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/);46if (presto_version) presto_version = Number(presto_version[1]);47if (presto_version && presto_version >= 15) { presto = false; webkit = true; }48// Some browsers use the wrong event properties to signal cmd/ctrl on OS X49var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));50var captureRightClick = gecko || (ie && ie_version >= 9);5152// Optimize some code when these features are not used.53var sawReadOnlySpans = false, sawCollapsedSpans = false;5455// EDITOR CONSTRUCTOR5657// A CodeMirror instance represents an editor. This is the object58// that user code is usually dealing with.5960function CodeMirror(place, options) {61if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);6263this.options = options = options ? copyObj(options) : {};64// Determine effective options based on given values and defaults.65copyObj(defaults, options, false);66setGuttersForLineNumbers(options);6768var doc = options.value;69if (typeof doc == "string") doc = new Doc(doc, options.mode);70this.doc = doc;7172var display = this.display = new Display(place, doc);73display.wrapper.CodeMirror = this;74updateGutters(this);75themeChanged(this);76if (options.lineWrapping)77this.display.wrapper.className += " CodeMirror-wrap";78if (options.autofocus && !mobile) focusInput(this);79initScrollbars(this);8081this.state = {82keyMaps: [], // stores maps added by addKeyMap83overlays: [], // highlighting overlays, as added by addOverlay84modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info85overwrite: false, focused: false,86suppressEdits: false, // used to disable editing during key handlers when in readOnly mode87pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in readInput88draggingText: false,89highlight: new Delayed(), // stores highlight worker timeout90keySeq: null // Unfinished key sequence91};9293// Override magic textarea content restore that IE sometimes does94// on our hidden textarea on reload95if (ie && ie_version < 11) setTimeout(bind(resetInput, this, true), 20);9697registerEventHandlers(this);98ensureGlobalHandlers();99100startOperation(this);101this.curOp.forceUpdate = true;102attachDoc(this, doc);103104if ((options.autofocus && !mobile) || activeElt() == display.input)105setTimeout(bind(onFocus, this), 20);106else107onBlur(this);108109for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))110optionHandlers[opt](this, options[opt], Init);111maybeUpdateLineNumberWidth(this);112for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);113endOperation(this);114// Suppress optimizelegibility in Webkit, since it breaks text115// measuring on line wrapping boundaries.116if (webkit && options.lineWrapping &&117getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")118display.lineDiv.style.textRendering = "auto";119}120121// DISPLAY CONSTRUCTOR122123// The display handles the DOM integration, both for input reading124// and content drawing. It holds references to DOM nodes and125// display-related state.126127function Display(place, doc) {128var d = this;129130// The semihidden textarea that is focused when the editor is131// focused, and receives input.132var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");133// The textarea is kept positioned near the cursor to prevent the134// fact that it'll be scrolled into view on input from scrolling135// our fake cursor out of view. On webkit, when wrap=off, paste is136// very slow. So make the area wide instead.137if (webkit) input.style.width = "1000px";138else input.setAttribute("wrap", "off");139// If border: 0; -- iOS fails to open keyboard (issue #1287)140if (ios) input.style.border = "1px solid black";141input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false");142143// Wraps and hides input textarea144d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");145// Covers bottom-right square when both scrollbars are present.146d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");147d.scrollbarFiller.setAttribute("not-content", "true");148// Covers bottom of gutter when coverGutterNextToScrollbar is on149// and h scrollbar is present.150d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");151d.gutterFiller.setAttribute("not-content", "true");152// Will contain the actual code, positioned to cover the viewport.153d.lineDiv = elt("div", null, "CodeMirror-code");154// Elements are added to these to represent selection and cursors.155d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");156d.cursorDiv = elt("div", null, "CodeMirror-cursors");157// A visibility: hidden element used to find the size of things.158d.measure = elt("div", null, "CodeMirror-measure");159// When lines outside of the viewport are measured, they are drawn in this.160d.lineMeasure = elt("div", null, "CodeMirror-measure");161// Wraps everything that needs to exist inside the vertically-padded coordinate system162d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],163null, "position: relative; outline: none");164// Moved around its parent to cover visible view.165d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");166// Set to the height of the document, allowing scrolling.167d.sizer = elt("div", [d.mover], "CodeMirror-sizer");168d.sizerWidth = null;169// Behavior of elts with overflow: auto and padding is170// inconsistent across browsers. This is used to ensure the171// scrollable area is big enough.172d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");173// Will contain the gutters, if any.174d.gutters = elt("div", null, "CodeMirror-gutters");175d.lineGutter = null;176// Actual scrollable element.177d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");178d.scroller.setAttribute("tabIndex", "-1");179// The element in which the editor lives.180d.wrapper = elt("div", [d.inputDiv, d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");181182// Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)183if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }184// Needed to hide big blue blinking cursor on Mobile Safari185if (ios) input.style.width = "0px";186if (!webkit) d.scroller.draggable = true;187// Needed to handle Tab key in KHTML188if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }189190if (place) {191if (place.appendChild) place.appendChild(d.wrapper);192else place(d.wrapper);193}194195// Current rendered range (may be bigger than the view window).196d.viewFrom = d.viewTo = doc.first;197d.reportedViewFrom = d.reportedViewTo = doc.first;198// Information about the rendered lines.199d.view = [];200d.renderedView = null;201// Holds info about a single rendered line when it was rendered202// for measurement, while not in view.203d.externalMeasured = null;204// Empty space (in pixels) above the view205d.viewOffset = 0;206d.lastWrapHeight = d.lastWrapWidth = 0;207d.updateLineNumbers = null;208209d.nativeBarWidth = d.barHeight = d.barWidth = 0;210d.scrollbarsClipped = false;211212// Used to only resize the line number gutter when necessary (when213// the amount of lines crosses a boundary that makes its width change)214d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;215// See readInput and resetInput216d.prevInput = "";217// Set to true when a non-horizontal-scrolling line widget is218// added. As an optimization, line widget aligning is skipped when219// this is false.220d.alignWidgets = false;221// Flag that indicates whether we expect input to appear real soon222// now (after some event like 'keypress' or 'input') and are223// polling intensively.224d.pollingFast = false;225// Self-resetting timeout for the poller226d.poll = new Delayed();227228d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;229230// Tracks when resetInput has punted to just putting a short231// string into the textarea instead of the full selection.232d.inaccurateSelection = false;233234// Tracks the maximum line length so that the horizontal scrollbar235// can be kept static when scrolling.236d.maxLine = null;237d.maxLineLength = 0;238d.maxLineChanged = false;239240// Used for measuring wheel scrolling granularity241d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;242243// True when shift is held down.244d.shift = false;245246// Used to track whether anything happened since the context menu247// was opened.248d.selForContextMenu = null;249}250251// STATE UPDATES252253// Used to get the editor into a consistent state again when options change.254255function loadMode(cm) {256cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);257resetModeState(cm);258}259260function resetModeState(cm) {261cm.doc.iter(function(line) {262if (line.stateAfter) line.stateAfter = null;263if (line.styles) line.styles = null;264});265cm.doc.frontier = cm.doc.first;266startWorker(cm, 100);267cm.state.modeGen++;268if (cm.curOp) regChange(cm);269}270271function wrappingChanged(cm) {272if (cm.options.lineWrapping) {273addClass(cm.display.wrapper, "CodeMirror-wrap");274cm.display.sizer.style.minWidth = "";275cm.display.sizerWidth = null;276} else {277rmClass(cm.display.wrapper, "CodeMirror-wrap");278findMaxLine(cm);279}280estimateLineHeights(cm);281regChange(cm);282clearCaches(cm);283setTimeout(function(){updateScrollbars(cm);}, 100);284}285286// Returns a function that estimates the height of a line, to use as287// first approximation until the line becomes visible (and is thus288// properly measurable).289function estimateHeight(cm) {290var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;291var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);292return function(line) {293if (lineIsHidden(cm.doc, line)) return 0;294295var widgetsHeight = 0;296if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {297if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;298}299300if (wrapping)301return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;302else303return widgetsHeight + th;304};305}306307function estimateLineHeights(cm) {308var doc = cm.doc, est = estimateHeight(cm);309doc.iter(function(line) {310var estHeight = est(line);311if (estHeight != line.height) updateLineHeight(line, estHeight);312});313}314315function themeChanged(cm) {316cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +317cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");318clearCaches(cm);319}320321function guttersChanged(cm) {322updateGutters(cm);323regChange(cm);324setTimeout(function(){alignHorizontally(cm);}, 20);325}326327// Rebuild the gutter elements, ensure the margin to the left of the328// code matches their width.329function updateGutters(cm) {330var gutters = cm.display.gutters, specs = cm.options.gutters;331removeChildren(gutters);332for (var i = 0; i < specs.length; ++i) {333var gutterClass = specs[i];334var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));335if (gutterClass == "CodeMirror-linenumbers") {336cm.display.lineGutter = gElt;337gElt.style.width = (cm.display.lineNumWidth || 1) + "px";338}339}340gutters.style.display = i ? "" : "none";341updateGutterSpace(cm);342}343344function updateGutterSpace(cm) {345var width = cm.display.gutters.offsetWidth;346cm.display.sizer.style.marginLeft = width + "px";347}348349// Compute the character length of a line, taking into account350// collapsed ranges (see markText) that might hide parts, and join351// other lines onto it.352function lineLength(line) {353if (line.height == 0) return 0;354var len = line.text.length, merged, cur = line;355while (merged = collapsedSpanAtStart(cur)) {356var found = merged.find(0, true);357cur = found.from.line;358len += found.from.ch - found.to.ch;359}360cur = line;361while (merged = collapsedSpanAtEnd(cur)) {362var found = merged.find(0, true);363len -= cur.text.length - found.from.ch;364cur = found.to.line;365len += cur.text.length - found.to.ch;366}367return len;368}369370// Find the longest line in the document.371function findMaxLine(cm) {372var d = cm.display, doc = cm.doc;373d.maxLine = getLine(doc, doc.first);374d.maxLineLength = lineLength(d.maxLine);375d.maxLineChanged = true;376doc.iter(function(line) {377var len = lineLength(line);378if (len > d.maxLineLength) {379d.maxLineLength = len;380d.maxLine = line;381}382});383}384385// Make sure the gutters options contains the element386// "CodeMirror-linenumbers" when the lineNumbers option is true.387function setGuttersForLineNumbers(options) {388var found = indexOf(options.gutters, "CodeMirror-linenumbers");389if (found == -1 && options.lineNumbers) {390options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);391} else if (found > -1 && !options.lineNumbers) {392options.gutters = options.gutters.slice(0);393options.gutters.splice(found, 1);394}395}396397// SCROLLBARS398399// Prepare DOM reads needed to update the scrollbars. Done in one400// shot to minimize update/measure roundtrips.401function measureForScrollbars(cm) {402var d = cm.display, gutterW = d.gutters.offsetWidth;403var docH = Math.round(cm.doc.height + paddingVert(cm.display));404return {405clientHeight: d.scroller.clientHeight,406viewHeight: d.wrapper.clientHeight,407scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,408viewWidth: d.wrapper.clientWidth,409barLeft: cm.options.fixedGutter ? gutterW : 0,410docHeight: docH,411scrollHeight: docH + scrollGap(cm) + d.barHeight,412nativeBarWidth: d.nativeBarWidth,413gutterWidth: gutterW414};415}416417function NativeScrollbars(place, scroll, cm) {418this.cm = cm;419var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");420var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");421place(vert); place(horiz);422423on(vert, "scroll", function() {424if (vert.clientHeight) scroll(vert.scrollTop, "vertical");425});426on(horiz, "scroll", function() {427if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");428});429430this.checkedOverlay = false;431// Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).432if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";433}434435NativeScrollbars.prototype = copyObj({436update: function(measure) {437var needsH = measure.scrollWidth > measure.clientWidth + 1;438var needsV = measure.scrollHeight > measure.clientHeight + 1;439var sWidth = measure.nativeBarWidth;440441if (needsV) {442this.vert.style.display = "block";443this.vert.style.bottom = needsH ? sWidth + "px" : "0";444var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);445// A bug in IE8 can cause this value to be negative, so guard it.446this.vert.firstChild.style.height =447Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";448} else {449this.vert.style.display = "";450this.vert.firstChild.style.height = "0";451}452453if (needsH) {454this.horiz.style.display = "block";455this.horiz.style.right = needsV ? sWidth + "px" : "0";456this.horiz.style.left = measure.barLeft + "px";457var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);458this.horiz.firstChild.style.width =459(measure.scrollWidth - measure.clientWidth + totalWidth) + "px";460} else {461this.horiz.style.display = "";462this.horiz.firstChild.style.width = "0";463}464465if (!this.checkedOverlay && measure.clientHeight > 0) {466if (sWidth == 0) this.overlayHack();467this.checkedOverlay = true;468}469470return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};471},472setScrollLeft: function(pos) {473if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;474},475setScrollTop: function(pos) {476if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;477},478overlayHack: function() {479var w = mac && !mac_geMountainLion ? "12px" : "18px";480this.horiz.style.minHeight = this.vert.style.minWidth = w;481var self = this;482var barMouseDown = function(e) {483if (e_target(e) != self.vert && e_target(e) != self.horiz)484operation(self.cm, onMouseDown)(e);485};486on(this.vert, "mousedown", barMouseDown);487on(this.horiz, "mousedown", barMouseDown);488},489clear: function() {490var parent = this.horiz.parentNode;491parent.removeChild(this.horiz);492parent.removeChild(this.vert);493}494}, NativeScrollbars.prototype);495496function NullScrollbars() {}497498NullScrollbars.prototype = copyObj({499update: function() { return {bottom: 0, right: 0}; },500setScrollLeft: function() {},501setScrollTop: function() {},502clear: function() {}503}, NullScrollbars.prototype);504505CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};506507function initScrollbars(cm) {508if (cm.display.scrollbars) {509cm.display.scrollbars.clear();510if (cm.display.scrollbars.addClass)511rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);512}513514cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {515cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);516on(node, "mousedown", function() {517if (cm.state.focused) setTimeout(bind(focusInput, cm), 0);518});519node.setAttribute("not-content", "true");520}, function(pos, axis) {521if (axis == "horizontal") setScrollLeft(cm, pos);522else setScrollTop(cm, pos);523}, cm);524if (cm.display.scrollbars.addClass)525addClass(cm.display.wrapper, cm.display.scrollbars.addClass);526}527528function updateScrollbars(cm, measure) {529if (!measure) measure = measureForScrollbars(cm);530var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;531updateScrollbarsInner(cm, measure);532for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {533if (startWidth != cm.display.barWidth && cm.options.lineWrapping)534updateHeightsInViewport(cm);535updateScrollbarsInner(cm, measureForScrollbars(cm));536startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;537}538}539540// Re-synchronize the fake scrollbars with the actual size of the541// content.542function updateScrollbarsInner(cm, measure) {543var d = cm.display;544var sizes = d.scrollbars.update(measure);545546d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";547d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";548549if (sizes.right && sizes.bottom) {550d.scrollbarFiller.style.display = "block";551d.scrollbarFiller.style.height = sizes.bottom + "px";552d.scrollbarFiller.style.width = sizes.right + "px";553} else d.scrollbarFiller.style.display = "";554if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {555d.gutterFiller.style.display = "block";556d.gutterFiller.style.height = sizes.bottom + "px";557d.gutterFiller.style.width = measure.gutterWidth + "px";558} else d.gutterFiller.style.display = "";559}560561// Compute the lines that are visible in a given viewport (defaults562// the the current scroll position). viewport may contain top,563// height, and ensure (see op.scrollToPos) properties.564function visibleLines(display, doc, viewport) {565var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;566top = Math.floor(top - paddingTop(display));567var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;568569var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);570// Ensure is a {from: {line, ch}, to: {line, ch}} object, and571// forces those lines into the viewport (if possible).572if (viewport && viewport.ensure) {573var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;574if (ensureFrom < from) {575from = ensureFrom;576to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);577} else if (Math.min(ensureTo, doc.lastLine()) >= to) {578from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);579to = ensureTo;580}581}582return {from: from, to: Math.max(to, from + 1)};583}584585// LINE NUMBERS586587// Re-align line numbers and gutter marks to compensate for588// horizontal scrolling.589function alignHorizontally(cm) {590var display = cm.display, view = display.view;591if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;592var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;593var gutterW = display.gutters.offsetWidth, left = comp + "px";594for (var i = 0; i < view.length; i++) if (!view[i].hidden) {595if (cm.options.fixedGutter && view[i].gutter)596view[i].gutter.style.left = left;597var align = view[i].alignable;598if (align) for (var j = 0; j < align.length; j++)599align[j].style.left = left;600}601if (cm.options.fixedGutter)602display.gutters.style.left = (comp + gutterW) + "px";603}604605// Used to ensure that the line number gutter is still the right606// size for the current document size. Returns true when an update607// is needed.608function maybeUpdateLineNumberWidth(cm) {609if (!cm.options.lineNumbers) return false;610var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;611if (last.length != display.lineNumChars) {612var test = display.measure.appendChild(elt("div", [elt("div", last)],613"CodeMirror-linenumber CodeMirror-gutter-elt"));614var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;615display.lineGutter.style.width = "";616display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);617display.lineNumWidth = display.lineNumInnerWidth + padding;618display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;619display.lineGutter.style.width = display.lineNumWidth + "px";620updateGutterSpace(cm);621return true;622}623return false;624}625626function lineNumberFor(options, i) {627return String(options.lineNumberFormatter(i + options.firstLineNumber));628}629630// Computes display.scroller.scrollLeft + display.gutters.offsetWidth,631// but using getBoundingClientRect to get a sub-pixel-accurate632// result.633function compensateForHScroll(display) {634return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;635}636637// DISPLAY DRAWING638639function DisplayUpdate(cm, viewport, force) {640var display = cm.display;641642this.viewport = viewport;643// Store some values that we'll need later (but don't want to force a relayout for)644this.visible = visibleLines(display, cm.doc, viewport);645this.editorIsHidden = !display.wrapper.offsetWidth;646this.wrapperHeight = display.wrapper.clientHeight;647this.wrapperWidth = display.wrapper.clientWidth;648this.oldDisplayWidth = displayWidth(cm);649this.force = force;650this.dims = getDimensions(cm);651}652653function maybeClipScrollbars(cm) {654var display = cm.display;655if (!display.scrollbarsClipped && display.scroller.offsetWidth) {656display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;657display.heightForcer.style.height = scrollGap(cm) + "px";658display.sizer.style.marginBottom = -display.nativeBarWidth + "px";659display.sizer.style.borderRightWidth = scrollGap(cm) + "px";660display.scrollbarsClipped = true;661}662}663664// Does the actual updating of the line display. Bails out665// (returning false) when there is nothing to be done and forced is666// false.667function updateDisplayIfNeeded(cm, update) {668var display = cm.display, doc = cm.doc;669670if (update.editorIsHidden) {671resetView(cm);672return false;673}674675// Bail out if the visible area is already rendered and nothing changed.676if (!update.force &&677update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&678(display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&679display.renderedView == display.view && countDirtyView(cm) == 0)680return false;681682if (maybeUpdateLineNumberWidth(cm)) {683resetView(cm);684update.dims = getDimensions(cm);685}686687// Compute a suitable new viewport (from & to)688var end = doc.first + doc.size;689var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);690var to = Math.min(end, update.visible.to + cm.options.viewportMargin);691if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);692if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);693if (sawCollapsedSpans) {694from = visualLineNo(cm.doc, from);695to = visualLineEndNo(cm.doc, to);696}697698var different = from != display.viewFrom || to != display.viewTo ||699display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;700adjustView(cm, from, to);701702display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));703// Position the mover div to align with the current scroll position704cm.display.mover.style.top = display.viewOffset + "px";705706var toUpdate = countDirtyView(cm);707if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&708(display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))709return false;710711// For big changes, we hide the enclosing element during the712// update, since that speeds up the operations on most browsers.713var focused = activeElt();714if (toUpdate > 4) display.lineDiv.style.display = "none";715patchDisplay(cm, display.updateLineNumbers, update.dims);716if (toUpdate > 4) display.lineDiv.style.display = "";717display.renderedView = display.view;718// There might have been a widget with a focused element that got719// hidden or updated, if so re-focus it.720if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();721722// Prevent selection and cursors from interfering with the scroll723// width and height.724removeChildren(display.cursorDiv);725removeChildren(display.selectionDiv);726display.gutters.style.height = 0;727728if (different) {729display.lastWrapHeight = update.wrapperHeight;730display.lastWrapWidth = update.wrapperWidth;731startWorker(cm, 400);732}733734display.updateLineNumbers = null;735736return true;737}738739function postUpdateDisplay(cm, update) {740var force = update.force, viewport = update.viewport;741for (var first = true;; first = false) {742if (first && cm.options.lineWrapping && update.oldDisplayWidth != displayWidth(cm)) {743force = true;744} else {745force = false;746// Clip forced viewport to actual scrollable area.747if (viewport && viewport.top != null)748viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};749// Updated line heights might result in the drawn area not750// actually covering the viewport. Keep looping until it does.751update.visible = visibleLines(cm.display, cm.doc, viewport);752if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)753break;754}755if (!updateDisplayIfNeeded(cm, update)) break;756updateHeightsInViewport(cm);757var barMeasure = measureForScrollbars(cm);758updateSelection(cm);759setDocumentHeight(cm, barMeasure);760updateScrollbars(cm, barMeasure);761}762763signalLater(cm, "update", cm);764if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {765signalLater(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);766cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;767}768}769770function updateDisplaySimple(cm, viewport) {771var update = new DisplayUpdate(cm, viewport);772if (updateDisplayIfNeeded(cm, update)) {773updateHeightsInViewport(cm);774postUpdateDisplay(cm, update);775var barMeasure = measureForScrollbars(cm);776updateSelection(cm);777setDocumentHeight(cm, barMeasure);778updateScrollbars(cm, barMeasure);779}780}781782function setDocumentHeight(cm, measure) {783cm.display.sizer.style.minHeight = measure.docHeight + "px";784var total = measure.docHeight + cm.display.barHeight;785cm.display.heightForcer.style.top = total + "px";786cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px";787}788789// Read the actual heights of the rendered lines, and update their790// stored heights to match.791function updateHeightsInViewport(cm) {792var display = cm.display;793var prevBottom = display.lineDiv.offsetTop;794for (var i = 0; i < display.view.length; i++) {795var cur = display.view[i], height;796if (cur.hidden) continue;797if (ie && ie_version < 8) {798var bot = cur.node.offsetTop + cur.node.offsetHeight;799height = bot - prevBottom;800prevBottom = bot;801} else {802var box = cur.node.getBoundingClientRect();803height = box.bottom - box.top;804}805var diff = cur.line.height - height;806if (height < 2) height = textHeight(display);807if (diff > .001 || diff < -.001) {808updateLineHeight(cur.line, height);809updateWidgetHeight(cur.line);810if (cur.rest) for (var j = 0; j < cur.rest.length; j++)811updateWidgetHeight(cur.rest[j]);812}813}814}815816// Read and store the height of line widgets associated with the817// given line.818function updateWidgetHeight(line) {819if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)820line.widgets[i].height = line.widgets[i].node.offsetHeight;821}822823// Do a bulk-read of the DOM positions and sizes needed to draw the824// view, so that we don't interleave reading and writing to the DOM.825function getDimensions(cm) {826var d = cm.display, left = {}, width = {};827var gutterLeft = d.gutters.clientLeft;828for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {829left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;830width[cm.options.gutters[i]] = n.clientWidth;831}832return {fixedPos: compensateForHScroll(d),833gutterTotalWidth: d.gutters.offsetWidth,834gutterLeft: left,835gutterWidth: width,836wrapperWidth: d.wrapper.clientWidth};837}838839// Sync the actual display DOM structure with display.view, removing840// nodes for lines that are no longer in view, and creating the ones841// that are not there yet, and updating the ones that are out of842// date.843function patchDisplay(cm, updateNumbersFrom, dims) {844var display = cm.display, lineNumbers = cm.options.lineNumbers;845var container = display.lineDiv, cur = container.firstChild;846847function rm(node) {848var next = node.nextSibling;849// Works around a throw-scroll bug in OS X Webkit850if (webkit && mac && cm.display.currentWheelTarget == node)851node.style.display = "none";852else853node.parentNode.removeChild(node);854return next;855}856857var view = display.view, lineN = display.viewFrom;858// Loop over the elements in the view, syncing cur (the DOM nodes859// in display.lineDiv) with the view as we go.860for (var i = 0; i < view.length; i++) {861var lineView = view[i];862if (lineView.hidden) {863} else if (!lineView.node) { // Not drawn yet864var node = buildLineElement(cm, lineView, lineN, dims);865container.insertBefore(node, cur);866} else { // Already drawn867while (cur != lineView.node) cur = rm(cur);868var updateNumber = lineNumbers && updateNumbersFrom != null &&869updateNumbersFrom <= lineN && lineView.lineNumber;870if (lineView.changes) {871if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;872updateLineForChanges(cm, lineView, lineN, dims);873}874if (updateNumber) {875removeChildren(lineView.lineNumber);876lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));877}878cur = lineView.node.nextSibling;879}880lineN += lineView.size;881}882while (cur) cur = rm(cur);883}884885// When an aspect of a line changes, a string is added to886// lineView.changes. This updates the relevant part of the line's887// DOM structure.888function updateLineForChanges(cm, lineView, lineN, dims) {889for (var j = 0; j < lineView.changes.length; j++) {890var type = lineView.changes[j];891if (type == "text") updateLineText(cm, lineView);892else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);893else if (type == "class") updateLineClasses(lineView);894else if (type == "widget") updateLineWidgets(lineView, dims);895}896lineView.changes = null;897}898899// Lines with gutter elements, widgets or a background class need to900// be wrapped, and have the extra elements added to the wrapper div901function ensureLineWrapped(lineView) {902if (lineView.node == lineView.text) {903lineView.node = elt("div", null, null, "position: relative");904if (lineView.text.parentNode)905lineView.text.parentNode.replaceChild(lineView.node, lineView.text);906lineView.node.appendChild(lineView.text);907if (ie && ie_version < 8) lineView.node.style.zIndex = 2;908}909return lineView.node;910}911912function updateLineBackground(lineView) {913var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;914if (cls) cls += " CodeMirror-linebackground";915if (lineView.background) {916if (cls) lineView.background.className = cls;917else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }918} else if (cls) {919var wrap = ensureLineWrapped(lineView);920lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);921}922}923924// Wrapper around buildLineContent which will reuse the structure925// in display.externalMeasured when possible.926function getLineContent(cm, lineView) {927var ext = cm.display.externalMeasured;928if (ext && ext.line == lineView.line) {929cm.display.externalMeasured = null;930lineView.measure = ext.measure;931return ext.built;932}933return buildLineContent(cm, lineView);934}935936// Redraw the line's text. Interacts with the background and text937// classes because the mode may output tokens that influence these938// classes.939function updateLineText(cm, lineView) {940var cls = lineView.text.className;941var built = getLineContent(cm, lineView);942if (lineView.text == lineView.node) lineView.node = built.pre;943lineView.text.parentNode.replaceChild(built.pre, lineView.text);944lineView.text = built.pre;945if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {946lineView.bgClass = built.bgClass;947lineView.textClass = built.textClass;948updateLineClasses(lineView);949} else if (cls) {950lineView.text.className = cls;951}952}953954function updateLineClasses(lineView) {955updateLineBackground(lineView);956if (lineView.line.wrapClass)957ensureLineWrapped(lineView).className = lineView.line.wrapClass;958else if (lineView.node != lineView.text)959lineView.node.className = "";960var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;961lineView.text.className = textClass || "";962}963964function updateLineGutter(cm, lineView, lineN, dims) {965if (lineView.gutter) {966lineView.node.removeChild(lineView.gutter);967lineView.gutter = null;968}969var markers = lineView.line.gutterMarkers;970if (cm.options.lineNumbers || markers) {971var wrap = ensureLineWrapped(lineView);972var gutterWrap = lineView.gutter =973wrap.insertBefore(elt("div", null, "CodeMirror-gutter-wrapper", "left: " +974(cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +975"px; width: " + dims.gutterTotalWidth + "px"),976lineView.text);977if (lineView.line.gutterClass)978gutterWrap.className += " " + lineView.line.gutterClass;979if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))980lineView.lineNumber = gutterWrap.appendChild(981elt("div", lineNumberFor(cm.options, lineN),982"CodeMirror-linenumber CodeMirror-gutter-elt",983"left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "984+ cm.display.lineNumInnerWidth + "px"));985if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {986var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];987if (found)988gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +989dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));990}991}992}993994function updateLineWidgets(lineView, dims) {995if (lineView.alignable) lineView.alignable = null;996for (var node = lineView.node.firstChild, next; node; node = next) {997var next = node.nextSibling;998if (node.className == "CodeMirror-linewidget")999lineView.node.removeChild(node);1000}1001insertLineWidgets(lineView, dims);1002}10031004// Build a line's DOM representation from scratch1005function buildLineElement(cm, lineView, lineN, dims) {1006var built = getLineContent(cm, lineView);1007lineView.text = lineView.node = built.pre;1008if (built.bgClass) lineView.bgClass = built.bgClass;1009if (built.textClass) lineView.textClass = built.textClass;10101011updateLineClasses(lineView);1012updateLineGutter(cm, lineView, lineN, dims);1013insertLineWidgets(lineView, dims);1014return lineView.node;1015}10161017// A lineView may contain multiple logical lines (when merged by1018// collapsed spans). The widgets for all of them need to be drawn.1019function insertLineWidgets(lineView, dims) {1020insertLineWidgetsFor(lineView.line, lineView, dims, true);1021if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)1022insertLineWidgetsFor(lineView.rest[i], lineView, dims, false);1023}10241025function insertLineWidgetsFor(line, lineView, dims, allowAbove) {1026if (!line.widgets) return;1027var wrap = ensureLineWrapped(lineView);1028for (var i = 0, ws = line.widgets; i < ws.length; ++i) {1029var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");1030if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");1031positionLineWidget(widget, node, lineView, dims);1032if (allowAbove && widget.above)1033wrap.insertBefore(node, lineView.gutter || lineView.text);1034else1035wrap.appendChild(node);1036signalLater(widget, "redraw");1037}1038}10391040function positionLineWidget(widget, node, lineView, dims) {1041if (widget.noHScroll) {1042(lineView.alignable || (lineView.alignable = [])).push(node);1043var width = dims.wrapperWidth;1044node.style.left = dims.fixedPos + "px";1045if (!widget.coverGutter) {1046width -= dims.gutterTotalWidth;1047node.style.paddingLeft = dims.gutterTotalWidth + "px";1048}1049node.style.width = width + "px";1050}1051if (widget.coverGutter) {1052node.style.zIndex = 5;1053node.style.position = "relative";1054if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";1055}1056}10571058// POSITION OBJECT10591060// A Pos instance represents a position within the text.1061var Pos = CodeMirror.Pos = function(line, ch) {1062if (!(this instanceof Pos)) return new Pos(line, ch);1063this.line = line; this.ch = ch;1064};10651066// Compare two positions, return 0 if they are the same, a negative1067// number when a is less, and a positive number otherwise.1068var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };10691070function copyPos(x) {return Pos(x.line, x.ch);}1071function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }1072function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }10731074// SELECTION / CURSOR10751076// Selection objects are immutable. A new one is created every time1077// the selection changes. A selection is one or more non-overlapping1078// (and non-touching) ranges, sorted, and an integer that indicates1079// which one is the primary selection (the one that's scrolled into1080// view, that getCursor returns, etc).1081function Selection(ranges, primIndex) {1082this.ranges = ranges;1083this.primIndex = primIndex;1084}10851086Selection.prototype = {1087primary: function() { return this.ranges[this.primIndex]; },1088equals: function(other) {1089if (other == this) return true;1090if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;1091for (var i = 0; i < this.ranges.length; i++) {1092var here = this.ranges[i], there = other.ranges[i];1093if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;1094}1095return true;1096},1097deepCopy: function() {1098for (var out = [], i = 0; i < this.ranges.length; i++)1099out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));1100return new Selection(out, this.primIndex);1101},1102somethingSelected: function() {1103for (var i = 0; i < this.ranges.length; i++)1104if (!this.ranges[i].empty()) return true;1105return false;1106},1107contains: function(pos, end) {1108if (!end) end = pos;1109for (var i = 0; i < this.ranges.length; i++) {1110var range = this.ranges[i];1111if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)1112return i;1113}1114return -1;1115}1116};11171118function Range(anchor, head) {1119this.anchor = anchor; this.head = head;1120}11211122Range.prototype = {1123from: function() { return minPos(this.anchor, this.head); },1124to: function() { return maxPos(this.anchor, this.head); },1125empty: function() {1126return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;1127}1128};11291130// Take an unsorted, potentially overlapping set of ranges, and1131// build a selection out of it. 'Consumes' ranges array (modifying1132// it).1133function normalizeSelection(ranges, primIndex) {1134var prim = ranges[primIndex];1135ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });1136primIndex = indexOf(ranges, prim);1137for (var i = 1; i < ranges.length; i++) {1138var cur = ranges[i], prev = ranges[i - 1];1139if (cmp(prev.to(), cur.from()) >= 0) {1140var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());1141var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;1142if (i <= primIndex) --primIndex;1143ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));1144}1145}1146return new Selection(ranges, primIndex);1147}11481149function simpleSelection(anchor, head) {1150return new Selection([new Range(anchor, head || anchor)], 0);1151}11521153// Most of the external API clips given positions to make sure they1154// actually exist within the document.1155function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}1156function clipPos(doc, pos) {1157if (pos.line < doc.first) return Pos(doc.first, 0);1158var last = doc.first + doc.size - 1;1159if (pos.line > last) return Pos(last, getLine(doc, last).text.length);1160return clipToLen(pos, getLine(doc, pos.line).text.length);1161}1162function clipToLen(pos, linelen) {1163var ch = pos.ch;1164if (ch == null || ch > linelen) return Pos(pos.line, linelen);1165else if (ch < 0) return Pos(pos.line, 0);1166else return pos;1167}1168function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}1169function clipPosArray(doc, array) {1170for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);1171return out;1172}11731174// SELECTION UPDATES11751176// The 'scroll' parameter given to many of these indicated whether1177// the new cursor position should be scrolled into view after1178// modifying the selection.11791180// If shift is held or the extend flag is set, extends a range to1181// include a given position (and optionally a second position).1182// Otherwise, simply returns the range between the given positions.1183// Used for cursor motion and such.1184function extendRange(doc, range, head, other) {1185if (doc.cm && doc.cm.display.shift || doc.extend) {1186var anchor = range.anchor;1187if (other) {1188var posBefore = cmp(head, anchor) < 0;1189if (posBefore != (cmp(other, anchor) < 0)) {1190anchor = head;1191head = other;1192} else if (posBefore != (cmp(head, other) < 0)) {1193head = other;1194}1195}1196return new Range(anchor, head);1197} else {1198return new Range(other || head, head);1199}1200}12011202// Extend the primary selection range, discard the rest.1203function extendSelection(doc, head, other, options) {1204setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);1205}12061207// Extend all selections (pos is an array of selections with length1208// equal the number of selections)1209function extendSelections(doc, heads, options) {1210for (var out = [], i = 0; i < doc.sel.ranges.length; i++)1211out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);1212var newSel = normalizeSelection(out, doc.sel.primIndex);1213setSelection(doc, newSel, options);1214}12151216// Updates a single range in the selection.1217function replaceOneSelection(doc, i, range, options) {1218var ranges = doc.sel.ranges.slice(0);1219ranges[i] = range;1220setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);1221}12221223// Reset the selection to a single range.1224function setSimpleSelection(doc, anchor, head, options) {1225setSelection(doc, simpleSelection(anchor, head), options);1226}12271228// Give beforeSelectionChange handlers a change to influence a1229// selection update.1230function filterSelectionChange(doc, sel) {1231var obj = {1232ranges: sel.ranges,1233update: function(ranges) {1234this.ranges = [];1235for (var i = 0; i < ranges.length; i++)1236this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),1237clipPos(doc, ranges[i].head));1238}1239};1240signal(doc, "beforeSelectionChange", doc, obj);1241if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);1242if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);1243else return sel;1244}12451246function setSelectionReplaceHistory(doc, sel, options) {1247var done = doc.history.done, last = lst(done);1248if (last && last.ranges) {1249done[done.length - 1] = sel;1250setSelectionNoUndo(doc, sel, options);1251} else {1252setSelection(doc, sel, options);1253}1254}12551256// Set a new selection.1257function setSelection(doc, sel, options) {1258setSelectionNoUndo(doc, sel, options);1259addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);1260}12611262function setSelectionNoUndo(doc, sel, options) {1263if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))1264sel = filterSelectionChange(doc, sel);12651266var bias = options && options.bias ||1267(cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);1268setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));12691270if (!(options && options.scroll === false) && doc.cm)1271ensureCursorVisible(doc.cm);1272}12731274function setSelectionInner(doc, sel) {1275if (sel.equals(doc.sel)) return;12761277doc.sel = sel;12781279if (doc.cm) {1280doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;1281signalCursorActivity(doc.cm);1282}1283signalLater(doc, "cursorActivity", doc);1284}12851286// Verify that the selection does not partially select any atomic1287// marked ranges.1288function reCheckSelection(doc) {1289setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);1290}12911292// Return a selection that does not partially select any atomic1293// ranges.1294function skipAtomicInSelection(doc, sel, bias, mayClear) {1295var out;1296for (var i = 0; i < sel.ranges.length; i++) {1297var range = sel.ranges[i];1298var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);1299var newHead = skipAtomic(doc, range.head, bias, mayClear);1300if (out || newAnchor != range.anchor || newHead != range.head) {1301if (!out) out = sel.ranges.slice(0, i);1302out[i] = new Range(newAnchor, newHead);1303}1304}1305return out ? normalizeSelection(out, sel.primIndex) : sel;1306}13071308// Ensure a given position is not inside an atomic range.1309function skipAtomic(doc, pos, bias, mayClear) {1310var flipped = false, curPos = pos;1311var dir = bias || 1;1312doc.cantEdit = false;1313search: for (;;) {1314var line = getLine(doc, curPos.line);1315if (line.markedSpans) {1316for (var i = 0; i < line.markedSpans.length; ++i) {1317var sp = line.markedSpans[i], m = sp.marker;1318if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&1319(sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {1320if (mayClear) {1321signal(m, "beforeCursorEnter");1322if (m.explicitlyCleared) {1323if (!line.markedSpans) break;1324else {--i; continue;}1325}1326}1327if (!m.atomic) continue;1328var newPos = m.find(dir < 0 ? -1 : 1);1329if (cmp(newPos, curPos) == 0) {1330newPos.ch += dir;1331if (newPos.ch < 0) {1332if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));1333else newPos = null;1334} else if (newPos.ch > line.text.length) {1335if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);1336else newPos = null;1337}1338if (!newPos) {1339if (flipped) {1340// Driven in a corner -- no valid cursor position found at all1341// -- try again *with* clearing, if we didn't already1342if (!mayClear) return skipAtomic(doc, pos, bias, true);1343// Otherwise, turn off editing until further notice, and return the start of the doc1344doc.cantEdit = true;1345return Pos(doc.first, 0);1346}1347flipped = true; newPos = pos; dir = -dir;1348}1349}1350curPos = newPos;1351continue search;1352}1353}1354}1355return curPos;1356}1357}13581359// SELECTION DRAWING13601361// Redraw the selection and/or cursor1362function drawSelection(cm) {1363var display = cm.display, doc = cm.doc, result = {};1364var curFragment = result.cursors = document.createDocumentFragment();1365var selFragment = result.selection = document.createDocumentFragment();13661367for (var i = 0; i < doc.sel.ranges.length; i++) {1368var range = doc.sel.ranges[i];1369var collapsed = range.empty();1370if (collapsed || cm.options.showCursorWhenSelecting)1371drawSelectionCursor(cm, range, curFragment);1372if (!collapsed)1373drawSelectionRange(cm, range, selFragment);1374}13751376// Move the hidden textarea near the cursor to prevent scrolling artifacts1377if (cm.options.moveInputWithCursor) {1378var headPos = cursorCoords(cm, doc.sel.primary().head, "div");1379var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();1380result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,1381headPos.top + lineOff.top - wrapOff.top));1382result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,1383headPos.left + lineOff.left - wrapOff.left));1384}13851386return result;1387}13881389function showSelection(cm, drawn) {1390removeChildrenAndAdd(cm.display.cursorDiv, drawn.cursors);1391removeChildrenAndAdd(cm.display.selectionDiv, drawn.selection);1392if (drawn.teTop != null) {1393cm.display.inputDiv.style.top = drawn.teTop + "px";1394cm.display.inputDiv.style.left = drawn.teLeft + "px";1395}1396}13971398function updateSelection(cm) {1399showSelection(cm, drawSelection(cm));1400}14011402// Draws a cursor for the given range1403function drawSelectionCursor(cm, range, output) {1404var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine);14051406var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));1407cursor.style.left = pos.left + "px";1408cursor.style.top = pos.top + "px";1409cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";14101411if (pos.other) {1412// Secondary cursor, shown when on a 'jump' in bi-directional text1413var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));1414otherCursor.style.display = "";1415otherCursor.style.left = pos.other.left + "px";1416otherCursor.style.top = pos.other.top + "px";1417otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";1418}1419}14201421// Draws the given range as a highlighted selection1422function drawSelectionRange(cm, range, output) {1423var display = cm.display, doc = cm.doc;1424var fragment = document.createDocumentFragment();1425var padding = paddingH(cm.display), leftSide = padding.left;1426var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;14271428function add(left, top, width, bottom) {1429if (top < 0) top = 0;1430top = Math.round(top);1431bottom = Math.round(bottom);1432fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +1433"px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +1434"px; height: " + (bottom - top) + "px"));1435}14361437function drawForLine(line, fromArg, toArg) {1438var lineObj = getLine(doc, line);1439var lineLen = lineObj.text.length;1440var start, end;1441function coords(ch, bias) {1442return charCoords(cm, Pos(line, ch), "div", lineObj, bias);1443}14441445iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {1446var leftPos = coords(from, "left"), rightPos, left, right;1447if (from == to) {1448rightPos = leftPos;1449left = right = leftPos.left;1450} else {1451rightPos = coords(to - 1, "right");1452if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }1453left = leftPos.left;1454right = rightPos.right;1455}1456if (fromArg == null && from == 0) left = leftSide;1457if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part1458add(left, leftPos.top, null, leftPos.bottom);1459left = leftSide;1460if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);1461}1462if (toArg == null && to == lineLen) right = rightSide;1463if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)1464start = leftPos;1465if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)1466end = rightPos;1467if (left < leftSide + 1) left = leftSide;1468add(left, rightPos.top, right - left, rightPos.bottom);1469});1470return {start: start, end: end};1471}14721473var sFrom = range.from(), sTo = range.to();1474if (sFrom.line == sTo.line) {1475drawForLine(sFrom.line, sFrom.ch, sTo.ch);1476} else {1477var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);1478var singleVLine = visualLine(fromLine) == visualLine(toLine);1479var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;1480var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;1481if (singleVLine) {1482if (leftEnd.top < rightStart.top - 2) {1483add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);1484add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);1485} else {1486add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);1487}1488}1489if (leftEnd.bottom < rightStart.top)1490add(leftSide, leftEnd.bottom, null, rightStart.top);1491}14921493output.appendChild(fragment);1494}14951496// Cursor-blinking1497function restartBlink(cm) {1498if (!cm.state.focused) return;1499var display = cm.display;1500clearInterval(display.blinker);1501var on = true;1502display.cursorDiv.style.visibility = "";1503if (cm.options.cursorBlinkRate > 0)1504display.blinker = setInterval(function() {1505display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";1506}, cm.options.cursorBlinkRate);1507else if (cm.options.cursorBlinkRate < 0)1508display.cursorDiv.style.visibility = "hidden";1509}15101511// HIGHLIGHT WORKER15121513function startWorker(cm, time) {1514if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)1515cm.state.highlight.set(time, bind(highlightWorker, cm));1516}15171518function highlightWorker(cm) {1519var doc = cm.doc;1520if (doc.frontier < doc.first) doc.frontier = doc.first;1521if (doc.frontier >= cm.display.viewTo) return;1522var end = +new Date + cm.options.workTime;1523var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));1524var changedLines = [];15251526doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {1527if (doc.frontier >= cm.display.viewFrom) { // Visible1528var oldStyles = line.styles;1529var highlighted = highlightLine(cm, line, state, true);1530line.styles = highlighted.styles;1531var oldCls = line.styleClasses, newCls = highlighted.classes;1532if (newCls) line.styleClasses = newCls;1533else if (oldCls) line.styleClasses = null;1534var ischange = !oldStyles || oldStyles.length != line.styles.length ||1535oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);1536for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];1537if (ischange) changedLines.push(doc.frontier);1538line.stateAfter = copyState(doc.mode, state);1539} else {1540processLine(cm, line.text, state);1541line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;1542}1543++doc.frontier;1544if (+new Date > end) {1545startWorker(cm, cm.options.workDelay);1546return true;1547}1548});1549if (changedLines.length) runInOp(cm, function() {1550for (var i = 0; i < changedLines.length; i++)1551regLineChange(cm, changedLines[i], "text");1552});1553}15541555// Finds the line to start with when starting a parse. Tries to1556// find a line with a stateAfter, so that it can start with a1557// valid state. If that fails, it returns the line with the1558// smallest indentation, which tends to need the least context to1559// parse correctly.1560function findStartLine(cm, n, precise) {1561var minindent, minline, doc = cm.doc;1562var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);1563for (var search = n; search > lim; --search) {1564if (search <= doc.first) return doc.first;1565var line = getLine(doc, search - 1);1566if (line.stateAfter && (!precise || search <= doc.frontier)) return search;1567var indented = countColumn(line.text, null, cm.options.tabSize);1568if (minline == null || minindent > indented) {1569minline = search - 1;1570minindent = indented;1571}1572}1573return minline;1574}15751576function getStateBefore(cm, n, precise) {1577var doc = cm.doc, display = cm.display;1578if (!doc.mode.startState) return true;1579var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;1580if (!state) state = startState(doc.mode);1581else state = copyState(doc.mode, state);1582doc.iter(pos, n, function(line) {1583processLine(cm, line.text, state);1584var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;1585line.stateAfter = save ? copyState(doc.mode, state) : null;1586++pos;1587});1588if (precise) doc.frontier = pos;1589return state;1590}15911592// POSITION MEASUREMENT15931594function paddingTop(display) {return display.lineSpace.offsetTop;}1595function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}1596function paddingH(display) {1597if (display.cachedPaddingH) return display.cachedPaddingH;1598var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));1599var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;1600var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};1601if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;1602return data;1603}16041605function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }1606function displayWidth(cm) {1607return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;1608}1609function displayHeight(cm) {1610return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;1611}16121613// Ensure the lineView.wrapping.heights array is populated. This is1614// an array of bottom offsets for the lines that make up a drawn1615// line. When lineWrapping is on, there might be more than one1616// height.1617function ensureLineHeights(cm, lineView, rect) {1618var wrapping = cm.options.lineWrapping;1619var curWidth = wrapping && displayWidth(cm);1620if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {1621var heights = lineView.measure.heights = [];1622if (wrapping) {1623lineView.measure.width = curWidth;1624var rects = lineView.text.firstChild.getClientRects();1625for (var i = 0; i < rects.length - 1; i++) {1626var cur = rects[i], next = rects[i + 1];1627if (Math.abs(cur.bottom - next.bottom) > 2)1628heights.push((cur.bottom + next.top) / 2 - rect.top);1629}1630}1631heights.push(rect.bottom - rect.top);1632}1633}16341635// Find a line map (mapping character offsets to text nodes) and a1636// measurement cache for the given line number. (A line view might1637// contain multiple lines when collapsed ranges are present.)1638function mapFromLineView(lineView, line, lineN) {1639if (lineView.line == line)1640return {map: lineView.measure.map, cache: lineView.measure.cache};1641for (var i = 0; i < lineView.rest.length; i++)1642if (lineView.rest[i] == line)1643return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};1644for (var i = 0; i < lineView.rest.length; i++)1645if (lineNo(lineView.rest[i]) > lineN)1646return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};1647}16481649// Render a line into the hidden node display.externalMeasured. Used1650// when measurement is needed for a line that's not in the viewport.1651function updateExternalMeasurement(cm, line) {1652line = visualLine(line);1653var lineN = lineNo(line);1654var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);1655view.lineN = lineN;1656var built = view.built = buildLineContent(cm, view);1657view.text = built.pre;1658removeChildrenAndAdd(cm.display.lineMeasure, built.pre);1659return view;1660}16611662// Get a {top, bottom, left, right} box (in line-local coordinates)1663// for a given character.1664function measureChar(cm, line, ch, bias) {1665return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);1666}16671668// Find a line view that corresponds to the given line number.1669function findViewForLine(cm, lineN) {1670if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)1671return cm.display.view[findViewIndex(cm, lineN)];1672var ext = cm.display.externalMeasured;1673if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)1674return ext;1675}16761677// Measurement can be split in two steps, the set-up work that1678// applies to the whole line, and the measurement of the actual1679// character. Functions like coordsChar, that need to do a lot of1680// measurements in a row, can thus ensure that the set-up work is1681// only done once.1682function prepareMeasureForLine(cm, line) {1683var lineN = lineNo(line);1684var view = findViewForLine(cm, lineN);1685if (view && !view.text)1686view = null;1687else if (view && view.changes)1688updateLineForChanges(cm, view, lineN, getDimensions(cm));1689if (!view)1690view = updateExternalMeasurement(cm, line);16911692var info = mapFromLineView(view, line, lineN);1693return {1694line: line, view: view, rect: null,1695map: info.map, cache: info.cache, before: info.before,1696hasHeights: false1697};1698}16991700// Given a prepared measurement object, measures the position of an1701// actual character (or fetches it from the cache).1702function measureCharPrepared(cm, prepared, ch, bias, varHeight) {1703if (prepared.before) ch = -1;1704var key = ch + (bias || ""), found;1705if (prepared.cache.hasOwnProperty(key)) {1706found = prepared.cache[key];1707} else {1708if (!prepared.rect)1709prepared.rect = prepared.view.text.getBoundingClientRect();1710if (!prepared.hasHeights) {1711ensureLineHeights(cm, prepared.view, prepared.rect);1712prepared.hasHeights = true;1713}1714found = measureCharInner(cm, prepared, ch, bias);1715if (!found.bogus) prepared.cache[key] = found;1716}1717return {left: found.left, right: found.right,1718top: varHeight ? found.rtop : found.top,1719bottom: varHeight ? found.rbottom : found.bottom};1720}17211722var nullRect = {left: 0, right: 0, top: 0, bottom: 0};17231724function measureCharInner(cm, prepared, ch, bias) {1725var map = prepared.map;17261727var node, start, end, collapse;1728// First, search the line map for the text node corresponding to,1729// or closest to, the target character.1730for (var i = 0; i < map.length; i += 3) {1731var mStart = map[i], mEnd = map[i + 1];1732if (ch < mStart) {1733start = 0; end = 1;1734collapse = "left";1735} else if (ch < mEnd) {1736start = ch - mStart;1737end = start + 1;1738} else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {1739end = mEnd - mStart;1740start = end - 1;1741if (ch >= mEnd) collapse = "right";1742}1743if (start != null) {1744node = map[i + 2];1745if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))1746collapse = bias;1747if (bias == "left" && start == 0)1748while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {1749node = map[(i -= 3) + 2];1750collapse = "left";1751}1752if (bias == "right" && start == mEnd - mStart)1753while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {1754node = map[(i += 3) + 2];1755collapse = "right";1756}1757break;1758}1759}17601761var rect;1762if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.1763for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned1764while (start && isExtendingChar(prepared.line.text.charAt(mStart + start))) --start;1765while (mStart + end < mEnd && isExtendingChar(prepared.line.text.charAt(mStart + end))) ++end;1766if (ie && ie_version < 9 && start == 0 && end == mEnd - mStart) {1767rect = node.parentNode.getBoundingClientRect();1768} else if (ie && cm.options.lineWrapping) {1769var rects = range(node, start, end).getClientRects();1770if (rects.length)1771rect = rects[bias == "right" ? rects.length - 1 : 0];1772else1773rect = nullRect;1774} else {1775rect = range(node, start, end).getBoundingClientRect() || nullRect;1776}1777if (rect.left || rect.right || start == 0) break;1778end = start;1779start = start - 1;1780collapse = "right";1781}1782if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);1783} else { // If it is a widget, simply get the box for the whole widget.1784if (start > 0) collapse = bias = "right";1785var rects;1786if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)1787rect = rects[bias == "right" ? rects.length - 1 : 0];1788else1789rect = node.getBoundingClientRect();1790}1791if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {1792var rSpan = node.parentNode.getClientRects()[0];1793if (rSpan)1794rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};1795else1796rect = nullRect;1797}17981799var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;1800var mid = (rtop + rbot) / 2;1801var heights = prepared.view.measure.heights;1802for (var i = 0; i < heights.length - 1; i++)1803if (mid < heights[i]) break;1804var top = i ? heights[i - 1] : 0, bot = heights[i];1805var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,1806right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,1807top: top, bottom: bot};1808if (!rect.left && !rect.right) result.bogus = true;1809if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }18101811return result;1812}18131814// Work around problem with bounding client rects on ranges being1815// returned incorrectly when zoomed on IE10 and below.1816function maybeUpdateRectForZooming(measure, rect) {1817if (!window.screen || screen.logicalXDPI == null ||1818screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))1819return rect;1820var scaleX = screen.logicalXDPI / screen.deviceXDPI;1821var scaleY = screen.logicalYDPI / screen.deviceYDPI;1822return {left: rect.left * scaleX, right: rect.right * scaleX,1823top: rect.top * scaleY, bottom: rect.bottom * scaleY};1824}18251826function clearLineMeasurementCacheFor(lineView) {1827if (lineView.measure) {1828lineView.measure.cache = {};1829lineView.measure.heights = null;1830if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)1831lineView.measure.caches[i] = {};1832}1833}18341835function clearLineMeasurementCache(cm) {1836cm.display.externalMeasure = null;1837removeChildren(cm.display.lineMeasure);1838for (var i = 0; i < cm.display.view.length; i++)1839clearLineMeasurementCacheFor(cm.display.view[i]);1840}18411842function clearCaches(cm) {1843clearLineMeasurementCache(cm);1844cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;1845if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;1846cm.display.lineNumChars = null;1847}18481849function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }1850function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }18511852// Converts a {top, bottom, left, right} box from line-local1853// coordinates into another coordinate system. Context may be one of1854// "line", "div" (display.lineDiv), "local"/null (editor), "window",1855// or "page".1856function intoCoordSystem(cm, lineObj, rect, context) {1857if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {1858var size = widgetHeight(lineObj.widgets[i]);1859rect.top += size; rect.bottom += size;1860}1861if (context == "line") return rect;1862if (!context) context = "local";1863var yOff = heightAtLine(lineObj);1864if (context == "local") yOff += paddingTop(cm.display);1865else yOff -= cm.display.viewOffset;1866if (context == "page" || context == "window") {1867var lOff = cm.display.lineSpace.getBoundingClientRect();1868yOff += lOff.top + (context == "window" ? 0 : pageScrollY());1869var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());1870rect.left += xOff; rect.right += xOff;1871}1872rect.top += yOff; rect.bottom += yOff;1873return rect;1874}18751876// Coverts a box from "div" coords to another coordinate system.1877// Context may be "window", "page", "div", or "local"/null.1878function fromCoordSystem(cm, coords, context) {1879if (context == "div") return coords;1880var left = coords.left, top = coords.top;1881// First move into "page" coordinate system1882if (context == "page") {1883left -= pageScrollX();1884top -= pageScrollY();1885} else if (context == "local" || !context) {1886var localBox = cm.display.sizer.getBoundingClientRect();1887left += localBox.left;1888top += localBox.top;1889}18901891var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();1892return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};1893}18941895function charCoords(cm, pos, context, lineObj, bias) {1896if (!lineObj) lineObj = getLine(cm.doc, pos.line);1897return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);1898}18991900// Returns a box for a given cursor position, which may have an1901// 'other' property containing the position of the secondary cursor1902// on a bidi boundary.1903function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {1904lineObj = lineObj || getLine(cm.doc, pos.line);1905if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);1906function get(ch, right) {1907var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);1908if (right) m.left = m.right; else m.right = m.left;1909return intoCoordSystem(cm, lineObj, m, context);1910}1911function getBidi(ch, partPos) {1912var part = order[partPos], right = part.level % 2;1913if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {1914part = order[--partPos];1915ch = bidiRight(part) - (part.level % 2 ? 0 : 1);1916right = true;1917} else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {1918part = order[++partPos];1919ch = bidiLeft(part) - part.level % 2;1920right = false;1921}1922if (right && ch == part.to && ch > part.from) return get(ch - 1);1923return get(ch, right);1924}1925var order = getOrder(lineObj), ch = pos.ch;1926if (!order) return get(ch);1927var partPos = getBidiPartAt(order, ch);1928var val = getBidi(ch, partPos);1929if (bidiOther != null) val.other = getBidi(ch, bidiOther);1930return val;1931}19321933// Used to cheaply estimate the coordinates for a position. Used for1934// intermediate scroll updates.1935function estimateCoords(cm, pos) {1936var left = 0, pos = clipPos(cm.doc, pos);1937if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;1938var lineObj = getLine(cm.doc, pos.line);1939var top = heightAtLine(lineObj) + paddingTop(cm.display);1940return {left: left, right: left, top: top, bottom: top + lineObj.height};1941}19421943// Positions returned by coordsChar contain some extra information.1944// xRel is the relative x position of the input coordinates compared1945// to the found position (so xRel > 0 means the coordinates are to1946// the right of the character position, for example). When outside1947// is true, that means the coordinates lie outside the line's1948// vertical range.1949function PosWithInfo(line, ch, outside, xRel) {1950var pos = Pos(line, ch);1951pos.xRel = xRel;1952if (outside) pos.outside = true;1953return pos;1954}19551956// Compute the character position closest to the given coordinates.1957// Input must be lineSpace-local ("div" coordinate system).1958function coordsChar(cm, x, y) {1959var doc = cm.doc;1960y += cm.display.viewOffset;1961if (y < 0) return PosWithInfo(doc.first, 0, true, -1);1962var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;1963if (lineN > last)1964return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);1965if (x < 0) x = 0;19661967var lineObj = getLine(doc, lineN);1968for (;;) {1969var found = coordsCharInner(cm, lineObj, lineN, x, y);1970var merged = collapsedSpanAtEnd(lineObj);1971var mergedPos = merged && merged.find(0, true);1972if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))1973lineN = lineNo(lineObj = mergedPos.to.line);1974else1975return found;1976}1977}19781979function coordsCharInner(cm, lineObj, lineNo, x, y) {1980var innerOff = y - heightAtLine(lineObj);1981var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;1982var preparedMeasure = prepareMeasureForLine(cm, lineObj);19831984function getX(ch) {1985var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);1986wrongLine = true;1987if (innerOff > sp.bottom) return sp.left - adjust;1988else if (innerOff < sp.top) return sp.left + adjust;1989else wrongLine = false;1990return sp.left;1991}19921993var bidi = getOrder(lineObj), dist = lineObj.text.length;1994var from = lineLeft(lineObj), to = lineRight(lineObj);1995var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;19961997if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);1998// Do a binary search between these bounds.1999for (;;) {2000if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {2001var ch = x < fromX || x - fromX <= toX - x ? from : to;2002var xDiff = x - (ch == from ? fromX : toX);2003while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;2004var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,2005xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);2006return pos;2007}2008var step = Math.ceil(dist / 2), middle = from + step;2009if (bidi) {2010middle = from;2011for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);2012}2013var middleX = getX(middle);2014if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}2015else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}2016}2017}20182019var measureText;2020// Compute the default text height.2021function textHeight(display) {2022if (display.cachedTextHeight != null) return display.cachedTextHeight;2023if (measureText == null) {2024measureText = elt("pre");2025// Measure a bunch of lines, for browsers that compute2026// fractional heights.2027for (var i = 0; i < 49; ++i) {2028measureText.appendChild(document.createTextNode("x"));2029measureText.appendChild(elt("br"));2030}2031measureText.appendChild(document.createTextNode("x"));2032}2033removeChildrenAndAdd(display.measure, measureText);2034var height = measureText.offsetHeight / 50;2035if (height > 3) display.cachedTextHeight = height;2036removeChildren(display.measure);2037return height || 1;2038}20392040// Compute the default character width.2041function charWidth(display) {2042if (display.cachedCharWidth != null) return display.cachedCharWidth;2043var anchor = elt("span", "xxxxxxxxxx");2044var pre = elt("pre", [anchor]);2045removeChildrenAndAdd(display.measure, pre);2046var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;2047if (width > 2) display.cachedCharWidth = width;2048return width || 10;2049}20502051// OPERATIONS20522053// Operations are used to wrap a series of changes to the editor2054// state in such a way that each change won't have to update the2055// cursor and display (which would be awkward, slow, and2056// error-prone). Instead, display updates are batched and then all2057// combined and executed at once.20582059var operationGroup = null;20602061var nextOpId = 0;2062// Start a new operation.2063function startOperation(cm) {2064cm.curOp = {2065cm: cm,2066viewChanged: false, // Flag that indicates that lines might need to be redrawn2067startHeight: cm.doc.height, // Used to detect need to update scrollbar2068forceUpdate: false, // Used to force a redraw2069updateInput: null, // Whether to reset the input textarea2070typing: false, // Whether this reset should be careful to leave existing text (for compositing)2071changeObjs: null, // Accumulated changes, for firing change events2072cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on2073cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already2074selectionChanged: false, // Whether the selection needs to be redrawn2075updateMaxLine: false, // Set when the widest line needs to be determined anew2076scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet2077scrollToPos: null, // Used to scroll to a specific position2078id: ++nextOpId // Unique ID2079};2080if (operationGroup) {2081operationGroup.ops.push(cm.curOp);2082} else {2083cm.curOp.ownsGroup = operationGroup = {2084ops: [cm.curOp],2085delayedCallbacks: []2086};2087}2088}20892090function fireCallbacksForOps(group) {2091// Calls delayed callbacks and cursorActivity handlers until no2092// new ones appear2093var callbacks = group.delayedCallbacks, i = 0;2094do {2095for (; i < callbacks.length; i++)2096callbacks[i]();2097for (var j = 0; j < group.ops.length; j++) {2098var op = group.ops[j];2099if (op.cursorActivityHandlers)2100while (op.cursorActivityCalled < op.cursorActivityHandlers.length)2101op.cursorActivityHandlers[op.cursorActivityCalled++](op.cm);2102}2103} while (i < callbacks.length);2104}21052106// Finish an operation, updating the display and signalling delayed events2107function endOperation(cm) {2108var op = cm.curOp, group = op.ownsGroup;2109if (!group) return;21102111try { fireCallbacksForOps(group); }2112finally {2113operationGroup = null;2114for (var i = 0; i < group.ops.length; i++)2115group.ops[i].cm.curOp = null;2116endOperations(group);2117}2118}21192120// The DOM updates done when an operation finishes are batched so2121// that the minimum number of relayouts are required.2122function endOperations(group) {2123var ops = group.ops;2124for (var i = 0; i < ops.length; i++) // Read DOM2125endOperation_R1(ops[i]);2126for (var i = 0; i < ops.length; i++) // Write DOM (maybe)2127endOperation_W1(ops[i]);2128for (var i = 0; i < ops.length; i++) // Read DOM2129endOperation_R2(ops[i]);2130for (var i = 0; i < ops.length; i++) // Write DOM (maybe)2131endOperation_W2(ops[i]);2132for (var i = 0; i < ops.length; i++) // Read DOM2133endOperation_finish(ops[i]);2134}21352136function endOperation_R1(op) {2137var cm = op.cm, display = cm.display;2138maybeClipScrollbars(cm);2139if (op.updateMaxLine) findMaxLine(cm);21402141op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||2142op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||2143op.scrollToPos.to.line >= display.viewTo) ||2144display.maxLineChanged && cm.options.lineWrapping;2145op.update = op.mustUpdate &&2146new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);2147}21482149function endOperation_W1(op) {2150op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);2151}21522153function endOperation_R2(op) {2154var cm = op.cm, display = cm.display;2155if (op.updatedDisplay) updateHeightsInViewport(cm);21562157op.barMeasure = measureForScrollbars(cm);21582159// If the max line changed since it was last measured, measure it,2160// and ensure the document's width matches it.2161// updateDisplay_W2 will use these properties to do the actual resizing2162if (display.maxLineChanged && !cm.options.lineWrapping) {2163op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;2164cm.display.sizerWidth = op.adjustWidthTo;2165op.barMeasure.scrollWidth =2166Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);2167op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));2168}21692170if (op.updatedDisplay || op.selectionChanged)2171op.newSelectionNodes = drawSelection(cm);2172}21732174function endOperation_W2(op) {2175var cm = op.cm;21762177if (op.adjustWidthTo != null) {2178cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";2179if (op.maxScrollLeft < cm.doc.scrollLeft)2180setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);2181cm.display.maxLineChanged = false;2182}21832184if (op.newSelectionNodes)2185showSelection(cm, op.newSelectionNodes);2186if (op.updatedDisplay)2187setDocumentHeight(cm, op.barMeasure);2188if (op.updatedDisplay || op.startHeight != cm.doc.height)2189updateScrollbars(cm, op.barMeasure);21902191if (op.selectionChanged) restartBlink(cm);21922193if (cm.state.focused && op.updateInput)2194resetInput(cm, op.typing);2195}21962197function endOperation_finish(op) {2198var cm = op.cm, display = cm.display, doc = cm.doc;21992200if (op.updatedDisplay) postUpdateDisplay(cm, op.update);22012202// Abort mouse wheel delta measurement, when scrolling explicitly2203if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))2204display.wheelStartX = display.wheelStartY = null;22052206// Propagate the scroll position to the actual DOM scroller2207if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {2208doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));2209display.scrollbars.setScrollTop(doc.scrollTop);2210display.scroller.scrollTop = doc.scrollTop;2211}2212if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {2213doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft));2214display.scrollbars.setScrollLeft(doc.scrollLeft);2215display.scroller.scrollLeft = doc.scrollLeft;2216alignHorizontally(cm);2217}2218// If we need to scroll a specific position into view, do so.2219if (op.scrollToPos) {2220var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),2221clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);2222if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);2223}22242225// Fire events for markers that are hidden/unidden by editing or2226// undoing2227var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;2228if (hidden) for (var i = 0; i < hidden.length; ++i)2229if (!hidden[i].lines.length) signal(hidden[i], "hide");2230if (unhidden) for (var i = 0; i < unhidden.length; ++i)2231if (unhidden[i].lines.length) signal(unhidden[i], "unhide");22322233if (display.wrapper.offsetHeight)2234doc.scrollTop = cm.display.scroller.scrollTop;22352236// Fire change events, and delayed event handlers2237if (op.changeObjs)2238signal(cm, "changes", cm, op.changeObjs);2239}22402241// Run the given function in an operation2242function runInOp(cm, f) {2243if (cm.curOp) return f();2244startOperation(cm);2245try { return f(); }2246finally { endOperation(cm); }2247}2248// Wraps a function in an operation. Returns the wrapped function.2249function operation(cm, f) {2250return function() {2251if (cm.curOp) return f.apply(cm, arguments);2252startOperation(cm);2253try { return f.apply(cm, arguments); }2254finally { endOperation(cm); }2255};2256}2257// Used to add methods to editor and doc instances, wrapping them in2258// operations.2259function methodOp(f) {2260return function() {2261if (this.curOp) return f.apply(this, arguments);2262startOperation(this);2263try { return f.apply(this, arguments); }2264finally { endOperation(this); }2265};2266}2267function docMethodOp(f) {2268return function() {2269var cm = this.cm;2270if (!cm || cm.curOp) return f.apply(this, arguments);2271startOperation(cm);2272try { return f.apply(this, arguments); }2273finally { endOperation(cm); }2274};2275}22762277// VIEW TRACKING22782279// These objects are used to represent the visible (currently drawn)2280// part of the document. A LineView may correspond to multiple2281// logical lines, if those are connected by collapsed ranges.2282function LineView(doc, line, lineN) {2283// The starting line2284this.line = line;2285// Continuing lines, if any2286this.rest = visualLineContinued(line);2287// Number of logical lines in this visual line2288this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;2289this.node = this.text = null;2290this.hidden = lineIsHidden(doc, line);2291}22922293// Create a range of LineView objects for the given lines.2294function buildViewArray(cm, from, to) {2295var array = [], nextPos;2296for (var pos = from; pos < to; pos = nextPos) {2297var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);2298nextPos = pos + view.size;2299array.push(view);2300}2301return array;2302}23032304// Updates the display.view data structure for a given change to the2305// document. From and to are in pre-change coordinates. Lendiff is2306// the amount of lines added or subtracted by the change. This is2307// used for changes that span multiple lines, or change the way2308// lines are divided into visual lines. regLineChange (below)2309// registers single-line changes.2310function regChange(cm, from, to, lendiff) {2311if (from == null) from = cm.doc.first;2312if (to == null) to = cm.doc.first + cm.doc.size;2313if (!lendiff) lendiff = 0;23142315var display = cm.display;2316if (lendiff && to < display.viewTo &&2317(display.updateLineNumbers == null || display.updateLineNumbers > from))2318display.updateLineNumbers = from;23192320cm.curOp.viewChanged = true;23212322if (from >= display.viewTo) { // Change after2323if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)2324resetView(cm);2325} else if (to <= display.viewFrom) { // Change before2326if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {2327resetView(cm);2328} else {2329display.viewFrom += lendiff;2330display.viewTo += lendiff;2331}2332} else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap2333resetView(cm);2334} else if (from <= display.viewFrom) { // Top overlap2335var cut = viewCuttingPoint(cm, to, to + lendiff, 1);2336if (cut) {2337display.view = display.view.slice(cut.index);2338display.viewFrom = cut.lineN;2339display.viewTo += lendiff;2340} else {2341resetView(cm);2342}2343} else if (to >= display.viewTo) { // Bottom overlap2344var cut = viewCuttingPoint(cm, from, from, -1);2345if (cut) {2346display.view = display.view.slice(0, cut.index);2347display.viewTo = cut.lineN;2348} else {2349resetView(cm);2350}2351} else { // Gap in the middle2352var cutTop = viewCuttingPoint(cm, from, from, -1);2353var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);2354if (cutTop && cutBot) {2355display.view = display.view.slice(0, cutTop.index)2356.concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))2357.concat(display.view.slice(cutBot.index));2358display.viewTo += lendiff;2359} else {2360resetView(cm);2361}2362}23632364var ext = display.externalMeasured;2365if (ext) {2366if (to < ext.lineN)2367ext.lineN += lendiff;2368else if (from < ext.lineN + ext.size)2369display.externalMeasured = null;2370}2371}23722373// Register a change to a single line. Type must be one of "text",2374// "gutter", "class", "widget"2375function regLineChange(cm, line, type) {2376cm.curOp.viewChanged = true;2377var display = cm.display, ext = cm.display.externalMeasured;2378if (ext && line >= ext.lineN && line < ext.lineN + ext.size)2379display.externalMeasured = null;23802381if (line < display.viewFrom || line >= display.viewTo) return;2382var lineView = display.view[findViewIndex(cm, line)];2383if (lineView.node == null) return;2384var arr = lineView.changes || (lineView.changes = []);2385if (indexOf(arr, type) == -1) arr.push(type);2386}23872388// Clear the view.2389function resetView(cm) {2390cm.display.viewFrom = cm.display.viewTo = cm.doc.first;2391cm.display.view = [];2392cm.display.viewOffset = 0;2393}23942395// Find the view element corresponding to a given line. Return null2396// when the line isn't visible.2397function findViewIndex(cm, n) {2398if (n >= cm.display.viewTo) return null;2399n -= cm.display.viewFrom;2400if (n < 0) return null;2401var view = cm.display.view;2402for (var i = 0; i < view.length; i++) {2403n -= view[i].size;2404if (n < 0) return i;2405}2406}24072408function viewCuttingPoint(cm, oldN, newN, dir) {2409var index = findViewIndex(cm, oldN), diff, view = cm.display.view;2410if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)2411return {index: index, lineN: newN};2412for (var i = 0, n = cm.display.viewFrom; i < index; i++)2413n += view[i].size;2414if (n != oldN) {2415if (dir > 0) {2416if (index == view.length - 1) return null;2417diff = (n + view[index].size) - oldN;2418index++;2419} else {2420diff = n - oldN;2421}2422oldN += diff; newN += diff;2423}2424while (visualLineNo(cm.doc, newN) != newN) {2425if (index == (dir < 0 ? 0 : view.length - 1)) return null;2426newN += dir * view[index - (dir < 0 ? 1 : 0)].size;2427index += dir;2428}2429return {index: index, lineN: newN};2430}24312432// Force the view to cover a given range, adding empty view element2433// or clipping off existing ones as needed.2434function adjustView(cm, from, to) {2435var display = cm.display, view = display.view;2436if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {2437display.view = buildViewArray(cm, from, to);2438display.viewFrom = from;2439} else {2440if (display.viewFrom > from)2441display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);2442else if (display.viewFrom < from)2443display.view = display.view.slice(findViewIndex(cm, from));2444display.viewFrom = from;2445if (display.viewTo < to)2446display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));2447else if (display.viewTo > to)2448display.view = display.view.slice(0, findViewIndex(cm, to));2449}2450display.viewTo = to;2451}24522453// Count the number of lines in the view whose DOM representation is2454// out of date (or nonexistent).2455function countDirtyView(cm) {2456var view = cm.display.view, dirty = 0;2457for (var i = 0; i < view.length; i++) {2458var lineView = view[i];2459if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;2460}2461return dirty;2462}24632464// INPUT HANDLING24652466// Poll for input changes, using the normal rate of polling. This2467// runs as long as the editor is focused.2468function slowPoll(cm) {2469if (cm.display.pollingFast) return;2470cm.display.poll.set(cm.options.pollInterval, function() {2471readInput(cm);2472if (cm.state.focused) slowPoll(cm);2473});2474}24752476// When an event has just come in that is likely to add or change2477// something in the input textarea, we poll faster, to ensure that2478// the change appears on the screen quickly.2479function fastPoll(cm) {2480var missed = false;2481cm.display.pollingFast = true;2482function p() {2483var changed = readInput(cm);2484if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}2485else {cm.display.pollingFast = false; slowPoll(cm);}2486}2487cm.display.poll.set(20, p);2488}24892490// This will be set to an array of strings when copying, so that,2491// when pasting, we know what kind of selections the copied text2492// was made out of.2493var lastCopied = null;24942495// Read input from the textarea, and update the document to match.2496// When something is selected, it is present in the textarea, and2497// selected (unless it is huge, in which case a placeholder is2498// used). When nothing is selected, the cursor sits after previously2499// seen text (can be empty), which is stored in prevInput (we must2500// not reset the textarea when typing, because that breaks IME).2501function readInput(cm) {2502var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc;2503// Since this is called a *lot*, try to bail out as cheaply as2504// possible when it is clear that nothing happened. hasSelection2505// will be the case when there is a lot of text in the textarea,2506// in which case reading its value would be expensive.2507if (!cm.state.focused || (hasSelection(input) && !prevInput) || isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq)2508return false;2509// See paste handler for more on the fakedLastChar kludge2510if (cm.state.pasteIncoming && cm.state.fakedLastChar) {2511input.value = input.value.substring(0, input.value.length - 1);2512cm.state.fakedLastChar = false;2513}2514var text = input.value;2515// If nothing changed, bail.2516if (text == prevInput && !cm.somethingSelected()) return false;2517// Work around nonsensical selection resetting in IE9/10, and2518// inexplicable appearance of private area unicode characters on2519// some key combos in Mac (#2689).2520if (ie && ie_version >= 9 && cm.display.inputHasSelection === text ||2521mac && /[\uf700-\uf7ff]/.test(text)) {2522resetInput(cm);2523return false;2524}25252526var withOp = !cm.curOp;2527if (withOp) startOperation(cm);2528cm.display.shift = false;25292530if (text.charCodeAt(0) == 0x200b && doc.sel == cm.display.selForContextMenu && !prevInput)2531prevInput = "\u200b";2532// Find the part of the input that is actually new2533var same = 0, l = Math.min(prevInput.length, text.length);2534while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;2535var inserted = text.slice(same), textLines = splitLines(inserted);25362537// When pasing N lines into N selections, insert one line per selection2538var multiPaste = null;2539if (cm.state.pasteIncoming && doc.sel.ranges.length > 1) {2540if (lastCopied && lastCopied.join("\n") == inserted)2541multiPaste = doc.sel.ranges.length % lastCopied.length == 0 && map(lastCopied, splitLines);2542else if (textLines.length == doc.sel.ranges.length)2543multiPaste = map(textLines, function(l) { return [l]; });2544}25452546// Normal behavior is to insert the new text into every selection2547for (var i = doc.sel.ranges.length - 1; i >= 0; i--) {2548var range = doc.sel.ranges[i];2549var from = range.from(), to = range.to();2550// Handle deletion2551if (same < prevInput.length)2552from = Pos(from.line, from.ch - (prevInput.length - same));2553// Handle overwrite2554else if (cm.state.overwrite && range.empty() && !cm.state.pasteIncoming)2555to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));2556var updateInput = cm.curOp.updateInput;2557var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,2558origin: cm.state.pasteIncoming ? "paste" : cm.state.cutIncoming ? "cut" : "+input"};2559makeChange(cm.doc, changeEvent);2560signalLater(cm, "inputRead", cm, changeEvent);2561// When an 'electric' character is inserted, immediately trigger a reindent2562if (inserted && !cm.state.pasteIncoming && cm.options.electricChars &&2563cm.options.smartIndent && range.head.ch < 100 &&2564(!i || doc.sel.ranges[i - 1].head.line != range.head.line)) {2565var mode = cm.getModeAt(range.head);2566var end = changeEnd(changeEvent);2567if (mode.electricChars) {2568for (var j = 0; j < mode.electricChars.length; j++)2569if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {2570indentLine(cm, end.line, "smart");2571break;2572}2573} else if (mode.electricInput) {2574if (mode.electricInput.test(getLine(doc, end.line).text.slice(0, end.ch)))2575indentLine(cm, end.line, "smart");2576}2577}2578}2579ensureCursorVisible(cm);2580cm.curOp.updateInput = updateInput;2581cm.curOp.typing = true;25822583// Don't leave long text in the textarea, since it makes further polling slow2584if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = "";2585else cm.display.prevInput = text;2586if (withOp) endOperation(cm);2587cm.state.pasteIncoming = cm.state.cutIncoming = false;2588return true;2589}25902591// Reset the input to correspond to the selection (or to be empty,2592// when not typing and nothing is selected)2593function resetInput(cm, typing) {2594if (cm.display.contextMenuPending) return;2595var minimal, selected, doc = cm.doc;2596if (cm.somethingSelected()) {2597cm.display.prevInput = "";2598var range = doc.sel.primary();2599minimal = hasCopyEvent &&2600(range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);2601var content = minimal ? "-" : selected || cm.getSelection();2602cm.display.input.value = content;2603if (cm.state.focused) selectInput(cm.display.input);2604if (ie && ie_version >= 9) cm.display.inputHasSelection = content;2605} else if (!typing) {2606cm.display.prevInput = cm.display.input.value = "";2607if (ie && ie_version >= 9) cm.display.inputHasSelection = null;2608}2609cm.display.inaccurateSelection = minimal;2610}26112612function focusInput(cm) {2613if (cm.options.readOnly != "nocursor" && (!mobile || activeElt() != cm.display.input))2614cm.display.input.focus();2615}26162617function ensureFocus(cm) {2618if (!cm.state.focused) { focusInput(cm); onFocus(cm); }2619}26202621function isReadOnly(cm) {2622return cm.options.readOnly || cm.doc.cantEdit;2623}26242625// EVENT HANDLERS26262627// Attach the necessary event handlers when initializing the editor2628function registerEventHandlers(cm) {2629var d = cm.display;2630on(d.scroller, "mousedown", operation(cm, onMouseDown));2631// Older IE's will not fire a second mousedown for a double click2632if (ie && ie_version < 11)2633on(d.scroller, "dblclick", operation(cm, function(e) {2634if (signalDOMEvent(cm, e)) return;2635var pos = posFromMouse(cm, e);2636if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;2637e_preventDefault(e);2638var word = cm.findWordAt(pos);2639extendSelection(cm.doc, word.anchor, word.head);2640}));2641else2642on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });2643// Prevent normal selection in the editor (we handle our own)2644on(d.lineSpace, "selectstart", function(e) {2645if (!eventInWidget(d, e)) e_preventDefault(e);2646});2647// Some browsers fire contextmenu *after* opening the menu, at2648// which point we can't mess with it anymore. Context menu is2649// handled in onMouseDown for these browsers.2650if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});26512652// Sync scrolling between fake scrollbars and real scrollable2653// area, ensure viewport is updated when scrolling.2654on(d.scroller, "scroll", function() {2655if (d.scroller.clientHeight) {2656setScrollTop(cm, d.scroller.scrollTop);2657setScrollLeft(cm, d.scroller.scrollLeft, true);2658signal(cm, "scroll", cm);2659}2660});26612662// Listen to wheel events in order to try and update the viewport on time.2663on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});2664on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});26652666// Prevent wrapper from ever scrolling2667on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });26682669on(d.input, "keyup", function(e) { onKeyUp.call(cm, e); });2670on(d.input, "input", function() {2671if (ie && ie_version >= 9 && cm.display.inputHasSelection) cm.display.inputHasSelection = null;2672readInput(cm);2673});2674on(d.input, "keydown", operation(cm, onKeyDown));2675on(d.input, "keypress", operation(cm, onKeyPress));2676on(d.input, "focus", bind(onFocus, cm));2677on(d.input, "blur", bind(onBlur, cm));26782679function drag_(e) {2680if (!signalDOMEvent(cm, e)) e_stop(e);2681}2682if (cm.options.dragDrop) {2683on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});2684on(d.scroller, "dragenter", drag_);2685on(d.scroller, "dragover", drag_);2686on(d.scroller, "drop", operation(cm, onDrop));2687}2688on(d.scroller, "paste", function(e) {2689if (eventInWidget(d, e)) return;2690cm.state.pasteIncoming = true;2691focusInput(cm);2692fastPoll(cm);2693});2694on(d.input, "paste", function() {2695// Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=902062696// Add a char to the end of textarea before paste occur so that2697// selection doesn't span to the end of textarea.2698if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) {2699var start = d.input.selectionStart, end = d.input.selectionEnd;2700d.input.value += "$";2701// The selection end needs to be set before the start, otherwise there2702// can be an intermediate non-empty selection between the two, which2703// can override the middle-click paste buffer on linux and cause the2704// wrong thing to get pasted.2705d.input.selectionEnd = end;2706d.input.selectionStart = start;2707cm.state.fakedLastChar = true;2708}2709cm.state.pasteIncoming = true;2710fastPoll(cm);2711});27122713function prepareCopyCut(e) {2714if (cm.somethingSelected()) {2715lastCopied = cm.getSelections();2716if (d.inaccurateSelection) {2717d.prevInput = "";2718d.inaccurateSelection = false;2719d.input.value = lastCopied.join("\n");2720selectInput(d.input);2721}2722} else {2723var text = [], ranges = [];2724for (var i = 0; i < cm.doc.sel.ranges.length; i++) {2725var line = cm.doc.sel.ranges[i].head.line;2726var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};2727ranges.push(lineRange);2728text.push(cm.getRange(lineRange.anchor, lineRange.head));2729}2730if (e.type == "cut") {2731cm.setSelections(ranges, null, sel_dontScroll);2732} else {2733d.prevInput = "";2734d.input.value = text.join("\n");2735selectInput(d.input);2736}2737lastCopied = text;2738}2739if (e.type == "cut") cm.state.cutIncoming = true;2740}2741on(d.input, "cut", prepareCopyCut);2742on(d.input, "copy", prepareCopyCut);27432744// Needed to handle Tab key in KHTML2745if (khtml) on(d.sizer, "mouseup", function() {2746if (activeElt() == d.input) d.input.blur();2747focusInput(cm);2748});2749}27502751// Called when the window resizes2752function onResize(cm) {2753var d = cm.display;2754if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)2755return;2756// Might be a text scaling operation, clear size caches.2757d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;2758d.scrollbarsClipped = false;2759cm.setSize();2760}27612762// MOUSE EVENTS27632764// Return true when the given mouse event happened in a widget2765function eventInWidget(display, e) {2766for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {2767if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||2768(n.parentNode == display.sizer && n != display.mover))2769return true;2770}2771}27722773// Given a mouse event, find the corresponding position. If liberal2774// is false, it checks whether a gutter or scrollbar was clicked,2775// and returns null if it was. forRect is used by rectangular2776// selections, and tries to estimate a character position even for2777// coordinates beyond the right of the text.2778function posFromMouse(cm, e, liberal, forRect) {2779var display = cm.display;2780if (!liberal && e_target(e).getAttribute("not-content") == "true") return null;27812782var x, y, space = display.lineSpace.getBoundingClientRect();2783// Fails unpredictably on IE[67] when mouse is dragged around quickly.2784try { x = e.clientX - space.left; y = e.clientY - space.top; }2785catch (e) { return null; }2786var coords = coordsChar(cm, x, y), line;2787if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {2788var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;2789coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));2790}2791return coords;2792}27932794// A mouse down can be a single click, double click, triple click,2795// start of selection drag, start of text drag, new cursor2796// (ctrl-click), rectangle drag (alt-drag), or xwin2797// middle-click-paste. Or it might be a click on something we should2798// not interfere with, such as a scrollbar or widget.2799function onMouseDown(e) {2800if (signalDOMEvent(this, e)) return;2801var cm = this, display = cm.display;2802display.shift = e.shiftKey;28032804if (eventInWidget(display, e)) {2805if (!webkit) {2806// Briefly turn off draggability, to allow widgets to do2807// normal dragging things.2808display.scroller.draggable = false;2809setTimeout(function(){display.scroller.draggable = true;}, 100);2810}2811return;2812}2813if (clickInGutter(cm, e)) return;2814var start = posFromMouse(cm, e);2815window.focus();28162817switch (e_button(e)) {2818case 1:2819if (start)2820leftButtonDown(cm, e, start);2821else if (e_target(e) == display.scroller)2822e_preventDefault(e);2823break;2824case 2:2825if (webkit) cm.state.lastMiddleDown = +new Date;2826if (start) extendSelection(cm.doc, start);2827setTimeout(bind(focusInput, cm), 20);2828e_preventDefault(e);2829break;2830case 3:2831if (captureRightClick) onContextMenu(cm, e);2832break;2833}2834}28352836var lastClick, lastDoubleClick;2837function leftButtonDown(cm, e, start) {2838setTimeout(bind(ensureFocus, cm), 0);28392840var now = +new Date, type;2841if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {2842type = "triple";2843} else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {2844type = "double";2845lastDoubleClick = {time: now, pos: start};2846} else {2847type = "single";2848lastClick = {time: now, pos: start};2849}28502851var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;2852if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) &&2853type == "single" && (contained = sel.contains(start)) > -1 &&2854!sel.ranges[contained].empty())2855leftButtonStartDrag(cm, e, start, modifier);2856else2857leftButtonSelect(cm, e, start, type, modifier);2858}28592860// Start a text drag. When it ends, see if any dragging actually2861// happen, and treat as a click if it didn't.2862function leftButtonStartDrag(cm, e, start, modifier) {2863var display = cm.display;2864var dragEnd = operation(cm, function(e2) {2865if (webkit) display.scroller.draggable = false;2866cm.state.draggingText = false;2867off(document, "mouseup", dragEnd);2868off(display.scroller, "drop", dragEnd);2869if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {2870e_preventDefault(e2);2871if (!modifier)2872extendSelection(cm.doc, start);2873focusInput(cm);2874// Work around unexplainable focus problem in IE9 (#2127)2875if (ie && ie_version == 9)2876setTimeout(function() {document.body.focus(); focusInput(cm);}, 20);2877}2878});2879// Let the drag handler handle this.2880if (webkit) display.scroller.draggable = true;2881cm.state.draggingText = dragEnd;2882// IE's approach to draggable2883if (display.scroller.dragDrop) display.scroller.dragDrop();2884on(document, "mouseup", dragEnd);2885on(display.scroller, "drop", dragEnd);2886}28872888// Normal selection, as opposed to text dragging.2889function leftButtonSelect(cm, e, start, type, addNew) {2890var display = cm.display, doc = cm.doc;2891e_preventDefault(e);28922893var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;2894if (addNew && !e.shiftKey) {2895ourIndex = doc.sel.contains(start);2896if (ourIndex > -1)2897ourRange = ranges[ourIndex];2898else2899ourRange = new Range(start, start);2900} else {2901ourRange = doc.sel.primary();2902}29032904if (e.altKey) {2905type = "rect";2906if (!addNew) ourRange = new Range(start, start);2907start = posFromMouse(cm, e, true, true);2908ourIndex = -1;2909} else if (type == "double") {2910var word = cm.findWordAt(start);2911if (cm.display.shift || doc.extend)2912ourRange = extendRange(doc, ourRange, word.anchor, word.head);2913else2914ourRange = word;2915} else if (type == "triple") {2916var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));2917if (cm.display.shift || doc.extend)2918ourRange = extendRange(doc, ourRange, line.anchor, line.head);2919else2920ourRange = line;2921} else {2922ourRange = extendRange(doc, ourRange, start);2923}29242925if (!addNew) {2926ourIndex = 0;2927setSelection(doc, new Selection([ourRange], 0), sel_mouse);2928startSel = doc.sel;2929} else if (ourIndex == -1) {2930ourIndex = ranges.length;2931setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),2932{scroll: false, origin: "*mouse"});2933} else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single") {2934setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0));2935startSel = doc.sel;2936} else {2937replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);2938}29392940var lastPos = start;2941function extendTo(pos) {2942if (cmp(lastPos, pos) == 0) return;2943lastPos = pos;29442945if (type == "rect") {2946var ranges = [], tabSize = cm.options.tabSize;2947var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);2948var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);2949var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);2950for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));2951line <= end; line++) {2952var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);2953if (left == right)2954ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));2955else if (text.length > leftPos)2956ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));2957}2958if (!ranges.length) ranges.push(new Range(start, start));2959setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),2960{origin: "*mouse", scroll: false});2961cm.scrollIntoView(pos);2962} else {2963var oldRange = ourRange;2964var anchor = oldRange.anchor, head = pos;2965if (type != "single") {2966if (type == "double")2967var range = cm.findWordAt(pos);2968else2969var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));2970if (cmp(range.anchor, anchor) > 0) {2971head = range.head;2972anchor = minPos(oldRange.from(), range.anchor);2973} else {2974head = range.anchor;2975anchor = maxPos(oldRange.to(), range.head);2976}2977}2978var ranges = startSel.ranges.slice(0);2979ranges[ourIndex] = new Range(clipPos(doc, anchor), head);2980setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);2981}2982}29832984var editorSize = display.wrapper.getBoundingClientRect();2985// Used to ensure timeout re-tries don't fire when another extend2986// happened in the meantime (clearTimeout isn't reliable -- at2987// least on Chrome, the timeouts still happen even when cleared,2988// if the clear happens after their scheduled firing time).2989var counter = 0;29902991function extend(e) {2992var curCount = ++counter;2993var cur = posFromMouse(cm, e, true, type == "rect");2994if (!cur) return;2995if (cmp(cur, lastPos) != 0) {2996ensureFocus(cm);2997extendTo(cur);2998var visible = visibleLines(display, doc);2999if (cur.line >= visible.to || cur.line < visible.from)3000setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);3001} else {3002var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;3003if (outside) setTimeout(operation(cm, function() {3004if (counter != curCount) return;3005display.scroller.scrollTop += outside;3006extend(e);3007}), 50);3008}3009}30103011function done(e) {3012counter = Infinity;3013e_preventDefault(e);3014focusInput(cm);3015off(document, "mousemove", move);3016off(document, "mouseup", up);3017doc.history.lastSelOrigin = null;3018}30193020var move = operation(cm, function(e) {3021if (!e_button(e)) done(e);3022else extend(e);3023});3024var up = operation(cm, done);3025on(document, "mousemove", move);3026on(document, "mouseup", up);3027}30283029// Determines whether an event happened in the gutter, and fires the3030// handlers for the corresponding event.3031function gutterEvent(cm, e, type, prevent, signalfn) {3032try { var mX = e.clientX, mY = e.clientY; }3033catch(e) { return false; }3034if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;3035if (prevent) e_preventDefault(e);30363037var display = cm.display;3038var lineBox = display.lineDiv.getBoundingClientRect();30393040if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);3041mY -= lineBox.top - display.viewOffset;30423043for (var i = 0; i < cm.options.gutters.length; ++i) {3044var g = display.gutters.childNodes[i];3045if (g && g.getBoundingClientRect().right >= mX) {3046var line = lineAtHeight(cm.doc, mY);3047var gutter = cm.options.gutters[i];3048signalfn(cm, type, cm, line, gutter, e);3049return e_defaultPrevented(e);3050}3051}3052}30533054function clickInGutter(cm, e) {3055return gutterEvent(cm, e, "gutterClick", true, signalLater);3056}30573058// Kludge to work around strange IE behavior where it'll sometimes3059// re-fire a series of drag-related events right after the drop (#1551)3060var lastDrop = 0;30613062function onDrop(e) {3063var cm = this;3064if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))3065return;3066e_preventDefault(e);3067if (ie) lastDrop = +new Date;3068var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;3069if (!pos || isReadOnly(cm)) return;3070// Might be a file drop, in which case we simply extract the text3071// and insert it.3072if (files && files.length && window.FileReader && window.File) {3073var n = files.length, text = Array(n), read = 0;3074var loadFile = function(file, i) {3075var reader = new FileReader;3076reader.onload = operation(cm, function() {3077text[i] = reader.result;3078if (++read == n) {3079pos = clipPos(cm.doc, pos);3080var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"};3081makeChange(cm.doc, change);3082setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));3083}3084});3085reader.readAsText(file);3086};3087for (var i = 0; i < n; ++i) loadFile(files[i], i);3088} else { // Normal drop3089// Don't do a replace if the drop happened inside of the selected text.3090if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {3091cm.state.draggingText(e);3092// Ensure the editor is re-focused3093setTimeout(bind(focusInput, cm), 20);3094return;3095}3096try {3097var text = e.dataTransfer.getData("Text");3098if (text) {3099if (cm.state.draggingText && !(mac ? e.metaKey : e.ctrlKey))3100var selected = cm.listSelections();3101setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));3102if (selected) for (var i = 0; i < selected.length; ++i)3103replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");3104cm.replaceSelection(text, "around", "paste");3105focusInput(cm);3106}3107}3108catch(e){}3109}3110}31113112function onDragStart(cm, e) {3113if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }3114if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;31153116e.dataTransfer.setData("Text", cm.getSelection());31173118// Use dummy image instead of default browsers image.3119// Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.3120if (e.dataTransfer.setDragImage && !safari) {3121var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");3122img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";3123if (presto) {3124img.width = img.height = 1;3125cm.display.wrapper.appendChild(img);3126// Force a relayout, or Opera won't use our image for some obscure reason3127img._top = img.offsetTop;3128}3129e.dataTransfer.setDragImage(img, 0, 0);3130if (presto) img.parentNode.removeChild(img);3131}3132}31333134// SCROLL EVENTS31353136// Sync the scrollable area and scrollbars, ensure the viewport3137// covers the visible area.3138function setScrollTop(cm, val) {3139if (Math.abs(cm.doc.scrollTop - val) < 2) return;3140cm.doc.scrollTop = val;3141if (!gecko) updateDisplaySimple(cm, {top: val});3142if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;3143cm.display.scrollbars.setScrollTop(val);3144if (gecko) updateDisplaySimple(cm);3145startWorker(cm, 100);3146}3147// Sync scroller and scrollbar, ensure the gutter elements are3148// aligned.3149function setScrollLeft(cm, val, isScroller) {3150if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;3151val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);3152cm.doc.scrollLeft = val;3153alignHorizontally(cm);3154if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;3155cm.display.scrollbars.setScrollLeft(val);3156}31573158// Since the delta values reported on mouse wheel events are3159// unstandardized between browsers and even browser versions, and3160// generally horribly unpredictable, this code starts by measuring3161// the scroll effect that the first few mouse wheel events have,3162// and, from that, detects the way it can convert deltas to pixel3163// offsets afterwards.3164//3165// The reason we want to know the amount a wheel event will scroll3166// is that it gives us a chance to update the display before the3167// actual scrolling happens, reducing flickering.31683169var wheelSamples = 0, wheelPixelsPerUnit = null;3170// Fill in a browser-detected starting value on browsers where we3171// know one. These don't have to be accurate -- the result of them3172// being wrong would just be a slight flicker on the first wheel3173// scroll (if it is large enough).3174if (ie) wheelPixelsPerUnit = -.53;3175else if (gecko) wheelPixelsPerUnit = 15;3176else if (chrome) wheelPixelsPerUnit = -.7;3177else if (safari) wheelPixelsPerUnit = -1/3;31783179var wheelEventDelta = function(e) {3180var dx = e.wheelDeltaX, dy = e.wheelDeltaY;3181if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;3182if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;3183else if (dy == null) dy = e.wheelDelta;3184return {x: dx, y: dy};3185};3186CodeMirror.wheelEventPixels = function(e) {3187var delta = wheelEventDelta(e);3188delta.x *= wheelPixelsPerUnit;3189delta.y *= wheelPixelsPerUnit;3190return delta;3191};31923193function onScrollWheel(cm, e) {3194var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;31953196var display = cm.display, scroll = display.scroller;3197// Quit if there's nothing to scroll here3198if (!(dx && scroll.scrollWidth > scroll.clientWidth ||3199dy && scroll.scrollHeight > scroll.clientHeight)) return;32003201// Webkit browsers on OS X abort momentum scrolls when the target3202// of the scroll event is removed from the scrollable element.3203// This hack (see related code in patchDisplay) makes sure the3204// element is kept around.3205if (dy && mac && webkit) {3206outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {3207for (var i = 0; i < view.length; i++) {3208if (view[i].node == cur) {3209cm.display.currentWheelTarget = cur;3210break outer;3211}3212}3213}3214}32153216// On some browsers, horizontal scrolling will cause redraws to3217// happen before the gutter has been realigned, causing it to3218// wriggle around in a most unseemly way. When we have an3219// estimated pixels/delta value, we just handle horizontal3220// scrolling entirely here. It'll be slightly off from native, but3221// better than glitching out.3222if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {3223if (dy)3224setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));3225setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));3226e_preventDefault(e);3227display.wheelStartX = null; // Abort measurement, if in progress3228return;3229}32303231// 'Project' the visible viewport to cover the area that is being3232// scrolled into view (if we know enough to estimate it).3233if (dy && wheelPixelsPerUnit != null) {3234var pixels = dy * wheelPixelsPerUnit;3235var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;3236if (pixels < 0) top = Math.max(0, top + pixels - 50);3237else bot = Math.min(cm.doc.height, bot + pixels + 50);3238updateDisplaySimple(cm, {top: top, bottom: bot});3239}32403241if (wheelSamples < 20) {3242if (display.wheelStartX == null) {3243display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;3244display.wheelDX = dx; display.wheelDY = dy;3245setTimeout(function() {3246if (display.wheelStartX == null) return;3247var movedX = scroll.scrollLeft - display.wheelStartX;3248var movedY = scroll.scrollTop - display.wheelStartY;3249var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||3250(movedX && display.wheelDX && movedX / display.wheelDX);3251display.wheelStartX = display.wheelStartY = null;3252if (!sample) return;3253wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);3254++wheelSamples;3255}, 200);3256} else {3257display.wheelDX += dx; display.wheelDY += dy;3258}3259}3260}32613262// KEY EVENTS32633264// Run a handler that was bound to a key.3265function doHandleBinding(cm, bound, dropShift) {3266if (typeof bound == "string") {3267bound = commands[bound];3268if (!bound) return false;3269}3270// Ensure previous input has been read, so that the handler sees a3271// consistent view of the document3272if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;3273var prevShift = cm.display.shift, done = false;3274try {3275if (isReadOnly(cm)) cm.state.suppressEdits = true;3276if (dropShift) cm.display.shift = false;3277done = bound(cm) != Pass;3278} finally {3279cm.display.shift = prevShift;3280cm.state.suppressEdits = false;3281}3282return done;3283}32843285function lookupKeyForEditor(cm, name, handle) {3286for (var i = 0; i < cm.state.keyMaps.length; i++) {3287var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);3288if (result) return result;3289}3290return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))3291|| lookupKey(name, cm.options.keyMap, handle, cm);3292}32933294var stopSeq = new Delayed;3295function dispatchKey(cm, name, e, handle) {3296var seq = cm.state.keySeq;3297if (seq) {3298if (isModifierKey(name)) return "handled";3299stopSeq.set(50, function() {3300if (cm.state.keySeq == seq) {3301cm.state.keySeq = null;3302resetInput(cm);3303}3304});3305name = seq + " " + name;3306}3307var result = lookupKeyForEditor(cm, name, handle);33083309if (result == "multi")3310cm.state.keySeq = name;3311if (result == "handled")3312signalLater(cm, "keyHandled", cm, name, e);33133314if (result == "handled" || result == "multi") {3315e_preventDefault(e);3316restartBlink(cm);3317}33183319if (seq && !result && /\'$/.test(name)) {3320e_preventDefault(e);3321return true;3322}3323return !!result;3324}33253326// Handle a key from the keydown event.3327function handleKeyBinding(cm, e) {3328var name = keyName(e, true);3329if (!name) return false;33303331if (e.shiftKey && !cm.state.keySeq) {3332// First try to resolve full name (including 'Shift-'). Failing3333// that, see if there is a cursor-motion command (starting with3334// 'go') bound to the keyname without 'Shift-'.3335return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})3336|| dispatchKey(cm, name, e, function(b) {3337if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)3338return doHandleBinding(cm, b);3339});3340} else {3341return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });3342}3343}33443345// Handle a key from the keypress event3346function handleCharBinding(cm, e, ch) {3347return dispatchKey(cm, "'" + ch + "'", e,3348function(b) { return doHandleBinding(cm, b, true); });3349}33503351var lastStoppedKey = null;3352function onKeyDown(e) {3353var cm = this;3354ensureFocus(cm);3355if (signalDOMEvent(cm, e)) return;3356// IE does strange things with escape.3357if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;3358var code = e.keyCode;3359cm.display.shift = code == 16 || e.shiftKey;3360var handled = handleKeyBinding(cm, e);3361if (presto) {3362lastStoppedKey = handled ? code : null;3363// Opera has no cut event... we try to at least catch the key combo3364if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))3365cm.replaceSelection("", null, "cut");3366}33673368// Turn mouse into crosshair when Alt is held on Mac.3369if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))3370showCrossHair(cm);3371}33723373function showCrossHair(cm) {3374var lineDiv = cm.display.lineDiv;3375addClass(lineDiv, "CodeMirror-crosshair");33763377function up(e) {3378if (e.keyCode == 18 || !e.altKey) {3379rmClass(lineDiv, "CodeMirror-crosshair");3380off(document, "keyup", up);3381off(document, "mouseover", up);3382}3383}3384on(document, "keyup", up);3385on(document, "mouseover", up);3386}33873388function onKeyUp(e) {3389if (e.keyCode == 16) this.doc.sel.shift = false;3390signalDOMEvent(this, e);3391}33923393function onKeyPress(e) {3394var cm = this;3395if (signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;3396var keyCode = e.keyCode, charCode = e.charCode;3397if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}3398if (((presto && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;3399var ch = String.fromCharCode(charCode == null ? keyCode : charCode);3400if (handleCharBinding(cm, e, ch)) return;3401if (ie && ie_version >= 9) cm.display.inputHasSelection = null;3402fastPoll(cm);3403}34043405// FOCUS/BLUR EVENTS34063407function onFocus(cm) {3408if (cm.options.readOnly == "nocursor") return;3409if (!cm.state.focused) {3410signal(cm, "focus", cm);3411cm.state.focused = true;3412addClass(cm.display.wrapper, "CodeMirror-focused");3413// The prevInput test prevents this from firing when a context3414// menu is closed (since the resetInput would kill the3415// select-all detection hack)3416if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {3417resetInput(cm);3418if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #17303419}3420}3421slowPoll(cm);3422restartBlink(cm);3423}3424function onBlur(cm) {3425if (cm.state.focused) {3426signal(cm, "blur", cm);3427cm.state.focused = false;3428rmClass(cm.display.wrapper, "CodeMirror-focused");3429}3430clearInterval(cm.display.blinker);3431setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);3432}34333434// CONTEXT MENU HANDLING34353436// To make the context menu work, we need to briefly unhide the3437// textarea (making it as unobtrusive as possible) to let the3438// right-click take effect on it.3439function onContextMenu(cm, e) {3440if (signalDOMEvent(cm, e, "contextmenu")) return;3441var display = cm.display;3442if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return;34433444var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;3445if (!pos || presto) return; // Opera is difficult.34463447// Reset the current text selection only if the click is done outside of the selection3448// and 'resetSelectionOnContextMenu' option is true.3449var reset = cm.options.resetSelectionOnContextMenu;3450if (reset && cm.doc.sel.contains(pos) == -1)3451operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);34523453var oldCSS = display.input.style.cssText;3454display.inputDiv.style.position = "absolute";3455display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +3456"px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +3457(ie ? "rgba(255, 255, 255, .05)" : "transparent") +3458"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";3459if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)3460focusInput(cm);3461if (webkit) window.scrollTo(null, oldScrollY);3462resetInput(cm);3463// Adds "Select all" to context menu in FF3464if (!cm.somethingSelected()) display.input.value = display.prevInput = " ";3465display.contextMenuPending = true;3466display.selForContextMenu = cm.doc.sel;3467clearTimeout(display.detectingSelectAll);34683469// Select-all will be greyed out if there's nothing to select, so3470// this adds a zero-width space so that we can later check whether3471// it got selected.3472function prepareSelectAllHack() {3473if (display.input.selectionStart != null) {3474var selected = cm.somethingSelected();3475var extval = display.input.value = "\u200b" + (selected ? display.input.value : "");3476display.prevInput = selected ? "" : "\u200b";3477display.input.selectionStart = 1; display.input.selectionEnd = extval.length;3478// Re-set this, in case some other handler touched the3479// selection in the meantime.3480display.selForContextMenu = cm.doc.sel;3481}3482}3483function rehide() {3484display.contextMenuPending = false;3485display.inputDiv.style.position = "relative";3486display.input.style.cssText = oldCSS;3487if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);3488slowPoll(cm);34893490// Try to detect the user choosing select-all3491if (display.input.selectionStart != null) {3492if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();3493var i = 0, poll = function() {3494if (display.selForContextMenu == cm.doc.sel && display.input.selectionStart == 0)3495operation(cm, commands.selectAll)(cm);3496else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);3497else resetInput(cm);3498};3499display.detectingSelectAll = setTimeout(poll, 200);3500}3501}35023503if (ie && ie_version >= 9) prepareSelectAllHack();3504if (captureRightClick) {3505e_stop(e);3506var mouseup = function() {3507off(window, "mouseup", mouseup);3508setTimeout(rehide, 20);3509};3510on(window, "mouseup", mouseup);3511} else {3512setTimeout(rehide, 50);3513}3514}35153516function contextMenuInGutter(cm, e) {3517if (!hasHandler(cm, "gutterContextMenu")) return false;3518return gutterEvent(cm, e, "gutterContextMenu", false, signal);3519}35203521// UPDATING35223523// Compute the position of the end of a change (its 'to' property3524// refers to the pre-change end).3525var changeEnd = CodeMirror.changeEnd = function(change) {3526if (!change.text) return change.to;3527return Pos(change.from.line + change.text.length - 1,3528lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));3529};35303531// Adjust a position to refer to the post-change position of the3532// same text, or the end of the change if the change covers it.3533function adjustForChange(pos, change) {3534if (cmp(pos, change.from) < 0) return pos;3535if (cmp(pos, change.to) <= 0) return changeEnd(change);35363537var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;3538if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;3539return Pos(line, ch);3540}35413542function computeSelAfterChange(doc, change) {3543var out = [];3544for (var i = 0; i < doc.sel.ranges.length; i++) {3545var range = doc.sel.ranges[i];3546out.push(new Range(adjustForChange(range.anchor, change),3547adjustForChange(range.head, change)));3548}3549return normalizeSelection(out, doc.sel.primIndex);3550}35513552function offsetPos(pos, old, nw) {3553if (pos.line == old.line)3554return Pos(nw.line, pos.ch - old.ch + nw.ch);3555else3556return Pos(nw.line + (pos.line - old.line), pos.ch);3557}35583559// Used by replaceSelections to allow moving the selection to the3560// start or around the replaced test. Hint may be "start" or "around".3561function computeReplacedSel(doc, changes, hint) {3562var out = [];3563var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;3564for (var i = 0; i < changes.length; i++) {3565var change = changes[i];3566var from = offsetPos(change.from, oldPrev, newPrev);3567var to = offsetPos(changeEnd(change), oldPrev, newPrev);3568oldPrev = change.to;3569newPrev = to;3570if (hint == "around") {3571var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;3572out[i] = new Range(inv ? to : from, inv ? from : to);3573} else {3574out[i] = new Range(from, from);3575}3576}3577return new Selection(out, doc.sel.primIndex);3578}35793580// Allow "beforeChange" event handlers to influence a change3581function filterChange(doc, change, update) {3582var obj = {3583canceled: false,3584from: change.from,3585to: change.to,3586text: change.text,3587origin: change.origin,3588cancel: function() { this.canceled = true; }3589};3590if (update) obj.update = function(from, to, text, origin) {3591if (from) this.from = clipPos(doc, from);3592if (to) this.to = clipPos(doc, to);3593if (text) this.text = text;3594if (origin !== undefined) this.origin = origin;3595};3596signal(doc, "beforeChange", doc, obj);3597if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);35983599if (obj.canceled) return null;3600return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};3601}36023603// Apply a change to a document, and add it to the document's3604// history, and propagating it to all linked documents.3605function makeChange(doc, change, ignoreReadOnly) {3606if (doc.cm) {3607if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);3608if (doc.cm.state.suppressEdits) return;3609}36103611if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {3612change = filterChange(doc, change, true);3613if (!change) return;3614}36153616// Possibly split or suppress the update based on the presence3617// of read-only spans in its range.3618var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);3619if (split) {3620for (var i = split.length - 1; i >= 0; --i)3621makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});3622} else {3623makeChangeInner(doc, change);3624}3625}36263627function makeChangeInner(doc, change) {3628if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;3629var selAfter = computeSelAfterChange(doc, change);3630addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);36313632makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));3633var rebased = [];36343635linkedDocs(doc, function(doc, sharedHist) {3636if (!sharedHist && indexOf(rebased, doc.history) == -1) {3637rebaseHist(doc.history, change);3638rebased.push(doc.history);3639}3640makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));3641});3642}36433644// Revert a change stored in a document's history.3645function makeChangeFromHistory(doc, type, allowSelectionOnly) {3646if (doc.cm && doc.cm.state.suppressEdits) return;36473648var hist = doc.history, event, selAfter = doc.sel;3649var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;36503651// Verify that there is a useable event (so that ctrl-z won't3652// needlessly clear selection events)3653for (var i = 0; i < source.length; i++) {3654event = source[i];3655if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)3656break;3657}3658if (i == source.length) return;3659hist.lastOrigin = hist.lastSelOrigin = null;36603661for (;;) {3662event = source.pop();3663if (event.ranges) {3664pushSelectionToHistory(event, dest);3665if (allowSelectionOnly && !event.equals(doc.sel)) {3666setSelection(doc, event, {clearRedo: false});3667return;3668}3669selAfter = event;3670}3671else break;3672}36733674// Build up a reverse change object to add to the opposite history3675// stack (redo when undoing, and vice versa).3676var antiChanges = [];3677pushSelectionToHistory(selAfter, dest);3678dest.push({changes: antiChanges, generation: hist.generation});3679hist.generation = event.generation || ++hist.maxGeneration;36803681var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");36823683for (var i = event.changes.length - 1; i >= 0; --i) {3684var change = event.changes[i];3685change.origin = type;3686if (filter && !filterChange(doc, change, false)) {3687source.length = 0;3688return;3689}36903691antiChanges.push(historyChangeFromChange(doc, change));36923693var after = i ? computeSelAfterChange(doc, change) : lst(source);3694makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));3695if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});3696var rebased = [];36973698// Propagate to the linked documents3699linkedDocs(doc, function(doc, sharedHist) {3700if (!sharedHist && indexOf(rebased, doc.history) == -1) {3701rebaseHist(doc.history, change);3702rebased.push(doc.history);3703}3704makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));3705});3706}3707}37083709// Sub-views need their line numbers shifted when text is added3710// above or below them in the parent document.3711function shiftDoc(doc, distance) {3712if (distance == 0) return;3713doc.first += distance;3714doc.sel = new Selection(map(doc.sel.ranges, function(range) {3715return new Range(Pos(range.anchor.line + distance, range.anchor.ch),3716Pos(range.head.line + distance, range.head.ch));3717}), doc.sel.primIndex);3718if (doc.cm) {3719regChange(doc.cm, doc.first, doc.first - distance, distance);3720for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)3721regLineChange(doc.cm, l, "gutter");3722}3723}37243725// More lower-level change function, handling only a single document3726// (not linked ones).3727function makeChangeSingleDoc(doc, change, selAfter, spans) {3728if (doc.cm && !doc.cm.curOp)3729return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);37303731if (change.to.line < doc.first) {3732shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));3733return;3734}3735if (change.from.line > doc.lastLine()) return;37363737// Clip the change to the size of this doc3738if (change.from.line < doc.first) {3739var shift = change.text.length - 1 - (doc.first - change.from.line);3740shiftDoc(doc, shift);3741change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),3742text: [lst(change.text)], origin: change.origin};3743}3744var last = doc.lastLine();3745if (change.to.line > last) {3746change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),3747text: [change.text[0]], origin: change.origin};3748}37493750change.removed = getBetween(doc, change.from, change.to);37513752if (!selAfter) selAfter = computeSelAfterChange(doc, change);3753if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);3754else updateDoc(doc, change, spans);3755setSelectionNoUndo(doc, selAfter, sel_dontScroll);3756}37573758// Handle the interaction of a change to a document with the editor3759// that this document is part of.3760function makeChangeSingleDocInEditor(cm, change, spans) {3761var doc = cm.doc, display = cm.display, from = change.from, to = change.to;37623763var recomputeMaxLength = false, checkWidthStart = from.line;3764if (!cm.options.lineWrapping) {3765checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));3766doc.iter(checkWidthStart, to.line + 1, function(line) {3767if (line == display.maxLine) {3768recomputeMaxLength = true;3769return true;3770}3771});3772}37733774if (doc.sel.contains(change.from, change.to) > -1)3775signalCursorActivity(cm);37763777updateDoc(doc, change, spans, estimateHeight(cm));37783779if (!cm.options.lineWrapping) {3780doc.iter(checkWidthStart, from.line + change.text.length, function(line) {3781var len = lineLength(line);3782if (len > display.maxLineLength) {3783display.maxLine = line;3784display.maxLineLength = len;3785display.maxLineChanged = true;3786recomputeMaxLength = false;3787}3788});3789if (recomputeMaxLength) cm.curOp.updateMaxLine = true;3790}37913792// Adjust frontier, schedule worker3793doc.frontier = Math.min(doc.frontier, from.line);3794startWorker(cm, 400);37953796var lendiff = change.text.length - (to.line - from.line) - 1;3797// Remember that these lines changed, for updating the display3798if (change.full)3799regChange(cm);3800else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))3801regLineChange(cm, from.line, "text");3802else3803regChange(cm, from.line, to.line + 1, lendiff);38043805var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");3806if (changeHandler || changesHandler) {3807var obj = {3808from: from, to: to,3809text: change.text,3810removed: change.removed,3811origin: change.origin3812};3813if (changeHandler) signalLater(cm, "change", cm, obj);3814if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);3815}3816cm.display.selForContextMenu = null;3817}38183819function replaceRange(doc, code, from, to, origin) {3820if (!to) to = from;3821if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }3822if (typeof code == "string") code = splitLines(code);3823makeChange(doc, {from: from, to: to, text: code, origin: origin});3824}38253826// SCROLLING THINGS INTO VIEW38273828// If an editor sits on the top or bottom of the window, partially3829// scrolled out of view, this ensures that the cursor is visible.3830function maybeScrollWindow(cm, coords) {3831if (signalDOMEvent(cm, "scrollCursorIntoView")) return;38323833var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;3834if (coords.top + box.top < 0) doScroll = true;3835else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;3836if (doScroll != null && !phantom) {3837var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +3838(coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +3839(coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +3840coords.left + "px; width: 2px;");3841cm.display.lineSpace.appendChild(scrollNode);3842scrollNode.scrollIntoView(doScroll);3843cm.display.lineSpace.removeChild(scrollNode);3844}3845}38463847// Scroll a given position into view (immediately), verifying that3848// it actually became visible (as line heights are accurately3849// measured, the position of something may 'drift' during drawing).3850function scrollPosIntoView(cm, pos, end, margin) {3851if (margin == null) margin = 0;3852for (var limit = 0; limit < 5; limit++) {3853var changed = false, coords = cursorCoords(cm, pos);3854var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);3855var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),3856Math.min(coords.top, endCoords.top) - margin,3857Math.max(coords.left, endCoords.left),3858Math.max(coords.bottom, endCoords.bottom) + margin);3859var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;3860if (scrollPos.scrollTop != null) {3861setScrollTop(cm, scrollPos.scrollTop);3862if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;3863}3864if (scrollPos.scrollLeft != null) {3865setScrollLeft(cm, scrollPos.scrollLeft);3866if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;3867}3868if (!changed) break;3869}3870return coords;3871}38723873// Scroll a given set of coordinates into view (immediately).3874function scrollIntoView(cm, x1, y1, x2, y2) {3875var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);3876if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);3877if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);3878}38793880// Calculate a new scroll position needed to scroll the given3881// rectangle into view. Returns an object with scrollTop and3882// scrollLeft properties. When these are undefined, the3883// vertical/horizontal position does not need to be adjusted.3884function calculateScrollPos(cm, x1, y1, x2, y2) {3885var display = cm.display, snapMargin = textHeight(cm.display);3886if (y1 < 0) y1 = 0;3887var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;3888var screen = displayHeight(cm), result = {};3889if (y2 - y1 > screen) y2 = y1 + screen;3890var docBottom = cm.doc.height + paddingVert(display);3891var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;3892if (y1 < screentop) {3893result.scrollTop = atTop ? 0 : y1;3894} else if (y2 > screentop + screen) {3895var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);3896if (newTop != screentop) result.scrollTop = newTop;3897}38983899var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;3900var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);3901var tooWide = x2 - x1 > screenw;3902if (tooWide) x2 = x1 + screenw;3903if (x1 < 10)3904result.scrollLeft = 0;3905else if (x1 < screenleft)3906result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));3907else if (x2 > screenw + screenleft - 3)3908result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;3909return result;3910}39113912// Store a relative adjustment to the scroll position in the current3913// operation (to be applied when the operation finishes).3914function addToScrollPos(cm, left, top) {3915if (left != null || top != null) resolveScrollToPos(cm);3916if (left != null)3917cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;3918if (top != null)3919cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;3920}39213922// Make sure that at the end of the operation the current cursor is3923// shown.3924function ensureCursorVisible(cm) {3925resolveScrollToPos(cm);3926var cur = cm.getCursor(), from = cur, to = cur;3927if (!cm.options.lineWrapping) {3928from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;3929to = Pos(cur.line, cur.ch + 1);3930}3931cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};3932}39333934// When an operation has its scrollToPos property set, and another3935// scroll action is applied before the end of the operation, this3936// 'simulates' scrolling that position into view in a cheap way, so3937// that the effect of intermediate scroll commands is not ignored.3938function resolveScrollToPos(cm) {3939var range = cm.curOp.scrollToPos;3940if (range) {3941cm.curOp.scrollToPos = null;3942var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);3943var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),3944Math.min(from.top, to.top) - range.margin,3945Math.max(from.right, to.right),3946Math.max(from.bottom, to.bottom) + range.margin);3947cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);3948}3949}39503951// API UTILITIES39523953// Indent the given line. The how parameter can be "smart",3954// "add"/null, "subtract", or "prev". When aggressive is false3955// (typically set to true for forced single-line indents), empty3956// lines are not indented, and places where the mode returns Pass3957// are left alone.3958function indentLine(cm, n, how, aggressive) {3959var doc = cm.doc, state;3960if (how == null) how = "add";3961if (how == "smart") {3962// Fall back to "prev" when the mode doesn't have an indentation3963// method.3964if (!doc.mode.indent) how = "prev";3965else state = getStateBefore(cm, n);3966}39673968var tabSize = cm.options.tabSize;3969var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);3970if (line.stateAfter) line.stateAfter = null;3971var curSpaceString = line.text.match(/^\s*/)[0], indentation;3972if (!aggressive && !/\S/.test(line.text)) {3973indentation = 0;3974how = "not";3975} else if (how == "smart") {3976indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);3977if (indentation == Pass || indentation > 150) {3978if (!aggressive) return;3979how = "prev";3980}3981}3982if (how == "prev") {3983if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);3984else indentation = 0;3985} else if (how == "add") {3986indentation = curSpace + cm.options.indentUnit;3987} else if (how == "subtract") {3988indentation = curSpace - cm.options.indentUnit;3989} else if (typeof how == "number") {3990indentation = curSpace + how;3991}3992indentation = Math.max(0, indentation);39933994var indentString = "", pos = 0;3995if (cm.options.indentWithTabs)3996for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}3997if (pos < indentation) indentString += spaceStr(indentation - pos);39983999if (indentString != curSpaceString) {4000replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");4001} else {4002// Ensure that, if the cursor was in the whitespace at the start4003// of the line, it is moved to the end of that space.4004for (var i = 0; i < doc.sel.ranges.length; i++) {4005var range = doc.sel.ranges[i];4006if (range.head.line == n && range.head.ch < curSpaceString.length) {4007var pos = Pos(n, curSpaceString.length);4008replaceOneSelection(doc, i, new Range(pos, pos));4009break;4010}4011}4012}4013line.stateAfter = null;4014}40154016// Utility for applying a change to a line by handle or number,4017// returning the number and optionally registering the line as4018// changed.4019function changeLine(doc, handle, changeType, op) {4020var no = handle, line = handle;4021if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));4022else no = lineNo(handle);4023if (no == null) return null;4024if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);4025return line;4026}40274028// Helper for deleting text near the selection(s), used to implement4029// backspace, delete, and similar functionality.4030function deleteNearSelection(cm, compute) {4031var ranges = cm.doc.sel.ranges, kill = [];4032// Build up a set of ranges to kill first, merging overlapping4033// ranges.4034for (var i = 0; i < ranges.length; i++) {4035var toKill = compute(ranges[i]);4036while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {4037var replaced = kill.pop();4038if (cmp(replaced.from, toKill.from) < 0) {4039toKill.from = replaced.from;4040break;4041}4042}4043kill.push(toKill);4044}4045// Next, remove those actual ranges.4046runInOp(cm, function() {4047for (var i = kill.length - 1; i >= 0; i--)4048replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");4049ensureCursorVisible(cm);4050});4051}40524053// Used for horizontal relative motion. Dir is -1 or 1 (left or4054// right), unit can be "char", "column" (like char, but doesn't4055// cross line boundaries), "word" (across next word), or "group" (to4056// the start of next group of word or non-word-non-whitespace4057// chars). The visually param controls whether, in right-to-left4058// text, direction 1 means to move towards the next index in the4059// string, or towards the character to the right of the current4060// position. The resulting position will have a hitSide=true4061// property if it reached the end of the document.4062function findPosH(doc, pos, dir, unit, visually) {4063var line = pos.line, ch = pos.ch, origDir = dir;4064var lineObj = getLine(doc, line);4065var possible = true;4066function findNextLine() {4067var l = line + dir;4068if (l < doc.first || l >= doc.first + doc.size) return (possible = false);4069line = l;4070return lineObj = getLine(doc, l);4071}4072function moveOnce(boundToLine) {4073var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);4074if (next == null) {4075if (!boundToLine && findNextLine()) {4076if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);4077else ch = dir < 0 ? lineObj.text.length : 0;4078} else return (possible = false);4079} else ch = next;4080return true;4081}40824083if (unit == "char") moveOnce();4084else if (unit == "column") moveOnce(true);4085else if (unit == "word" || unit == "group") {4086var sawType = null, group = unit == "group";4087var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");4088for (var first = true;; first = false) {4089if (dir < 0 && !moveOnce(!first)) break;4090var cur = lineObj.text.charAt(ch) || "\n";4091var type = isWordChar(cur, helper) ? "w"4092: group && cur == "\n" ? "n"4093: !group || /\s/.test(cur) ? null4094: "p";4095if (group && !first && !type) type = "s";4096if (sawType && sawType != type) {4097if (dir < 0) {dir = 1; moveOnce();}4098break;4099}41004101if (type) sawType = type;4102if (dir > 0 && !moveOnce(!first)) break;4103}4104}4105var result = skipAtomic(doc, Pos(line, ch), origDir, true);4106if (!possible) result.hitSide = true;4107return result;4108}41094110// For relative vertical movement. Dir may be -1 or 1. Unit can be4111// "page" or "line". The resulting position will have a hitSide=true4112// property if it reached the end of the document.4113function findPosV(cm, pos, dir, unit) {4114var doc = cm.doc, x = pos.left, y;4115if (unit == "page") {4116var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);4117y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));4118} else if (unit == "line") {4119y = dir > 0 ? pos.bottom + 3 : pos.top - 3;4120}4121for (;;) {4122var target = coordsChar(cm, x, y);4123if (!target.outside) break;4124if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }4125y += dir * 5;4126}4127return target;4128}41294130// EDITOR METHODS41314132// The publicly visible API. Note that methodOp(f) means4133// 'wrap f in an operation, performed on its `this` parameter'.41344135// This is not the complete set of editor methods. Most of the4136// methods defined on the Doc type are also injected into4137// CodeMirror.prototype, for backwards compatibility and4138// convenience.41394140CodeMirror.prototype = {4141constructor: CodeMirror,4142focus: function(){window.focus(); focusInput(this); fastPoll(this);},41434144setOption: function(option, value) {4145var options = this.options, old = options[option];4146if (options[option] == value && option != "mode") return;4147options[option] = value;4148if (optionHandlers.hasOwnProperty(option))4149operation(this, optionHandlers[option])(this, value, old);4150},41514152getOption: function(option) {return this.options[option];},4153getDoc: function() {return this.doc;},41544155addKeyMap: function(map, bottom) {4156this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));4157},4158removeKeyMap: function(map) {4159var maps = this.state.keyMaps;4160for (var i = 0; i < maps.length; ++i)4161if (maps[i] == map || maps[i].name == map) {4162maps.splice(i, 1);4163return true;4164}4165},41664167addOverlay: methodOp(function(spec, options) {4168var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);4169if (mode.startState) throw new Error("Overlays may not be stateful.");4170this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});4171this.state.modeGen++;4172regChange(this);4173}),4174removeOverlay: methodOp(function(spec) {4175var overlays = this.state.overlays;4176for (var i = 0; i < overlays.length; ++i) {4177var cur = overlays[i].modeSpec;4178if (cur == spec || typeof spec == "string" && cur.name == spec) {4179overlays.splice(i, 1);4180this.state.modeGen++;4181regChange(this);4182return;4183}4184}4185}),41864187indentLine: methodOp(function(n, dir, aggressive) {4188if (typeof dir != "string" && typeof dir != "number") {4189if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";4190else dir = dir ? "add" : "subtract";4191}4192if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);4193}),4194indentSelection: methodOp(function(how) {4195var ranges = this.doc.sel.ranges, end = -1;4196for (var i = 0; i < ranges.length; i++) {4197var range = ranges[i];4198if (!range.empty()) {4199var from = range.from(), to = range.to();4200var start = Math.max(end, from.line);4201end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;4202for (var j = start; j < end; ++j)4203indentLine(this, j, how);4204var newRanges = this.doc.sel.ranges;4205if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)4206replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);4207} else if (range.head.line > end) {4208indentLine(this, range.head.line, how, true);4209end = range.head.line;4210if (i == this.doc.sel.primIndex) ensureCursorVisible(this);4211}4212}4213}),42144215// Fetch the parser token for a given character. Useful for hacks4216// that want to inspect the mode state (say, for completion).4217getTokenAt: function(pos, precise) {4218return takeToken(this, pos, precise);4219},42204221getLineTokens: function(line, precise) {4222return takeToken(this, Pos(line), precise, true);4223},42244225getTokenTypeAt: function(pos) {4226pos = clipPos(this.doc, pos);4227var styles = getLineStyles(this, getLine(this.doc, pos.line));4228var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;4229var type;4230if (ch == 0) type = styles[2];4231else for (;;) {4232var mid = (before + after) >> 1;4233if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;4234else if (styles[mid * 2 + 1] < ch) before = mid + 1;4235else { type = styles[mid * 2 + 2]; break; }4236}4237var cut = type ? type.indexOf("cm-overlay ") : -1;4238return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);4239},42404241getModeAt: function(pos) {4242var mode = this.doc.mode;4243if (!mode.innerMode) return mode;4244return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;4245},42464247getHelper: function(pos, type) {4248return this.getHelpers(pos, type)[0];4249},42504251getHelpers: function(pos, type) {4252var found = [];4253if (!helpers.hasOwnProperty(type)) return helpers;4254var help = helpers[type], mode = this.getModeAt(pos);4255if (typeof mode[type] == "string") {4256if (help[mode[type]]) found.push(help[mode[type]]);4257} else if (mode[type]) {4258for (var i = 0; i < mode[type].length; i++) {4259var val = help[mode[type][i]];4260if (val) found.push(val);4261}4262} else if (mode.helperType && help[mode.helperType]) {4263found.push(help[mode.helperType]);4264} else if (help[mode.name]) {4265found.push(help[mode.name]);4266}4267for (var i = 0; i < help._global.length; i++) {4268var cur = help._global[i];4269if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)4270found.push(cur.val);4271}4272return found;4273},42744275getStateAfter: function(line, precise) {4276var doc = this.doc;4277line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);4278return getStateBefore(this, line + 1, precise);4279},42804281cursorCoords: function(start, mode) {4282var pos, range = this.doc.sel.primary();4283if (start == null) pos = range.head;4284else if (typeof start == "object") pos = clipPos(this.doc, start);4285else pos = start ? range.from() : range.to();4286return cursorCoords(this, pos, mode || "page");4287},42884289charCoords: function(pos, mode) {4290return charCoords(this, clipPos(this.doc, pos), mode || "page");4291},42924293coordsChar: function(coords, mode) {4294coords = fromCoordSystem(this, coords, mode || "page");4295return coordsChar(this, coords.left, coords.top);4296},42974298lineAtHeight: function(height, mode) {4299height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;4300return lineAtHeight(this.doc, height + this.display.viewOffset);4301},4302heightAtLine: function(line, mode) {4303var end = false, last = this.doc.first + this.doc.size - 1;4304if (line < this.doc.first) line = this.doc.first;4305else if (line > last) { line = last; end = true; }4306var lineObj = getLine(this.doc, line);4307return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +4308(end ? this.doc.height - heightAtLine(lineObj) : 0);4309},43104311defaultTextHeight: function() { return textHeight(this.display); },4312defaultCharWidth: function() { return charWidth(this.display); },43134314setGutterMarker: methodOp(function(line, gutterID, value) {4315return changeLine(this.doc, line, "gutter", function(line) {4316var markers = line.gutterMarkers || (line.gutterMarkers = {});4317markers[gutterID] = value;4318if (!value && isEmpty(markers)) line.gutterMarkers = null;4319return true;4320});4321}),43224323clearGutter: methodOp(function(gutterID) {4324var cm = this, doc = cm.doc, i = doc.first;4325doc.iter(function(line) {4326if (line.gutterMarkers && line.gutterMarkers[gutterID]) {4327line.gutterMarkers[gutterID] = null;4328regLineChange(cm, i, "gutter");4329if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;4330}4331++i;4332});4333}),43344335addLineWidget: methodOp(function(handle, node, options) {4336return addLineWidget(this, handle, node, options);4337}),43384339removeLineWidget: function(widget) { widget.clear(); },43404341lineInfo: function(line) {4342if (typeof line == "number") {4343if (!isLine(this.doc, line)) return null;4344var n = line;4345line = getLine(this.doc, line);4346if (!line) return null;4347} else {4348var n = lineNo(line);4349if (n == null) return null;4350}4351return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,4352textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,4353widgets: line.widgets};4354},43554356getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},43574358addWidget: function(pos, node, scroll, vert, horiz) {4359var display = this.display;4360pos = cursorCoords(this, clipPos(this.doc, pos));4361var top = pos.bottom, left = pos.left;4362node.style.position = "absolute";4363node.setAttribute("cm-ignore-events", "true");4364display.sizer.appendChild(node);4365if (vert == "over") {4366top = pos.top;4367} else if (vert == "above" || vert == "near") {4368var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),4369hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);4370// Default to positioning above (if specified and possible); otherwise default to positioning below4371if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)4372top = pos.top - node.offsetHeight;4373else if (pos.bottom + node.offsetHeight <= vspace)4374top = pos.bottom;4375if (left + node.offsetWidth > hspace)4376left = hspace - node.offsetWidth;4377}4378node.style.top = top + "px";4379node.style.left = node.style.right = "";4380if (horiz == "right") {4381left = display.sizer.clientWidth - node.offsetWidth;4382node.style.right = "0px";4383} else {4384if (horiz == "left") left = 0;4385else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;4386node.style.left = left + "px";4387}4388if (scroll)4389scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);4390},43914392triggerOnKeyDown: methodOp(onKeyDown),4393triggerOnKeyPress: methodOp(onKeyPress),4394triggerOnKeyUp: onKeyUp,43954396execCommand: function(cmd) {4397if (commands.hasOwnProperty(cmd))4398return commands[cmd](this);4399},44004401findPosH: function(from, amount, unit, visually) {4402var dir = 1;4403if (amount < 0) { dir = -1; amount = -amount; }4404for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {4405cur = findPosH(this.doc, cur, dir, unit, visually);4406if (cur.hitSide) break;4407}4408return cur;4409},44104411moveH: methodOp(function(dir, unit) {4412var cm = this;4413cm.extendSelectionsBy(function(range) {4414if (cm.display.shift || cm.doc.extend || range.empty())4415return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);4416else4417return dir < 0 ? range.from() : range.to();4418}, sel_move);4419}),44204421deleteH: methodOp(function(dir, unit) {4422var sel = this.doc.sel, doc = this.doc;4423if (sel.somethingSelected())4424doc.replaceSelection("", null, "+delete");4425else4426deleteNearSelection(this, function(range) {4427var other = findPosH(doc, range.head, dir, unit, false);4428return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};4429});4430}),44314432findPosV: function(from, amount, unit, goalColumn) {4433var dir = 1, x = goalColumn;4434if (amount < 0) { dir = -1; amount = -amount; }4435for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {4436var coords = cursorCoords(this, cur, "div");4437if (x == null) x = coords.left;4438else coords.left = x;4439cur = findPosV(this, coords, dir, unit);4440if (cur.hitSide) break;4441}4442return cur;4443},44444445moveV: methodOp(function(dir, unit) {4446var cm = this, doc = this.doc, goals = [];4447var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();4448doc.extendSelectionsBy(function(range) {4449if (collapse)4450return dir < 0 ? range.from() : range.to();4451var headPos = cursorCoords(cm, range.head, "div");4452if (range.goalColumn != null) headPos.left = range.goalColumn;4453goals.push(headPos.left);4454var pos = findPosV(cm, headPos, dir, unit);4455if (unit == "page" && range == doc.sel.primary())4456addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);4457return pos;4458}, sel_move);4459if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)4460doc.sel.ranges[i].goalColumn = goals[i];4461}),44624463// Find the word at the given position (as returned by coordsChar).4464findWordAt: function(pos) {4465var doc = this.doc, line = getLine(doc, pos.line).text;4466var start = pos.ch, end = pos.ch;4467if (line) {4468var helper = this.getHelper(pos, "wordChars");4469if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;4470var startChar = line.charAt(start);4471var check = isWordChar(startChar, helper)4472? function(ch) { return isWordChar(ch, helper); }4473: /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}4474: function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};4475while (start > 0 && check(line.charAt(start - 1))) --start;4476while (end < line.length && check(line.charAt(end))) ++end;4477}4478return new Range(Pos(pos.line, start), Pos(pos.line, end));4479},44804481toggleOverwrite: function(value) {4482if (value != null && value == this.state.overwrite) return;4483if (this.state.overwrite = !this.state.overwrite)4484addClass(this.display.cursorDiv, "CodeMirror-overwrite");4485else4486rmClass(this.display.cursorDiv, "CodeMirror-overwrite");44874488signal(this, "overwriteToggle", this, this.state.overwrite);4489},4490hasFocus: function() { return activeElt() == this.display.input; },44914492scrollTo: methodOp(function(x, y) {4493if (x != null || y != null) resolveScrollToPos(this);4494if (x != null) this.curOp.scrollLeft = x;4495if (y != null) this.curOp.scrollTop = y;4496}),4497getScrollInfo: function() {4498var scroller = this.display.scroller;4499return {left: scroller.scrollLeft, top: scroller.scrollTop,4500height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,4501width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,4502clientHeight: displayHeight(this), clientWidth: displayWidth(this)};4503},45044505scrollIntoView: methodOp(function(range, margin) {4506if (range == null) {4507range = {from: this.doc.sel.primary().head, to: null};4508if (margin == null) margin = this.options.cursorScrollMargin;4509} else if (typeof range == "number") {4510range = {from: Pos(range, 0), to: null};4511} else if (range.from == null) {4512range = {from: range, to: null};4513}4514if (!range.to) range.to = range.from;4515range.margin = margin || 0;45164517if (range.from.line != null) {4518resolveScrollToPos(this);4519this.curOp.scrollToPos = range;4520} else {4521var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),4522Math.min(range.from.top, range.to.top) - range.margin,4523Math.max(range.from.right, range.to.right),4524Math.max(range.from.bottom, range.to.bottom) + range.margin);4525this.scrollTo(sPos.scrollLeft, sPos.scrollTop);4526}4527}),45284529setSize: methodOp(function(width, height) {4530var cm = this;4531function interpret(val) {4532return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;4533}4534if (width != null) cm.display.wrapper.style.width = interpret(width);4535if (height != null) cm.display.wrapper.style.height = interpret(height);4536if (cm.options.lineWrapping) clearLineMeasurementCache(this);4537var lineNo = cm.display.viewFrom;4538cm.doc.iter(lineNo, cm.display.viewTo, function(line) {4539if (line.widgets) for (var i = 0; i < line.widgets.length; i++)4540if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }4541++lineNo;4542});4543cm.curOp.forceUpdate = true;4544signal(cm, "refresh", this);4545}),45464547operation: function(f){return runInOp(this, f);},45484549refresh: methodOp(function() {4550var oldHeight = this.display.cachedTextHeight;4551regChange(this);4552this.curOp.forceUpdate = true;4553clearCaches(this);4554this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);4555updateGutterSpace(this);4556if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)4557estimateLineHeights(this);4558signal(this, "refresh", this);4559}),45604561swapDoc: methodOp(function(doc) {4562var old = this.doc;4563old.cm = null;4564attachDoc(this, doc);4565clearCaches(this);4566resetInput(this);4567this.scrollTo(doc.scrollLeft, doc.scrollTop);4568this.curOp.forceScroll = true;4569signalLater(this, "swapDoc", this, old);4570return old;4571}),45724573getInputField: function(){return this.display.input;},4574getWrapperElement: function(){return this.display.wrapper;},4575getScrollerElement: function(){return this.display.scroller;},4576getGutterElement: function(){return this.display.gutters;}4577};4578eventMixin(CodeMirror);45794580// OPTION DEFAULTS45814582// The default configuration options.4583var defaults = CodeMirror.defaults = {};4584// Functions to run when options are changed.4585var optionHandlers = CodeMirror.optionHandlers = {};45864587function option(name, deflt, handle, notOnInit) {4588CodeMirror.defaults[name] = deflt;4589if (handle) optionHandlers[name] =4590notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;4591}45924593// Passed to option handlers when there is no old value.4594var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};45954596// These two are, on init, called from the constructor because they4597// have to be initialized before the editor can start at all.4598option("value", "", function(cm, val) {4599cm.setValue(val);4600}, true);4601option("mode", null, function(cm, val) {4602cm.doc.modeOption = val;4603loadMode(cm);4604}, true);46054606option("indentUnit", 2, loadMode, true);4607option("indentWithTabs", false);4608option("smartIndent", true);4609option("tabSize", 4, function(cm) {4610resetModeState(cm);4611clearCaches(cm);4612regChange(cm);4613}, true);4614option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val) {4615cm.options.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");4616cm.refresh();4617}, true);4618option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);4619option("electricChars", true);4620option("rtlMoveVisually", !windows);4621option("wholeLineUpdateBefore", true);46224623option("theme", "default", function(cm) {4624themeChanged(cm);4625guttersChanged(cm);4626}, true);4627option("keyMap", "default", function(cm, val, old) {4628var next = getKeyMap(val);4629var prev = old != CodeMirror.Init && getKeyMap(old);4630if (prev && prev.detach) prev.detach(cm, next);4631if (next.attach) next.attach(cm, prev || null);4632});4633option("extraKeys", null);46344635option("lineWrapping", false, wrappingChanged, true);4636option("gutters", [], function(cm) {4637setGuttersForLineNumbers(cm.options);4638guttersChanged(cm);4639}, true);4640option("fixedGutter", true, function(cm, val) {4641cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";4642cm.refresh();4643}, true);4644option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);4645option("scrollbarStyle", "native", function(cm) {4646initScrollbars(cm);4647updateScrollbars(cm);4648cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);4649cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);4650}, true);4651option("lineNumbers", false, function(cm) {4652setGuttersForLineNumbers(cm.options);4653guttersChanged(cm);4654}, true);4655option("firstLineNumber", 1, guttersChanged, true);4656option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);4657option("showCursorWhenSelecting", false, updateSelection, true);46584659option("resetSelectionOnContextMenu", true);46604661option("readOnly", false, function(cm, val) {4662if (val == "nocursor") {4663onBlur(cm);4664cm.display.input.blur();4665cm.display.disabled = true;4666} else {4667cm.display.disabled = false;4668if (!val) resetInput(cm);4669}4670});4671option("disableInput", false, function(cm, val) {if (!val) resetInput(cm);}, true);4672option("dragDrop", true);46734674option("cursorBlinkRate", 530);4675option("cursorScrollMargin", 0);4676option("cursorHeight", 1, updateSelection, true);4677option("singleCursorHeightPerLine", true, updateSelection, true);4678option("workTime", 100);4679option("workDelay", 100);4680option("flattenSpans", true, resetModeState, true);4681option("addModeClass", false, resetModeState, true);4682option("pollInterval", 100);4683option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});4684option("historyEventDelay", 1250);4685option("viewportMargin", 10, function(cm){cm.refresh();}, true);4686option("maxHighlightLength", 10000, resetModeState, true);4687option("moveInputWithCursor", true, function(cm, val) {4688if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0;4689});46904691option("tabindex", null, function(cm, val) {4692cm.display.input.tabIndex = val || "";4693});4694option("autofocus", null);46954696// MODE DEFINITION AND QUERYING46974698// Known modes, by name and by MIME4699var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};47004701// Extra arguments are stored as the mode's dependencies, which is4702// used by (legacy) mechanisms like loadmode.js to automatically4703// load a mode. (Preferred mechanism is the require/define calls.)4704CodeMirror.defineMode = function(name, mode) {4705if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;4706if (arguments.length > 2)4707mode.dependencies = Array.prototype.slice.call(arguments, 2);4708modes[name] = mode;4709};47104711CodeMirror.defineMIME = function(mime, spec) {4712mimeModes[mime] = spec;4713};47144715// Given a MIME type, a {name, ...options} config object, or a name4716// string, return a mode config object.4717CodeMirror.resolveMode = function(spec) {4718if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {4719spec = mimeModes[spec];4720} else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {4721var found = mimeModes[spec.name];4722if (typeof found == "string") found = {name: found};4723spec = createObj(found, spec);4724spec.name = found.name;4725} else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {4726return CodeMirror.resolveMode("application/xml");4727}4728if (typeof spec == "string") return {name: spec};4729else return spec || {name: "null"};4730};47314732// Given a mode spec (anything that resolveMode accepts), find and4733// initialize an actual mode object.4734CodeMirror.getMode = function(options, spec) {4735var spec = CodeMirror.resolveMode(spec);4736var mfactory = modes[spec.name];4737if (!mfactory) return CodeMirror.getMode(options, "text/plain");4738var modeObj = mfactory(options, spec);4739if (modeExtensions.hasOwnProperty(spec.name)) {4740var exts = modeExtensions[spec.name];4741for (var prop in exts) {4742if (!exts.hasOwnProperty(prop)) continue;4743if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];4744modeObj[prop] = exts[prop];4745}4746}4747modeObj.name = spec.name;4748if (spec.helperType) modeObj.helperType = spec.helperType;4749if (spec.modeProps) for (var prop in spec.modeProps)4750modeObj[prop] = spec.modeProps[prop];47514752return modeObj;4753};47544755// Minimal default mode.4756CodeMirror.defineMode("null", function() {4757return {token: function(stream) {stream.skipToEnd();}};4758});4759CodeMirror.defineMIME("text/plain", "null");47604761// This can be used to attach properties to mode objects from4762// outside the actual mode definition.4763var modeExtensions = CodeMirror.modeExtensions = {};4764CodeMirror.extendMode = function(mode, properties) {4765var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});4766copyObj(properties, exts);4767};47684769// EXTENSIONS47704771CodeMirror.defineExtension = function(name, func) {4772CodeMirror.prototype[name] = func;4773};4774CodeMirror.defineDocExtension = function(name, func) {4775Doc.prototype[name] = func;4776};4777CodeMirror.defineOption = option;47784779var initHooks = [];4780CodeMirror.defineInitHook = function(f) {initHooks.push(f);};47814782var helpers = CodeMirror.helpers = {};4783CodeMirror.registerHelper = function(type, name, value) {4784if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};4785helpers[type][name] = value;4786};4787CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {4788CodeMirror.registerHelper(type, name, value);4789helpers[type]._global.push({pred: predicate, val: value});4790};47914792// MODE STATE HANDLING47934794// Utility functions for working with state. Exported because nested4795// modes need to do this for their inner modes.47964797var copyState = CodeMirror.copyState = function(mode, state) {4798if (state === true) return state;4799if (mode.copyState) return mode.copyState(state);4800var nstate = {};4801for (var n in state) {4802var val = state[n];4803if (val instanceof Array) val = val.concat([]);4804nstate[n] = val;4805}4806return nstate;4807};48084809var startState = CodeMirror.startState = function(mode, a1, a2) {4810return mode.startState ? mode.startState(a1, a2) : true;4811};48124813// Given a mode and a state (for that mode), find the inner mode and4814// state at the position that the state refers to.4815CodeMirror.innerMode = function(mode, state) {4816while (mode.innerMode) {4817var info = mode.innerMode(state);4818if (!info || info.mode == mode) break;4819state = info.state;4820mode = info.mode;4821}4822return info || {mode: mode, state: state};4823};48244825// STANDARD COMMANDS48264827// Commands are parameter-less actions that can be performed on an4828// editor, mostly used for keybindings.4829var commands = CodeMirror.commands = {4830selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},4831singleSelection: function(cm) {4832cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);4833},4834killLine: function(cm) {4835deleteNearSelection(cm, function(range) {4836if (range.empty()) {4837var len = getLine(cm.doc, range.head.line).text.length;4838if (range.head.ch == len && range.head.line < cm.lastLine())4839return {from: range.head, to: Pos(range.head.line + 1, 0)};4840else4841return {from: range.head, to: Pos(range.head.line, len)};4842} else {4843return {from: range.from(), to: range.to()};4844}4845});4846},4847deleteLine: function(cm) {4848deleteNearSelection(cm, function(range) {4849return {from: Pos(range.from().line, 0),4850to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};4851});4852},4853delLineLeft: function(cm) {4854deleteNearSelection(cm, function(range) {4855return {from: Pos(range.from().line, 0), to: range.from()};4856});4857},4858delWrappedLineLeft: function(cm) {4859deleteNearSelection(cm, function(range) {4860var top = cm.charCoords(range.head, "div").top + 5;4861var leftPos = cm.coordsChar({left: 0, top: top}, "div");4862return {from: leftPos, to: range.from()};4863});4864},4865delWrappedLineRight: function(cm) {4866deleteNearSelection(cm, function(range) {4867var top = cm.charCoords(range.head, "div").top + 5;4868var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");4869return {from: range.from(), to: rightPos };4870});4871},4872undo: function(cm) {cm.undo();},4873redo: function(cm) {cm.redo();},4874undoSelection: function(cm) {cm.undoSelection();},4875redoSelection: function(cm) {cm.redoSelection();},4876goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},4877goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},4878goLineStart: function(cm) {4879cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },4880{origin: "+move", bias: 1});4881},4882goLineStartSmart: function(cm) {4883cm.extendSelectionsBy(function(range) {4884return lineStartSmart(cm, range.head);4885}, {origin: "+move", bias: 1});4886},4887goLineEnd: function(cm) {4888cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },4889{origin: "+move", bias: -1});4890},4891goLineRight: function(cm) {4892cm.extendSelectionsBy(function(range) {4893var top = cm.charCoords(range.head, "div").top + 5;4894return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");4895}, sel_move);4896},4897goLineLeft: function(cm) {4898cm.extendSelectionsBy(function(range) {4899var top = cm.charCoords(range.head, "div").top + 5;4900return cm.coordsChar({left: 0, top: top}, "div");4901}, sel_move);4902},4903goLineLeftSmart: function(cm) {4904cm.extendSelectionsBy(function(range) {4905var top = cm.charCoords(range.head, "div").top + 5;4906var pos = cm.coordsChar({left: 0, top: top}, "div");4907if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);4908return pos;4909}, sel_move);4910},4911goLineUp: function(cm) {cm.moveV(-1, "line");},4912goLineDown: function(cm) {cm.moveV(1, "line");},4913goPageUp: function(cm) {cm.moveV(-1, "page");},4914goPageDown: function(cm) {cm.moveV(1, "page");},4915goCharLeft: function(cm) {cm.moveH(-1, "char");},4916goCharRight: function(cm) {cm.moveH(1, "char");},4917goColumnLeft: function(cm) {cm.moveH(-1, "column");},4918goColumnRight: function(cm) {cm.moveH(1, "column");},4919goWordLeft: function(cm) {cm.moveH(-1, "word");},4920goGroupRight: function(cm) {cm.moveH(1, "group");},4921goGroupLeft: function(cm) {cm.moveH(-1, "group");},4922goWordRight: function(cm) {cm.moveH(1, "word");},4923delCharBefore: function(cm) {cm.deleteH(-1, "char");},4924delCharAfter: function(cm) {cm.deleteH(1, "char");},4925delWordBefore: function(cm) {cm.deleteH(-1, "word");},4926delWordAfter: function(cm) {cm.deleteH(1, "word");},4927delGroupBefore: function(cm) {cm.deleteH(-1, "group");},4928delGroupAfter: function(cm) {cm.deleteH(1, "group");},4929indentAuto: function(cm) {cm.indentSelection("smart");},4930indentMore: function(cm) {cm.indentSelection("add");},4931indentLess: function(cm) {cm.indentSelection("subtract");},4932insertTab: function(cm) {cm.replaceSelection("\t");},4933insertSoftTab: function(cm) {4934var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;4935for (var i = 0; i < ranges.length; i++) {4936var pos = ranges[i].from();4937var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);4938spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));4939}4940cm.replaceSelections(spaces);4941},4942defaultTab: function(cm) {4943if (cm.somethingSelected()) cm.indentSelection("add");4944else cm.execCommand("insertTab");4945},4946transposeChars: function(cm) {4947runInOp(cm, function() {4948var ranges = cm.listSelections(), newSel = [];4949for (var i = 0; i < ranges.length; i++) {4950var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;4951if (line) {4952if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);4953if (cur.ch > 0) {4954cur = new Pos(cur.line, cur.ch + 1);4955cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),4956Pos(cur.line, cur.ch - 2), cur, "+transpose");4957} else if (cur.line > cm.doc.first) {4958var prev = getLine(cm.doc, cur.line - 1).text;4959if (prev)4960cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1),4961Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");4962}4963}4964newSel.push(new Range(cur, cur));4965}4966cm.setSelections(newSel);4967});4968},4969newlineAndIndent: function(cm) {4970runInOp(cm, function() {4971var len = cm.listSelections().length;4972for (var i = 0; i < len; i++) {4973var range = cm.listSelections()[i];4974cm.replaceRange("\n", range.anchor, range.head, "+input");4975cm.indentLine(range.from().line + 1, null, true);4976ensureCursorVisible(cm);4977}4978});4979},4980toggleOverwrite: function(cm) {cm.toggleOverwrite();}4981};498249834984// STANDARD KEYMAPS49854986var keyMap = CodeMirror.keyMap = {};49874988keyMap.basic = {4989"Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",4990"End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",4991"Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",4992"Tab": "defaultTab", "Shift-Tab": "indentAuto",4993"Enter": "newlineAndIndent", "Insert": "toggleOverwrite",4994"Esc": "singleSelection"4995};4996// Note that the save and find-related commands aren't defined by4997// default. User code or addons can define them. Unknown commands4998// are simply ignored.4999keyMap.pcDefault = {5000"Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",5001"Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",5002"Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",5003"Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",5004"Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",5005"Ctrl-[": "indentLess", "Ctrl-]": "indentMore",5006"Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",5007fallthrough: "basic"5008};5009// Very basic readline/emacs-style bindings, which are standard on Mac.5010keyMap.emacsy = {5011"Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",5012"Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",5013"Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",5014"Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"5015};5016keyMap.macDefault = {5017"Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",5018"Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",5019"Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",5020"Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",5021"Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",5022"Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",5023"Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",5024fallthrough: ["basic", "emacsy"]5025};5026keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;50275028// KEYMAP DISPATCH50295030function normalizeKeyName(name) {5031var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];5032var alt, ctrl, shift, cmd;5033for (var i = 0; i < parts.length - 1; i++) {5034var mod = parts[i];5035if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;5036else if (/^a(lt)?$/i.test(mod)) alt = true;5037else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;5038else if (/^s(hift)$/i.test(mod)) shift = true;5039else throw new Error("Unrecognized modifier name: " + mod);5040}5041if (alt) name = "Alt-" + name;5042if (ctrl) name = "Ctrl-" + name;5043if (cmd) name = "Cmd-" + name;5044if (shift) name = "Shift-" + name;5045return name;5046}50475048// This is a kludge to keep keymaps mostly working as raw objects5049// (backwards compatibility) while at the same time support features5050// like normalization and multi-stroke key bindings. It compiles a5051// new normalized keymap, and then updates the old object to reflect5052// this.5053CodeMirror.normalizeKeyMap = function(keymap) {5054var copy = {};5055for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {5056var value = keymap[keyname];5057if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;5058if (value == "...") { delete keymap[keyname]; continue; }50595060var keys = map(keyname.split(" "), normalizeKeyName);5061for (var i = 0; i < keys.length; i++) {5062var val, name;5063if (i == keys.length - 1) {5064name = keyname;5065val = value;5066} else {5067name = keys.slice(0, i + 1).join(" ");5068val = "...";5069}5070var prev = copy[name];5071if (!prev) copy[name] = val;5072else if (prev != val) throw new Error("Inconsistent bindings for " + name);5073}5074delete keymap[keyname];5075}5076for (var prop in copy) keymap[prop] = copy[prop];5077return keymap;5078};50795080var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {5081map = getKeyMap(map);5082var found = map.call ? map.call(key, context) : map[key];5083if (found === false) return "nothing";5084if (found === "...") return "multi";5085if (found != null && handle(found)) return "handled";50865087if (map.fallthrough) {5088if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")5089return lookupKey(key, map.fallthrough, handle, context);5090for (var i = 0; i < map.fallthrough.length; i++) {5091var result = lookupKey(key, map.fallthrough[i], handle, context);5092if (result) return result;5093}5094}5095};50965097// Modifier key presses don't count as 'real' key presses for the5098// purpose of keymap fallthrough.5099var isModifierKey = CodeMirror.isModifierKey = function(value) {5100var name = typeof value == "string" ? value : keyNames[value.keyCode];5101return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";5102};51035104// Look up the name of a key as indicated by an event object.5105var keyName = CodeMirror.keyName = function(event, noShift) {5106if (presto && event.keyCode == 34 && event["char"]) return false;5107var base = keyNames[event.keyCode], name = base;5108if (name == null || event.altGraphKey) return false;5109if (event.altKey && base != "Alt") name = "Alt-" + name;5110if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;5111if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;5112if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;5113return name;5114};51155116function getKeyMap(val) {5117return typeof val == "string" ? keyMap[val] : val;5118}51195120// FROMTEXTAREA51215122CodeMirror.fromTextArea = function(textarea, options) {5123if (!options) options = {};5124options.value = textarea.value;5125if (!options.tabindex && textarea.tabindex)5126options.tabindex = textarea.tabindex;5127if (!options.placeholder && textarea.placeholder)5128options.placeholder = textarea.placeholder;5129// Set autofocus to true if this textarea is focused, or if it has5130// autofocus and no other element is focused.5131if (options.autofocus == null) {5132var hasFocus = activeElt();5133options.autofocus = hasFocus == textarea ||5134textarea.getAttribute("autofocus") != null && hasFocus == document.body;5135}51365137function save() {textarea.value = cm.getValue();}5138if (textarea.form) {5139on(textarea.form, "submit", save);5140// Deplorable hack to make the submit method do the right thing.5141if (!options.leaveSubmitMethodAlone) {5142var form = textarea.form, realSubmit = form.submit;5143try {5144var wrappedSubmit = form.submit = function() {5145save();5146form.submit = realSubmit;5147form.submit();5148form.submit = wrappedSubmit;5149};5150} catch(e) {}5151}5152}51535154textarea.style.display = "none";5155var cm = CodeMirror(function(node) {5156textarea.parentNode.insertBefore(node, textarea.nextSibling);5157}, options);5158cm.save = save;5159cm.getTextArea = function() { return textarea; };5160cm.toTextArea = function() {5161cm.toTextArea = isNaN; // Prevent this from being ran twice5162save();5163textarea.parentNode.removeChild(cm.getWrapperElement());5164textarea.style.display = "";5165if (textarea.form) {5166off(textarea.form, "submit", save);5167if (typeof textarea.form.submit == "function")5168textarea.form.submit = realSubmit;5169}5170};5171return cm;5172};51735174// STRING STREAM51755176// Fed to the mode parsers, provides helper functions to make5177// parsers more succinct.51785179var StringStream = CodeMirror.StringStream = function(string, tabSize) {5180this.pos = this.start = 0;5181this.string = string;5182this.tabSize = tabSize || 8;5183this.lastColumnPos = this.lastColumnValue = 0;5184this.lineStart = 0;5185};51865187StringStream.prototype = {5188eol: function() {return this.pos >= this.string.length;},5189sol: function() {return this.pos == this.lineStart;},5190peek: function() {return this.string.charAt(this.pos) || undefined;},5191next: function() {5192if (this.pos < this.string.length)5193return this.string.charAt(this.pos++);5194},5195eat: function(match) {5196var ch = this.string.charAt(this.pos);5197if (typeof match == "string") var ok = ch == match;5198else var ok = ch && (match.test ? match.test(ch) : match(ch));5199if (ok) {++this.pos; return ch;}5200},5201eatWhile: function(match) {5202var start = this.pos;5203while (this.eat(match)){}5204return this.pos > start;5205},5206eatSpace: function() {5207var start = this.pos;5208while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;5209return this.pos > start;5210},5211skipToEnd: function() {this.pos = this.string.length;},5212skipTo: function(ch) {5213var found = this.string.indexOf(ch, this.pos);5214if (found > -1) {this.pos = found; return true;}5215},5216backUp: function(n) {this.pos -= n;},5217column: function() {5218if (this.lastColumnPos < this.start) {5219this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);5220this.lastColumnPos = this.start;5221}5222return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);5223},5224indentation: function() {5225return countColumn(this.string, null, this.tabSize) -5226(this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);5227},5228match: function(pattern, consume, caseInsensitive) {5229if (typeof pattern == "string") {5230var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};5231var substr = this.string.substr(this.pos, pattern.length);5232if (cased(substr) == cased(pattern)) {5233if (consume !== false) this.pos += pattern.length;5234return true;5235}5236} else {5237var match = this.string.slice(this.pos).match(pattern);5238if (match && match.index > 0) return null;5239if (match && consume !== false) this.pos += match[0].length;5240return match;5241}5242},5243current: function(){return this.string.slice(this.start, this.pos);},5244hideFirstChars: function(n, inner) {5245this.lineStart += n;5246try { return inner(); }5247finally { this.lineStart -= n; }5248}5249};52505251// TEXTMARKERS52525253// Created with markText and setBookmark methods. A TextMarker is a5254// handle that can be used to clear or find a marked position in the5255// document. Line objects hold arrays (markedSpans) containing5256// {from, to, marker} object pointing to such marker objects, and5257// indicating that such a marker is present on that line. Multiple5258// lines may point to the same marker when it spans across lines.5259// The spans will have null for their from/to properties when the5260// marker continues beyond the start/end of the line. Markers have5261// links back to the lines they currently touch.52625263var TextMarker = CodeMirror.TextMarker = function(doc, type) {5264this.lines = [];5265this.type = type;5266this.doc = doc;5267};5268eventMixin(TextMarker);52695270// Clear the marker.5271TextMarker.prototype.clear = function() {5272if (this.explicitlyCleared) return;5273var cm = this.doc.cm, withOp = cm && !cm.curOp;5274if (withOp) startOperation(cm);5275if (hasHandler(this, "clear")) {5276var found = this.find();5277if (found) signalLater(this, "clear", found.from, found.to);5278}5279var min = null, max = null;5280for (var i = 0; i < this.lines.length; ++i) {5281var line = this.lines[i];5282var span = getMarkedSpanFor(line.markedSpans, this);5283if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");5284else if (cm) {5285if (span.to != null) max = lineNo(line);5286if (span.from != null) min = lineNo(line);5287}5288line.markedSpans = removeMarkedSpan(line.markedSpans, span);5289if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)5290updateLineHeight(line, textHeight(cm.display));5291}5292if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {5293var visual = visualLine(this.lines[i]), len = lineLength(visual);5294if (len > cm.display.maxLineLength) {5295cm.display.maxLine = visual;5296cm.display.maxLineLength = len;5297cm.display.maxLineChanged = true;5298}5299}53005301if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);5302this.lines.length = 0;5303this.explicitlyCleared = true;5304if (this.atomic && this.doc.cantEdit) {5305this.doc.cantEdit = false;5306if (cm) reCheckSelection(cm.doc);5307}5308if (cm) signalLater(cm, "markerCleared", cm, this);5309if (withOp) endOperation(cm);5310if (this.parent) this.parent.clear();5311};53125313// Find the position of the marker in the document. Returns a {from,5314// to} object by default. Side can be passed to get a specific side5315// -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the5316// Pos objects returned contain a line object, rather than a line5317// number (used to prevent looking up the same line twice).5318TextMarker.prototype.find = function(side, lineObj) {5319if (side == null && this.type == "bookmark") side = 1;5320var from, to;5321for (var i = 0; i < this.lines.length; ++i) {5322var line = this.lines[i];5323var span = getMarkedSpanFor(line.markedSpans, this);5324if (span.from != null) {5325from = Pos(lineObj ? line : lineNo(line), span.from);5326if (side == -1) return from;5327}5328if (span.to != null) {5329to = Pos(lineObj ? line : lineNo(line), span.to);5330if (side == 1) return to;5331}5332}5333return from && {from: from, to: to};5334};53355336// Signals that the marker's widget changed, and surrounding layout5337// should be recomputed.5338TextMarker.prototype.changed = function() {5339var pos = this.find(-1, true), widget = this, cm = this.doc.cm;5340if (!pos || !cm) return;5341runInOp(cm, function() {5342var line = pos.line, lineN = lineNo(pos.line);5343var view = findViewForLine(cm, lineN);5344if (view) {5345clearLineMeasurementCacheFor(view);5346cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;5347}5348cm.curOp.updateMaxLine = true;5349if (!lineIsHidden(widget.doc, line) && widget.height != null) {5350var oldHeight = widget.height;5351widget.height = null;5352var dHeight = widgetHeight(widget) - oldHeight;5353if (dHeight)5354updateLineHeight(line, line.height + dHeight);5355}5356});5357};53585359TextMarker.prototype.attachLine = function(line) {5360if (!this.lines.length && this.doc.cm) {5361var op = this.doc.cm.curOp;5362if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)5363(op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);5364}5365this.lines.push(line);5366};5367TextMarker.prototype.detachLine = function(line) {5368this.lines.splice(indexOf(this.lines, line), 1);5369if (!this.lines.length && this.doc.cm) {5370var op = this.doc.cm.curOp;5371(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);5372}5373};53745375// Collapsed markers have unique ids, in order to be able to order5376// them, which is needed for uniquely determining an outer marker5377// when they overlap (they may nest, but not partially overlap).5378var nextMarkerId = 0;53795380// Create a marker, wire it up to the right lines, and5381function markText(doc, from, to, options, type) {5382// Shared markers (across linked documents) are handled separately5383// (markTextShared will call out to this again, once per5384// document).5385if (options && options.shared) return markTextShared(doc, from, to, options, type);5386// Ensure we are in an operation.5387if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);53885389var marker = new TextMarker(doc, type), diff = cmp(from, to);5390if (options) copyObj(options, marker, false);5391// Don't connect empty markers unless clearWhenEmpty is false5392if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)5393return marker;5394if (marker.replacedWith) {5395// Showing up as a widget implies collapsed (widget replaces text)5396marker.collapsed = true;5397marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");5398if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");5399if (options.insertLeft) marker.widgetNode.insertLeft = true;5400}5401if (marker.collapsed) {5402if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||5403from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))5404throw new Error("Inserting collapsed marker partially overlapping an existing one");5405sawCollapsedSpans = true;5406}54075408if (marker.addToHistory)5409addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);54105411var curLine = from.line, cm = doc.cm, updateMaxLine;5412doc.iter(curLine, to.line + 1, function(line) {5413if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)5414updateMaxLine = true;5415if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);5416addMarkedSpan(line, new MarkedSpan(marker,5417curLine == from.line ? from.ch : null,5418curLine == to.line ? to.ch : null));5419++curLine;5420});5421// lineIsHidden depends on the presence of the spans, so needs a second pass5422if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {5423if (lineIsHidden(doc, line)) updateLineHeight(line, 0);5424});54255426if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });54275428if (marker.readOnly) {5429sawReadOnlySpans = true;5430if (doc.history.done.length || doc.history.undone.length)5431doc.clearHistory();5432}5433if (marker.collapsed) {5434marker.id = ++nextMarkerId;5435marker.atomic = true;5436}5437if (cm) {5438// Sync editor state5439if (updateMaxLine) cm.curOp.updateMaxLine = true;5440if (marker.collapsed)5441regChange(cm, from.line, to.line + 1);5442else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)5443for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");5444if (marker.atomic) reCheckSelection(cm.doc);5445signalLater(cm, "markerAdded", cm, marker);5446}5447return marker;5448}54495450// SHARED TEXTMARKERS54515452// A shared marker spans multiple linked documents. It is5453// implemented as a meta-marker-object controlling multiple normal5454// markers.5455var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {5456this.markers = markers;5457this.primary = primary;5458for (var i = 0; i < markers.length; ++i)5459markers[i].parent = this;5460};5461eventMixin(SharedTextMarker);54625463SharedTextMarker.prototype.clear = function() {5464if (this.explicitlyCleared) return;5465this.explicitlyCleared = true;5466for (var i = 0; i < this.markers.length; ++i)5467this.markers[i].clear();5468signalLater(this, "clear");5469};5470SharedTextMarker.prototype.find = function(side, lineObj) {5471return this.primary.find(side, lineObj);5472};54735474function markTextShared(doc, from, to, options, type) {5475options = copyObj(options);5476options.shared = false;5477var markers = [markText(doc, from, to, options, type)], primary = markers[0];5478var widget = options.widgetNode;5479linkedDocs(doc, function(doc) {5480if (widget) options.widgetNode = widget.cloneNode(true);5481markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));5482for (var i = 0; i < doc.linked.length; ++i)5483if (doc.linked[i].isParent) return;5484primary = lst(markers);5485});5486return new SharedTextMarker(markers, primary);5487}54885489function findSharedMarkers(doc) {5490return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),5491function(m) { return m.parent; });5492}54935494function copySharedMarkers(doc, markers) {5495for (var i = 0; i < markers.length; i++) {5496var marker = markers[i], pos = marker.find();5497var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);5498if (cmp(mFrom, mTo)) {5499var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);5500marker.markers.push(subMark);5501subMark.parent = marker;5502}5503}5504}55055506function detachSharedMarkers(markers) {5507for (var i = 0; i < markers.length; i++) {5508var marker = markers[i], linked = [marker.primary.doc];;5509linkedDocs(marker.primary.doc, function(d) { linked.push(d); });5510for (var j = 0; j < marker.markers.length; j++) {5511var subMarker = marker.markers[j];5512if (indexOf(linked, subMarker.doc) == -1) {5513subMarker.parent = null;5514marker.markers.splice(j--, 1);5515}5516}5517}5518}55195520// TEXTMARKER SPANS55215522function MarkedSpan(marker, from, to) {5523this.marker = marker;5524this.from = from; this.to = to;5525}55265527// Search an array of spans for a span matching the given marker.5528function getMarkedSpanFor(spans, marker) {5529if (spans) for (var i = 0; i < spans.length; ++i) {5530var span = spans[i];5531if (span.marker == marker) return span;5532}5533}5534// Remove a span from an array, returning undefined if no spans are5535// left (we don't store arrays for lines without spans).5536function removeMarkedSpan(spans, span) {5537for (var r, i = 0; i < spans.length; ++i)5538if (spans[i] != span) (r || (r = [])).push(spans[i]);5539return r;5540}5541// Add a span to a line.5542function addMarkedSpan(line, span) {5543line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];5544span.marker.attachLine(line);5545}55465547// Used for the algorithm that adjusts markers for a change in the5548// document. These functions cut an array of spans at a given5549// character position, returning an array of remaining chunks (or5550// undefined if nothing remains).5551function markedSpansBefore(old, startCh, isInsert) {5552if (old) for (var i = 0, nw; i < old.length; ++i) {5553var span = old[i], marker = span.marker;5554var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);5555if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {5556var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);5557(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));5558}5559}5560return nw;5561}5562function markedSpansAfter(old, endCh, isInsert) {5563if (old) for (var i = 0, nw; i < old.length; ++i) {5564var span = old[i], marker = span.marker;5565var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);5566if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {5567var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);5568(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,5569span.to == null ? null : span.to - endCh));5570}5571}5572return nw;5573}55745575// Given a change object, compute the new set of marker spans that5576// cover the line in which the change took place. Removes spans5577// entirely within the change, reconnects spans belonging to the5578// same marker that appear on both sides of the change, and cuts off5579// spans partially within the change. Returns an array of span5580// arrays with one element for each line in (after) the change.5581function stretchSpansOverChange(doc, change) {5582if (change.full) return null;5583var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;5584var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;5585if (!oldFirst && !oldLast) return null;55865587var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;5588// Get the spans that 'stick out' on both sides5589var first = markedSpansBefore(oldFirst, startCh, isInsert);5590var last = markedSpansAfter(oldLast, endCh, isInsert);55915592// Next, merge those two ends5593var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);5594if (first) {5595// Fix up .to properties of first5596for (var i = 0; i < first.length; ++i) {5597var span = first[i];5598if (span.to == null) {5599var found = getMarkedSpanFor(last, span.marker);5600if (!found) span.to = startCh;5601else if (sameLine) span.to = found.to == null ? null : found.to + offset;5602}5603}5604}5605if (last) {5606// Fix up .from in last (or move them into first in case of sameLine)5607for (var i = 0; i < last.length; ++i) {5608var span = last[i];5609if (span.to != null) span.to += offset;5610if (span.from == null) {5611var found = getMarkedSpanFor(first, span.marker);5612if (!found) {5613span.from = offset;5614if (sameLine) (first || (first = [])).push(span);5615}5616} else {5617span.from += offset;5618if (sameLine) (first || (first = [])).push(span);5619}5620}5621}5622// Make sure we didn't create any zero-length spans5623if (first) first = clearEmptySpans(first);5624if (last && last != first) last = clearEmptySpans(last);56255626var newMarkers = [first];5627if (!sameLine) {5628// Fill gap with whole-line-spans5629var gap = change.text.length - 2, gapMarkers;5630if (gap > 0 && first)5631for (var i = 0; i < first.length; ++i)5632if (first[i].to == null)5633(gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));5634for (var i = 0; i < gap; ++i)5635newMarkers.push(gapMarkers);5636newMarkers.push(last);5637}5638return newMarkers;5639}56405641// Remove spans that are empty and don't have a clearWhenEmpty5642// option of false.5643function clearEmptySpans(spans) {5644for (var i = 0; i < spans.length; ++i) {5645var span = spans[i];5646if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)5647spans.splice(i--, 1);5648}5649if (!spans.length) return null;5650return spans;5651}56525653// Used for un/re-doing changes from the history. Combines the5654// result of computing the existing spans with the set of spans that5655// existed in the history (so that deleting around a span and then5656// undoing brings back the span).5657function mergeOldSpans(doc, change) {5658var old = getOldSpans(doc, change);5659var stretched = stretchSpansOverChange(doc, change);5660if (!old) return stretched;5661if (!stretched) return old;56625663for (var i = 0; i < old.length; ++i) {5664var oldCur = old[i], stretchCur = stretched[i];5665if (oldCur && stretchCur) {5666spans: for (var j = 0; j < stretchCur.length; ++j) {5667var span = stretchCur[j];5668for (var k = 0; k < oldCur.length; ++k)5669if (oldCur[k].marker == span.marker) continue spans;5670oldCur.push(span);5671}5672} else if (stretchCur) {5673old[i] = stretchCur;5674}5675}5676return old;5677}56785679// Used to 'clip' out readOnly ranges when making a change.5680function removeReadOnlyRanges(doc, from, to) {5681var markers = null;5682doc.iter(from.line, to.line + 1, function(line) {5683if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {5684var mark = line.markedSpans[i].marker;5685if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))5686(markers || (markers = [])).push(mark);5687}5688});5689if (!markers) return null;5690var parts = [{from: from, to: to}];5691for (var i = 0; i < markers.length; ++i) {5692var mk = markers[i], m = mk.find(0);5693for (var j = 0; j < parts.length; ++j) {5694var p = parts[j];5695if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;5696var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);5697if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)5698newParts.push({from: p.from, to: m.from});5699if (dto > 0 || !mk.inclusiveRight && !dto)5700newParts.push({from: m.to, to: p.to});5701parts.splice.apply(parts, newParts);5702j += newParts.length - 1;5703}5704}5705return parts;5706}57075708// Connect or disconnect spans from a line.5709function detachMarkedSpans(line) {5710var spans = line.markedSpans;5711if (!spans) return;5712for (var i = 0; i < spans.length; ++i)5713spans[i].marker.detachLine(line);5714line.markedSpans = null;5715}5716function attachMarkedSpans(line, spans) {5717if (!spans) return;5718for (var i = 0; i < spans.length; ++i)5719spans[i].marker.attachLine(line);5720line.markedSpans = spans;5721}57225723// Helpers used when computing which overlapping collapsed span5724// counts as the larger one.5725function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }5726function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }57275728// Returns a number indicating which of two overlapping collapsed5729// spans is larger (and thus includes the other). Falls back to5730// comparing ids when the spans cover exactly the same range.5731function compareCollapsedMarkers(a, b) {5732var lenDiff = a.lines.length - b.lines.length;5733if (lenDiff != 0) return lenDiff;5734var aPos = a.find(), bPos = b.find();5735var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);5736if (fromCmp) return -fromCmp;5737var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);5738if (toCmp) return toCmp;5739return b.id - a.id;5740}57415742// Find out whether a line ends or starts in a collapsed span. If5743// so, return the marker for that span.5744function collapsedSpanAtSide(line, start) {5745var sps = sawCollapsedSpans && line.markedSpans, found;5746if (sps) for (var sp, i = 0; i < sps.length; ++i) {5747sp = sps[i];5748if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&5749(!found || compareCollapsedMarkers(found, sp.marker) < 0))5750found = sp.marker;5751}5752return found;5753}5754function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }5755function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }57565757// Test whether there exists a collapsed span that partially5758// overlaps (covers the start or end, but not both) of a new span.5759// Such overlap is not allowed.5760function conflictingCollapsedRange(doc, lineNo, from, to, marker) {5761var line = getLine(doc, lineNo);5762var sps = sawCollapsedSpans && line.markedSpans;5763if (sps) for (var i = 0; i < sps.length; ++i) {5764var sp = sps[i];5765if (!sp.marker.collapsed) continue;5766var found = sp.marker.find(0);5767var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);5768var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);5769if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;5770if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||5771fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))5772return true;5773}5774}57755776// A visual line is a line as drawn on the screen. Folding, for5777// example, can cause multiple logical lines to appear on the same5778// visual line. This finds the start of the visual line that the5779// given line is part of (usually that is the line itself).5780function visualLine(line) {5781var merged;5782while (merged = collapsedSpanAtStart(line))5783line = merged.find(-1, true).line;5784return line;5785}57865787// Returns an array of logical lines that continue the visual line5788// started by the argument, or undefined if there are no such lines.5789function visualLineContinued(line) {5790var merged, lines;5791while (merged = collapsedSpanAtEnd(line)) {5792line = merged.find(1, true).line;5793(lines || (lines = [])).push(line);5794}5795return lines;5796}57975798// Get the line number of the start of the visual line that the5799// given line number is part of.5800function visualLineNo(doc, lineN) {5801var line = getLine(doc, lineN), vis = visualLine(line);5802if (line == vis) return lineN;5803return lineNo(vis);5804}5805// Get the line number of the start of the next visual line after5806// the given line.5807function visualLineEndNo(doc, lineN) {5808if (lineN > doc.lastLine()) return lineN;5809var line = getLine(doc, lineN), merged;5810if (!lineIsHidden(doc, line)) return lineN;5811while (merged = collapsedSpanAtEnd(line))5812line = merged.find(1, true).line;5813return lineNo(line) + 1;5814}58155816// Compute whether a line is hidden. Lines count as hidden when they5817// are part of a visual line that starts with another line, or when5818// they are entirely covered by collapsed, non-widget span.5819function lineIsHidden(doc, line) {5820var sps = sawCollapsedSpans && line.markedSpans;5821if (sps) for (var sp, i = 0; i < sps.length; ++i) {5822sp = sps[i];5823if (!sp.marker.collapsed) continue;5824if (sp.from == null) return true;5825if (sp.marker.widgetNode) continue;5826if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))5827return true;5828}5829}5830function lineIsHiddenInner(doc, line, span) {5831if (span.to == null) {5832var end = span.marker.find(1, true);5833return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));5834}5835if (span.marker.inclusiveRight && span.to == line.text.length)5836return true;5837for (var sp, i = 0; i < line.markedSpans.length; ++i) {5838sp = line.markedSpans[i];5839if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&5840(sp.to == null || sp.to != span.from) &&5841(sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&5842lineIsHiddenInner(doc, line, sp)) return true;5843}5844}58455846// LINE WIDGETS58475848// Line widgets are block elements displayed above or below a line.58495850var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {5851if (options) for (var opt in options) if (options.hasOwnProperty(opt))5852this[opt] = options[opt];5853this.cm = cm;5854this.node = node;5855};5856eventMixin(LineWidget);58575858function adjustScrollWhenAboveVisible(cm, line, diff) {5859if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))5860addToScrollPos(cm, null, diff);5861}58625863LineWidget.prototype.clear = function() {5864var cm = this.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);5865if (no == null || !ws) return;5866for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);5867if (!ws.length) line.widgets = null;5868var height = widgetHeight(this);5869runInOp(cm, function() {5870adjustScrollWhenAboveVisible(cm, line, -height);5871regLineChange(cm, no, "widget");5872updateLineHeight(line, Math.max(0, line.height - height));5873});5874};5875LineWidget.prototype.changed = function() {5876var oldH = this.height, cm = this.cm, line = this.line;5877this.height = null;5878var diff = widgetHeight(this) - oldH;5879if (!diff) return;5880runInOp(cm, function() {5881cm.curOp.forceUpdate = true;5882adjustScrollWhenAboveVisible(cm, line, diff);5883updateLineHeight(line, line.height + diff);5884});5885};58865887function widgetHeight(widget) {5888if (widget.height != null) return widget.height;5889if (!contains(document.body, widget.node)) {5890var parentStyle = "position: relative;";5891if (widget.coverGutter)5892parentStyle += "margin-left: -" + widget.cm.display.gutters.offsetWidth + "px;";5893if (widget.noHScroll)5894parentStyle += "width: " + widget.cm.display.wrapper.clientWidth + "px;";5895removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, parentStyle));5896}5897return widget.height = widget.node.offsetHeight;5898}58995900function addLineWidget(cm, handle, node, options) {5901var widget = new LineWidget(cm, node, options);5902if (widget.noHScroll) cm.display.alignWidgets = true;5903changeLine(cm.doc, handle, "widget", function(line) {5904var widgets = line.widgets || (line.widgets = []);5905if (widget.insertAt == null) widgets.push(widget);5906else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);5907widget.line = line;5908if (!lineIsHidden(cm.doc, line)) {5909var aboveVisible = heightAtLine(line) < cm.doc.scrollTop;5910updateLineHeight(line, line.height + widgetHeight(widget));5911if (aboveVisible) addToScrollPos(cm, null, widget.height);5912cm.curOp.forceUpdate = true;5913}5914return true;5915});5916return widget;5917}59185919// LINE DATA STRUCTURE59205921// Line objects. These hold state related to a line, including5922// highlighting info (the styles array).5923var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {5924this.text = text;5925attachMarkedSpans(this, markedSpans);5926this.height = estimateHeight ? estimateHeight(this) : 1;5927};5928eventMixin(Line);5929Line.prototype.lineNo = function() { return lineNo(this); };59305931// Change the content (text, markers) of a line. Automatically5932// invalidates cached information and tries to re-estimate the5933// line's height.5934function updateLine(line, text, markedSpans, estimateHeight) {5935line.text = text;5936if (line.stateAfter) line.stateAfter = null;5937if (line.styles) line.styles = null;5938if (line.order != null) line.order = null;5939detachMarkedSpans(line);5940attachMarkedSpans(line, markedSpans);5941var estHeight = estimateHeight ? estimateHeight(line) : 1;5942if (estHeight != line.height) updateLineHeight(line, estHeight);5943}59445945// Detach a line from the document tree and its markers.5946function cleanUpLine(line) {5947line.parent = null;5948detachMarkedSpans(line);5949}59505951function extractLineClasses(type, output) {5952if (type) for (;;) {5953var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);5954if (!lineClass) break;5955type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);5956var prop = lineClass[1] ? "bgClass" : "textClass";5957if (output[prop] == null)5958output[prop] = lineClass[2];5959else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))5960output[prop] += " " + lineClass[2];5961}5962return type;5963}59645965function callBlankLine(mode, state) {5966if (mode.blankLine) return mode.blankLine(state);5967if (!mode.innerMode) return;5968var inner = CodeMirror.innerMode(mode, state);5969if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);5970}59715972function readToken(mode, stream, state, inner) {5973for (var i = 0; i < 10; i++) {5974if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;5975var style = mode.token(stream, state);5976if (stream.pos > stream.start) return style;5977}5978throw new Error("Mode " + mode.name + " failed to advance stream.");5979}59805981// Utility for getTokenAt and getLineTokens5982function takeToken(cm, pos, precise, asArray) {5983function getObj(copy) {5984return {start: stream.start, end: stream.pos,5985string: stream.current(),5986type: style || null,5987state: copy ? copyState(doc.mode, state) : state};5988}59895990var doc = cm.doc, mode = doc.mode, style;5991pos = clipPos(doc, pos);5992var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);5993var stream = new StringStream(line.text, cm.options.tabSize), tokens;5994if (asArray) tokens = [];5995while ((asArray || stream.pos < pos.ch) && !stream.eol()) {5996stream.start = stream.pos;5997style = readToken(mode, stream, state);5998if (asArray) tokens.push(getObj(true));5999}6000return asArray ? tokens : getObj();6001}60026003// Run the given mode's parser over a line, calling f for each token.6004function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {6005var flattenSpans = mode.flattenSpans;6006if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;6007var curStart = 0, curStyle = null;6008var stream = new StringStream(text, cm.options.tabSize), style;6009var inner = cm.options.addModeClass && [null];6010if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);6011while (!stream.eol()) {6012if (stream.pos > cm.options.maxHighlightLength) {6013flattenSpans = false;6014if (forceToEnd) processLine(cm, text, state, stream.pos);6015stream.pos = text.length;6016style = null;6017} else {6018style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);6019}6020if (inner) {6021var mName = inner[0].name;6022if (mName) style = "m-" + (style ? mName + " " + style : mName);6023}6024if (!flattenSpans || curStyle != style) {6025while (curStart < stream.start) {6026curStart = Math.min(stream.start, curStart + 50000);6027f(curStart, curStyle);6028}6029curStyle = style;6030}6031stream.start = stream.pos;6032}6033while (curStart < stream.pos) {6034// Webkit seems to refuse to render text nodes longer than 57444 characters6035var pos = Math.min(stream.pos, curStart + 50000);6036f(pos, curStyle);6037curStart = pos;6038}6039}60406041// Compute a style array (an array starting with a mode generation6042// -- for invalidation -- followed by pairs of end positions and6043// style strings), which is used to highlight the tokens on the6044// line.6045function highlightLine(cm, line, state, forceToEnd) {6046// A styles array always starts with a number identifying the6047// mode/overlays that it is based on (for easy invalidation).6048var st = [cm.state.modeGen], lineClasses = {};6049// Compute the base array of styles6050runMode(cm, line.text, cm.doc.mode, state, function(end, style) {6051st.push(end, style);6052}, lineClasses, forceToEnd);60536054// Run overlays, adjust style array.6055for (var o = 0; o < cm.state.overlays.length; ++o) {6056var overlay = cm.state.overlays[o], i = 1, at = 0;6057runMode(cm, line.text, overlay.mode, true, function(end, style) {6058var start = i;6059// Ensure there's a token end at the current position, and that i points at it6060while (at < end) {6061var i_end = st[i];6062if (i_end > end)6063st.splice(i, 1, end, st[i+1], i_end);6064i += 2;6065at = Math.min(end, i_end);6066}6067if (!style) return;6068if (overlay.opaque) {6069st.splice(start, i - start, end, "cm-overlay " + style);6070i = start + 2;6071} else {6072for (; start < i; start += 2) {6073var cur = st[start+1];6074st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;6075}6076}6077}, lineClasses);6078}60796080return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};6081}60826083function getLineStyles(cm, line, updateFrontier) {6084if (!line.styles || line.styles[0] != cm.state.modeGen) {6085var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));6086line.styles = result.styles;6087if (result.classes) line.styleClasses = result.classes;6088else if (line.styleClasses) line.styleClasses = null;6089if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;6090}6091return line.styles;6092}60936094// Lightweight form of highlight -- proceed over this line and6095// update state, but don't save a style array. Used for lines that6096// aren't currently visible.6097function processLine(cm, text, state, startAt) {6098var mode = cm.doc.mode;6099var stream = new StringStream(text, cm.options.tabSize);6100stream.start = stream.pos = startAt || 0;6101if (text == "") callBlankLine(mode, state);6102while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {6103readToken(mode, stream, state);6104stream.start = stream.pos;6105}6106}61076108// Convert a style as returned by a mode (either null, or a string6109// containing one or more styles) to a CSS style. This is cached,6110// and also looks for line-wide styles.6111var styleToClassCache = {}, styleToClassCacheWithMode = {};6112function interpretTokenStyle(style, options) {6113if (!style || /^\s*$/.test(style)) return null;6114var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;6115return cache[style] ||6116(cache[style] = style.replace(/\S+/g, "cm-$&"));6117}61186119// Render the DOM representation of the text of a line. Also builds6120// up a 'line map', which points at the DOM nodes that represent6121// specific stretches of text, and is used by the measuring code.6122// The returned object contains the DOM node, this map, and6123// information about line-wide styles that were set by the mode.6124function buildLineContent(cm, lineView) {6125// The padding-right forces the element to have a 'border', which6126// is needed on Webkit to be able to get line-level bounding6127// rectangles for it (in measureChar).6128var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);6129var builder = {pre: elt("pre", [content]), content: content, col: 0, pos: 0, cm: cm};6130lineView.measure = {};61316132// Iterate over the logical lines that make up this visual line.6133for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {6134var line = i ? lineView.rest[i - 1] : lineView.line, order;6135builder.pos = 0;6136builder.addToken = buildToken;6137// Optionally wire in some hacks into the token-rendering6138// algorithm, to deal with browser quirks.6139if ((ie || webkit) && cm.getOption("lineWrapping"))6140builder.addToken = buildTokenSplitSpaces(builder.addToken);6141if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))6142builder.addToken = buildTokenBadBidi(builder.addToken, order);6143builder.map = [];6144var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);6145insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));6146if (line.styleClasses) {6147if (line.styleClasses.bgClass)6148builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");6149if (line.styleClasses.textClass)6150builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");6151}61526153// Ensure at least a single node is present, for measuring.6154if (builder.map.length == 0)6155builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));61566157// Store the map and a cache object for the current logical line6158if (i == 0) {6159lineView.measure.map = builder.map;6160lineView.measure.cache = {};6161} else {6162(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);6163(lineView.measure.caches || (lineView.measure.caches = [])).push({});6164}6165}61666167// See issue #29016168if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))6169builder.content.className = "cm-tab-wrap-hack";61706171signal(cm, "renderLine", cm, lineView.line, builder.pre);6172if (builder.pre.className)6173builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");61746175return builder;6176}61776178function defaultSpecialCharPlaceholder(ch) {6179var token = elt("span", "\u2022", "cm-invalidchar");6180token.title = "\\u" + ch.charCodeAt(0).toString(16);6181return token;6182}61836184// Build up the DOM representation for a single token, and add it to6185// the line map. Takes care to render special characters separately.6186function buildToken(builder, text, style, startStyle, endStyle, title, css) {6187if (!text) return;6188var special = builder.cm.options.specialChars, mustWrap = false;6189if (!special.test(text)) {6190builder.col += text.length;6191var content = document.createTextNode(text);6192builder.map.push(builder.pos, builder.pos + text.length, content);6193if (ie && ie_version < 9) mustWrap = true;6194builder.pos += text.length;6195} else {6196var content = document.createDocumentFragment(), pos = 0;6197while (true) {6198special.lastIndex = pos;6199var m = special.exec(text);6200var skipped = m ? m.index - pos : text.length - pos;6201if (skipped) {6202var txt = document.createTextNode(text.slice(pos, pos + skipped));6203if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));6204else content.appendChild(txt);6205builder.map.push(builder.pos, builder.pos + skipped, txt);6206builder.col += skipped;6207builder.pos += skipped;6208}6209if (!m) break;6210pos += skipped + 1;6211if (m[0] == "\t") {6212var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;6213var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));6214builder.col += tabWidth;6215} else {6216var txt = builder.cm.options.specialCharPlaceholder(m[0]);6217if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));6218else content.appendChild(txt);6219builder.col += 1;6220}6221builder.map.push(builder.pos, builder.pos + 1, txt);6222builder.pos++;6223}6224}6225if (style || startStyle || endStyle || mustWrap || css) {6226var fullStyle = style || "";6227if (startStyle) fullStyle += startStyle;6228if (endStyle) fullStyle += endStyle;6229var token = elt("span", [content], fullStyle, css);6230if (title) token.title = title;6231return builder.content.appendChild(token);6232}6233builder.content.appendChild(content);6234}62356236function buildTokenSplitSpaces(inner) {6237function split(old) {6238var out = " ";6239for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";6240out += " ";6241return out;6242}6243return function(builder, text, style, startStyle, endStyle, title) {6244inner(builder, text.replace(/ {3,}/g, split), style, startStyle, endStyle, title);6245};6246}62476248// Work around nonsense dimensions being reported for stretches of6249// right-to-left text.6250function buildTokenBadBidi(inner, order) {6251return function(builder, text, style, startStyle, endStyle, title) {6252style = style ? style + " cm-force-border" : "cm-force-border";6253var start = builder.pos, end = start + text.length;6254for (;;) {6255// Find the part that overlaps with the start of this text6256for (var i = 0; i < order.length; i++) {6257var part = order[i];6258if (part.to > start && part.from <= start) break;6259}6260if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title);6261inner(builder, text.slice(0, part.to - start), style, startStyle, null, title);6262startStyle = null;6263text = text.slice(part.to - start);6264start = part.to;6265}6266};6267}62686269function buildCollapsedSpan(builder, size, marker, ignoreWidget) {6270var widget = !ignoreWidget && marker.widgetNode;6271if (widget) {6272builder.map.push(builder.pos, builder.pos + size, widget);6273builder.content.appendChild(widget);6274}6275builder.pos += size;6276}62776278// Outputs a number of spans to make up a line, taking highlighting6279// and marked text into account.6280function insertLineContent(line, builder, styles) {6281var spans = line.markedSpans, allText = line.text, at = 0;6282if (!spans) {6283for (var i = 1; i < styles.length; i+=2)6284builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));6285return;6286}62876288var len = allText.length, pos = 0, i = 1, text = "", style, css;6289var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;6290for (;;) {6291if (nextChange == pos) { // Update current marker set6292spanStyle = spanEndStyle = spanStartStyle = title = css = "";6293collapsed = null; nextChange = Infinity;6294var foundBookmarks = [];6295for (var j = 0; j < spans.length; ++j) {6296var sp = spans[j], m = sp.marker;6297if (sp.from <= pos && (sp.to == null || sp.to > pos)) {6298if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }6299if (m.className) spanStyle += " " + m.className;6300if (m.css) css = m.css;6301if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;6302if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;6303if (m.title && !title) title = m.title;6304if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))6305collapsed = sp;6306} else if (sp.from > pos && nextChange > sp.from) {6307nextChange = sp.from;6308}6309if (m.type == "bookmark" && sp.from == pos && m.widgetNode) foundBookmarks.push(m);6310}6311if (collapsed && (collapsed.from || 0) == pos) {6312buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,6313collapsed.marker, collapsed.from == null);6314if (collapsed.to == null) return;6315}6316if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)6317buildCollapsedSpan(builder, 0, foundBookmarks[j]);6318}6319if (pos >= len) break;63206321var upto = Math.min(len, nextChange);6322while (true) {6323if (text) {6324var end = pos + text.length;6325if (!collapsed) {6326var tokenText = end > upto ? text.slice(0, upto - pos) : text;6327builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,6328spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);6329}6330if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}6331pos = end;6332spanStartStyle = "";6333}6334text = allText.slice(at, at = styles[i++]);6335style = interpretTokenStyle(styles[i++], builder.cm.options);6336}6337}6338}63396340// DOCUMENT DATA STRUCTURE63416342// By default, updates that start and end at the beginning of a line6343// are treated specially, in order to make the association of line6344// widgets and marker elements with the text behave more intuitive.6345function isWholeLineUpdate(doc, change) {6346return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&6347(!doc.cm || doc.cm.options.wholeLineUpdateBefore);6348}63496350// Perform a change on the document data structure.6351function updateDoc(doc, change, markedSpans, estimateHeight) {6352function spansFor(n) {return markedSpans ? markedSpans[n] : null;}6353function update(line, text, spans) {6354updateLine(line, text, spans, estimateHeight);6355signalLater(line, "change", line, change);6356}6357function linesFor(start, end) {6358for (var i = start, result = []; i < end; ++i)6359result.push(new Line(text[i], spansFor(i), estimateHeight));6360return result;6361}63626363var from = change.from, to = change.to, text = change.text;6364var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);6365var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;63666367// Adjust the line structure6368if (change.full) {6369doc.insert(0, linesFor(0, text.length));6370doc.remove(text.length, doc.size - text.length);6371} else if (isWholeLineUpdate(doc, change)) {6372// This is a whole-line replace. Treated specially to make6373// sure line objects move the way they are supposed to.6374var added = linesFor(0, text.length - 1);6375update(lastLine, lastLine.text, lastSpans);6376if (nlines) doc.remove(from.line, nlines);6377if (added.length) doc.insert(from.line, added);6378} else if (firstLine == lastLine) {6379if (text.length == 1) {6380update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);6381} else {6382var added = linesFor(1, text.length - 1);6383added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));6384update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));6385doc.insert(from.line + 1, added);6386}6387} else if (text.length == 1) {6388update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));6389doc.remove(from.line + 1, nlines);6390} else {6391update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));6392update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);6393var added = linesFor(1, text.length - 1);6394if (nlines > 1) doc.remove(from.line + 1, nlines - 1);6395doc.insert(from.line + 1, added);6396}63976398signalLater(doc, "change", doc, change);6399}64006401// The document is represented as a BTree consisting of leaves, with6402// chunk of lines in them, and branches, with up to ten leaves or6403// other branch nodes below them. The top node is always a branch6404// node, and is the document object itself (meaning it has6405// additional methods and properties).6406//6407// All nodes have parent links. The tree is used both to go from6408// line numbers to line objects, and to go from objects to numbers.6409// It also indexes by height, and is used to convert between height6410// and line object, and to find the total height of the document.6411//6412// See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html64136414function LeafChunk(lines) {6415this.lines = lines;6416this.parent = null;6417for (var i = 0, height = 0; i < lines.length; ++i) {6418lines[i].parent = this;6419height += lines[i].height;6420}6421this.height = height;6422}64236424LeafChunk.prototype = {6425chunkSize: function() { return this.lines.length; },6426// Remove the n lines at offset 'at'.6427removeInner: function(at, n) {6428for (var i = at, e = at + n; i < e; ++i) {6429var line = this.lines[i];6430this.height -= line.height;6431cleanUpLine(line);6432signalLater(line, "delete");6433}6434this.lines.splice(at, n);6435},6436// Helper used to collapse a small branch into a single leaf.6437collapse: function(lines) {6438lines.push.apply(lines, this.lines);6439},6440// Insert the given array of lines at offset 'at', count them as6441// having the given height.6442insertInner: function(at, lines, height) {6443this.height += height;6444this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));6445for (var i = 0; i < lines.length; ++i) lines[i].parent = this;6446},6447// Used to iterate over a part of the tree.6448iterN: function(at, n, op) {6449for (var e = at + n; at < e; ++at)6450if (op(this.lines[at])) return true;6451}6452};64536454function BranchChunk(children) {6455this.children = children;6456var size = 0, height = 0;6457for (var i = 0; i < children.length; ++i) {6458var ch = children[i];6459size += ch.chunkSize(); height += ch.height;6460ch.parent = this;6461}6462this.size = size;6463this.height = height;6464this.parent = null;6465}64666467BranchChunk.prototype = {6468chunkSize: function() { return this.size; },6469removeInner: function(at, n) {6470this.size -= n;6471for (var i = 0; i < this.children.length; ++i) {6472var child = this.children[i], sz = child.chunkSize();6473if (at < sz) {6474var rm = Math.min(n, sz - at), oldHeight = child.height;6475child.removeInner(at, rm);6476this.height -= oldHeight - child.height;6477if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }6478if ((n -= rm) == 0) break;6479at = 0;6480} else at -= sz;6481}6482// If the result is smaller than 25 lines, ensure that it is a6483// single leaf node.6484if (this.size - n < 25 &&6485(this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {6486var lines = [];6487this.collapse(lines);6488this.children = [new LeafChunk(lines)];6489this.children[0].parent = this;6490}6491},6492collapse: function(lines) {6493for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);6494},6495insertInner: function(at, lines, height) {6496this.size += lines.length;6497this.height += height;6498for (var i = 0; i < this.children.length; ++i) {6499var child = this.children[i], sz = child.chunkSize();6500if (at <= sz) {6501child.insertInner(at, lines, height);6502if (child.lines && child.lines.length > 50) {6503while (child.lines.length > 50) {6504var spilled = child.lines.splice(child.lines.length - 25, 25);6505var newleaf = new LeafChunk(spilled);6506child.height -= newleaf.height;6507this.children.splice(i + 1, 0, newleaf);6508newleaf.parent = this;6509}6510this.maybeSpill();6511}6512break;6513}6514at -= sz;6515}6516},6517// When a node has grown, check whether it should be split.6518maybeSpill: function() {6519if (this.children.length <= 10) return;6520var me = this;6521do {6522var spilled = me.children.splice(me.children.length - 5, 5);6523var sibling = new BranchChunk(spilled);6524if (!me.parent) { // Become the parent node6525var copy = new BranchChunk(me.children);6526copy.parent = me;6527me.children = [copy, sibling];6528me = copy;6529} else {6530me.size -= sibling.size;6531me.height -= sibling.height;6532var myIndex = indexOf(me.parent.children, me);6533me.parent.children.splice(myIndex + 1, 0, sibling);6534}6535sibling.parent = me.parent;6536} while (me.children.length > 10);6537me.parent.maybeSpill();6538},6539iterN: function(at, n, op) {6540for (var i = 0; i < this.children.length; ++i) {6541var child = this.children[i], sz = child.chunkSize();6542if (at < sz) {6543var used = Math.min(n, sz - at);6544if (child.iterN(at, used, op)) return true;6545if ((n -= used) == 0) break;6546at = 0;6547} else at -= sz;6548}6549}6550};65516552var nextDocId = 0;6553var Doc = CodeMirror.Doc = function(text, mode, firstLine) {6554if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);6555if (firstLine == null) firstLine = 0;65566557BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);6558this.first = firstLine;6559this.scrollTop = this.scrollLeft = 0;6560this.cantEdit = false;6561this.cleanGeneration = 1;6562this.frontier = firstLine;6563var start = Pos(firstLine, 0);6564this.sel = simpleSelection(start);6565this.history = new History(null);6566this.id = ++nextDocId;6567this.modeOption = mode;65686569if (typeof text == "string") text = splitLines(text);6570updateDoc(this, {from: start, to: start, text: text});6571setSelection(this, simpleSelection(start), sel_dontScroll);6572};65736574Doc.prototype = createObj(BranchChunk.prototype, {6575constructor: Doc,6576// Iterate over the document. Supports two forms -- with only one6577// argument, it calls that for each line in the document. With6578// three, it iterates over the range given by the first two (with6579// the second being non-inclusive).6580iter: function(from, to, op) {6581if (op) this.iterN(from - this.first, to - from, op);6582else this.iterN(this.first, this.first + this.size, from);6583},65846585// Non-public interface for adding and removing lines.6586insert: function(at, lines) {6587var height = 0;6588for (var i = 0; i < lines.length; ++i) height += lines[i].height;6589this.insertInner(at - this.first, lines, height);6590},6591remove: function(at, n) { this.removeInner(at - this.first, n); },65926593// From here, the methods are part of the public interface. Most6594// are also available from CodeMirror (editor) instances.65956596getValue: function(lineSep) {6597var lines = getLines(this, this.first, this.first + this.size);6598if (lineSep === false) return lines;6599return lines.join(lineSep || "\n");6600},6601setValue: docMethodOp(function(code) {6602var top = Pos(this.first, 0), last = this.first + this.size - 1;6603makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),6604text: splitLines(code), origin: "setValue", full: true}, true);6605setSelection(this, simpleSelection(top));6606}),6607replaceRange: function(code, from, to, origin) {6608from = clipPos(this, from);6609to = to ? clipPos(this, to) : from;6610replaceRange(this, code, from, to, origin);6611},6612getRange: function(from, to, lineSep) {6613var lines = getBetween(this, clipPos(this, from), clipPos(this, to));6614if (lineSep === false) return lines;6615return lines.join(lineSep || "\n");6616},66176618getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},66196620getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},6621getLineNumber: function(line) {return lineNo(line);},66226623getLineHandleVisualStart: function(line) {6624if (typeof line == "number") line = getLine(this, line);6625return visualLine(line);6626},66276628lineCount: function() {return this.size;},6629firstLine: function() {return this.first;},6630lastLine: function() {return this.first + this.size - 1;},66316632clipPos: function(pos) {return clipPos(this, pos);},66336634getCursor: function(start) {6635var range = this.sel.primary(), pos;6636if (start == null || start == "head") pos = range.head;6637else if (start == "anchor") pos = range.anchor;6638else if (start == "end" || start == "to" || start === false) pos = range.to();6639else pos = range.from();6640return pos;6641},6642listSelections: function() { return this.sel.ranges; },6643somethingSelected: function() {return this.sel.somethingSelected();},66446645setCursor: docMethodOp(function(line, ch, options) {6646setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);6647}),6648setSelection: docMethodOp(function(anchor, head, options) {6649setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);6650}),6651extendSelection: docMethodOp(function(head, other, options) {6652extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);6653}),6654extendSelections: docMethodOp(function(heads, options) {6655extendSelections(this, clipPosArray(this, heads, options));6656}),6657extendSelectionsBy: docMethodOp(function(f, options) {6658extendSelections(this, map(this.sel.ranges, f), options);6659}),6660setSelections: docMethodOp(function(ranges, primary, options) {6661if (!ranges.length) return;6662for (var i = 0, out = []; i < ranges.length; i++)6663out[i] = new Range(clipPos(this, ranges[i].anchor),6664clipPos(this, ranges[i].head));6665if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);6666setSelection(this, normalizeSelection(out, primary), options);6667}),6668addSelection: docMethodOp(function(anchor, head, options) {6669var ranges = this.sel.ranges.slice(0);6670ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));6671setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);6672}),66736674getSelection: function(lineSep) {6675var ranges = this.sel.ranges, lines;6676for (var i = 0; i < ranges.length; i++) {6677var sel = getBetween(this, ranges[i].from(), ranges[i].to());6678lines = lines ? lines.concat(sel) : sel;6679}6680if (lineSep === false) return lines;6681else return lines.join(lineSep || "\n");6682},6683getSelections: function(lineSep) {6684var parts = [], ranges = this.sel.ranges;6685for (var i = 0; i < ranges.length; i++) {6686var sel = getBetween(this, ranges[i].from(), ranges[i].to());6687if (lineSep !== false) sel = sel.join(lineSep || "\n");6688parts[i] = sel;6689}6690return parts;6691},6692replaceSelection: function(code, collapse, origin) {6693var dup = [];6694for (var i = 0; i < this.sel.ranges.length; i++)6695dup[i] = code;6696this.replaceSelections(dup, collapse, origin || "+input");6697},6698replaceSelections: docMethodOp(function(code, collapse, origin) {6699var changes = [], sel = this.sel;6700for (var i = 0; i < sel.ranges.length; i++) {6701var range = sel.ranges[i];6702changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin};6703}6704var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);6705for (var i = changes.length - 1; i >= 0; i--)6706makeChange(this, changes[i]);6707if (newSel) setSelectionReplaceHistory(this, newSel);6708else if (this.cm) ensureCursorVisible(this.cm);6709}),6710undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),6711redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),6712undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),6713redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),67146715setExtending: function(val) {this.extend = val;},6716getExtending: function() {return this.extend;},67176718historySize: function() {6719var hist = this.history, done = 0, undone = 0;6720for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;6721for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;6722return {undo: done, redo: undone};6723},6724clearHistory: function() {this.history = new History(this.history.maxGeneration);},67256726markClean: function() {6727this.cleanGeneration = this.changeGeneration(true);6728},6729changeGeneration: function(forceSplit) {6730if (forceSplit)6731this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;6732return this.history.generation;6733},6734isClean: function (gen) {6735return this.history.generation == (gen || this.cleanGeneration);6736},67376738getHistory: function() {6739return {done: copyHistoryArray(this.history.done),6740undone: copyHistoryArray(this.history.undone)};6741},6742setHistory: function(histData) {6743var hist = this.history = new History(this.history.maxGeneration);6744hist.done = copyHistoryArray(histData.done.slice(0), null, true);6745hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);6746},67476748addLineClass: docMethodOp(function(handle, where, cls) {6749return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {6750var prop = where == "text" ? "textClass"6751: where == "background" ? "bgClass"6752: where == "gutter" ? "gutterClass" : "wrapClass";6753if (!line[prop]) line[prop] = cls;6754else if (classTest(cls).test(line[prop])) return false;6755else line[prop] += " " + cls;6756return true;6757});6758}),6759removeLineClass: docMethodOp(function(handle, where, cls) {6760return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {6761var prop = where == "text" ? "textClass"6762: where == "background" ? "bgClass"6763: where == "gutter" ? "gutterClass" : "wrapClass";6764var cur = line[prop];6765if (!cur) return false;6766else if (cls == null) line[prop] = null;6767else {6768var found = cur.match(classTest(cls));6769if (!found) return false;6770var end = found.index + found[0].length;6771line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;6772}6773return true;6774});6775}),67766777markText: function(from, to, options) {6778return markText(this, clipPos(this, from), clipPos(this, to), options, "range");6779},6780setBookmark: function(pos, options) {6781var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),6782insertLeft: options && options.insertLeft,6783clearWhenEmpty: false, shared: options && options.shared};6784pos = clipPos(this, pos);6785return markText(this, pos, pos, realOpts, "bookmark");6786},6787findMarksAt: function(pos) {6788pos = clipPos(this, pos);6789var markers = [], spans = getLine(this, pos.line).markedSpans;6790if (spans) for (var i = 0; i < spans.length; ++i) {6791var span = spans[i];6792if ((span.from == null || span.from <= pos.ch) &&6793(span.to == null || span.to >= pos.ch))6794markers.push(span.marker.parent || span.marker);6795}6796return markers;6797},6798findMarks: function(from, to, filter) {6799from = clipPos(this, from); to = clipPos(this, to);6800var found = [], lineNo = from.line;6801this.iter(from.line, to.line + 1, function(line) {6802var spans = line.markedSpans;6803if (spans) for (var i = 0; i < spans.length; i++) {6804var span = spans[i];6805if (!(lineNo == from.line && from.ch > span.to ||6806span.from == null && lineNo != from.line||6807lineNo == to.line && span.from > to.ch) &&6808(!filter || filter(span.marker)))6809found.push(span.marker.parent || span.marker);6810}6811++lineNo;6812});6813return found;6814},6815getAllMarks: function() {6816var markers = [];6817this.iter(function(line) {6818var sps = line.markedSpans;6819if (sps) for (var i = 0; i < sps.length; ++i)6820if (sps[i].from != null) markers.push(sps[i].marker);6821});6822return markers;6823},68246825posFromIndex: function(off) {6826var ch, lineNo = this.first;6827this.iter(function(line) {6828var sz = line.text.length + 1;6829if (sz > off) { ch = off; return true; }6830off -= sz;6831++lineNo;6832});6833return clipPos(this, Pos(lineNo, ch));6834},6835indexFromPos: function (coords) {6836coords = clipPos(this, coords);6837var index = coords.ch;6838if (coords.line < this.first || coords.ch < 0) return 0;6839this.iter(this.first, coords.line, function (line) {6840index += line.text.length + 1;6841});6842return index;6843},68446845copy: function(copyHistory) {6846var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);6847doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;6848doc.sel = this.sel;6849doc.extend = false;6850if (copyHistory) {6851doc.history.undoDepth = this.history.undoDepth;6852doc.setHistory(this.getHistory());6853}6854return doc;6855},68566857linkedDoc: function(options) {6858if (!options) options = {};6859var from = this.first, to = this.first + this.size;6860if (options.from != null && options.from > from) from = options.from;6861if (options.to != null && options.to < to) to = options.to;6862var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);6863if (options.sharedHist) copy.history = this.history;6864(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});6865copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];6866copySharedMarkers(copy, findSharedMarkers(this));6867return copy;6868},6869unlinkDoc: function(other) {6870if (other instanceof CodeMirror) other = other.doc;6871if (this.linked) for (var i = 0; i < this.linked.length; ++i) {6872var link = this.linked[i];6873if (link.doc != other) continue;6874this.linked.splice(i, 1);6875other.unlinkDoc(this);6876detachSharedMarkers(findSharedMarkers(this));6877break;6878}6879// If the histories were shared, split them again6880if (other.history == this.history) {6881var splitIds = [other.id];6882linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);6883other.history = new History(null);6884other.history.done = copyHistoryArray(this.history.done, splitIds);6885other.history.undone = copyHistoryArray(this.history.undone, splitIds);6886}6887},6888iterLinkedDocs: function(f) {linkedDocs(this, f);},68896890getMode: function() {return this.mode;},6891getEditor: function() {return this.cm;}6892});68936894// Public alias.6895Doc.prototype.eachLine = Doc.prototype.iter;68966897// Set up methods on CodeMirror's prototype to redirect to the editor's document.6898var dontDelegate = "iter insert remove copy getEditor".split(" ");6899for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)6900CodeMirror.prototype[prop] = (function(method) {6901return function() {return method.apply(this.doc, arguments);};6902})(Doc.prototype[prop]);69036904eventMixin(Doc);69056906// Call f for all linked documents.6907function linkedDocs(doc, f, sharedHistOnly) {6908function propagate(doc, skip, sharedHist) {6909if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {6910var rel = doc.linked[i];6911if (rel.doc == skip) continue;6912var shared = sharedHist && rel.sharedHist;6913if (sharedHistOnly && !shared) continue;6914f(rel.doc, shared);6915propagate(rel.doc, doc, shared);6916}6917}6918propagate(doc, null, true);6919}69206921// Attach a document to an editor.6922function attachDoc(cm, doc) {6923if (doc.cm) throw new Error("This document is already in use.");6924cm.doc = doc;6925doc.cm = cm;6926estimateLineHeights(cm);6927loadMode(cm);6928if (!cm.options.lineWrapping) findMaxLine(cm);6929cm.options.mode = doc.modeOption;6930regChange(cm);6931}69326933// LINE UTILITIES69346935// Find the line object corresponding to the given line number.6936function getLine(doc, n) {6937n -= doc.first;6938if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");6939for (var chunk = doc; !chunk.lines;) {6940for (var i = 0;; ++i) {6941var child = chunk.children[i], sz = child.chunkSize();6942if (n < sz) { chunk = child; break; }6943n -= sz;6944}6945}6946return chunk.lines[n];6947}69486949// Get the part of a document between two positions, as an array of6950// strings.6951function getBetween(doc, start, end) {6952var out = [], n = start.line;6953doc.iter(start.line, end.line + 1, function(line) {6954var text = line.text;6955if (n == end.line) text = text.slice(0, end.ch);6956if (n == start.line) text = text.slice(start.ch);6957out.push(text);6958++n;6959});6960return out;6961}6962// Get the lines between from and to, as array of strings.6963function getLines(doc, from, to) {6964var out = [];6965doc.iter(from, to, function(line) { out.push(line.text); });6966return out;6967}69686969// Update the height of a line, propagating the height change6970// upwards to parent nodes.6971function updateLineHeight(line, height) {6972var diff = height - line.height;6973if (diff) for (var n = line; n; n = n.parent) n.height += diff;6974}69756976// Given a line object, find its line number by walking up through6977// its parent links.6978function lineNo(line) {6979if (line.parent == null) return null;6980var cur = line.parent, no = indexOf(cur.lines, line);6981for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {6982for (var i = 0;; ++i) {6983if (chunk.children[i] == cur) break;6984no += chunk.children[i].chunkSize();6985}6986}6987return no + cur.first;6988}69896990// Find the line at the given vertical position, using the height6991// information in the document tree.6992function lineAtHeight(chunk, h) {6993var n = chunk.first;6994outer: do {6995for (var i = 0; i < chunk.children.length; ++i) {6996var child = chunk.children[i], ch = child.height;6997if (h < ch) { chunk = child; continue outer; }6998h -= ch;6999n += child.chunkSize();7000}7001return n;7002} while (!chunk.lines);7003for (var i = 0; i < chunk.lines.length; ++i) {7004var line = chunk.lines[i], lh = line.height;7005if (h < lh) break;7006h -= lh;7007}7008return n + i;7009}701070117012// Find the height above the given line.7013function heightAtLine(lineObj) {7014lineObj = visualLine(lineObj);70157016var h = 0, chunk = lineObj.parent;7017for (var i = 0; i < chunk.lines.length; ++i) {7018var line = chunk.lines[i];7019if (line == lineObj) break;7020else h += line.height;7021}7022for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {7023for (var i = 0; i < p.children.length; ++i) {7024var cur = p.children[i];7025if (cur == chunk) break;7026else h += cur.height;7027}7028}7029return h;7030}70317032// Get the bidi ordering for the given line (and cache it). Returns7033// false for lines that are fully left-to-right, and an array of7034// BidiSpan objects otherwise.7035function getOrder(line) {7036var order = line.order;7037if (order == null) order = line.order = bidiOrdering(line.text);7038return order;7039}70407041// HISTORY70427043function History(startGen) {7044// Arrays of change events and selections. Doing something adds an7045// event to done and clears undo. Undoing moves events from done7046// to undone, redoing moves them in the other direction.7047this.done = []; this.undone = [];7048this.undoDepth = Infinity;7049// Used to track when changes can be merged into a single undo7050// event7051this.lastModTime = this.lastSelTime = 0;7052this.lastOp = this.lastSelOp = null;7053this.lastOrigin = this.lastSelOrigin = null;7054// Used by the isClean() method7055this.generation = this.maxGeneration = startGen || 1;7056}70577058// Create a history change event from an updateDoc-style change7059// object.7060function historyChangeFromChange(doc, change) {7061var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};7062attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);7063linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);7064return histChange;7065}70667067// Pop all selection events off the end of a history array. Stop at7068// a change event.7069function clearSelectionEvents(array) {7070while (array.length) {7071var last = lst(array);7072if (last.ranges) array.pop();7073else break;7074}7075}70767077// Find the top change event in the history. Pop off selection7078// events that are in the way.7079function lastChangeEvent(hist, force) {7080if (force) {7081clearSelectionEvents(hist.done);7082return lst(hist.done);7083} else if (hist.done.length && !lst(hist.done).ranges) {7084return lst(hist.done);7085} else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {7086hist.done.pop();7087return lst(hist.done);7088}7089}70907091// Register a change in the history. Merges changes that are within7092// a single operation, ore are close together with an origin that7093// allows merging (starting with "+") into a single event.7094function addChangeToHistory(doc, change, selAfter, opId) {7095var hist = doc.history;7096hist.undone.length = 0;7097var time = +new Date, cur;70987099if ((hist.lastOp == opId ||7100hist.lastOrigin == change.origin && change.origin &&7101((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||7102change.origin.charAt(0) == "*")) &&7103(cur = lastChangeEvent(hist, hist.lastOp == opId))) {7104// Merge this change into the last event7105var last = lst(cur.changes);7106if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {7107// Optimized case for simple insertion -- don't want to add7108// new changesets for every character typed7109last.to = changeEnd(change);7110} else {7111// Add new sub-event7112cur.changes.push(historyChangeFromChange(doc, change));7113}7114} else {7115// Can not be merged, start a new event.7116var before = lst(hist.done);7117if (!before || !before.ranges)7118pushSelectionToHistory(doc.sel, hist.done);7119cur = {changes: [historyChangeFromChange(doc, change)],7120generation: hist.generation};7121hist.done.push(cur);7122while (hist.done.length > hist.undoDepth) {7123hist.done.shift();7124if (!hist.done[0].ranges) hist.done.shift();7125}7126}7127hist.done.push(selAfter);7128hist.generation = ++hist.maxGeneration;7129hist.lastModTime = hist.lastSelTime = time;7130hist.lastOp = hist.lastSelOp = opId;7131hist.lastOrigin = hist.lastSelOrigin = change.origin;71327133if (!last) signal(doc, "historyAdded");7134}71357136function selectionEventCanBeMerged(doc, origin, prev, sel) {7137var ch = origin.charAt(0);7138return ch == "*" ||7139ch == "+" &&7140prev.ranges.length == sel.ranges.length &&7141prev.somethingSelected() == sel.somethingSelected() &&7142new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);7143}71447145// Called whenever the selection changes, sets the new selection as7146// the pending selection in the history, and pushes the old pending7147// selection into the 'done' array when it was significantly7148// different (in number of selected ranges, emptiness, or time).7149function addSelectionToHistory(doc, sel, opId, options) {7150var hist = doc.history, origin = options && options.origin;71517152// A new event is started when the previous origin does not match7153// the current, or the origins don't allow matching. Origins7154// starting with * are always merged, those starting with + are7155// merged when similar and close together in time.7156if (opId == hist.lastSelOp ||7157(origin && hist.lastSelOrigin == origin &&7158(hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||7159selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))7160hist.done[hist.done.length - 1] = sel;7161else7162pushSelectionToHistory(sel, hist.done);71637164hist.lastSelTime = +new Date;7165hist.lastSelOrigin = origin;7166hist.lastSelOp = opId;7167if (options && options.clearRedo !== false)7168clearSelectionEvents(hist.undone);7169}71707171function pushSelectionToHistory(sel, dest) {7172var top = lst(dest);7173if (!(top && top.ranges && top.equals(sel)))7174dest.push(sel);7175}71767177// Used to store marked span information in the history.7178function attachLocalSpans(doc, change, from, to) {7179var existing = change["spans_" + doc.id], n = 0;7180doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {7181if (line.markedSpans)7182(existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;7183++n;7184});7185}71867187// When un/re-doing restores text containing marked spans, those7188// that have been explicitly cleared should not be restored.7189function removeClearedSpans(spans) {7190if (!spans) return null;7191for (var i = 0, out; i < spans.length; ++i) {7192if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }7193else if (out) out.push(spans[i]);7194}7195return !out ? spans : out.length ? out : null;7196}71977198// Retrieve and filter the old marked spans stored in a change event.7199function getOldSpans(doc, change) {7200var found = change["spans_" + doc.id];7201if (!found) return null;7202for (var i = 0, nw = []; i < change.text.length; ++i)7203nw.push(removeClearedSpans(found[i]));7204return nw;7205}72067207// Used both to provide a JSON-safe object in .getHistory, and, when7208// detaching a document, to split the history in two7209function copyHistoryArray(events, newGroup, instantiateSel) {7210for (var i = 0, copy = []; i < events.length; ++i) {7211var event = events[i];7212if (event.ranges) {7213copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);7214continue;7215}7216var changes = event.changes, newChanges = [];7217copy.push({changes: newChanges});7218for (var j = 0; j < changes.length; ++j) {7219var change = changes[j], m;7220newChanges.push({from: change.from, to: change.to, text: change.text});7221if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {7222if (indexOf(newGroup, Number(m[1])) > -1) {7223lst(newChanges)[prop] = change[prop];7224delete change[prop];7225}7226}7227}7228}7229return copy;7230}72317232// Rebasing/resetting history to deal with externally-sourced changes72337234function rebaseHistSelSingle(pos, from, to, diff) {7235if (to < pos.line) {7236pos.line += diff;7237} else if (from < pos.line) {7238pos.line = from;7239pos.ch = 0;7240}7241}72427243// Tries to rebase an array of history events given a change in the7244// document. If the change touches the same lines as the event, the7245// event, and everything 'behind' it, is discarded. If the change is7246// before the event, the event's positions are updated. Uses a7247// copy-on-write scheme for the positions, to avoid having to7248// reallocate them all on every rebase, but also avoid problems with7249// shared position objects being unsafely updated.7250function rebaseHistArray(array, from, to, diff) {7251for (var i = 0; i < array.length; ++i) {7252var sub = array[i], ok = true;7253if (sub.ranges) {7254if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }7255for (var j = 0; j < sub.ranges.length; j++) {7256rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);7257rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);7258}7259continue;7260}7261for (var j = 0; j < sub.changes.length; ++j) {7262var cur = sub.changes[j];7263if (to < cur.from.line) {7264cur.from = Pos(cur.from.line + diff, cur.from.ch);7265cur.to = Pos(cur.to.line + diff, cur.to.ch);7266} else if (from <= cur.to.line) {7267ok = false;7268break;7269}7270}7271if (!ok) {7272array.splice(0, i + 1);7273i = 0;7274}7275}7276}72777278function rebaseHist(hist, change) {7279var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;7280rebaseHistArray(hist.done, from, to, diff);7281rebaseHistArray(hist.undone, from, to, diff);7282}72837284// EVENT UTILITIES72857286// Due to the fact that we still support jurassic IE versions, some7287// compatibility wrappers are needed.72887289var e_preventDefault = CodeMirror.e_preventDefault = function(e) {7290if (e.preventDefault) e.preventDefault();7291else e.returnValue = false;7292};7293var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {7294if (e.stopPropagation) e.stopPropagation();7295else e.cancelBubble = true;7296};7297function e_defaultPrevented(e) {7298return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;7299}7300var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};73017302function e_target(e) {return e.target || e.srcElement;}7303function e_button(e) {7304var b = e.which;7305if (b == null) {7306if (e.button & 1) b = 1;7307else if (e.button & 2) b = 3;7308else if (e.button & 4) b = 2;7309}7310if (mac && e.ctrlKey && b == 1) b = 3;7311return b;7312}73137314// EVENT HANDLING73157316// Lightweight event framework. on/off also work on DOM nodes,7317// registering native DOM handlers.73187319var on = CodeMirror.on = function(emitter, type, f) {7320if (emitter.addEventListener)7321emitter.addEventListener(type, f, false);7322else if (emitter.attachEvent)7323emitter.attachEvent("on" + type, f);7324else {7325var map = emitter._handlers || (emitter._handlers = {});7326var arr = map[type] || (map[type] = []);7327arr.push(f);7328}7329};73307331var off = CodeMirror.off = function(emitter, type, f) {7332if (emitter.removeEventListener)7333emitter.removeEventListener(type, f, false);7334else if (emitter.detachEvent)7335emitter.detachEvent("on" + type, f);7336else {7337var arr = emitter._handlers && emitter._handlers[type];7338if (!arr) return;7339for (var i = 0; i < arr.length; ++i)7340if (arr[i] == f) { arr.splice(i, 1); break; }7341}7342};73437344var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {7345var arr = emitter._handlers && emitter._handlers[type];7346if (!arr) return;7347var args = Array.prototype.slice.call(arguments, 2);7348for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);7349};73507351var orphanDelayedCallbacks = null;73527353// Often, we want to signal events at a point where we are in the7354// middle of some work, but don't want the handler to start calling7355// other methods on the editor, which might be in an inconsistent7356// state or simply not expect any other events to happen.7357// signalLater looks whether there are any handlers, and schedules7358// them to be executed when the last operation ends, or, if no7359// operation is active, when a timeout fires.7360function signalLater(emitter, type /*, values...*/) {7361var arr = emitter._handlers && emitter._handlers[type];7362if (!arr) return;7363var args = Array.prototype.slice.call(arguments, 2), list;7364if (operationGroup) {7365list = operationGroup.delayedCallbacks;7366} else if (orphanDelayedCallbacks) {7367list = orphanDelayedCallbacks;7368} else {7369list = orphanDelayedCallbacks = [];7370setTimeout(fireOrphanDelayed, 0);7371}7372function bnd(f) {return function(){f.apply(null, args);};};7373for (var i = 0; i < arr.length; ++i)7374list.push(bnd(arr[i]));7375}73767377function fireOrphanDelayed() {7378var delayed = orphanDelayedCallbacks;7379orphanDelayedCallbacks = null;7380for (var i = 0; i < delayed.length; ++i) delayed[i]();7381}73827383// The DOM events that CodeMirror handles can be overridden by7384// registering a (non-DOM) handler on the editor for the event name,7385// and preventDefault-ing the event in that handler.7386function signalDOMEvent(cm, e, override) {7387if (typeof e == "string")7388e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};7389signal(cm, override || e.type, cm, e);7390return e_defaultPrevented(e) || e.codemirrorIgnore;7391}73927393function signalCursorActivity(cm) {7394var arr = cm._handlers && cm._handlers.cursorActivity;7395if (!arr) return;7396var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);7397for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)7398set.push(arr[i]);7399}74007401function hasHandler(emitter, type) {7402var arr = emitter._handlers && emitter._handlers[type];7403return arr && arr.length > 0;7404}74057406// Add on and off methods to a constructor's prototype, to make7407// registering events on such objects more convenient.7408function eventMixin(ctor) {7409ctor.prototype.on = function(type, f) {on(this, type, f);};7410ctor.prototype.off = function(type, f) {off(this, type, f);};7411}74127413// MISC UTILITIES74147415// Number of pixels added to scroller and sizer to hide scrollbar7416var scrollerGap = 30;74177418// Returned or thrown by various protocols to signal 'I'm not7419// handling this'.7420var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};74217422// Reused option objects for setSelection & friends7423var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};74247425function Delayed() {this.id = null;}7426Delayed.prototype.set = function(ms, f) {7427clearTimeout(this.id);7428this.id = setTimeout(f, ms);7429};74307431// Counts the column offset in a string, taking tabs into account.7432// Used mostly to find indentation.7433var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {7434if (end == null) {7435end = string.search(/[^\s\u00a0]/);7436if (end == -1) end = string.length;7437}7438for (var i = startIndex || 0, n = startValue || 0;;) {7439var nextTab = string.indexOf("\t", i);7440if (nextTab < 0 || nextTab >= end)7441return n + (end - i);7442n += nextTab - i;7443n += tabSize - (n % tabSize);7444i = nextTab + 1;7445}7446};74477448// The inverse of countColumn -- find the offset that corresponds to7449// a particular column.7450function findColumn(string, goal, tabSize) {7451for (var pos = 0, col = 0;;) {7452var nextTab = string.indexOf("\t", pos);7453if (nextTab == -1) nextTab = string.length;7454var skipped = nextTab - pos;7455if (nextTab == string.length || col + skipped >= goal)7456return pos + Math.min(skipped, goal - col);7457col += nextTab - pos;7458col += tabSize - (col % tabSize);7459pos = nextTab + 1;7460if (col >= goal) return pos;7461}7462}74637464var spaceStrs = [""];7465function spaceStr(n) {7466while (spaceStrs.length <= n)7467spaceStrs.push(lst(spaceStrs) + " ");7468return spaceStrs[n];7469}74707471function lst(arr) { return arr[arr.length-1]; }74727473var selectInput = function(node) { node.select(); };7474if (ios) // Mobile Safari apparently has a bug where select() is broken.7475selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };7476else if (ie) // Suppress mysterious IE10 errors7477selectInput = function(node) { try { node.select(); } catch(_e) {} };74787479function indexOf(array, elt) {7480for (var i = 0; i < array.length; ++i)7481if (array[i] == elt) return i;7482return -1;7483}7484function map(array, f) {7485var out = [];7486for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);7487return out;7488}74897490function createObj(base, props) {7491var inst;7492if (Object.create) {7493inst = Object.create(base);7494} else {7495var ctor = function() {};7496ctor.prototype = base;7497inst = new ctor();7498}7499if (props) copyObj(props, inst);7500return inst;7501};75027503function copyObj(obj, target, overwrite) {7504if (!target) target = {};7505for (var prop in obj)7506if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))7507target[prop] = obj[prop];7508return target;7509}75107511function bind(f) {7512var args = Array.prototype.slice.call(arguments, 1);7513return function(){return f.apply(null, args);};7514}75157516var nonASCIISingleCaseWordChar = /[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;7517var isWordCharBasic = CodeMirror.isWordChar = function(ch) {7518return /\w/.test(ch) || ch > "\x80" &&7519(ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));7520};7521function isWordChar(ch, helper) {7522if (!helper) return isWordCharBasic(ch);7523if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;7524return helper.test(ch);7525}75267527function isEmpty(obj) {7528for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;7529return true;7530}75317532// Extending unicode characters. A series of a non-extending char +7533// any number of extending chars is treated as a single unit as far7534// as editing and measuring is concerned. This is not fully correct,7535// since some scripts/fonts/browsers also treat other configurations7536// of code points as a group.7537var 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]/;7538function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }75397540// DOM UTILITIES75417542function elt(tag, content, className, style) {7543var e = document.createElement(tag);7544if (className) e.className = className;7545if (style) e.style.cssText = style;7546if (typeof content == "string") e.appendChild(document.createTextNode(content));7547else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);7548return e;7549}75507551var range;7552if (document.createRange) range = function(node, start, end) {7553var r = document.createRange();7554r.setEnd(node, end);7555r.setStart(node, start);7556return r;7557};7558else range = function(node, start, end) {7559var r = document.body.createTextRange();7560try { r.moveToElementText(node.parentNode); }7561catch(e) { return r; }7562r.collapse(true);7563r.moveEnd("character", end);7564r.moveStart("character", start);7565return r;7566};75677568function removeChildren(e) {7569for (var count = e.childNodes.length; count > 0; --count)7570e.removeChild(e.firstChild);7571return e;7572}75737574function removeChildrenAndAdd(parent, e) {7575return removeChildren(parent).appendChild(e);7576}75777578function contains(parent, child) {7579if (parent.contains)7580return parent.contains(child);7581while (child = child.parentNode)7582if (child == parent) return true;7583}75847585function activeElt() { return document.activeElement; }7586// Older versions of IE throws unspecified error when touching7587// document.activeElement in some cases (during loading, in iframe)7588if (ie && ie_version < 11) activeElt = function() {7589try { return document.activeElement; }7590catch(e) { return document.body; }7591};75927593function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }7594var rmClass = CodeMirror.rmClass = function(node, cls) {7595var current = node.className;7596var match = classTest(cls).exec(current);7597if (match) {7598var after = current.slice(match.index + match[0].length);7599node.className = current.slice(0, match.index) + (after ? match[1] + after : "");7600}7601};7602var addClass = CodeMirror.addClass = function(node, cls) {7603var current = node.className;7604if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;7605};7606function joinClasses(a, b) {7607var as = a.split(" ");7608for (var i = 0; i < as.length; i++)7609if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];7610return b;7611}76127613// WINDOW-WIDE EVENTS76147615// These must be handled carefully, because naively registering a7616// handler for each editor will cause the editors to never be7617// garbage collected.76187619function forEachCodeMirror(f) {7620if (!document.body.getElementsByClassName) return;7621var byClass = document.body.getElementsByClassName("CodeMirror");7622for (var i = 0; i < byClass.length; i++) {7623var cm = byClass[i].CodeMirror;7624if (cm) f(cm);7625}7626}76277628var globalsRegistered = false;7629function ensureGlobalHandlers() {7630if (globalsRegistered) return;7631registerGlobalHandlers();7632globalsRegistered = true;7633}7634function registerGlobalHandlers() {7635// When the window resizes, we need to refresh active editors.7636var resizeTimer;7637on(window, "resize", function() {7638if (resizeTimer == null) resizeTimer = setTimeout(function() {7639resizeTimer = null;7640forEachCodeMirror(onResize);7641}, 100);7642});7643// When the window loses focus, we want to show the editor as blurred7644on(window, "blur", function() {7645forEachCodeMirror(onBlur);7646});7647}76487649// FEATURE DETECTION76507651// Detect drag-and-drop7652var dragAndDrop = function() {7653// There is *some* kind of drag-and-drop support in IE6-8, but I7654// couldn't get it to work yet.7655if (ie && ie_version < 9) return false;7656var div = elt('div');7657return "draggable" in div || "dragDrop" in div;7658}();76597660var zwspSupported;7661function zeroWidthElement(measure) {7662if (zwspSupported == null) {7663var test = elt("span", "\u200b");7664removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));7665if (measure.firstChild.offsetHeight != 0)7666zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);7667}7668if (zwspSupported) return elt("span", "\u200b");7669else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");7670}76717672// Feature-detect IE's crummy client rect reporting for bidi text7673var badBidiRects;7674function hasBadBidiRects(measure) {7675if (badBidiRects != null) return badBidiRects;7676var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));7677var r0 = range(txt, 0, 1).getBoundingClientRect();7678if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)7679var r1 = range(txt, 1, 2).getBoundingClientRect();7680return badBidiRects = (r1.right - r0.right < 3);7681}76827683// See if "".split is the broken IE version, if so, provide an7684// alternative way to split lines.7685var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {7686var pos = 0, result = [], l = string.length;7687while (pos <= l) {7688var nl = string.indexOf("\n", pos);7689if (nl == -1) nl = string.length;7690var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);7691var rt = line.indexOf("\r");7692if (rt != -1) {7693result.push(line.slice(0, rt));7694pos += rt + 1;7695} else {7696result.push(line);7697pos = nl + 1;7698}7699}7700return result;7701} : function(string){return string.split(/\r\n?|\n/);};77027703var hasSelection = window.getSelection ? function(te) {7704try { return te.selectionStart != te.selectionEnd; }7705catch(e) { return false; }7706} : function(te) {7707try {var range = te.ownerDocument.selection.createRange();}7708catch(e) {}7709if (!range || range.parentElement() != te) return false;7710return range.compareEndPoints("StartToEnd", range) != 0;7711};77127713var hasCopyEvent = (function() {7714var e = elt("div");7715if ("oncopy" in e) return true;7716e.setAttribute("oncopy", "return;");7717return typeof e.oncopy == "function";7718})();77197720var badZoomedRects = null;7721function hasBadZoomedRects(measure) {7722if (badZoomedRects != null) return badZoomedRects;7723var node = removeChildrenAndAdd(measure, elt("span", "x"));7724var normal = node.getBoundingClientRect();7725var fromRange = range(node, 0, 1).getBoundingClientRect();7726return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;7727}77287729// KEY NAMES77307731var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",773219: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",773336: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",773446: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete",7735173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",7736221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",773763273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"};7738CodeMirror.keyNames = keyNames;7739(function() {7740// Number keys7741for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);7742// Alphabetic keys7743for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);7744// Function keys7745for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;7746})();77477748// BIDI HELPERS77497750function iterateBidiSections(order, from, to, f) {7751if (!order) return f(from, to, "ltr");7752var found = false;7753for (var i = 0; i < order.length; ++i) {7754var part = order[i];7755if (part.from < to && part.to > from || from == to && part.to == from) {7756f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");7757found = true;7758}7759}7760if (!found) f(from, to, "ltr");7761}77627763function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }7764function bidiRight(part) { return part.level % 2 ? part.from : part.to; }77657766function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }7767function lineRight(line) {7768var order = getOrder(line);7769if (!order) return line.text.length;7770return bidiRight(lst(order));7771}77727773function lineStart(cm, lineN) {7774var line = getLine(cm.doc, lineN);7775var visual = visualLine(line);7776if (visual != line) lineN = lineNo(visual);7777var order = getOrder(visual);7778var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);7779return Pos(lineN, ch);7780}7781function lineEnd(cm, lineN) {7782var merged, line = getLine(cm.doc, lineN);7783while (merged = collapsedSpanAtEnd(line)) {7784line = merged.find(1, true).line;7785lineN = null;7786}7787var order = getOrder(line);7788var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);7789return Pos(lineN == null ? lineNo(line) : lineN, ch);7790}7791function lineStartSmart(cm, pos) {7792var start = lineStart(cm, pos.line);7793var line = getLine(cm.doc, start.line);7794var order = getOrder(line);7795if (!order || order[0].level == 0) {7796var firstNonWS = Math.max(0, line.text.search(/\S/));7797var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;7798return Pos(start.line, inWS ? 0 : firstNonWS);7799}7800return start;7801}78027803function compareBidiLevel(order, a, b) {7804var linedir = order[0].level;7805if (a == linedir) return true;7806if (b == linedir) return false;7807return a < b;7808}7809var bidiOther;7810function getBidiPartAt(order, pos) {7811bidiOther = null;7812for (var i = 0, found; i < order.length; ++i) {7813var cur = order[i];7814if (cur.from < pos && cur.to > pos) return i;7815if ((cur.from == pos || cur.to == pos)) {7816if (found == null) {7817found = i;7818} else if (compareBidiLevel(order, cur.level, order[found].level)) {7819if (cur.from != cur.to) bidiOther = found;7820return i;7821} else {7822if (cur.from != cur.to) bidiOther = i;7823return found;7824}7825}7826}7827return found;7828}78297830function moveInLine(line, pos, dir, byUnit) {7831if (!byUnit) return pos + dir;7832do pos += dir;7833while (pos > 0 && isExtendingChar(line.text.charAt(pos)));7834return pos;7835}78367837// This is needed in order to move 'visually' through bi-directional7838// text -- i.e., pressing left should make the cursor go left, even7839// when in RTL text. The tricky part is the 'jumps', where RTL and7840// LTR text touch each other. This often requires the cursor offset7841// to move more than one unit, in order to visually move one unit.7842function moveVisually(line, start, dir, byUnit) {7843var bidi = getOrder(line);7844if (!bidi) return moveLogically(line, start, dir, byUnit);7845var pos = getBidiPartAt(bidi, start), part = bidi[pos];7846var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);78477848for (;;) {7849if (target > part.from && target < part.to) return target;7850if (target == part.from || target == part.to) {7851if (getBidiPartAt(bidi, target) == pos) return target;7852part = bidi[pos += dir];7853return (dir > 0) == part.level % 2 ? part.to : part.from;7854} else {7855part = bidi[pos += dir];7856if (!part) return null;7857if ((dir > 0) == part.level % 2)7858target = moveInLine(line, part.to, -1, byUnit);7859else7860target = moveInLine(line, part.from, 1, byUnit);7861}7862}7863}78647865function moveLogically(line, start, dir, byUnit) {7866var target = start + dir;7867if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;7868return target < 0 || target > line.text.length ? null : target;7869}78707871// Bidirectional ordering algorithm7872// See http://unicode.org/reports/tr9/tr9-13.html for the algorithm7873// that this (partially) implements.78747875// One-char codes used for character types:7876// L (L): Left-to-Right7877// R (R): Right-to-Left7878// r (AL): Right-to-Left Arabic7879// 1 (EN): European Number7880// + (ES): European Number Separator7881// % (ET): European Number Terminator7882// n (AN): Arabic Number7883// , (CS): Common Number Separator7884// m (NSM): Non-Spacing Mark7885// b (BN): Boundary Neutral7886// s (B): Paragraph Separator7887// t (S): Segment Separator7888// w (WS): Whitespace7889// N (ON): Other Neutrals78907891// Returns null if characters are ordered as they appear7892// (left-to-right), or an array of sections ({from, to, level}7893// objects) in the order in which they occur visually.7894var bidiOrdering = (function() {7895// Character types for codepoints 0 to 0xff7896var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";7897// Character types for codepoints 0x600 to 0x6ff7898var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";7899function charType(code) {7900if (code <= 0xf7) return lowTypes.charAt(code);7901else if (0x590 <= code && code <= 0x5f4) return "R";7902else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);7903else if (0x6ee <= code && code <= 0x8ac) return "r";7904else if (0x2000 <= code && code <= 0x200b) return "w";7905else if (code == 0x200c) return "b";7906else return "L";7907}79087909var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;7910var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;7911// Browsers seem to always treat the boundaries of block elements as being L.7912var outerType = "L";79137914function BidiSpan(level, from, to) {7915this.level = level;7916this.from = from; this.to = to;7917}79187919return function(str) {7920if (!bidiRE.test(str)) return false;7921var len = str.length, types = [];7922for (var i = 0, type; i < len; ++i)7923types.push(type = charType(str.charCodeAt(i)));79247925// W1. Examine each non-spacing mark (NSM) in the level run, and7926// change the type of the NSM to the type of the previous7927// character. If the NSM is at the start of the level run, it will7928// get the type of sor.7929for (var i = 0, prev = outerType; i < len; ++i) {7930var type = types[i];7931if (type == "m") types[i] = prev;7932else prev = type;7933}79347935// W2. Search backwards from each instance of a European number7936// until the first strong type (R, L, AL, or sor) is found. If an7937// AL is found, change the type of the European number to Arabic7938// number.7939// W3. Change all ALs to R.7940for (var i = 0, cur = outerType; i < len; ++i) {7941var type = types[i];7942if (type == "1" && cur == "r") types[i] = "n";7943else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }7944}79457946// W4. A single European separator between two European numbers7947// changes to a European number. A single common separator between7948// two numbers of the same type changes to that type.7949for (var i = 1, prev = types[0]; i < len - 1; ++i) {7950var type = types[i];7951if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";7952else if (type == "," && prev == types[i+1] &&7953(prev == "1" || prev == "n")) types[i] = prev;7954prev = type;7955}79567957// W5. A sequence of European terminators adjacent to European7958// numbers changes to all European numbers.7959// W6. Otherwise, separators and terminators change to Other7960// Neutral.7961for (var i = 0; i < len; ++i) {7962var type = types[i];7963if (type == ",") types[i] = "N";7964else if (type == "%") {7965for (var end = i + 1; end < len && types[end] == "%"; ++end) {}7966var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";7967for (var j = i; j < end; ++j) types[j] = replace;7968i = end - 1;7969}7970}79717972// W7. Search backwards from each instance of a European number7973// until the first strong type (R, L, or sor) is found. If an L is7974// found, then change the type of the European number to L.7975for (var i = 0, cur = outerType; i < len; ++i) {7976var type = types[i];7977if (cur == "L" && type == "1") types[i] = "L";7978else if (isStrong.test(type)) cur = type;7979}79807981// N1. A sequence of neutrals takes the direction of the7982// surrounding strong text if the text on both sides has the same7983// direction. European and Arabic numbers act as if they were R in7984// terms of their influence on neutrals. Start-of-level-run (sor)7985// and end-of-level-run (eor) are used at level run boundaries.7986// N2. Any remaining neutrals take the embedding direction.7987for (var i = 0; i < len; ++i) {7988if (isNeutral.test(types[i])) {7989for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}7990var before = (i ? types[i-1] : outerType) == "L";7991var after = (end < len ? types[end] : outerType) == "L";7992var replace = before || after ? "L" : "R";7993for (var j = i; j < end; ++j) types[j] = replace;7994i = end - 1;7995}7996}79977998// Here we depart from the documented algorithm, in order to avoid7999// building up an actual levels array. Since there are only three8000// levels (0, 1, 2) in an implementation that doesn't take8001// explicit embedding into account, we can build up the order on8002// the fly, without following the level-based algorithm.8003var order = [], m;8004for (var i = 0; i < len;) {8005if (countsAsLeft.test(types[i])) {8006var start = i;8007for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}8008order.push(new BidiSpan(0, start, i));8009} else {8010var pos = i, at = order.length;8011for (++i; i < len && types[i] != "L"; ++i) {}8012for (var j = pos; j < i;) {8013if (countsAsNum.test(types[j])) {8014if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));8015var nstart = j;8016for (++j; j < i && countsAsNum.test(types[j]); ++j) {}8017order.splice(at, 0, new BidiSpan(2, nstart, j));8018pos = j;8019} else ++j;8020}8021if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));8022}8023}8024if (order[0].level == 1 && (m = str.match(/^\s+/))) {8025order[0].from = m[0].length;8026order.unshift(new BidiSpan(0, 0, m[0].length));8027}8028if (lst(order).level == 1 && (m = str.match(/\s+$/))) {8029lst(order).to -= m[0].length;8030order.push(new BidiSpan(0, len - m[0].length, len));8031}8032if (order[0].level != lst(order).level)8033order.push(new BidiSpan(order[0].level, len, len));80348035return order;8036};8037})();80388039// THE END80408041CodeMirror.version = "4.12.0";80428043return CodeMirror;8044});804580468047