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