1 // CodeMirror, copyright (c) by Marijn Haverbeke and others
2 // Distributed under an MIT license: http://codemirror.net/LICENSE
4 // This is CodeMirror (http://codemirror.net), a code editor
5 // implemented in JavaScript on top of the browser's DOM.
7 // You can find some technical background for some of the code below
8 // at http://marijnhaverbeke.nl/blog/#cm-internals .
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();
22 // Kludges for bugs and behavior differences that can't be feature
23 // detected are enabled based on userAgent etc sniffing.
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
);
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
);
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);
53 // Optimize some code when these features are not used.
54 var sawReadOnlySpans
= false, sawCollapsedSpans
= false;
58 // A CodeMirror instance represents an editor. This is the object
59 // that user code is usually dealing with.
61 function CodeMirror(place
, options
) {
62 if (!(this instanceof CodeMirror
)) return new CodeMirror(place
, options
);
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
);
69 var doc
= options
.value
;
70 if (typeof doc
== "string") doc
= new Doc(doc
, options
.mode
);
73 var display
= this.display
= new Display(place
, doc
);
74 display
.wrapper
.CodeMirror
= this;
77 if (options
.lineWrapping
)
78 this.display
.wrapper
.className
+= " CodeMirror-wrap";
79 if (options
.autofocus
&& !mobile
) focusInput(this);
83 keyMaps
: [], // stores maps added by addKeyMap
84 overlays
: [], // highlighting overlays, as added by addOverlay
85 modeGen
: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
86 overwrite
: false, focused
: false,
87 suppressEdits
: false, // used to disable editing during key handlers when in readOnly mode
88 pasteIncoming
: false, cutIncoming
: false, // help recognize paste/cut edits in readInput
90 highlight
: new Delayed(), // stores highlight worker timeout
91 keySeq
: null // Unfinished key sequence
94 // Override magic textarea content restore that IE sometimes does
95 // on our hidden textarea on reload
96 if (ie
&& ie_version
< 11) setTimeout(bind(resetInput
, this, true), 20);
98 registerEventHandlers(this);
99 ensureGlobalHandlers();
101 startOperation(this);
102 this.curOp
.forceUpdate
= true;
103 attachDoc(this, doc
);
105 if ((options
.autofocus
&& !mobile
) || activeElt() == display
.input
)
106 setTimeout(bind(onFocus
, this), 20);
110 for (var opt
in optionHandlers
) if (optionHandlers
.hasOwnProperty(opt
))
111 optionHandlers
[opt
](this, options
[opt
], Init
);
112 maybeUpdateLineNumberWidth(this);
113 for (var i
= 0; i
< initHooks
.length
; ++i
) initHooks
[i
](this);
115 // Suppress optimizelegibility in Webkit, since it breaks text
116 // measuring on line wrapping boundaries.
117 if (webkit
&& options
.lineWrapping
&&
118 getComputedStyle(display
.lineDiv
).textRendering
== "optimizelegibility")
119 display
.lineDiv
.style
.textRendering
= "auto";
122 // DISPLAY CONSTRUCTOR
124 // The display handles the DOM integration, both for input reading
125 // and content drawing. It holds references to DOM nodes and
126 // display-related state.
128 function Display(place
, doc
) {
131 // The semihidden textarea that is focused when the editor is
132 // focused, and receives input.
133 var input
= d
.input
= elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
134 // The textarea is kept positioned near the cursor to prevent the
135 // fact that it'll be scrolled into view on input from scrolling
136 // our fake cursor out of view. On webkit, when wrap=off, paste is
137 // very slow. So make the area wide instead.
138 if (webkit
) input
.style
.width
= "1000px";
139 else input
.setAttribute("wrap", "off");
140 // If border: 0; -- iOS fails to open keyboard (issue #1287)
141 if (ios
) input
.style
.border
= "1px solid black";
142 input
.setAttribute("autocorrect", "off"); input
.setAttribute("autocapitalize", "off"); input
.setAttribute("spellcheck", "false");
144 // Wraps and hides input textarea
145 d
.inputDiv
= elt("div", [input
], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
146 // Covers bottom-right square when both scrollbars are present.
147 d
.scrollbarFiller
= elt("div", null, "CodeMirror-scrollbar-filler");
148 d
.scrollbarFiller
.setAttribute("not-content", "true");
149 // Covers bottom of gutter when coverGutterNextToScrollbar is on
150 // and h scrollbar is present.
151 d
.gutterFiller
= elt("div", null, "CodeMirror-gutter-filler");
152 d
.gutterFiller
.setAttribute("not-content", "true");
153 // Will contain the actual code, positioned to cover the viewport.
154 d
.lineDiv
= elt("div", null, "CodeMirror-code");
155 // Elements are added to these to represent selection and cursors.
156 d
.selectionDiv
= elt("div", null, null, "position: relative; z-index: 1");
157 d
.cursorDiv
= elt("div", null, "CodeMirror-cursors");
158 // A visibility: hidden element used to find the size of things.
159 d
.measure
= elt("div", null, "CodeMirror-measure");
160 // When lines outside of the viewport are measured, they are drawn in this.
161 d
.lineMeasure
= elt("div", null, "CodeMirror-measure");
162 // Wraps everything that needs to exist inside the vertically-padded coordinate system
163 d
.lineSpace
= elt("div", [d
.measure
, d
.lineMeasure
, d
.selectionDiv
, d
.cursorDiv
, d
.lineDiv
],
164 null, "position: relative; outline: none");
165 // Moved around its parent to cover visible view.
166 d
.mover
= elt("div", [elt("div", [d
.lineSpace
], "CodeMirror-lines")], null, "position: relative");
167 // Set to the height of the document, allowing scrolling.
168 d
.sizer
= elt("div", [d
.mover
], "CodeMirror-sizer");
170 // Behavior of elts with overflow: auto and padding is
171 // inconsistent across browsers. This is used to ensure the
172 // scrollable area is big enough.
173 d
.heightForcer
= elt("div", null, null, "position: absolute; height: " + scrollerGap
+ "px; width: 1px;");
174 // Will contain the gutters, if any.
175 d
.gutters
= elt("div", null, "CodeMirror-gutters");
177 // Actual scrollable element.
178 d
.scroller
= elt("div", [d
.sizer
, d
.heightForcer
, d
.gutters
], "CodeMirror-scroll");
179 d
.scroller
.setAttribute("tabIndex", "-1");
180 // The element in which the editor lives.
181 d
.wrapper
= elt("div", [d
.inputDiv
, d
.scrollbarFiller
, d
.gutterFiller
, d
.scroller
], "CodeMirror");
183 // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
184 if (ie
&& ie_version
< 8) { d
.gutters
.style
.zIndex
= -1; d
.scroller
.style
.paddingRight
= 0; }
185 // Needed to hide big blue blinking cursor on Mobile Safari
186 if (ios
) input
.style
.width
= "0px";
187 if (!webkit
) d
.scroller
.draggable
= true;
188 // Needed to handle Tab key in KHTML
189 if (khtml
) { d
.inputDiv
.style
.height
= "1px"; d
.inputDiv
.style
.position
= "absolute"; }
192 if (place
.appendChild
) place
.appendChild(d
.wrapper
);
193 else place(d
.wrapper
);
196 // Current rendered range (may be bigger than the view window).
197 d
.viewFrom
= d
.viewTo
= doc
.first
;
198 d
.reportedViewFrom
= d
.reportedViewTo
= doc
.first
;
199 // Information about the rendered lines.
201 d
.renderedView
= null;
202 // Holds info about a single rendered line when it was rendered
203 // for measurement, while not in view.
204 d
.externalMeasured
= null;
205 // Empty space (in pixels) above the view
207 d
.lastWrapHeight
= d
.lastWrapWidth
= 0;
208 d
.updateLineNumbers
= null;
210 d
.nativeBarWidth
= d
.barHeight
= d
.barWidth
= 0;
211 d
.scrollbarsClipped
= false;
213 // Used to only resize the line number gutter when necessary (when
214 // the amount of lines crosses a boundary that makes its width change)
215 d
.lineNumWidth
= d
.lineNumInnerWidth
= d
.lineNumChars
= null;
216 // See readInput and resetInput
218 // Set to true when a non-horizontal-scrolling line widget is
219 // added. As an optimization, line widget aligning is skipped when
221 d
.alignWidgets
= false;
222 // Flag that indicates whether we expect input to appear real soon
223 // now (after some event like 'keypress' or 'input') and are
224 // polling intensively.
225 d
.pollingFast
= false;
226 // Self-resetting timeout for the poller
227 d
.poll
= new Delayed();
229 d
.cachedCharWidth
= d
.cachedTextHeight
= d
.cachedPaddingH
= null;
231 // Tracks when resetInput has punted to just putting a short
232 // string into the textarea instead of the full selection.
233 d
.inaccurateSelection
= false;
235 // Tracks the maximum line length so that the horizontal scrollbar
236 // can be kept static when scrolling.
239 d
.maxLineChanged
= false;
241 // Used for measuring wheel scrolling granularity
242 d
.wheelDX
= d
.wheelDY
= d
.wheelStartX
= d
.wheelStartY
= null;
244 // True when shift is held down.
247 // Used to track whether anything happened since the context menu
249 d
.selForContextMenu
= null;
254 // Used to get the editor into a consistent state again when options change.
256 function loadMode(cm
) {
257 cm
.doc
.mode
= CodeMirror
.getMode(cm
.options
, cm
.doc
.modeOption
);
261 function resetModeState(cm
) {
262 cm
.doc
.iter(function(line
) {
263 if (line
.stateAfter
) line
.stateAfter
= null;
264 if (line
.styles
) line
.styles
= null;
266 cm
.doc
.frontier
= cm
.doc
.first
;
267 startWorker(cm
, 100);
269 if (cm
.curOp
) regChange(cm
);
272 function wrappingChanged(cm
) {
273 if (cm
.options
.lineWrapping
) {
274 addClass(cm
.display
.wrapper
, "CodeMirror-wrap");
275 cm
.display
.sizer
.style
.minWidth
= "";
276 cm
.display
.sizerWidth
= null;
278 rmClass(cm
.display
.wrapper
, "CodeMirror-wrap");
281 estimateLineHeights(cm
);
284 setTimeout(function(){updateScrollbars(cm
);}, 100);
287 // Returns a function that estimates the height of a line, to use as
288 // first approximation until the line becomes visible (and is thus
289 // properly measurable).
290 function estimateHeight(cm
) {
291 var th
= textHeight(cm
.display
), wrapping
= cm
.options
.lineWrapping
;
292 var perLine
= wrapping
&& Math
.max(5, cm
.display
.scroller
.clientWidth
/ charWidth(cm
.display
) - 3);
293 return function(line
) {
294 if (lineIsHidden(cm
.doc
, line
)) return 0;
296 var widgetsHeight
= 0;
297 if (line
.widgets
) for (var i
= 0; i
< line
.widgets
.length
; i
++) {
298 if (line
.widgets
[i
].height
) widgetsHeight
+= line
.widgets
[i
].height
;
302 return widgetsHeight
+ (Math
.ceil(line
.text
.length
/ perLine
) || 1) * th
;
304 return widgetsHeight
+ th
;
308 function estimateLineHeights(cm
) {
309 var doc
= cm
.doc
, est
= estimateHeight(cm
);
310 doc
.iter(function(line
) {
311 var estHeight
= est(line
);
312 if (estHeight
!= line
.height
) updateLineHeight(line
, estHeight
);
316 function themeChanged(cm
) {
317 cm
.display
.wrapper
.className
= cm
.display
.wrapper
.className
.replace(/\s*cm-s-\S+/g, "") +
318 cm
.options
.theme
.replace(/(^|\s)\s*/g, " cm-s-");
322 function guttersChanged(cm
) {
325 setTimeout(function(){alignHorizontally(cm
);}, 20);
328 // Rebuild the gutter elements, ensure the margin to the left of the
329 // code matches their width.
330 function updateGutters(cm
) {
331 var gutters
= cm
.display
.gutters
, specs
= cm
.options
.gutters
;
332 removeChildren(gutters
);
333 for (var i
= 0; i
< specs
.length
; ++i
) {
334 var gutterClass
= specs
[i
];
335 var gElt
= gutters
.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass
));
336 if (gutterClass
== "CodeMirror-linenumbers") {
337 cm
.display
.lineGutter
= gElt
;
338 gElt
.style
.width
= (cm
.display
.lineNumWidth
|| 1) + "px";
341 gutters
.style
.display
= i
? "" : "none";
342 updateGutterSpace(cm
);
345 function updateGutterSpace(cm
) {
346 var width
= cm
.display
.gutters
.offsetWidth
;
347 cm
.display
.sizer
.style
.marginLeft
= width
+ "px";
350 // Compute the character length of a line, taking into account
351 // collapsed ranges (see markText) that might hide parts, and join
352 // other lines onto it.
353 function lineLength(line
) {
354 if (line
.height
== 0) return 0;
355 var len
= line
.text
.length
, merged
, cur
= line
;
356 while (merged
= collapsedSpanAtStart(cur
)) {
357 var found
= merged
.find(0, true);
358 cur
= found
.from.line
;
359 len
+= found
.from.ch
- found
.to
.ch
;
362 while (merged
= collapsedSpanAtEnd(cur
)) {
363 var found
= merged
.find(0, true);
364 len
-= cur
.text
.length
- found
.from.ch
;
366 len
+= cur
.text
.length
- found
.to
.ch
;
371 // Find the longest line in the document.
372 function findMaxLine(cm
) {
373 var d
= cm
.display
, doc
= cm
.doc
;
374 d
.maxLine
= getLine(doc
, doc
.first
);
375 d
.maxLineLength
= lineLength(d
.maxLine
);
376 d
.maxLineChanged
= true;
377 doc
.iter(function(line
) {
378 var len
= lineLength(line
);
379 if (len
> d
.maxLineLength
) {
380 d
.maxLineLength
= len
;
386 // Make sure the gutters options contains the element
387 // "CodeMirror-linenumbers" when the lineNumbers option is true.
388 function setGuttersForLineNumbers(options
) {
389 var found
= indexOf(options
.gutters
, "CodeMirror-linenumbers");
390 if (found
== -1 && options
.lineNumbers
) {
391 options
.gutters
= options
.gutters
.concat(["CodeMirror-linenumbers"]);
392 } else if (found
> -1 && !options
.lineNumbers
) {
393 options
.gutters
= options
.gutters
.slice(0);
394 options
.gutters
.splice(found
, 1);
400 // Prepare DOM reads needed to update the scrollbars. Done in one
401 // shot to minimize update/measure roundtrips.
402 function measureForScrollbars(cm
) {
403 var d
= cm
.display
, gutterW
= d
.gutters
.offsetWidth
;
404 var docH
= Math
.round(cm
.doc
.height
+ paddingVert(cm
.display
));
406 clientHeight
: d
.scroller
.clientHeight
,
407 viewHeight
: d
.wrapper
.clientHeight
,
408 scrollWidth
: d
.scroller
.scrollWidth
, clientWidth
: d
.scroller
.clientWidth
,
409 viewWidth
: d
.wrapper
.clientWidth
,
410 barLeft
: cm
.options
.fixedGutter
? gutterW
: 0,
412 scrollHeight
: docH
+ scrollGap(cm
) + d
.barHeight
,
413 nativeBarWidth
: d
.nativeBarWidth
,
418 function NativeScrollbars(place
, scroll
, cm
) {
420 var vert
= this.vert
= elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
421 var horiz
= this.horiz
= elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
422 place(vert
); place(horiz
);
424 on(vert
, "scroll", function() {
425 if (vert
.clientHeight
) scroll(vert
.scrollTop
, "vertical");
427 on(horiz
, "scroll", function() {
428 if (horiz
.clientWidth
) scroll(horiz
.scrollLeft
, "horizontal");
431 this.checkedOverlay
= false;
432 // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
433 if (ie
&& ie_version
< 8) this.horiz
.style
.minHeight
= this.vert
.style
.minWidth
= "18px";
436 NativeScrollbars
.prototype = copyObj({
437 update: function(measure
) {
438 var needsH
= measure
.scrollWidth
> measure
.clientWidth
+ 1;
439 var needsV
= measure
.scrollHeight
> measure
.clientHeight
+ 1;
440 var sWidth
= measure
.nativeBarWidth
;
443 this.vert
.style
.display
= "block";
444 this.vert
.style
.bottom
= needsH
? sWidth
+ "px" : "0";
445 var totalHeight
= measure
.viewHeight
- (needsH
? sWidth
: 0);
446 // A bug in IE8 can cause this value to be negative, so guard it.
447 this.vert
.firstChild
.style
.height
=
448 Math
.max(0, measure
.scrollHeight
- measure
.clientHeight
+ totalHeight
) + "px";
450 this.vert
.style
.display
= "";
451 this.vert
.firstChild
.style
.height
= "0";
455 this.horiz
.style
.display
= "block";
456 this.horiz
.style
.right
= needsV
? sWidth
+ "px" : "0";
457 this.horiz
.style
.left
= measure
.barLeft
+ "px";
458 var totalWidth
= measure
.viewWidth
- measure
.barLeft
- (needsV
? sWidth
: 0);
459 this.horiz
.firstChild
.style
.width
=
460 (measure
.scrollWidth
- measure
.clientWidth
+ totalWidth
) + "px";
462 this.horiz
.style
.display
= "";
463 this.horiz
.firstChild
.style
.width
= "0";
466 if (!this.checkedOverlay
&& measure
.clientHeight
> 0) {
467 if (sWidth
== 0) this.overlayHack();
468 this.checkedOverlay
= true;
471 return {right
: needsV
? sWidth
: 0, bottom
: needsH
? sWidth
: 0};
473 setScrollLeft: function(pos
) {
474 if (this.horiz
.scrollLeft
!= pos
) this.horiz
.scrollLeft
= pos
;
476 setScrollTop: function(pos
) {
477 if (this.vert
.scrollTop
!= pos
) this.vert
.scrollTop
= pos
;
479 overlayHack: function() {
480 var w
= mac
&& !mac_geMountainLion
? "12px" : "18px";
481 this.horiz
.style
.minHeight
= this.vert
.style
.minWidth
= w
;
483 var barMouseDown = function(e
) {
484 if (e_target(e
) != self
.vert
&& e_target(e
) != self
.horiz
)
485 operation(self
.cm
, onMouseDown
)(e
);
487 on(this.vert
, "mousedown", barMouseDown
);
488 on(this.horiz
, "mousedown", barMouseDown
);
491 var parent
= this.horiz
.parentNode
;
492 parent
.removeChild(this.horiz
);
493 parent
.removeChild(this.vert
);
495 }, NativeScrollbars
.prototype);
497 function NullScrollbars() {}
499 NullScrollbars
.prototype = copyObj({
500 update: function() { return {bottom
: 0, right
: 0}; },
501 setScrollLeft: function() {},
502 setScrollTop: function() {},
504 }, NullScrollbars
.prototype);
506 CodeMirror
.scrollbarModel
= {"native": NativeScrollbars
, "null": NullScrollbars
};
508 function initScrollbars(cm
) {
509 if (cm
.display
.scrollbars
) {
510 cm
.display
.scrollbars
.clear();
511 if (cm
.display
.scrollbars
.addClass
)
512 rmClass(cm
.display
.wrapper
, cm
.display
.scrollbars
.addClass
);
515 cm
.display
.scrollbars
= new CodeMirror
.scrollbarModel
[cm
.options
.scrollbarStyle
](function(node
) {
516 cm
.display
.wrapper
.insertBefore(node
, cm
.display
.scrollbarFiller
);
517 on(node
, "mousedown", function() {
518 if (cm
.state
.focused
) setTimeout(bind(focusInput
, cm
), 0);
520 node
.setAttribute("not-content", "true");
521 }, function(pos
, axis
) {
522 if (axis
== "horizontal") setScrollLeft(cm
, pos
);
523 else setScrollTop(cm
, pos
);
525 if (cm
.display
.scrollbars
.addClass
)
526 addClass(cm
.display
.wrapper
, cm
.display
.scrollbars
.addClass
);
529 function updateScrollbars(cm
, measure
) {
530 if (!measure
) measure
= measureForScrollbars(cm
);
531 var startWidth
= cm
.display
.barWidth
, startHeight
= cm
.display
.barHeight
;
532 updateScrollbarsInner(cm
, measure
);
533 for (var i
= 0; i
< 4 && startWidth
!= cm
.display
.barWidth
|| startHeight
!= cm
.display
.barHeight
; i
++) {
534 if (startWidth
!= cm
.display
.barWidth
&& cm
.options
.lineWrapping
)
535 updateHeightsInViewport(cm
);
536 updateScrollbarsInner(cm
, measureForScrollbars(cm
));
537 startWidth
= cm
.display
.barWidth
; startHeight
= cm
.display
.barHeight
;
541 // Re-synchronize the fake scrollbars with the actual size of the
543 function updateScrollbarsInner(cm
, measure
) {
545 var sizes
= d
.scrollbars
.update(measure
);
547 d
.sizer
.style
.paddingRight
= (d
.barWidth
= sizes
.right
) + "px";
548 d
.sizer
.style
.paddingBottom
= (d
.barHeight
= sizes
.bottom
) + "px";
550 if (sizes
.right
&& sizes
.bottom
) {
551 d
.scrollbarFiller
.style
.display
= "block";
552 d
.scrollbarFiller
.style
.height
= sizes
.bottom
+ "px";
553 d
.scrollbarFiller
.style
.width
= sizes
.right
+ "px";
554 } else d
.scrollbarFiller
.style
.display
= "";
555 if (sizes
.bottom
&& cm
.options
.coverGutterNextToScrollbar
&& cm
.options
.fixedGutter
) {
556 d
.gutterFiller
.style
.display
= "block";
557 d
.gutterFiller
.style
.height
= sizes
.bottom
+ "px";
558 d
.gutterFiller
.style
.width
= measure
.gutterWidth
+ "px";
559 } else d
.gutterFiller
.style
.display
= "";
562 // Compute the lines that are visible in a given viewport (defaults
563 // the the current scroll position). viewport may contain top,
564 // height, and ensure (see op.scrollToPos) properties.
565 function visibleLines(display
, doc
, viewport
) {
566 var top
= viewport
&& viewport
.top
!= null ? Math
.max(0, viewport
.top
) : display
.scroller
.scrollTop
;
567 top
= Math
.floor(top
- paddingTop(display
));
568 var bottom
= viewport
&& viewport
.bottom
!= null ? viewport
.bottom
: top
+ display
.wrapper
.clientHeight
;
570 var from = lineAtHeight(doc
, top
), to
= lineAtHeight(doc
, bottom
);
571 // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
572 // forces those lines into the viewport (if possible).
573 if (viewport
&& viewport
.ensure
) {
574 var ensureFrom
= viewport
.ensure
.from.line
, ensureTo
= viewport
.ensure
.to
.line
;
575 if (ensureFrom
< from) {
577 to
= lineAtHeight(doc
, heightAtLine(getLine(doc
, ensureFrom
)) + display
.wrapper
.clientHeight
);
578 } else if (Math
.min(ensureTo
, doc
.lastLine()) >= to
) {
579 from = lineAtHeight(doc
, heightAtLine(getLine(doc
, ensureTo
)) - display
.wrapper
.clientHeight
);
583 return {from: from, to
: Math
.max(to
, from + 1)};
588 // Re-align line numbers and gutter marks to compensate for
589 // horizontal scrolling.
590 function alignHorizontally(cm
) {
591 var display
= cm
.display
, view
= display
.view
;
592 if (!display
.alignWidgets
&& (!display
.gutters
.firstChild
|| !cm
.options
.fixedGutter
)) return;
593 var comp
= compensateForHScroll(display
) - display
.scroller
.scrollLeft
+ cm
.doc
.scrollLeft
;
594 var gutterW
= display
.gutters
.offsetWidth
, left
= comp
+ "px";
595 for (var i
= 0; i
< view
.length
; i
++) if (!view
[i
].hidden
) {
596 if (cm
.options
.fixedGutter
&& view
[i
].gutter
)
597 view
[i
].gutter
.style
.left
= left
;
598 var align
= view
[i
].alignable
;
599 if (align
) for (var j
= 0; j
< align
.length
; j
++)
600 align
[j
].style
.left
= left
;
602 if (cm
.options
.fixedGutter
)
603 display
.gutters
.style
.left
= (comp
+ gutterW
) + "px";
606 // Used to ensure that the line number gutter is still the right
607 // size for the current document size. Returns true when an update
609 function maybeUpdateLineNumberWidth(cm
) {
610 if (!cm
.options
.lineNumbers
) return false;
611 var doc
= cm
.doc
, last
= lineNumberFor(cm
.options
, doc
.first
+ doc
.size
- 1), display
= cm
.display
;
612 if (last
.length
!= display
.lineNumChars
) {
613 var test
= display
.measure
.appendChild(elt("div", [elt("div", last
)],
614 "CodeMirror-linenumber CodeMirror-gutter-elt"));
615 var innerW
= test
.firstChild
.offsetWidth
, padding
= test
.offsetWidth
- innerW
;
616 display
.lineGutter
.style
.width
= "";
617 display
.lineNumInnerWidth
= Math
.max(innerW
, display
.lineGutter
.offsetWidth
- padding
);
618 display
.lineNumWidth
= display
.lineNumInnerWidth
+ padding
;
619 display
.lineNumChars
= display
.lineNumInnerWidth
? last
.length
: -1;
620 display
.lineGutter
.style
.width
= display
.lineNumWidth
+ "px";
621 updateGutterSpace(cm
);
627 function lineNumberFor(options
, i
) {
628 return String(options
.lineNumberFormatter(i
+ options
.firstLineNumber
));
631 // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
632 // but using getBoundingClientRect to get a sub-pixel-accurate
634 function compensateForHScroll(display
) {
635 return display
.scroller
.getBoundingClientRect().left
- display
.sizer
.getBoundingClientRect().left
;
640 function DisplayUpdate(cm
, viewport
, force
) {
641 var display
= cm
.display
;
643 this.viewport
= viewport
;
644 // Store some values that we'll need later (but don't want to force a relayout for)
645 this.visible
= visibleLines(display
, cm
.doc
, viewport
);
646 this.editorIsHidden
= !display
.wrapper
.offsetWidth
;
647 this.wrapperHeight
= display
.wrapper
.clientHeight
;
648 this.wrapperWidth
= display
.wrapper
.clientWidth
;
649 this.oldDisplayWidth
= displayWidth(cm
);
651 this.dims
= getDimensions(cm
);
654 function maybeClipScrollbars(cm
) {
655 var display
= cm
.display
;
656 if (!display
.scrollbarsClipped
&& display
.scroller
.offsetWidth
) {
657 display
.nativeBarWidth
= display
.scroller
.offsetWidth
- display
.scroller
.clientWidth
;
658 display
.heightForcer
.style
.height
= scrollGap(cm
) + "px";
659 display
.sizer
.style
.marginBottom
= -display
.nativeBarWidth
+ "px";
660 display
.sizer
.style
.borderRightWidth
= scrollGap(cm
) + "px";
661 display
.scrollbarsClipped
= true;
665 // Does the actual updating of the line display. Bails out
666 // (returning false) when there is nothing to be done and forced is
668 function updateDisplayIfNeeded(cm
, update
) {
669 var display
= cm
.display
, doc
= cm
.doc
;
671 if (update
.editorIsHidden
) {
676 // Bail out if the visible area is already rendered and nothing changed.
678 update
.visible
.from >= display
.viewFrom
&& update
.visible
.to
<= display
.viewTo
&&
679 (display
.updateLineNumbers
== null || display
.updateLineNumbers
>= display
.viewTo
) &&
680 display
.renderedView
== display
.view
&& countDirtyView(cm
) == 0)
683 if (maybeUpdateLineNumberWidth(cm
)) {
685 update
.dims
= getDimensions(cm
);
688 // Compute a suitable new viewport (from & to)
689 var end
= doc
.first
+ doc
.size
;
690 var from = Math
.max(update
.visible
.from - cm
.options
.viewportMargin
, doc
.first
);
691 var to
= Math
.min(end
, update
.visible
.to
+ cm
.options
.viewportMargin
);
692 if (display
.viewFrom
< from && from - display
.viewFrom
< 20) from = Math
.max(doc
.first
, display
.viewFrom
);
693 if (display
.viewTo
> to
&& display
.viewTo
- to
< 20) to
= Math
.min(end
, display
.viewTo
);
694 if (sawCollapsedSpans
) {
695 from = visualLineNo(cm
.doc
, from);
696 to
= visualLineEndNo(cm
.doc
, to
);
699 var different
= from != display
.viewFrom
|| to
!= display
.viewTo
||
700 display
.lastWrapHeight
!= update
.wrapperHeight
|| display
.lastWrapWidth
!= update
.wrapperWidth
;
701 adjustView(cm
, from, to
);
703 display
.viewOffset
= heightAtLine(getLine(cm
.doc
, display
.viewFrom
));
704 // Position the mover div to align with the current scroll position
705 cm
.display
.mover
.style
.top
= display
.viewOffset
+ "px";
707 var toUpdate
= countDirtyView(cm
);
708 if (!different
&& toUpdate
== 0 && !update
.force
&& display
.renderedView
== display
.view
&&
709 (display
.updateLineNumbers
== null || display
.updateLineNumbers
>= display
.viewTo
))
712 // For big changes, we hide the enclosing element during the
713 // update, since that speeds up the operations on most browsers.
714 var focused
= activeElt();
715 if (toUpdate
> 4) display
.lineDiv
.style
.display
= "none";
716 patchDisplay(cm
, display
.updateLineNumbers
, update
.dims
);
717 if (toUpdate
> 4) display
.lineDiv
.style
.display
= "";
718 display
.renderedView
= display
.view
;
719 // There might have been a widget with a focused element that got
720 // hidden or updated, if so re-focus it.
721 if (focused
&& activeElt() != focused
&& focused
.offsetHeight
) focused
.focus();
723 // Prevent selection and cursors from interfering with the scroll
725 removeChildren(display
.cursorDiv
);
726 removeChildren(display
.selectionDiv
);
727 display
.gutters
.style
.height
= 0;
730 display
.lastWrapHeight
= update
.wrapperHeight
;
731 display
.lastWrapWidth
= update
.wrapperWidth
;
732 startWorker(cm
, 400);
735 display
.updateLineNumbers
= null;
740 function postUpdateDisplay(cm
, update
) {
741 var force
= update
.force
, viewport
= update
.viewport
;
742 for (var first
= true;; first
= false) {
743 if (first
&& cm
.options
.lineWrapping
&& update
.oldDisplayWidth
!= displayWidth(cm
)) {
747 // Clip forced viewport to actual scrollable area.
748 if (viewport
&& viewport
.top
!= null)
749 viewport
= {top
: Math
.min(cm
.doc
.height
+ paddingVert(cm
.display
) - displayHeight(cm
), viewport
.top
)};
750 // Updated line heights might result in the drawn area not
751 // actually covering the viewport. Keep looping until it does.
752 update
.visible
= visibleLines(cm
.display
, cm
.doc
, viewport
);
753 if (update
.visible
.from >= cm
.display
.viewFrom
&& update
.visible
.to
<= cm
.display
.viewTo
)
756 if (!updateDisplayIfNeeded(cm
, update
)) break;
757 updateHeightsInViewport(cm
);
758 var barMeasure
= measureForScrollbars(cm
);
760 setDocumentHeight(cm
, barMeasure
);
761 updateScrollbars(cm
, barMeasure
);
764 signalLater(cm
, "update", cm
);
765 if (cm
.display
.viewFrom
!= cm
.display
.reportedViewFrom
|| cm
.display
.viewTo
!= cm
.display
.reportedViewTo
) {
766 signalLater(cm
, "viewportChange", cm
, cm
.display
.viewFrom
, cm
.display
.viewTo
);
767 cm
.display
.reportedViewFrom
= cm
.display
.viewFrom
; cm
.display
.reportedViewTo
= cm
.display
.viewTo
;
771 function updateDisplaySimple(cm
, viewport
) {
772 var update
= new DisplayUpdate(cm
, viewport
);
773 if (updateDisplayIfNeeded(cm
, update
)) {
774 updateHeightsInViewport(cm
);
775 postUpdateDisplay(cm
, update
);
776 var barMeasure
= measureForScrollbars(cm
);
778 setDocumentHeight(cm
, barMeasure
);
779 updateScrollbars(cm
, barMeasure
);
783 function setDocumentHeight(cm
, measure
) {
784 cm
.display
.sizer
.style
.minHeight
= measure
.docHeight
+ "px";
785 var total
= measure
.docHeight
+ cm
.display
.barHeight
;
786 cm
.display
.heightForcer
.style
.top
= total
+ "px";
787 cm
.display
.gutters
.style
.height
= Math
.max(total
+ scrollGap(cm
), measure
.clientHeight
) + "px";
790 // Read the actual heights of the rendered lines, and update their
791 // stored heights to match.
792 function updateHeightsInViewport(cm
) {
793 var display
= cm
.display
;
794 var prevBottom
= display
.lineDiv
.offsetTop
;
795 for (var i
= 0; i
< display
.view
.length
; i
++) {
796 var cur
= display
.view
[i
], height
;
797 if (cur
.hidden
) continue;
798 if (ie
&& ie_version
< 8) {
799 var bot
= cur
.node
.offsetTop
+ cur
.node
.offsetHeight
;
800 height
= bot
- prevBottom
;
803 var box
= cur
.node
.getBoundingClientRect();
804 height
= box
.bottom
- box
.top
;
806 var diff
= cur
.line
.height
- height
;
807 if (height
< 2) height
= textHeight(display
);
808 if (diff
> .001 || diff
< -.001) {
809 updateLineHeight(cur
.line
, height
);
810 updateWidgetHeight(cur
.line
);
811 if (cur
.rest
) for (var j
= 0; j
< cur
.rest
.length
; j
++)
812 updateWidgetHeight(cur
.rest
[j
]);
817 // Read and store the height of line widgets associated with the
819 function updateWidgetHeight(line
) {
820 if (line
.widgets
) for (var i
= 0; i
< line
.widgets
.length
; ++i
)
821 line
.widgets
[i
].height
= line
.widgets
[i
].node
.offsetHeight
;
824 // Do a bulk-read of the DOM positions and sizes needed to draw the
825 // view, so that we don't interleave reading and writing to the DOM.
826 function getDimensions(cm
) {
827 var d
= cm
.display
, left
= {}, width
= {};
828 var gutterLeft
= d
.gutters
.clientLeft
;
829 for (var n
= d
.gutters
.firstChild
, i
= 0; n
; n
= n
.nextSibling
, ++i
) {
830 left
[cm
.options
.gutters
[i
]] = n
.offsetLeft
+ n
.clientLeft
+ gutterLeft
;
831 width
[cm
.options
.gutters
[i
]] = n
.clientWidth
;
833 return {fixedPos
: compensateForHScroll(d
),
834 gutterTotalWidth
: d
.gutters
.offsetWidth
,
837 wrapperWidth
: d
.wrapper
.clientWidth
};
840 // Sync the actual display DOM structure with display.view, removing
841 // nodes for lines that are no longer in view, and creating the ones
842 // that are not there yet, and updating the ones that are out of
844 function patchDisplay(cm
, updateNumbersFrom
, dims
) {
845 var display
= cm
.display
, lineNumbers
= cm
.options
.lineNumbers
;
846 var container
= display
.lineDiv
, cur
= container
.firstChild
;
849 var next
= node
.nextSibling
;
850 // Works around a throw-scroll bug in OS X Webkit
851 if (webkit
&& mac
&& cm
.display
.currentWheelTarget
== node
)
852 node
.style
.display
= "none";
854 node
.parentNode
.removeChild(node
);
858 var view
= display
.view
, lineN
= display
.viewFrom
;
859 // Loop over the elements in the view, syncing cur (the DOM nodes
860 // in display.lineDiv) with the view as we go.
861 for (var i
= 0; i
< view
.length
; i
++) {
862 var lineView
= view
[i
];
863 if (lineView
.hidden
) {
864 } else if (!lineView
.node
) { // Not drawn yet
865 var node
= buildLineElement(cm
, lineView
, lineN
, dims
);
866 container
.insertBefore(node
, cur
);
867 } else { // Already drawn
868 while (cur
!= lineView
.node
) cur
= rm(cur
);
869 var updateNumber
= lineNumbers
&& updateNumbersFrom
!= null &&
870 updateNumbersFrom
<= lineN
&& lineView
.lineNumber
;
871 if (lineView
.changes
) {
872 if (indexOf(lineView
.changes
, "gutter") > -1) updateNumber
= false;
873 updateLineForChanges(cm
, lineView
, lineN
, dims
);
876 removeChildren(lineView
.lineNumber
);
877 lineView
.lineNumber
.appendChild(document
.createTextNode(lineNumberFor(cm
.options
, lineN
)));
879 cur
= lineView
.node
.nextSibling
;
881 lineN
+= lineView
.size
;
883 while (cur
) cur
= rm(cur
);
886 // When an aspect of a line changes, a string is added to
887 // lineView.changes. This updates the relevant part of the line's
889 function updateLineForChanges(cm
, lineView
, lineN
, dims
) {
890 for (var j
= 0; j
< lineView
.changes
.length
; j
++) {
891 var type
= lineView
.changes
[j
];
892 if (type
== "text") updateLineText(cm
, lineView
);
893 else if (type
== "gutter") updateLineGutter(cm
, lineView
, lineN
, dims
);
894 else if (type
== "class") updateLineClasses(lineView
);
895 else if (type
== "widget") updateLineWidgets(lineView
, dims
);
897 lineView
.changes
= null;
900 // Lines with gutter elements, widgets or a background class need to
901 // be wrapped, and have the extra elements added to the wrapper div
902 function ensureLineWrapped(lineView
) {
903 if (lineView
.node
== lineView
.text
) {
904 lineView
.node
= elt("div", null, null, "position: relative");
905 if (lineView
.text
.parentNode
)
906 lineView
.text
.parentNode
.replaceChild(lineView
.node
, lineView
.text
);
907 lineView
.node
.appendChild(lineView
.text
);
908 if (ie
&& ie_version
< 8) lineView
.node
.style
.zIndex
= 2;
910 return lineView
.node
;
913 function updateLineBackground(lineView
) {
914 var cls
= lineView
.bgClass
? lineView
.bgClass
+ " " + (lineView
.line
.bgClass
|| "") : lineView
.line
.bgClass
;
915 if (cls
) cls
+= " CodeMirror-linebackground";
916 if (lineView
.background
) {
917 if (cls
) lineView
.background
.className
= cls
;
918 else { lineView
.background
.parentNode
.removeChild(lineView
.background
); lineView
.background
= null; }
920 var wrap
= ensureLineWrapped(lineView
);
921 lineView
.background
= wrap
.insertBefore(elt("div", null, cls
), wrap
.firstChild
);
925 // Wrapper around buildLineContent which will reuse the structure
926 // in display.externalMeasured when possible.
927 function getLineContent(cm
, lineView
) {
928 var ext
= cm
.display
.externalMeasured
;
929 if (ext
&& ext
.line
== lineView
.line
) {
930 cm
.display
.externalMeasured
= null;
931 lineView
.measure
= ext
.measure
;
934 return buildLineContent(cm
, lineView
);
937 // Redraw the line's text. Interacts with the background and text
938 // classes because the mode may output tokens that influence these
940 function updateLineText(cm
, lineView
) {
941 var cls
= lineView
.text
.className
;
942 var built
= getLineContent(cm
, lineView
);
943 if (lineView
.text
== lineView
.node
) lineView
.node
= built
.pre
;
944 lineView
.text
.parentNode
.replaceChild(built
.pre
, lineView
.text
);
945 lineView
.text
= built
.pre
;
946 if (built
.bgClass
!= lineView
.bgClass
|| built
.textClass
!= lineView
.textClass
) {
947 lineView
.bgClass
= built
.bgClass
;
948 lineView
.textClass
= built
.textClass
;
949 updateLineClasses(lineView
);
951 lineView
.text
.className
= cls
;
955 function updateLineClasses(lineView
) {
956 updateLineBackground(lineView
);
957 if (lineView
.line
.wrapClass
)
958 ensureLineWrapped(lineView
).className
= lineView
.line
.wrapClass
;
959 else if (lineView
.node
!= lineView
.text
)
960 lineView
.node
.className
= "";
961 var textClass
= lineView
.textClass
? lineView
.textClass
+ " " + (lineView
.line
.textClass
|| "") : lineView
.line
.textClass
;
962 lineView
.text
.className
= textClass
|| "";
965 function updateLineGutter(cm
, lineView
, lineN
, dims
) {
966 if (lineView
.gutter
) {
967 lineView
.node
.removeChild(lineView
.gutter
);
968 lineView
.gutter
= null;
970 var markers
= lineView
.line
.gutterMarkers
;
971 if (cm
.options
.lineNumbers
|| markers
) {
972 var wrap
= ensureLineWrapped(lineView
);
973 var gutterWrap
= lineView
.gutter
=
974 wrap
.insertBefore(elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
975 (cm
.options
.fixedGutter
? dims
.fixedPos
: -dims
.gutterTotalWidth
) +
976 "px; width: " + dims
.gutterTotalWidth
+ "px"),
978 if (lineView
.line
.gutterClass
)
979 gutterWrap
.className
+= " " + lineView
.line
.gutterClass
;
980 if (cm
.options
.lineNumbers
&& (!markers
|| !markers
["CodeMirror-linenumbers"]))
981 lineView
.lineNumber
= gutterWrap
.appendChild(
982 elt("div", lineNumberFor(cm
.options
, lineN
),
983 "CodeMirror-linenumber CodeMirror-gutter-elt",
984 "left: " + dims
.gutterLeft
["CodeMirror-linenumbers"] + "px; width: "
985 + cm
.display
.lineNumInnerWidth
+ "px"));
986 if (markers
) for (var k
= 0; k
< cm
.options
.gutters
.length
; ++k
) {
987 var id
= cm
.options
.gutters
[k
], found
= markers
.hasOwnProperty(id
) && markers
[id
];
989 gutterWrap
.appendChild(elt("div", [found
], "CodeMirror-gutter-elt", "left: " +
990 dims
.gutterLeft
[id
] + "px; width: " + dims
.gutterWidth
[id
] + "px"));
995 function updateLineWidgets(lineView
, dims
) {
996 if (lineView
.alignable
) lineView
.alignable
= null;
997 for (var node
= lineView
.node
.firstChild
, next
; node
; node
= next
) {
998 var next
= node
.nextSibling
;
999 if (node
.className
== "CodeMirror-linewidget")
1000 lineView
.node
.removeChild(node
);
1002 insertLineWidgets(lineView
, dims
);
1005 // Build a line's DOM representation from scratch
1006 function buildLineElement(cm
, lineView
, lineN
, dims
) {
1007 var built
= getLineContent(cm
, lineView
);
1008 lineView
.text
= lineView
.node
= built
.pre
;
1009 if (built
.bgClass
) lineView
.bgClass
= built
.bgClass
;
1010 if (built
.textClass
) lineView
.textClass
= built
.textClass
;
1012 updateLineClasses(lineView
);
1013 updateLineGutter(cm
, lineView
, lineN
, dims
);
1014 insertLineWidgets(lineView
, dims
);
1015 return lineView
.node
;
1018 // A lineView may contain multiple logical lines (when merged by
1019 // collapsed spans). The widgets for all of them need to be drawn.
1020 function insertLineWidgets(lineView
, dims
) {
1021 insertLineWidgetsFor(lineView
.line
, lineView
, dims
, true);
1022 if (lineView
.rest
) for (var i
= 0; i
< lineView
.rest
.length
; i
++)
1023 insertLineWidgetsFor(lineView
.rest
[i
], lineView
, dims
, false);
1026 function insertLineWidgetsFor(line
, lineView
, dims
, allowAbove
) {
1027 if (!line
.widgets
) return;
1028 var wrap
= ensureLineWrapped(lineView
);
1029 for (var i
= 0, ws
= line
.widgets
; i
< ws
.length
; ++i
) {
1030 var widget
= ws
[i
], node
= elt("div", [widget
.node
], "CodeMirror-linewidget");
1031 if (!widget
.handleMouseEvents
) node
.setAttribute("cm-ignore-events", "true");
1032 positionLineWidget(widget
, node
, lineView
, dims
);
1033 if (allowAbove
&& widget
.above
)
1034 wrap
.insertBefore(node
, lineView
.gutter
|| lineView
.text
);
1036 wrap
.appendChild(node
);
1037 signalLater(widget
, "redraw");
1041 function positionLineWidget(widget
, node
, lineView
, dims
) {
1042 if (widget
.noHScroll
) {
1043 (lineView
.alignable
|| (lineView
.alignable
= [])).push(node
);
1044 var width
= dims
.wrapperWidth
;
1045 node
.style
.left
= dims
.fixedPos
+ "px";
1046 if (!widget
.coverGutter
) {
1047 width
-= dims
.gutterTotalWidth
;
1048 node
.style
.paddingLeft
= dims
.gutterTotalWidth
+ "px";
1050 node
.style
.width
= width
+ "px";
1052 if (widget
.coverGutter
) {
1053 node
.style
.zIndex
= 5;
1054 node
.style
.position
= "relative";
1055 if (!widget
.noHScroll
) node
.style
.marginLeft
= -dims
.gutterTotalWidth
+ "px";
1061 // A Pos instance represents a position within the text.
1062 var Pos
= CodeMirror
.Pos = function(line
, ch
) {
1063 if (!(this instanceof Pos
)) return new Pos(line
, ch
);
1064 this.line
= line
; this.ch
= ch
;
1067 // Compare two positions, return 0 if they are the same, a negative
1068 // number when a is less, and a positive number otherwise.
1069 var cmp
= CodeMirror
.cmpPos = function(a
, b
) { return a
.line
- b
.line
|| a
.ch
- b
.ch
; };
1071 function copyPos(x
) {return Pos(x
.line
, x
.ch
);}
1072 function maxPos(a
, b
) { return cmp(a
, b
) < 0 ? b
: a
; }
1073 function minPos(a
, b
) { return cmp(a
, b
) < 0 ? a
: b
; }
1075 // SELECTION / CURSOR
1077 // Selection objects are immutable. A new one is created every time
1078 // the selection changes. A selection is one or more non-overlapping
1079 // (and non-touching) ranges, sorted, and an integer that indicates
1080 // which one is the primary selection (the one that's scrolled into
1081 // view, that getCursor returns, etc).
1082 function Selection(ranges
, primIndex
) {
1083 this.ranges
= ranges
;
1084 this.primIndex
= primIndex
;
1087 Selection
.prototype = {
1088 primary: function() { return this.ranges
[this.primIndex
]; },
1089 equals: function(other
) {
1090 if (other
== this) return true;
1091 if (other
.primIndex
!= this.primIndex
|| other
.ranges
.length
!= this.ranges
.length
) return false;
1092 for (var i
= 0; i
< this.ranges
.length
; i
++) {
1093 var here
= this.ranges
[i
], there
= other
.ranges
[i
];
1094 if (cmp(here
.anchor
, there
.anchor
) != 0 || cmp(here
.head
, there
.head
) != 0) return false;
1098 deepCopy: function() {
1099 for (var out
= [], i
= 0; i
< this.ranges
.length
; i
++)
1100 out
[i
] = new Range(copyPos(this.ranges
[i
].anchor
), copyPos(this.ranges
[i
].head
));
1101 return new Selection(out
, this.primIndex
);
1103 somethingSelected: function() {
1104 for (var i
= 0; i
< this.ranges
.length
; i
++)
1105 if (!this.ranges
[i
].empty()) return true;
1108 contains: function(pos
, end
) {
1109 if (!end
) end
= pos
;
1110 for (var i
= 0; i
< this.ranges
.length
; i
++) {
1111 var range
= this.ranges
[i
];
1112 if (cmp(end
, range
.from()) >= 0 && cmp(pos
, range
.to()) <= 0)
1119 function Range(anchor
, head
) {
1120 this.anchor
= anchor
; this.head
= head
;
1124 from: function() { return minPos(this.anchor
, this.head
); },
1125 to: function() { return maxPos(this.anchor
, this.head
); },
1127 return this.head
.line
== this.anchor
.line
&& this.head
.ch
== this.anchor
.ch
;
1131 // Take an unsorted, potentially overlapping set of ranges, and
1132 // build a selection out of it. 'Consumes' ranges array (modifying
1134 function normalizeSelection(ranges
, primIndex
) {
1135 var prim
= ranges
[primIndex
];
1136 ranges
.sort(function(a
, b
) { return cmp(a
.from(), b
.from()); });
1137 primIndex
= indexOf(ranges
, prim
);
1138 for (var i
= 1; i
< ranges
.length
; i
++) {
1139 var cur
= ranges
[i
], prev
= ranges
[i
- 1];
1140 if (cmp(prev
.to(), cur
.from()) >= 0) {
1141 var from = minPos(prev
.from(), cur
.from()), to
= maxPos(prev
.to(), cur
.to());
1142 var inv
= prev
.empty() ? cur
.from() == cur
.head
: prev
.from() == prev
.head
;
1143 if (i
<= primIndex
) --primIndex
;
1144 ranges
.splice(--i
, 2, new Range(inv
? to
: from, inv
? from : to
));
1147 return new Selection(ranges
, primIndex
);
1150 function simpleSelection(anchor
, head
) {
1151 return new Selection([new Range(anchor
, head
|| anchor
)], 0);
1154 // Most of the external API clips given positions to make sure they
1155 // actually exist within the document.
1156 function clipLine(doc
, n
) {return Math
.max(doc
.first
, Math
.min(n
, doc
.first
+ doc
.size
- 1));}
1157 function clipPos(doc
, pos
) {
1158 if (pos
.line
< doc
.first
) return Pos(doc
.first
, 0);
1159 var last
= doc
.first
+ doc
.size
- 1;
1160 if (pos
.line
> last
) return Pos(last
, getLine(doc
, last
).text
.length
);
1161 return clipToLen(pos
, getLine(doc
, pos
.line
).text
.length
);
1163 function clipToLen(pos
, linelen
) {
1165 if (ch
== null || ch
> linelen
) return Pos(pos
.line
, linelen
);
1166 else if (ch
< 0) return Pos(pos
.line
, 0);
1169 function isLine(doc
, l
) {return l
>= doc
.first
&& l
< doc
.first
+ doc
.size
;}
1170 function clipPosArray(doc
, array
) {
1171 for (var out
= [], i
= 0; i
< array
.length
; i
++) out
[i
] = clipPos(doc
, array
[i
]);
1175 // SELECTION UPDATES
1177 // The 'scroll' parameter given to many of these indicated whether
1178 // the new cursor position should be scrolled into view after
1179 // modifying the selection.
1181 // If shift is held or the extend flag is set, extends a range to
1182 // include a given position (and optionally a second position).
1183 // Otherwise, simply returns the range between the given positions.
1184 // Used for cursor motion and such.
1185 function extendRange(doc
, range
, head
, other
) {
1186 if (doc
.cm
&& doc
.cm
.display
.shift
|| doc
.extend
) {
1187 var anchor
= range
.anchor
;
1189 var posBefore
= cmp(head
, anchor
) < 0;
1190 if (posBefore
!= (cmp(other
, anchor
) < 0)) {
1193 } else if (posBefore
!= (cmp(head
, other
) < 0)) {
1197 return new Range(anchor
, head
);
1199 return new Range(other
|| head
, head
);
1203 // Extend the primary selection range, discard the rest.
1204 function extendSelection(doc
, head
, other
, options
) {
1205 setSelection(doc
, new Selection([extendRange(doc
, doc
.sel
.primary(), head
, other
)], 0), options
);
1208 // Extend all selections (pos is an array of selections with length
1209 // equal the number of selections)
1210 function extendSelections(doc
, heads
, options
) {
1211 for (var out
= [], i
= 0; i
< doc
.sel
.ranges
.length
; i
++)
1212 out
[i
] = extendRange(doc
, doc
.sel
.ranges
[i
], heads
[i
], null);
1213 var newSel
= normalizeSelection(out
, doc
.sel
.primIndex
);
1214 setSelection(doc
, newSel
, options
);
1217 // Updates a single range in the selection.
1218 function replaceOneSelection(doc
, i
, range
, options
) {
1219 var ranges
= doc
.sel
.ranges
.slice(0);
1221 setSelection(doc
, normalizeSelection(ranges
, doc
.sel
.primIndex
), options
);
1224 // Reset the selection to a single range.
1225 function setSimpleSelection(doc
, anchor
, head
, options
) {
1226 setSelection(doc
, simpleSelection(anchor
, head
), options
);
1229 // Give beforeSelectionChange handlers a change to influence a
1230 // selection update.
1231 function filterSelectionChange(doc
, sel
) {
1234 update: function(ranges
) {
1236 for (var i
= 0; i
< ranges
.length
; i
++)
1237 this.ranges
[i
] = new Range(clipPos(doc
, ranges
[i
].anchor
),
1238 clipPos(doc
, ranges
[i
].head
));
1241 signal(doc
, "beforeSelectionChange", doc
, obj
);
1242 if (doc
.cm
) signal(doc
.cm
, "beforeSelectionChange", doc
.cm
, obj
);
1243 if (obj
.ranges
!= sel
.ranges
) return normalizeSelection(obj
.ranges
, obj
.ranges
.length
- 1);
1247 function setSelectionReplaceHistory(doc
, sel
, options
) {
1248 var done
= doc
.history
.done
, last
= lst(done
);
1249 if (last
&& last
.ranges
) {
1250 done
[done
.length
- 1] = sel
;
1251 setSelectionNoUndo(doc
, sel
, options
);
1253 setSelection(doc
, sel
, options
);
1257 // Set a new selection.
1258 function setSelection(doc
, sel
, options
) {
1259 setSelectionNoUndo(doc
, sel
, options
);
1260 addSelectionToHistory(doc
, doc
.sel
, doc
.cm
? doc
.cm
.curOp
.id
: NaN
, options
);
1263 function setSelectionNoUndo(doc
, sel
, options
) {
1264 if (hasHandler(doc
, "beforeSelectionChange") || doc
.cm
&& hasHandler(doc
.cm
, "beforeSelectionChange"))
1265 sel
= filterSelectionChange(doc
, sel
);
1267 var bias
= options
&& options
.bias
||
1268 (cmp(sel
.primary().head
, doc
.sel
.primary().head
) < 0 ? -1 : 1);
1269 setSelectionInner(doc
, skipAtomicInSelection(doc
, sel
, bias
, true));
1271 if (!(options
&& options
.scroll
=== false) && doc
.cm
)
1272 ensureCursorVisible(doc
.cm
);
1275 function setSelectionInner(doc
, sel
) {
1276 if (sel
.equals(doc
.sel
)) return;
1281 doc
.cm
.curOp
.updateInput
= doc
.cm
.curOp
.selectionChanged
= true;
1282 signalCursorActivity(doc
.cm
);
1284 signalLater(doc
, "cursorActivity", doc
);
1287 // Verify that the selection does not partially select any atomic
1289 function reCheckSelection(doc
) {
1290 setSelectionInner(doc
, skipAtomicInSelection(doc
, doc
.sel
, null, false), sel_dontScroll
);
1293 // Return a selection that does not partially select any atomic
1295 function skipAtomicInSelection(doc
, sel
, bias
, mayClear
) {
1297 for (var i
= 0; i
< sel
.ranges
.length
; i
++) {
1298 var range
= sel
.ranges
[i
];
1299 var newAnchor
= skipAtomic(doc
, range
.anchor
, bias
, mayClear
);
1300 var newHead
= skipAtomic(doc
, range
.head
, bias
, mayClear
);
1301 if (out
|| newAnchor
!= range
.anchor
|| newHead
!= range
.head
) {
1302 if (!out
) out
= sel
.ranges
.slice(0, i
);
1303 out
[i
] = new Range(newAnchor
, newHead
);
1306 return out
? normalizeSelection(out
, sel
.primIndex
) : sel
;
1309 // Ensure a given position is not inside an atomic range.
1310 function skipAtomic(doc
, pos
, bias
, mayClear
) {
1311 var flipped
= false, curPos
= pos
;
1312 var dir
= bias
|| 1;
1313 doc
.cantEdit
= false;
1315 var line
= getLine(doc
, curPos
.line
);
1316 if (line
.markedSpans
) {
1317 for (var i
= 0; i
< line
.markedSpans
.length
; ++i
) {
1318 var sp
= line
.markedSpans
[i
], m
= sp
.marker
;
1319 if ((sp
.from == null || (m
.inclusiveLeft
? sp
.from <= curPos
.ch
: sp
.from < curPos
.ch
)) &&
1320 (sp
.to
== null || (m
.inclusiveRight
? sp
.to
>= curPos
.ch
: sp
.to
> curPos
.ch
))) {
1322 signal(m
, "beforeCursorEnter");
1323 if (m
.explicitlyCleared
) {
1324 if (!line
.markedSpans
) break;
1325 else {--i
; continue;}
1328 if (!m
.atomic
) continue;
1329 var newPos
= m
.find(dir
< 0 ? -1 : 1);
1330 if (cmp(newPos
, curPos
) == 0) {
1332 if (newPos
.ch
< 0) {
1333 if (newPos
.line
> doc
.first
) newPos
= clipPos(doc
, Pos(newPos
.line
- 1));
1335 } else if (newPos
.ch
> line
.text
.length
) {
1336 if (newPos
.line
< doc
.first
+ doc
.size
- 1) newPos
= Pos(newPos
.line
+ 1, 0);
1341 // Driven in a corner -- no valid cursor position found at all
1342 // -- try again *with* clearing, if we didn't already
1343 if (!mayClear
) return skipAtomic(doc
, pos
, bias
, true);
1344 // Otherwise, turn off editing until further notice, and return the start of the doc
1345 doc
.cantEdit
= true;
1346 return Pos(doc
.first
, 0);
1348 flipped
= true; newPos
= pos
; dir
= -dir
;
1360 // SELECTION DRAWING
1362 // Redraw the selection and/or cursor
1363 function drawSelection(cm
) {
1364 var display
= cm
.display
, doc
= cm
.doc
, result
= {};
1365 var curFragment
= result
.cursors
= document
.createDocumentFragment();
1366 var selFragment
= result
.selection
= document
.createDocumentFragment();
1368 for (var i
= 0; i
< doc
.sel
.ranges
.length
; i
++) {
1369 var range
= doc
.sel
.ranges
[i
];
1370 var collapsed
= range
.empty();
1371 if (collapsed
|| cm
.options
.showCursorWhenSelecting
)
1372 drawSelectionCursor(cm
, range
, curFragment
);
1374 drawSelectionRange(cm
, range
, selFragment
);
1377 // Move the hidden textarea near the cursor to prevent scrolling artifacts
1378 if (cm
.options
.moveInputWithCursor
) {
1379 var headPos
= cursorCoords(cm
, doc
.sel
.primary().head
, "div");
1380 var wrapOff
= display
.wrapper
.getBoundingClientRect(), lineOff
= display
.lineDiv
.getBoundingClientRect();
1381 result
.teTop
= Math
.max(0, Math
.min(display
.wrapper
.clientHeight
- 10,
1382 headPos
.top
+ lineOff
.top
- wrapOff
.top
));
1383 result
.teLeft
= Math
.max(0, Math
.min(display
.wrapper
.clientWidth
- 10,
1384 headPos
.left
+ lineOff
.left
- wrapOff
.left
));
1390 function showSelection(cm
, drawn
) {
1391 removeChildrenAndAdd(cm
.display
.cursorDiv
, drawn
.cursors
);
1392 removeChildrenAndAdd(cm
.display
.selectionDiv
, drawn
.selection
);
1393 if (drawn
.teTop
!= null) {
1394 cm
.display
.inputDiv
.style
.top
= drawn
.teTop
+ "px";
1395 cm
.display
.inputDiv
.style
.left
= drawn
.teLeft
+ "px";
1399 function updateSelection(cm
) {
1400 showSelection(cm
, drawSelection(cm
));
1403 // Draws a cursor for the given range
1404 function drawSelectionCursor(cm
, range
, output
) {
1405 var pos
= cursorCoords(cm
, range
.head
, "div", null, null, !cm
.options
.singleCursorHeightPerLine
);
1407 var cursor
= output
.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
1408 cursor
.style
.left
= pos
.left
+ "px";
1409 cursor
.style
.top
= pos
.top
+ "px";
1410 cursor
.style
.height
= Math
.max(0, pos
.bottom
- pos
.top
) * cm
.options
.cursorHeight
+ "px";
1413 // Secondary cursor, shown when on a 'jump' in bi-directional text
1414 var otherCursor
= output
.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
1415 otherCursor
.style
.display
= "";
1416 otherCursor
.style
.left
= pos
.other
.left
+ "px";
1417 otherCursor
.style
.top
= pos
.other
.top
+ "px";
1418 otherCursor
.style
.height
= (pos
.other
.bottom
- pos
.other
.top
) * .85 + "px";
1422 // Draws the given range as a highlighted selection
1423 function drawSelectionRange(cm
, range
, output
) {
1424 var display
= cm
.display
, doc
= cm
.doc
;
1425 var fragment
= document
.createDocumentFragment();
1426 var padding
= paddingH(cm
.display
), leftSide
= padding
.left
;
1427 var rightSide
= Math
.max(display
.sizerWidth
, displayWidth(cm
) - display
.sizer
.offsetLeft
) - padding
.right
;
1429 function add(left
, top
, width
, bottom
) {
1430 if (top
< 0) top
= 0;
1431 top
= Math
.round(top
);
1432 bottom
= Math
.round(bottom
);
1433 fragment
.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left
+
1434 "px; top: " + top
+ "px; width: " + (width
== null ? rightSide
- left
: width
) +
1435 "px; height: " + (bottom
- top
) + "px"));
1438 function drawForLine(line
, fromArg
, toArg
) {
1439 var lineObj
= getLine(doc
, line
);
1440 var lineLen
= lineObj
.text
.length
;
1442 function coords(ch
, bias
) {
1443 return charCoords(cm
, Pos(line
, ch
), "div", lineObj
, bias
);
1446 iterateBidiSections(getOrder(lineObj
), fromArg
|| 0, toArg
== null ? lineLen
: toArg
, function(from, to
, dir
) {
1447 var leftPos
= coords(from, "left"), rightPos
, left
, right
;
1450 left
= right
= leftPos
.left
;
1452 rightPos
= coords(to
- 1, "right");
1453 if (dir
== "rtl") { var tmp
= leftPos
; leftPos
= rightPos
; rightPos
= tmp
; }
1454 left
= leftPos
.left
;
1455 right
= rightPos
.right
;
1457 if (fromArg
== null && from == 0) left
= leftSide
;
1458 if (rightPos
.top
- leftPos
.top
> 3) { // Different lines, draw top part
1459 add(left
, leftPos
.top
, null, leftPos
.bottom
);
1461 if (leftPos
.bottom
< rightPos
.top
) add(left
, leftPos
.bottom
, null, rightPos
.top
);
1463 if (toArg
== null && to
== lineLen
) right
= rightSide
;
1464 if (!start
|| leftPos
.top
< start
.top
|| leftPos
.top
== start
.top
&& leftPos
.left
< start
.left
)
1466 if (!end
|| rightPos
.bottom
> end
.bottom
|| rightPos
.bottom
== end
.bottom
&& rightPos
.right
> end
.right
)
1468 if (left
< leftSide
+ 1) left
= leftSide
;
1469 add(left
, rightPos
.top
, right
- left
, rightPos
.bottom
);
1471 return {start
: start
, end
: end
};
1474 var sFrom
= range
.from(), sTo
= range
.to();
1475 if (sFrom
.line
== sTo
.line
) {
1476 drawForLine(sFrom
.line
, sFrom
.ch
, sTo
.ch
);
1478 var fromLine
= getLine(doc
, sFrom
.line
), toLine
= getLine(doc
, sTo
.line
);
1479 var singleVLine
= visualLine(fromLine
) == visualLine(toLine
);
1480 var leftEnd
= drawForLine(sFrom
.line
, sFrom
.ch
, singleVLine
? fromLine
.text
.length
+ 1 : null).end
;
1481 var rightStart
= drawForLine(sTo
.line
, singleVLine
? 0 : null, sTo
.ch
).start
;
1483 if (leftEnd
.top
< rightStart
.top
- 2) {
1484 add(leftEnd
.right
, leftEnd
.top
, null, leftEnd
.bottom
);
1485 add(leftSide
, rightStart
.top
, rightStart
.left
, rightStart
.bottom
);
1487 add(leftEnd
.right
, leftEnd
.top
, rightStart
.left
- leftEnd
.right
, leftEnd
.bottom
);
1490 if (leftEnd
.bottom
< rightStart
.top
)
1491 add(leftSide
, leftEnd
.bottom
, null, rightStart
.top
);
1494 output
.appendChild(fragment
);
1498 function restartBlink(cm
) {
1499 if (!cm
.state
.focused
) return;
1500 var display
= cm
.display
;
1501 clearInterval(display
.blinker
);
1503 display
.cursorDiv
.style
.visibility
= "";
1504 if (cm
.options
.cursorBlinkRate
> 0)
1505 display
.blinker
= setInterval(function() {
1506 display
.cursorDiv
.style
.visibility
= (on
= !on
) ? "" : "hidden";
1507 }, cm
.options
.cursorBlinkRate
);
1508 else if (cm
.options
.cursorBlinkRate
< 0)
1509 display
.cursorDiv
.style
.visibility
= "hidden";
1514 function startWorker(cm
, time
) {
1515 if (cm
.doc
.mode
.startState
&& cm
.doc
.frontier
< cm
.display
.viewTo
)
1516 cm
.state
.highlight
.set(time
, bind(highlightWorker
, cm
));
1519 function highlightWorker(cm
) {
1521 if (doc
.frontier
< doc
.first
) doc
.frontier
= doc
.first
;
1522 if (doc
.frontier
>= cm
.display
.viewTo
) return;
1523 var end
= +new Date
+ cm
.options
.workTime
;
1524 var state
= copyState(doc
.mode
, getStateBefore(cm
, doc
.frontier
));
1525 var changedLines
= [];
1527 doc
.iter(doc
.frontier
, Math
.min(doc
.first
+ doc
.size
, cm
.display
.viewTo
+ 500), function(line
) {
1528 if (doc
.frontier
>= cm
.display
.viewFrom
) { // Visible
1529 var oldStyles
= line
.styles
;
1530 var highlighted
= highlightLine(cm
, line
, state
, true);
1531 line
.styles
= highlighted
.styles
;
1532 var oldCls
= line
.styleClasses
, newCls
= highlighted
.classes
;
1533 if (newCls
) line
.styleClasses
= newCls
;
1534 else if (oldCls
) line
.styleClasses
= null;
1535 var ischange
= !oldStyles
|| oldStyles
.length
!= line
.styles
.length
||
1536 oldCls
!= newCls
&& (!oldCls
|| !newCls
|| oldCls
.bgClass
!= newCls
.bgClass
|| oldCls
.textClass
!= newCls
.textClass
);
1537 for (var i
= 0; !ischange
&& i
< oldStyles
.length
; ++i
) ischange
= oldStyles
[i
] != line
.styles
[i
];
1538 if (ischange
) changedLines
.push(doc
.frontier
);
1539 line
.stateAfter
= copyState(doc
.mode
, state
);
1541 processLine(cm
, line
.text
, state
);
1542 line
.stateAfter
= doc
.frontier
% 5 == 0 ? copyState(doc
.mode
, state
) : null;
1545 if (+new Date
> end
) {
1546 startWorker(cm
, cm
.options
.workDelay
);
1550 if (changedLines
.length
) runInOp(cm
, function() {
1551 for (var i
= 0; i
< changedLines
.length
; i
++)
1552 regLineChange(cm
, changedLines
[i
], "text");
1556 // Finds the line to start with when starting a parse. Tries to
1557 // find a line with a stateAfter, so that it can start with a
1558 // valid state. If that fails, it returns the line with the
1559 // smallest indentation, which tends to need the least context to
1561 function findStartLine(cm
, n
, precise
) {
1562 var minindent
, minline
, doc
= cm
.doc
;
1563 var lim
= precise
? -1 : n
- (cm
.doc
.mode
.innerMode
? 1000 : 100);
1564 for (var search
= n
; search
> lim
; --search
) {
1565 if (search
<= doc
.first
) return doc
.first
;
1566 var line
= getLine(doc
, search
- 1);
1567 if (line
.stateAfter
&& (!precise
|| search
<= doc
.frontier
)) return search
;
1568 var indented
= countColumn(line
.text
, null, cm
.options
.tabSize
);
1569 if (minline
== null || minindent
> indented
) {
1570 minline
= search
- 1;
1571 minindent
= indented
;
1577 function getStateBefore(cm
, n
, precise
) {
1578 var doc
= cm
.doc
, display
= cm
.display
;
1579 if (!doc
.mode
.startState
) return true;
1580 var pos
= findStartLine(cm
, n
, precise
), state
= pos
> doc
.first
&& getLine(doc
, pos
-1).stateAfter
;
1581 if (!state
) state
= startState(doc
.mode
);
1582 else state
= copyState(doc
.mode
, state
);
1583 doc
.iter(pos
, n
, function(line
) {
1584 processLine(cm
, line
.text
, state
);
1585 var save
= pos
== n
- 1 || pos
% 5 == 0 || pos
>= display
.viewFrom
&& pos
< display
.viewTo
;
1586 line
.stateAfter
= save
? copyState(doc
.mode
, state
) : null;
1589 if (precise
) doc
.frontier
= pos
;
1593 // POSITION MEASUREMENT
1595 function paddingTop(display
) {return display
.lineSpace
.offsetTop
;}
1596 function paddingVert(display
) {return display
.mover
.offsetHeight
- display
.lineSpace
.offsetHeight
;}
1597 function paddingH(display
) {
1598 if (display
.cachedPaddingH
) return display
.cachedPaddingH
;
1599 var e
= removeChildrenAndAdd(display
.measure
, elt("pre", "x"));
1600 var style
= window
.getComputedStyle
? window
.getComputedStyle(e
) : e
.currentStyle
;
1601 var data
= {left
: parseInt(style
.paddingLeft
), right
: parseInt(style
.paddingRight
)};
1602 if (!isNaN(data
.left
) && !isNaN(data
.right
)) display
.cachedPaddingH
= data
;
1606 function scrollGap(cm
) { return scrollerGap
- cm
.display
.nativeBarWidth
; }
1607 function displayWidth(cm
) {
1608 return cm
.display
.scroller
.clientWidth
- scrollGap(cm
) - cm
.display
.barWidth
;
1610 function displayHeight(cm
) {
1611 return cm
.display
.scroller
.clientHeight
- scrollGap(cm
) - cm
.display
.barHeight
;
1614 // Ensure the lineView.wrapping.heights array is populated. This is
1615 // an array of bottom offsets for the lines that make up a drawn
1616 // line. When lineWrapping is on, there might be more than one
1618 function ensureLineHeights(cm
, lineView
, rect
) {
1619 var wrapping
= cm
.options
.lineWrapping
;
1620 var curWidth
= wrapping
&& displayWidth(cm
);
1621 if (!lineView
.measure
.heights
|| wrapping
&& lineView
.measure
.width
!= curWidth
) {
1622 var heights
= lineView
.measure
.heights
= [];
1624 lineView
.measure
.width
= curWidth
;
1625 var rects
= lineView
.text
.firstChild
.getClientRects();
1626 for (var i
= 0; i
< rects
.length
- 1; i
++) {
1627 var cur
= rects
[i
], next
= rects
[i
+ 1];
1628 if (Math
.abs(cur
.bottom
- next
.bottom
) > 2)
1629 heights
.push((cur
.bottom
+ next
.top
) / 2 - rect
.top
);
1632 heights
.push(rect
.bottom
- rect
.top
);
1636 // Find a line map (mapping character offsets to text nodes) and a
1637 // measurement cache for the given line number. (A line view might
1638 // contain multiple lines when collapsed ranges are present.)
1639 function mapFromLineView(lineView
, line
, lineN
) {
1640 if (lineView
.line
== line
)
1641 return {map
: lineView
.measure
.map
, cache
: lineView
.measure
.cache
};
1642 for (var i
= 0; i
< lineView
.rest
.length
; i
++)
1643 if (lineView
.rest
[i
] == line
)
1644 return {map
: lineView
.measure
.maps
[i
], cache
: lineView
.measure
.caches
[i
]};
1645 for (var i
= 0; i
< lineView
.rest
.length
; i
++)
1646 if (lineNo(lineView
.rest
[i
]) > lineN
)
1647 return {map
: lineView
.measure
.maps
[i
], cache
: lineView
.measure
.caches
[i
], before
: true};
1650 // Render a line into the hidden node display.externalMeasured. Used
1651 // when measurement is needed for a line that's not in the viewport.
1652 function updateExternalMeasurement(cm
, line
) {
1653 line
= visualLine(line
);
1654 var lineN
= lineNo(line
);
1655 var view
= cm
.display
.externalMeasured
= new LineView(cm
.doc
, line
, lineN
);
1657 var built
= view
.built
= buildLineContent(cm
, view
);
1658 view
.text
= built
.pre
;
1659 removeChildrenAndAdd(cm
.display
.lineMeasure
, built
.pre
);
1663 // Get a {top, bottom, left, right} box (in line-local coordinates)
1664 // for a given character.
1665 function measureChar(cm
, line
, ch
, bias
) {
1666 return measureCharPrepared(cm
, prepareMeasureForLine(cm
, line
), ch
, bias
);
1669 // Find a line view that corresponds to the given line number.
1670 function findViewForLine(cm
, lineN
) {
1671 if (lineN
>= cm
.display
.viewFrom
&& lineN
< cm
.display
.viewTo
)
1672 return cm
.display
.view
[findViewIndex(cm
, lineN
)];
1673 var ext
= cm
.display
.externalMeasured
;
1674 if (ext
&& lineN
>= ext
.lineN
&& lineN
< ext
.lineN
+ ext
.size
)
1678 // Measurement can be split in two steps, the set-up work that
1679 // applies to the whole line, and the measurement of the actual
1680 // character. Functions like coordsChar, that need to do a lot of
1681 // measurements in a row, can thus ensure that the set-up work is
1683 function prepareMeasureForLine(cm
, line
) {
1684 var lineN
= lineNo(line
);
1685 var view
= findViewForLine(cm
, lineN
);
1686 if (view
&& !view
.text
)
1688 else if (view
&& view
.changes
)
1689 updateLineForChanges(cm
, view
, lineN
, getDimensions(cm
));
1691 view
= updateExternalMeasurement(cm
, line
);
1693 var info
= mapFromLineView(view
, line
, lineN
);
1695 line
: line
, view
: view
, rect
: null,
1696 map
: info
.map
, cache
: info
.cache
, before
: info
.before
,
1701 // Given a prepared measurement object, measures the position of an
1702 // actual character (or fetches it from the cache).
1703 function measureCharPrepared(cm
, prepared
, ch
, bias
, varHeight
) {
1704 if (prepared
.before
) ch
= -1;
1705 var key
= ch
+ (bias
|| ""), found
;
1706 if (prepared
.cache
.hasOwnProperty(key
)) {
1707 found
= prepared
.cache
[key
];
1710 prepared
.rect
= prepared
.view
.text
.getBoundingClientRect();
1711 if (!prepared
.hasHeights
) {
1712 ensureLineHeights(cm
, prepared
.view
, prepared
.rect
);
1713 prepared
.hasHeights
= true;
1715 found
= measureCharInner(cm
, prepared
, ch
, bias
);
1716 if (!found
.bogus
) prepared
.cache
[key
] = found
;
1718 return {left
: found
.left
, right
: found
.right
,
1719 top
: varHeight
? found
.rtop
: found
.top
,
1720 bottom
: varHeight
? found
.rbottom
: found
.bottom
};
1723 var nullRect
= {left
: 0, right
: 0, top
: 0, bottom
: 0};
1725 function measureCharInner(cm
, prepared
, ch
, bias
) {
1726 var map
= prepared
.map
;
1728 var node
, start
, end
, collapse
;
1729 // First, search the line map for the text node corresponding to,
1730 // or closest to, the target character.
1731 for (var i
= 0; i
< map
.length
; i
+= 3) {
1732 var mStart
= map
[i
], mEnd
= map
[i
+ 1];
1736 } else if (ch
< mEnd
) {
1737 start
= ch
- mStart
;
1739 } else if (i
== map
.length
- 3 || ch
== mEnd
&& map
[i
+ 3] > ch
) {
1740 end
= mEnd
- mStart
;
1742 if (ch
>= mEnd
) collapse
= "right";
1744 if (start
!= null) {
1746 if (mStart
== mEnd
&& bias
== (node
.insertLeft
? "left" : "right"))
1748 if (bias
== "left" && start
== 0)
1749 while (i
&& map
[i
- 2] == map
[i
- 3] && map
[i
- 1].insertLeft
) {
1750 node
= map
[(i
-= 3) + 2];
1753 if (bias
== "right" && start
== mEnd
- mStart
)
1754 while (i
< map
.length
- 3 && map
[i
+ 3] == map
[i
+ 4] && !map
[i
+ 5].insertLeft
) {
1755 node
= map
[(i
+= 3) + 2];
1763 if (node
.nodeType
== 3) { // If it is a text node, use a range to retrieve the coordinates.
1764 for (var i
= 0; i
< 4; i
++) { // Retry a maximum of 4 times when nonsense rectangles are returned
1765 while (start
&& isExtendingChar(prepared
.line
.text
.charAt(mStart
+ start
))) --start
;
1766 while (mStart
+ end
< mEnd
&& isExtendingChar(prepared
.line
.text
.charAt(mStart
+ end
))) ++end
;
1767 if (ie
&& ie_version
< 9 && start
== 0 && end
== mEnd
- mStart
) {
1768 rect
= node
.parentNode
.getBoundingClientRect();
1769 } else if (ie
&& cm
.options
.lineWrapping
) {
1770 var rects
= range(node
, start
, end
).getClientRects();
1772 rect
= rects
[bias
== "right" ? rects
.length
- 1 : 0];
1776 rect
= range(node
, start
, end
).getBoundingClientRect() || nullRect
;
1778 if (rect
.left
|| rect
.right
|| start
== 0) break;
1783 if (ie
&& ie_version
< 11) rect
= maybeUpdateRectForZooming(cm
.display
.measure
, rect
);
1784 } else { // If it is a widget, simply get the box for the whole widget.
1785 if (start
> 0) collapse
= bias
= "right";
1787 if (cm
.options
.lineWrapping
&& (rects
= node
.getClientRects()).length
> 1)
1788 rect
= rects
[bias
== "right" ? rects
.length
- 1 : 0];
1790 rect
= node
.getBoundingClientRect();
1792 if (ie
&& ie_version
< 9 && !start
&& (!rect
|| !rect
.left
&& !rect
.right
)) {
1793 var rSpan
= node
.parentNode
.getClientRects()[0];
1795 rect
= {left
: rSpan
.left
, right
: rSpan
.left
+ charWidth(cm
.display
), top
: rSpan
.top
, bottom
: rSpan
.bottom
};
1800 var rtop
= rect
.top
- prepared
.rect
.top
, rbot
= rect
.bottom
- prepared
.rect
.top
;
1801 var mid
= (rtop
+ rbot
) / 2;
1802 var heights
= prepared
.view
.measure
.heights
;
1803 for (var i
= 0; i
< heights
.length
- 1; i
++)
1804 if (mid
< heights
[i
]) break;
1805 var top
= i
? heights
[i
- 1] : 0, bot
= heights
[i
];
1806 var result
= {left
: (collapse
== "right" ? rect
.right
: rect
.left
) - prepared
.rect
.left
,
1807 right
: (collapse
== "left" ? rect
.left
: rect
.right
) - prepared
.rect
.left
,
1808 top
: top
, bottom
: bot
};
1809 if (!rect
.left
&& !rect
.right
) result
.bogus
= true;
1810 if (!cm
.options
.singleCursorHeightPerLine
) { result
.rtop
= rtop
; result
.rbottom
= rbot
; }
1815 // Work around problem with bounding client rects on ranges being
1816 // returned incorrectly when zoomed on IE10 and below.
1817 function maybeUpdateRectForZooming(measure
, rect
) {
1818 if (!window
.screen
|| screen
.logicalXDPI
== null ||
1819 screen
.logicalXDPI
== screen
.deviceXDPI
|| !hasBadZoomedRects(measure
))
1821 var scaleX
= screen
.logicalXDPI
/ screen
.deviceXDPI
;
1822 var scaleY
= screen
.logicalYDPI
/ screen
.deviceYDPI
;
1823 return {left
: rect
.left
* scaleX
, right
: rect
.right
* scaleX
,
1824 top
: rect
.top
* scaleY
, bottom
: rect
.bottom
* scaleY
};
1827 function clearLineMeasurementCacheFor(lineView
) {
1828 if (lineView
.measure
) {
1829 lineView
.measure
.cache
= {};
1830 lineView
.measure
.heights
= null;
1831 if (lineView
.rest
) for (var i
= 0; i
< lineView
.rest
.length
; i
++)
1832 lineView
.measure
.caches
[i
] = {};
1836 function clearLineMeasurementCache(cm
) {
1837 cm
.display
.externalMeasure
= null;
1838 removeChildren(cm
.display
.lineMeasure
);
1839 for (var i
= 0; i
< cm
.display
.view
.length
; i
++)
1840 clearLineMeasurementCacheFor(cm
.display
.view
[i
]);
1843 function clearCaches(cm
) {
1844 clearLineMeasurementCache(cm
);
1845 cm
.display
.cachedCharWidth
= cm
.display
.cachedTextHeight
= cm
.display
.cachedPaddingH
= null;
1846 if (!cm
.options
.lineWrapping
) cm
.display
.maxLineChanged
= true;
1847 cm
.display
.lineNumChars
= null;
1850 function pageScrollX() { return window
.pageXOffset
|| (document
.documentElement
|| document
.body
).scrollLeft
; }
1851 function pageScrollY() { return window
.pageYOffset
|| (document
.documentElement
|| document
.body
).scrollTop
; }
1853 // Converts a {top, bottom, left, right} box from line-local
1854 // coordinates into another coordinate system. Context may be one of
1855 // "line", "div" (display.lineDiv), "local"/null (editor), "window",
1857 function intoCoordSystem(cm
, lineObj
, rect
, context
) {
1858 if (lineObj
.widgets
) for (var i
= 0; i
< lineObj
.widgets
.length
; ++i
) if (lineObj
.widgets
[i
].above
) {
1859 var size
= widgetHeight(lineObj
.widgets
[i
]);
1860 rect
.top
+= size
; rect
.bottom
+= size
;
1862 if (context
== "line") return rect
;
1863 if (!context
) context
= "local";
1864 var yOff
= heightAtLine(lineObj
);
1865 if (context
== "local") yOff
+= paddingTop(cm
.display
);
1866 else yOff
-= cm
.display
.viewOffset
;
1867 if (context
== "page" || context
== "window") {
1868 var lOff
= cm
.display
.lineSpace
.getBoundingClientRect();
1869 yOff
+= lOff
.top
+ (context
== "window" ? 0 : pageScrollY());
1870 var xOff
= lOff
.left
+ (context
== "window" ? 0 : pageScrollX());
1871 rect
.left
+= xOff
; rect
.right
+= xOff
;
1873 rect
.top
+= yOff
; rect
.bottom
+= yOff
;
1877 // Coverts a box from "div" coords to another coordinate system.
1878 // Context may be "window", "page", "div", or "local"/null.
1879 function fromCoordSystem(cm
, coords
, context
) {
1880 if (context
== "div") return coords
;
1881 var left
= coords
.left
, top
= coords
.top
;
1882 // First move into "page" coordinate system
1883 if (context
== "page") {
1884 left
-= pageScrollX();
1885 top
-= pageScrollY();
1886 } else if (context
== "local" || !context
) {
1887 var localBox
= cm
.display
.sizer
.getBoundingClientRect();
1888 left
+= localBox
.left
;
1889 top
+= localBox
.top
;
1892 var lineSpaceBox
= cm
.display
.lineSpace
.getBoundingClientRect();
1893 return {left
: left
- lineSpaceBox
.left
, top
: top
- lineSpaceBox
.top
};
1896 function charCoords(cm
, pos
, context
, lineObj
, bias
) {
1897 if (!lineObj
) lineObj
= getLine(cm
.doc
, pos
.line
);
1898 return intoCoordSystem(cm
, lineObj
, measureChar(cm
, lineObj
, pos
.ch
, bias
), context
);
1901 // Returns a box for a given cursor position, which may have an
1902 // 'other' property containing the position of the secondary cursor
1903 // on a bidi boundary.
1904 function cursorCoords(cm
, pos
, context
, lineObj
, preparedMeasure
, varHeight
) {
1905 lineObj
= lineObj
|| getLine(cm
.doc
, pos
.line
);
1906 if (!preparedMeasure
) preparedMeasure
= prepareMeasureForLine(cm
, lineObj
);
1907 function get(ch
, right
) {
1908 var m
= measureCharPrepared(cm
, preparedMeasure
, ch
, right
? "right" : "left", varHeight
);
1909 if (right
) m
.left
= m
.right
; else m
.right
= m
.left
;
1910 return intoCoordSystem(cm
, lineObj
, m
, context
);
1912 function getBidi(ch
, partPos
) {
1913 var part
= order
[partPos
], right
= part
.level
% 2;
1914 if (ch
== bidiLeft(part
) && partPos
&& part
.level
< order
[partPos
- 1].level
) {
1915 part
= order
[--partPos
];
1916 ch
= bidiRight(part
) - (part
.level
% 2 ? 0 : 1);
1918 } else if (ch
== bidiRight(part
) && partPos
< order
.length
- 1 && part
.level
< order
[partPos
+ 1].level
) {
1919 part
= order
[++partPos
];
1920 ch
= bidiLeft(part
) - part
.level
% 2;
1923 if (right
&& ch
== part
.to
&& ch
> part
.from) return get(ch
- 1);
1924 return get(ch
, right
);
1926 var order
= getOrder(lineObj
), ch
= pos
.ch
;
1927 if (!order
) return get(ch
);
1928 var partPos
= getBidiPartAt(order
, ch
);
1929 var val
= getBidi(ch
, partPos
);
1930 if (bidiOther
!= null) val
.other
= getBidi(ch
, bidiOther
);
1934 // Used to cheaply estimate the coordinates for a position. Used for
1935 // intermediate scroll updates.
1936 function estimateCoords(cm
, pos
) {
1937 var left
= 0, pos
= clipPos(cm
.doc
, pos
);
1938 if (!cm
.options
.lineWrapping
) left
= charWidth(cm
.display
) * pos
.ch
;
1939 var lineObj
= getLine(cm
.doc
, pos
.line
);
1940 var top
= heightAtLine(lineObj
) + paddingTop(cm
.display
);
1941 return {left
: left
, right
: left
, top
: top
, bottom
: top
+ lineObj
.height
};
1944 // Positions returned by coordsChar contain some extra information.
1945 // xRel is the relative x position of the input coordinates compared
1946 // to the found position (so xRel > 0 means the coordinates are to
1947 // the right of the character position, for example). When outside
1948 // is true, that means the coordinates lie outside the line's
1950 function PosWithInfo(line
, ch
, outside
, xRel
) {
1951 var pos
= Pos(line
, ch
);
1953 if (outside
) pos
.outside
= true;
1957 // Compute the character position closest to the given coordinates.
1958 // Input must be lineSpace-local ("div" coordinate system).
1959 function coordsChar(cm
, x
, y
) {
1961 y
+= cm
.display
.viewOffset
;
1962 if (y
< 0) return PosWithInfo(doc
.first
, 0, true, -1);
1963 var lineN
= lineAtHeight(doc
, y
), last
= doc
.first
+ doc
.size
- 1;
1965 return PosWithInfo(doc
.first
+ doc
.size
- 1, getLine(doc
, last
).text
.length
, true, 1);
1968 var lineObj
= getLine(doc
, lineN
);
1970 var found
= coordsCharInner(cm
, lineObj
, lineN
, x
, y
);
1971 var merged
= collapsedSpanAtEnd(lineObj
);
1972 var mergedPos
= merged
&& merged
.find(0, true);
1973 if (merged
&& (found
.ch
> mergedPos
.from.ch
|| found
.ch
== mergedPos
.from.ch
&& found
.xRel
> 0))
1974 lineN
= lineNo(lineObj
= mergedPos
.to
.line
);
1980 function coordsCharInner(cm
, lineObj
, lineNo
, x
, y
) {
1981 var innerOff
= y
- heightAtLine(lineObj
);
1982 var wrongLine
= false, adjust
= 2 * cm
.display
.wrapper
.clientWidth
;
1983 var preparedMeasure
= prepareMeasureForLine(cm
, lineObj
);
1986 var sp
= cursorCoords(cm
, Pos(lineNo
, ch
), "line", lineObj
, preparedMeasure
);
1988 if (innerOff
> sp
.bottom
) return sp
.left
- adjust
;
1989 else if (innerOff
< sp
.top
) return sp
.left
+ adjust
;
1990 else wrongLine
= false;
1994 var bidi
= getOrder(lineObj
), dist
= lineObj
.text
.length
;
1995 var from = lineLeft(lineObj
), to
= lineRight(lineObj
);
1996 var fromX
= getX(from), fromOutside
= wrongLine
, toX
= getX(to
), toOutside
= wrongLine
;
1998 if (x
> toX
) return PosWithInfo(lineNo
, to
, toOutside
, 1);
1999 // Do a binary search between these bounds.
2001 if (bidi
? to
== from || to
== moveVisually(lineObj
, from, 1) : to
- from <= 1) {
2002 var ch
= x
< fromX
|| x
- fromX
<= toX
- x
? from : to
;
2003 var xDiff
= x
- (ch
== from ? fromX
: toX
);
2004 while (isExtendingChar(lineObj
.text
.charAt(ch
))) ++ch
;
2005 var pos
= PosWithInfo(lineNo
, ch
, ch
== from ? fromOutside
: toOutside
,
2006 xDiff
< -1 ? -1 : xDiff
> 1 ? 1 : 0);
2009 var step
= Math
.ceil(dist
/ 2), middle
= from + step
;
2012 for (var i
= 0; i
< step
; ++i
) middle
= moveVisually(lineObj
, middle
, 1);
2014 var middleX
= getX(middle
);
2015 if (middleX
> x
) {to
= middle
; toX
= middleX
; if (toOutside
= wrongLine
) toX
+= 1000; dist
= step
;}
2016 else {from = middle
; fromX
= middleX
; fromOutside
= wrongLine
; dist
-= step
;}
2021 // Compute the default text height.
2022 function textHeight(display
) {
2023 if (display
.cachedTextHeight
!= null) return display
.cachedTextHeight
;
2024 if (measureText
== null) {
2025 measureText
= elt("pre");
2026 // Measure a bunch of lines, for browsers that compute
2027 // fractional heights.
2028 for (var i
= 0; i
< 49; ++i
) {
2029 measureText
.appendChild(document
.createTextNode("x"));
2030 measureText
.appendChild(elt("br"));
2032 measureText
.appendChild(document
.createTextNode("x"));
2034 removeChildrenAndAdd(display
.measure
, measureText
);
2035 var height
= measureText
.offsetHeight
/ 50;
2036 if (height
> 3) display
.cachedTextHeight
= height
;
2037 removeChildren(display
.measure
);
2041 // Compute the default character width.
2042 function charWidth(display
) {
2043 if (display
.cachedCharWidth
!= null) return display
.cachedCharWidth
;
2044 var anchor
= elt("span", "xxxxxxxxxx");
2045 var pre
= elt("pre", [anchor
]);
2046 removeChildrenAndAdd(display
.measure
, pre
);
2047 var rect
= anchor
.getBoundingClientRect(), width
= (rect
.right
- rect
.left
) / 10;
2048 if (width
> 2) display
.cachedCharWidth
= width
;
2054 // Operations are used to wrap a series of changes to the editor
2055 // state in such a way that each change won't have to update the
2056 // cursor and display (which would be awkward, slow, and
2057 // error-prone). Instead, display updates are batched and then all
2058 // combined and executed at once.
2060 var operationGroup
= null;
2063 // Start a new operation.
2064 function startOperation(cm
) {
2067 viewChanged
: false, // Flag that indicates that lines might need to be redrawn
2068 startHeight
: cm
.doc
.height
, // Used to detect need to update scrollbar
2069 forceUpdate
: false, // Used to force a redraw
2070 updateInput
: null, // Whether to reset the input textarea
2071 typing
: false, // Whether this reset should be careful to leave existing text (for compositing)
2072 changeObjs
: null, // Accumulated changes, for firing change events
2073 cursorActivityHandlers
: null, // Set of handlers to fire cursorActivity on
2074 cursorActivityCalled
: 0, // Tracks which cursorActivity handlers have been called already
2075 selectionChanged
: false, // Whether the selection needs to be redrawn
2076 updateMaxLine
: false, // Set when the widest line needs to be determined anew
2077 scrollLeft
: null, scrollTop
: null, // Intermediate scroll position, not pushed to DOM yet
2078 scrollToPos
: null, // Used to scroll to a specific position
2079 id
: ++nextOpId
// Unique ID
2081 if (operationGroup
) {
2082 operationGroup
.ops
.push(cm
.curOp
);
2084 cm
.curOp
.ownsGroup
= operationGroup
= {
2086 delayedCallbacks
: []
2091 function fireCallbacksForOps(group
) {
2092 // Calls delayed callbacks and cursorActivity handlers until no
2094 var callbacks
= group
.delayedCallbacks
, i
= 0;
2096 for (; i
< callbacks
.length
; i
++)
2098 for (var j
= 0; j
< group
.ops
.length
; j
++) {
2099 var op
= group
.ops
[j
];
2100 if (op
.cursorActivityHandlers
)
2101 while (op
.cursorActivityCalled
< op
.cursorActivityHandlers
.length
)
2102 op
.cursorActivityHandlers
[op
.cursorActivityCalled
++](op
.cm
);
2104 } while (i
< callbacks
.length
);
2107 // Finish an operation, updating the display and signalling delayed events
2108 function endOperation(cm
) {
2109 var op
= cm
.curOp
, group
= op
.ownsGroup
;
2112 try { fireCallbacksForOps(group
); }
2114 operationGroup
= null;
2115 for (var i
= 0; i
< group
.ops
.length
; i
++)
2116 group
.ops
[i
].cm
.curOp
= null;
2117 endOperations(group
);
2121 // The DOM updates done when an operation finishes are batched so
2122 // that the minimum number of relayouts are required.
2123 function endOperations(group
) {
2124 var ops
= group
.ops
;
2125 for (var i
= 0; i
< ops
.length
; i
++) // Read DOM
2126 endOperation_R1(ops
[i
]);
2127 for (var i
= 0; i
< ops
.length
; i
++) // Write DOM (maybe)
2128 endOperation_W1(ops
[i
]);
2129 for (var i
= 0; i
< ops
.length
; i
++) // Read DOM
2130 endOperation_R2(ops
[i
]);
2131 for (var i
= 0; i
< ops
.length
; i
++) // Write DOM (maybe)
2132 endOperation_W2(ops
[i
]);
2133 for (var i
= 0; i
< ops
.length
; i
++) // Read DOM
2134 endOperation_finish(ops
[i
]);
2137 function endOperation_R1(op
) {
2138 var cm
= op
.cm
, display
= cm
.display
;
2139 maybeClipScrollbars(cm
);
2140 if (op
.updateMaxLine
) findMaxLine(cm
);
2142 op
.mustUpdate
= op
.viewChanged
|| op
.forceUpdate
|| op
.scrollTop
!= null ||
2143 op
.scrollToPos
&& (op
.scrollToPos
.from.line
< display
.viewFrom
||
2144 op
.scrollToPos
.to
.line
>= display
.viewTo
) ||
2145 display
.maxLineChanged
&& cm
.options
.lineWrapping
;
2146 op
.update
= op
.mustUpdate
&&
2147 new DisplayUpdate(cm
, op
.mustUpdate
&& {top
: op
.scrollTop
, ensure
: op
.scrollToPos
}, op
.forceUpdate
);
2150 function endOperation_W1(op
) {
2151 op
.updatedDisplay
= op
.mustUpdate
&& updateDisplayIfNeeded(op
.cm
, op
.update
);
2154 function endOperation_R2(op
) {
2155 var cm
= op
.cm
, display
= cm
.display
;
2156 if (op
.updatedDisplay
) updateHeightsInViewport(cm
);
2158 op
.barMeasure
= measureForScrollbars(cm
);
2160 // If the max line changed since it was last measured, measure it,
2161 // and ensure the document's width matches it.
2162 // updateDisplay_W2 will use these properties to do the actual resizing
2163 if (display
.maxLineChanged
&& !cm
.options
.lineWrapping
) {
2164 op
.adjustWidthTo
= measureChar(cm
, display
.maxLine
, display
.maxLine
.text
.length
).left
+ 3;
2165 cm
.display
.sizerWidth
= op
.adjustWidthTo
;
2166 op
.barMeasure
.scrollWidth
=
2167 Math
.max(display
.scroller
.clientWidth
, display
.sizer
.offsetLeft
+ op
.adjustWidthTo
+ scrollGap(cm
) + cm
.display
.barWidth
);
2168 op
.maxScrollLeft
= Math
.max(0, display
.sizer
.offsetLeft
+ op
.adjustWidthTo
- displayWidth(cm
));
2171 if (op
.updatedDisplay
|| op
.selectionChanged
)
2172 op
.newSelectionNodes
= drawSelection(cm
);
2175 function endOperation_W2(op
) {
2178 if (op
.adjustWidthTo
!= null) {
2179 cm
.display
.sizer
.style
.minWidth
= op
.adjustWidthTo
+ "px";
2180 if (op
.maxScrollLeft
< cm
.doc
.scrollLeft
)
2181 setScrollLeft(cm
, Math
.min(cm
.display
.scroller
.scrollLeft
, op
.maxScrollLeft
), true);
2182 cm
.display
.maxLineChanged
= false;
2185 if (op
.newSelectionNodes
)
2186 showSelection(cm
, op
.newSelectionNodes
);
2187 if (op
.updatedDisplay
)
2188 setDocumentHeight(cm
, op
.barMeasure
);
2189 if (op
.updatedDisplay
|| op
.startHeight
!= cm
.doc
.height
)
2190 updateScrollbars(cm
, op
.barMeasure
);
2192 if (op
.selectionChanged
) restartBlink(cm
);
2194 if (cm
.state
.focused
&& op
.updateInput
)
2195 resetInput(cm
, op
.typing
);
2198 function endOperation_finish(op
) {
2199 var cm
= op
.cm
, display
= cm
.display
, doc
= cm
.doc
;
2201 if (op
.updatedDisplay
) postUpdateDisplay(cm
, op
.update
);
2203 // Abort mouse wheel delta measurement, when scrolling explicitly
2204 if (display
.wheelStartX
!= null && (op
.scrollTop
!= null || op
.scrollLeft
!= null || op
.scrollToPos
))
2205 display
.wheelStartX
= display
.wheelStartY
= null;
2207 // Propagate the scroll position to the actual DOM scroller
2208 if (op
.scrollTop
!= null && (display
.scroller
.scrollTop
!= op
.scrollTop
|| op
.forceScroll
)) {
2209 doc
.scrollTop
= Math
.max(0, Math
.min(display
.scroller
.scrollHeight
- display
.scroller
.clientHeight
, op
.scrollTop
));
2210 display
.scrollbars
.setScrollTop(doc
.scrollTop
);
2211 display
.scroller
.scrollTop
= doc
.scrollTop
;
2213 if (op
.scrollLeft
!= null && (display
.scroller
.scrollLeft
!= op
.scrollLeft
|| op
.forceScroll
)) {
2214 doc
.scrollLeft
= Math
.max(0, Math
.min(display
.scroller
.scrollWidth
- displayWidth(cm
), op
.scrollLeft
));
2215 display
.scrollbars
.setScrollLeft(doc
.scrollLeft
);
2216 display
.scroller
.scrollLeft
= doc
.scrollLeft
;
2217 alignHorizontally(cm
);
2219 // If we need to scroll a specific position into view, do so.
2220 if (op
.scrollToPos
) {
2221 var coords
= scrollPosIntoView(cm
, clipPos(doc
, op
.scrollToPos
.from),
2222 clipPos(doc
, op
.scrollToPos
.to
), op
.scrollToPos
.margin
);
2223 if (op
.scrollToPos
.isCursor
&& cm
.state
.focused
) maybeScrollWindow(cm
, coords
);
2226 // Fire events for markers that are hidden/unidden by editing or
2228 var hidden
= op
.maybeHiddenMarkers
, unhidden
= op
.maybeUnhiddenMarkers
;
2229 if (hidden
) for (var i
= 0; i
< hidden
.length
; ++i
)
2230 if (!hidden
[i
].lines
.length
) signal(hidden
[i
], "hide");
2231 if (unhidden
) for (var i
= 0; i
< unhidden
.length
; ++i
)
2232 if (unhidden
[i
].lines
.length
) signal(unhidden
[i
], "unhide");
2234 if (display
.wrapper
.offsetHeight
)
2235 doc
.scrollTop
= cm
.display
.scroller
.scrollTop
;
2237 // Fire change events, and delayed event handlers
2239 signal(cm
, "changes", cm
, op
.changeObjs
);
2242 // Run the given function in an operation
2243 function runInOp(cm
, f
) {
2244 if (cm
.curOp
) return f();
2247 finally { endOperation(cm
); }
2249 // Wraps a function in an operation. Returns the wrapped function.
2250 function operation(cm
, f
) {
2252 if (cm
.curOp
) return f
.apply(cm
, arguments
);
2254 try { return f
.apply(cm
, arguments
); }
2255 finally { endOperation(cm
); }
2258 // Used to add methods to editor and doc instances, wrapping them in
2260 function methodOp(f
) {
2262 if (this.curOp
) return f
.apply(this, arguments
);
2263 startOperation(this);
2264 try { return f
.apply(this, arguments
); }
2265 finally { endOperation(this); }
2268 function docMethodOp(f
) {
2271 if (!cm
|| cm
.curOp
) return f
.apply(this, arguments
);
2273 try { return f
.apply(this, arguments
); }
2274 finally { endOperation(cm
); }
2280 // These objects are used to represent the visible (currently drawn)
2281 // part of the document. A LineView may correspond to multiple
2282 // logical lines, if those are connected by collapsed ranges.
2283 function LineView(doc
, line
, lineN
) {
2284 // The starting line
2286 // Continuing lines, if any
2287 this.rest
= visualLineContinued(line
);
2288 // Number of logical lines in this visual line
2289 this.size
= this.rest
? lineNo(lst(this.rest
)) - lineN
+ 1 : 1;
2290 this.node
= this.text
= null;
2291 this.hidden
= lineIsHidden(doc
, line
);
2294 // Create a range of LineView objects for the given lines.
2295 function buildViewArray(cm
, from, to
) {
2296 var array
= [], nextPos
;
2297 for (var pos
= from; pos
< to
; pos
= nextPos
) {
2298 var view
= new LineView(cm
.doc
, getLine(cm
.doc
, pos
), pos
);
2299 nextPos
= pos
+ view
.size
;
2305 // Updates the display.view data structure for a given change to the
2306 // document. From and to are in pre-change coordinates. Lendiff is
2307 // the amount of lines added or subtracted by the change. This is
2308 // used for changes that span multiple lines, or change the way
2309 // lines are divided into visual lines. regLineChange (below)
2310 // registers single-line changes.
2311 function regChange(cm
, from, to
, lendiff
) {
2312 if (from == null) from = cm
.doc
.first
;
2313 if (to
== null) to
= cm
.doc
.first
+ cm
.doc
.size
;
2314 if (!lendiff
) lendiff
= 0;
2316 var display
= cm
.display
;
2317 if (lendiff
&& to
< display
.viewTo
&&
2318 (display
.updateLineNumbers
== null || display
.updateLineNumbers
> from))
2319 display
.updateLineNumbers
= from;
2321 cm
.curOp
.viewChanged
= true;
2323 if (from >= display
.viewTo
) { // Change after
2324 if (sawCollapsedSpans
&& visualLineNo(cm
.doc
, from) < display
.viewTo
)
2326 } else if (to
<= display
.viewFrom
) { // Change before
2327 if (sawCollapsedSpans
&& visualLineEndNo(cm
.doc
, to
+ lendiff
) > display
.viewFrom
) {
2330 display
.viewFrom
+= lendiff
;
2331 display
.viewTo
+= lendiff
;
2333 } else if (from <= display
.viewFrom
&& to
>= display
.viewTo
) { // Full overlap
2335 } else if (from <= display
.viewFrom
) { // Top overlap
2336 var cut
= viewCuttingPoint(cm
, to
, to
+ lendiff
, 1);
2338 display
.view
= display
.view
.slice(cut
.index
);
2339 display
.viewFrom
= cut
.lineN
;
2340 display
.viewTo
+= lendiff
;
2344 } else if (to
>= display
.viewTo
) { // Bottom overlap
2345 var cut
= viewCuttingPoint(cm
, from, from, -1);
2347 display
.view
= display
.view
.slice(0, cut
.index
);
2348 display
.viewTo
= cut
.lineN
;
2352 } else { // Gap in the middle
2353 var cutTop
= viewCuttingPoint(cm
, from, from, -1);
2354 var cutBot
= viewCuttingPoint(cm
, to
, to
+ lendiff
, 1);
2355 if (cutTop
&& cutBot
) {
2356 display
.view
= display
.view
.slice(0, cutTop
.index
)
2357 .concat(buildViewArray(cm
, cutTop
.lineN
, cutBot
.lineN
))
2358 .concat(display
.view
.slice(cutBot
.index
));
2359 display
.viewTo
+= lendiff
;
2365 var ext
= display
.externalMeasured
;
2368 ext
.lineN
+= lendiff
;
2369 else if (from < ext
.lineN
+ ext
.size
)
2370 display
.externalMeasured
= null;
2374 // Register a change to a single line. Type must be one of "text",
2375 // "gutter", "class", "widget"
2376 function regLineChange(cm
, line
, type
) {
2377 cm
.curOp
.viewChanged
= true;
2378 var display
= cm
.display
, ext
= cm
.display
.externalMeasured
;
2379 if (ext
&& line
>= ext
.lineN
&& line
< ext
.lineN
+ ext
.size
)
2380 display
.externalMeasured
= null;
2382 if (line
< display
.viewFrom
|| line
>= display
.viewTo
) return;
2383 var lineView
= display
.view
[findViewIndex(cm
, line
)];
2384 if (lineView
.node
== null) return;
2385 var arr
= lineView
.changes
|| (lineView
.changes
= []);
2386 if (indexOf(arr
, type
) == -1) arr
.push(type
);
2390 function resetView(cm
) {
2391 cm
.display
.viewFrom
= cm
.display
.viewTo
= cm
.doc
.first
;
2392 cm
.display
.view
= [];
2393 cm
.display
.viewOffset
= 0;
2396 // Find the view element corresponding to a given line. Return null
2397 // when the line isn't visible.
2398 function findViewIndex(cm
, n
) {
2399 if (n
>= cm
.display
.viewTo
) return null;
2400 n
-= cm
.display
.viewFrom
;
2401 if (n
< 0) return null;
2402 var view
= cm
.display
.view
;
2403 for (var i
= 0; i
< view
.length
; i
++) {
2405 if (n
< 0) return i
;
2409 function viewCuttingPoint(cm
, oldN
, newN
, dir
) {
2410 var index
= findViewIndex(cm
, oldN
), diff
, view
= cm
.display
.view
;
2411 if (!sawCollapsedSpans
|| newN
== cm
.doc
.first
+ cm
.doc
.size
)
2412 return {index
: index
, lineN
: newN
};
2413 for (var i
= 0, n
= cm
.display
.viewFrom
; i
< index
; i
++)
2417 if (index
== view
.length
- 1) return null;
2418 diff
= (n
+ view
[index
].size
) - oldN
;
2423 oldN
+= diff
; newN
+= diff
;
2425 while (visualLineNo(cm
.doc
, newN
) != newN
) {
2426 if (index
== (dir
< 0 ? 0 : view
.length
- 1)) return null;
2427 newN
+= dir
* view
[index
- (dir
< 0 ? 1 : 0)].size
;
2430 return {index
: index
, lineN
: newN
};
2433 // Force the view to cover a given range, adding empty view element
2434 // or clipping off existing ones as needed.
2435 function adjustView(cm
, from, to
) {
2436 var display
= cm
.display
, view
= display
.view
;
2437 if (view
.length
== 0 || from >= display
.viewTo
|| to
<= display
.viewFrom
) {
2438 display
.view
= buildViewArray(cm
, from, to
);
2439 display
.viewFrom
= from;
2441 if (display
.viewFrom
> from)
2442 display
.view
= buildViewArray(cm
, from, display
.viewFrom
).concat(display
.view
);
2443 else if (display
.viewFrom
< from)
2444 display
.view
= display
.view
.slice(findViewIndex(cm
, from));
2445 display
.viewFrom
= from;
2446 if (display
.viewTo
< to
)
2447 display
.view
= display
.view
.concat(buildViewArray(cm
, display
.viewTo
, to
));
2448 else if (display
.viewTo
> to
)
2449 display
.view
= display
.view
.slice(0, findViewIndex(cm
, to
));
2451 display
.viewTo
= to
;
2454 // Count the number of lines in the view whose DOM representation is
2455 // out of date (or nonexistent).
2456 function countDirtyView(cm
) {
2457 var view
= cm
.display
.view
, dirty
= 0;
2458 for (var i
= 0; i
< view
.length
; i
++) {
2459 var lineView
= view
[i
];
2460 if (!lineView
.hidden
&& (!lineView
.node
|| lineView
.changes
)) ++dirty
;
2467 // Poll for input changes, using the normal rate of polling. This
2468 // runs as long as the editor is focused.
2469 function slowPoll(cm
) {
2470 if (cm
.display
.pollingFast
) return;
2471 cm
.display
.poll
.set(cm
.options
.pollInterval
, function() {
2473 if (cm
.state
.focused
) slowPoll(cm
);
2477 // When an event has just come in that is likely to add or change
2478 // something in the input textarea, we poll faster, to ensure that
2479 // the change appears on the screen quickly.
2480 function fastPoll(cm
) {
2482 cm
.display
.pollingFast
= true;
2484 var changed
= readInput(cm
);
2485 if (!changed
&& !missed
) {missed
= true; cm
.display
.poll
.set(60, p
);}
2486 else {cm
.display
.pollingFast
= false; slowPoll(cm
);}
2488 cm
.display
.poll
.set(20, p
);
2491 // This will be set to an array of strings when copying, so that,
2492 // when pasting, we know what kind of selections the copied text
2494 var lastCopied
= null;
2496 // Read input from the textarea, and update the document to match.
2497 // When something is selected, it is present in the textarea, and
2498 // selected (unless it is huge, in which case a placeholder is
2499 // used). When nothing is selected, the cursor sits after previously
2500 // seen text (can be empty), which is stored in prevInput (we must
2501 // not reset the textarea when typing, because that breaks IME).
2502 function readInput(cm
) {
2503 var input
= cm
.display
.input
, prevInput
= cm
.display
.prevInput
, doc
= cm
.doc
;
2504 // Since this is called a *lot*, try to bail out as cheaply as
2505 // possible when it is clear that nothing happened. hasSelection
2506 // will be the case when there is a lot of text in the textarea,
2507 // in which case reading its value would be expensive.
2508 if (!cm
.state
.focused
|| (hasSelection(input
) && !prevInput
) || isReadOnly(cm
) || cm
.options
.disableInput
|| cm
.state
.keySeq
)
2510 // See paste handler for more on the fakedLastChar kludge
2511 if (cm
.state
.pasteIncoming
&& cm
.state
.fakedLastChar
) {
2512 input
.value
= input
.value
.substring(0, input
.value
.length
- 1);
2513 cm
.state
.fakedLastChar
= false;
2515 var text
= input
.value
;
2516 // If nothing changed, bail.
2517 if (text
== prevInput
&& !cm
.somethingSelected()) return false;
2518 // Work around nonsensical selection resetting in IE9/10, and
2519 // inexplicable appearance of private area unicode characters on
2520 // some key combos in Mac (#2689).
2521 if (ie
&& ie_version
>= 9 && cm
.display
.inputHasSelection
=== text
||
2522 mac
&& /[\uf700-\uf7ff]/.test(text
)) {
2527 var withOp
= !cm
.curOp
;
2528 if (withOp
) startOperation(cm
);
2529 cm
.display
.shift
= false;
2531 if (text
.charCodeAt(0) == 0x200b && doc
.sel
== cm
.display
.selForContextMenu
&& !prevInput
)
2532 prevInput
= "\u200b";
2533 // Find the part of the input that is actually new
2534 var same
= 0, l
= Math
.min(prevInput
.length
, text
.length
);
2535 while (same
< l
&& prevInput
.charCodeAt(same
) == text
.charCodeAt(same
)) ++same
;
2536 var inserted
= text
.slice(same
), textLines
= splitLines(inserted
);
2538 // When pasing N lines into N selections, insert one line per selection
2539 var multiPaste
= null;
2540 if (cm
.state
.pasteIncoming
&& doc
.sel
.ranges
.length
> 1) {
2541 if (lastCopied
&& lastCopied
.join("\n") == inserted
)
2542 multiPaste
= doc
.sel
.ranges
.length
% lastCopied
.length
== 0 && map(lastCopied
, splitLines
);
2543 else if (textLines
.length
== doc
.sel
.ranges
.length
)
2544 multiPaste
= map(textLines
, function(l
) { return [l
]; });
2547 // Normal behavior is to insert the new text into every selection
2548 for (var i
= doc
.sel
.ranges
.length
- 1; i
>= 0; i
--) {
2549 var range
= doc
.sel
.ranges
[i
];
2550 var from = range
.from(), to
= range
.to();
2552 if (same
< prevInput
.length
)
2553 from = Pos(from.line
, from.ch
- (prevInput
.length
- same
));
2555 else if (cm
.state
.overwrite
&& range
.empty() && !cm
.state
.pasteIncoming
)
2556 to
= Pos(to
.line
, Math
.min(getLine(doc
, to
.line
).text
.length
, to
.ch
+ lst(textLines
).length
));
2557 var updateInput
= cm
.curOp
.updateInput
;
2558 var changeEvent
= {from: from, to
: to
, text
: multiPaste
? multiPaste
[i
% multiPaste
.length
] : textLines
,
2559 origin
: cm
.state
.pasteIncoming
? "paste" : cm
.state
.cutIncoming
? "cut" : "+input"};
2560 makeChange(cm
.doc
, changeEvent
);
2561 signalLater(cm
, "inputRead", cm
, changeEvent
);
2562 // When an 'electric' character is inserted, immediately trigger a reindent
2563 if (inserted
&& !cm
.state
.pasteIncoming
&& cm
.options
.electricChars
&&
2564 cm
.options
.smartIndent
&& range
.head
.ch
< 100 &&
2565 (!i
|| doc
.sel
.ranges
[i
- 1].head
.line
!= range
.head
.line
)) {
2566 var mode
= cm
.getModeAt(range
.head
);
2567 var end
= changeEnd(changeEvent
);
2568 if (mode
.electricChars
) {
2569 for (var j
= 0; j
< mode
.electricChars
.length
; j
++)
2570 if (inserted
.indexOf(mode
.electricChars
.charAt(j
)) > -1) {
2571 indentLine(cm
, end
.line
, "smart");
2574 } else if (mode
.electricInput
) {
2575 if (mode
.electricInput
.test(getLine(doc
, end
.line
).text
.slice(0, end
.ch
)))
2576 indentLine(cm
, end
.line
, "smart");
2580 ensureCursorVisible(cm
);
2581 cm
.curOp
.updateInput
= updateInput
;
2582 cm
.curOp
.typing
= true;
2584 // Don't leave long text in the textarea, since it makes further polling slow
2585 if (text
.length
> 1000 || text
.indexOf("\n") > -1) input
.value
= cm
.display
.prevInput
= "";
2586 else cm
.display
.prevInput
= text
;
2587 if (withOp
) endOperation(cm
);
2588 cm
.state
.pasteIncoming
= cm
.state
.cutIncoming
= false;
2592 // Reset the input to correspond to the selection (or to be empty,
2593 // when not typing and nothing is selected)
2594 function resetInput(cm
, typing
) {
2595 if (cm
.display
.contextMenuPending
) return;
2596 var minimal
, selected
, doc
= cm
.doc
;
2597 if (cm
.somethingSelected()) {
2598 cm
.display
.prevInput
= "";
2599 var range
= doc
.sel
.primary();
2600 minimal
= hasCopyEvent
&&
2601 (range
.to().line
- range
.from().line
> 100 || (selected
= cm
.getSelection()).length
> 1000);
2602 var content
= minimal
? "-" : selected
|| cm
.getSelection();
2603 cm
.display
.input
.value
= content
;
2604 if (cm
.state
.focused
) selectInput(cm
.display
.input
);
2605 if (ie
&& ie_version
>= 9) cm
.display
.inputHasSelection
= content
;
2606 } else if (!typing
) {
2607 cm
.display
.prevInput
= cm
.display
.input
.value
= "";
2608 if (ie
&& ie_version
>= 9) cm
.display
.inputHasSelection
= null;
2610 cm
.display
.inaccurateSelection
= minimal
;
2613 function focusInput(cm
) {
2614 if (cm
.options
.readOnly
!= "nocursor" && (!mobile
|| activeElt() != cm
.display
.input
))
2615 cm
.display
.input
.focus();
2618 function ensureFocus(cm
) {
2619 if (!cm
.state
.focused
) { focusInput(cm
); onFocus(cm
); }
2622 function isReadOnly(cm
) {
2623 return cm
.options
.readOnly
|| cm
.doc
.cantEdit
;
2628 // Attach the necessary event handlers when initializing the editor
2629 function registerEventHandlers(cm
) {
2631 on(d
.scroller
, "mousedown", operation(cm
, onMouseDown
));
2632 // Older IE's will not fire a second mousedown for a double click
2633 if (ie
&& ie_version
< 11)
2634 on(d
.scroller
, "dblclick", operation(cm
, function(e
) {
2635 if (signalDOMEvent(cm
, e
)) return;
2636 var pos
= posFromMouse(cm
, e
);
2637 if (!pos
|| clickInGutter(cm
, e
) || eventInWidget(cm
.display
, e
)) return;
2638 e_preventDefault(e
);
2639 var word
= cm
.findWordAt(pos
);
2640 extendSelection(cm
.doc
, word
.anchor
, word
.head
);
2643 on(d
.scroller
, "dblclick", function(e
) { signalDOMEvent(cm
, e
) || e_preventDefault(e
); });
2644 // Prevent normal selection in the editor (we handle our own)
2645 on(d
.lineSpace
, "selectstart", function(e
) {
2646 if (!eventInWidget(d
, e
)) e_preventDefault(e
);
2648 // Some browsers fire contextmenu *after* opening the menu, at
2649 // which point we can't mess with it anymore. Context menu is
2650 // handled in onMouseDown for these browsers.
2651 if (!captureRightClick
) on(d
.scroller
, "contextmenu", function(e
) {onContextMenu(cm
, e
);});
2653 // Sync scrolling between fake scrollbars and real scrollable
2654 // area, ensure viewport is updated when scrolling.
2655 on(d
.scroller
, "scroll", function() {
2656 if (d
.scroller
.clientHeight
) {
2657 setScrollTop(cm
, d
.scroller
.scrollTop
);
2658 setScrollLeft(cm
, d
.scroller
.scrollLeft
, true);
2659 signal(cm
, "scroll", cm
);
2663 // Listen to wheel events in order to try and update the viewport on time.
2664 on(d
.scroller
, "mousewheel", function(e
){onScrollWheel(cm
, e
);});
2665 on(d
.scroller
, "DOMMouseScroll", function(e
){onScrollWheel(cm
, e
);});
2667 // Prevent wrapper from ever scrolling
2668 on(d
.wrapper
, "scroll", function() { d
.wrapper
.scrollTop
= d
.wrapper
.scrollLeft
= 0; });
2670 on(d
.input
, "keyup", function(e
) { onKeyUp
.call(cm
, e
); });
2671 on(d
.input
, "input", function() {
2672 if (ie
&& ie_version
>= 9 && cm
.display
.inputHasSelection
) cm
.display
.inputHasSelection
= null;
2675 on(d
.input
, "keydown", operation(cm
, onKeyDown
));
2676 on(d
.input
, "keypress", operation(cm
, onKeyPress
));
2677 on(d
.input
, "focus", bind(onFocus
, cm
));
2678 on(d
.input
, "blur", bind(onBlur
, cm
));
2681 if (!signalDOMEvent(cm
, e
)) e_stop(e
);
2683 if (cm
.options
.dragDrop
) {
2684 on(d
.scroller
, "dragstart", function(e
){onDragStart(cm
, e
);});
2685 on(d
.scroller
, "dragenter", drag_
);
2686 on(d
.scroller
, "dragover", drag_
);
2687 on(d
.scroller
, "drop", operation(cm
, onDrop
));
2689 on(d
.scroller
, "paste", function(e
) {
2690 if (eventInWidget(d
, e
)) return;
2691 cm
.state
.pasteIncoming
= true;
2695 on(d
.input
, "paste", function() {
2696 // Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206
2697 // Add a char to the end of textarea before paste occur so that
2698 // selection doesn't span to the end of textarea.
2699 if (webkit
&& !cm
.state
.fakedLastChar
&& !(new Date
- cm
.state
.lastMiddleDown
< 200)) {
2700 var start
= d
.input
.selectionStart
, end
= d
.input
.selectionEnd
;
2701 d
.input
.value
+= "$";
2702 // The selection end needs to be set before the start, otherwise there
2703 // can be an intermediate non-empty selection between the two, which
2704 // can override the middle-click paste buffer on linux and cause the
2705 // wrong thing to get pasted.
2706 d
.input
.selectionEnd
= end
;
2707 d
.input
.selectionStart
= start
;
2708 cm
.state
.fakedLastChar
= true;
2710 cm
.state
.pasteIncoming
= true;
2714 function prepareCopyCut(e
) {
2715 if (cm
.somethingSelected()) {
2716 lastCopied
= cm
.getSelections();
2717 if (d
.inaccurateSelection
) {
2719 d
.inaccurateSelection
= false;
2720 d
.input
.value
= lastCopied
.join("\n");
2721 selectInput(d
.input
);
2724 var text
= [], ranges
= [];
2725 for (var i
= 0; i
< cm
.doc
.sel
.ranges
.length
; i
++) {
2726 var line
= cm
.doc
.sel
.ranges
[i
].head
.line
;
2727 var lineRange
= {anchor
: Pos(line
, 0), head
: Pos(line
+ 1, 0)};
2728 ranges
.push(lineRange
);
2729 text
.push(cm
.getRange(lineRange
.anchor
, lineRange
.head
));
2731 if (e
.type
== "cut") {
2732 cm
.setSelections(ranges
, null, sel_dontScroll
);
2735 d
.input
.value
= text
.join("\n");
2736 selectInput(d
.input
);
2740 if (e
.type
== "cut") cm
.state
.cutIncoming
= true;
2742 on(d
.input
, "cut", prepareCopyCut
);
2743 on(d
.input
, "copy", prepareCopyCut
);
2745 // Needed to handle Tab key in KHTML
2746 if (khtml
) on(d
.sizer
, "mouseup", function() {
2747 if (activeElt() == d
.input
) d
.input
.blur();
2752 // Called when the window resizes
2753 function onResize(cm
) {
2755 if (d
.lastWrapHeight
== d
.wrapper
.clientHeight
&& d
.lastWrapWidth
== d
.wrapper
.clientWidth
)
2757 // Might be a text scaling operation, clear size caches.
2758 d
.cachedCharWidth
= d
.cachedTextHeight
= d
.cachedPaddingH
= null;
2759 d
.scrollbarsClipped
= false;
2765 // Return true when the given mouse event happened in a widget
2766 function eventInWidget(display
, e
) {
2767 for (var n
= e_target(e
); n
!= display
.wrapper
; n
= n
.parentNode
) {
2768 if (!n
|| (n
.nodeType
== 1 && n
.getAttribute("cm-ignore-events") == "true") ||
2769 (n
.parentNode
== display
.sizer
&& n
!= display
.mover
))
2774 // Given a mouse event, find the corresponding position. If liberal
2775 // is false, it checks whether a gutter or scrollbar was clicked,
2776 // and returns null if it was. forRect is used by rectangular
2777 // selections, and tries to estimate a character position even for
2778 // coordinates beyond the right of the text.
2779 function posFromMouse(cm
, e
, liberal
, forRect
) {
2780 var display
= cm
.display
;
2781 if (!liberal
&& e_target(e
).getAttribute("not-content") == "true") return null;
2783 var x
, y
, space
= display
.lineSpace
.getBoundingClientRect();
2784 // Fails unpredictably on IE[67] when mouse is dragged around quickly.
2785 try { x
= e
.clientX
- space
.left
; y
= e
.clientY
- space
.top
; }
2786 catch (e
) { return null; }
2787 var coords
= coordsChar(cm
, x
, y
), line
;
2788 if (forRect
&& coords
.xRel
== 1 && (line
= getLine(cm
.doc
, coords
.line
).text
).length
== coords
.ch
) {
2789 var colDiff
= countColumn(line
, line
.length
, cm
.options
.tabSize
) - line
.length
;
2790 coords
= Pos(coords
.line
, Math
.max(0, Math
.round((x
- paddingH(cm
.display
).left
) / charWidth(cm
.display
)) - colDiff
));
2795 // A mouse down can be a single click, double click, triple click,
2796 // start of selection drag, start of text drag, new cursor
2797 // (ctrl-click), rectangle drag (alt-drag), or xwin
2798 // middle-click-paste. Or it might be a click on something we should
2799 // not interfere with, such as a scrollbar or widget.
2800 function onMouseDown(e
) {
2801 if (signalDOMEvent(this, e
)) return;
2802 var cm
= this, display
= cm
.display
;
2803 display
.shift
= e
.shiftKey
;
2805 if (eventInWidget(display
, e
)) {
2807 // Briefly turn off draggability, to allow widgets to do
2808 // normal dragging things.
2809 display
.scroller
.draggable
= false;
2810 setTimeout(function(){display
.scroller
.draggable
= true;}, 100);
2814 if (clickInGutter(cm
, e
)) return;
2815 var start
= posFromMouse(cm
, e
);
2818 switch (e_button(e
)) {
2821 leftButtonDown(cm
, e
, start
);
2822 else if (e_target(e
) == display
.scroller
)
2823 e_preventDefault(e
);
2826 if (webkit
) cm
.state
.lastMiddleDown
= +new Date
;
2827 if (start
) extendSelection(cm
.doc
, start
);
2828 setTimeout(bind(focusInput
, cm
), 20);
2829 e_preventDefault(e
);
2832 if (captureRightClick
) onContextMenu(cm
, e
);
2837 var lastClick
, lastDoubleClick
;
2838 function leftButtonDown(cm
, e
, start
) {
2839 setTimeout(bind(ensureFocus
, cm
), 0);
2841 var now
= +new Date
, type
;
2842 if (lastDoubleClick
&& lastDoubleClick
.time
> now
- 400 && cmp(lastDoubleClick
.pos
, start
) == 0) {
2844 } else if (lastClick
&& lastClick
.time
> now
- 400 && cmp(lastClick
.pos
, start
) == 0) {
2846 lastDoubleClick
= {time
: now
, pos
: start
};
2849 lastClick
= {time
: now
, pos
: start
};
2852 var sel
= cm
.doc
.sel
, modifier
= mac
? e
.metaKey
: e
.ctrlKey
, contained
;
2853 if (cm
.options
.dragDrop
&& dragAndDrop
&& !isReadOnly(cm
) &&
2854 type
== "single" && (contained
= sel
.contains(start
)) > -1 &&
2855 !sel
.ranges
[contained
].empty())
2856 leftButtonStartDrag(cm
, e
, start
, modifier
);
2858 leftButtonSelect(cm
, e
, start
, type
, modifier
);
2861 // Start a text drag. When it ends, see if any dragging actually
2862 // happen, and treat as a click if it didn't.
2863 function leftButtonStartDrag(cm
, e
, start
, modifier
) {
2864 var display
= cm
.display
;
2865 var dragEnd
= operation(cm
, function(e2
) {
2866 if (webkit
) display
.scroller
.draggable
= false;
2867 cm
.state
.draggingText
= false;
2868 off(document
, "mouseup", dragEnd
);
2869 off(display
.scroller
, "drop", dragEnd
);
2870 if (Math
.abs(e
.clientX
- e2
.clientX
) + Math
.abs(e
.clientY
- e2
.clientY
) < 10) {
2871 e_preventDefault(e2
);
2873 extendSelection(cm
.doc
, start
);
2875 // Work around unexplainable focus problem in IE9 (#2127)
2876 if (ie
&& ie_version
== 9)
2877 setTimeout(function() {document
.body
.focus(); focusInput(cm
);}, 20);
2880 // Let the drag handler handle this.
2881 if (webkit
) display
.scroller
.draggable
= true;
2882 cm
.state
.draggingText
= dragEnd
;
2883 // IE's approach to draggable
2884 if (display
.scroller
.dragDrop
) display
.scroller
.dragDrop();
2885 on(document
, "mouseup", dragEnd
);
2886 on(display
.scroller
, "drop", dragEnd
);
2889 // Normal selection, as opposed to text dragging.
2890 function leftButtonSelect(cm
, e
, start
, type
, addNew
) {
2891 var display
= cm
.display
, doc
= cm
.doc
;
2892 e_preventDefault(e
);
2894 var ourRange
, ourIndex
, startSel
= doc
.sel
, ranges
= startSel
.ranges
;
2895 if (addNew
&& !e
.shiftKey
) {
2896 ourIndex
= doc
.sel
.contains(start
);
2898 ourRange
= ranges
[ourIndex
];
2900 ourRange
= new Range(start
, start
);
2902 ourRange
= doc
.sel
.primary();
2907 if (!addNew
) ourRange
= new Range(start
, start
);
2908 start
= posFromMouse(cm
, e
, true, true);
2910 } else if (type
== "double") {
2911 var word
= cm
.findWordAt(start
);
2912 if (cm
.display
.shift
|| doc
.extend
)
2913 ourRange
= extendRange(doc
, ourRange
, word
.anchor
, word
.head
);
2916 } else if (type
== "triple") {
2917 var line
= new Range(Pos(start
.line
, 0), clipPos(doc
, Pos(start
.line
+ 1, 0)));
2918 if (cm
.display
.shift
|| doc
.extend
)
2919 ourRange
= extendRange(doc
, ourRange
, line
.anchor
, line
.head
);
2923 ourRange
= extendRange(doc
, ourRange
, start
);
2928 setSelection(doc
, new Selection([ourRange
], 0), sel_mouse
);
2930 } else if (ourIndex
== -1) {
2931 ourIndex
= ranges
.length
;
2932 setSelection(doc
, normalizeSelection(ranges
.concat([ourRange
]), ourIndex
),
2933 {scroll
: false, origin
: "*mouse"});
2934 } else if (ranges
.length
> 1 && ranges
[ourIndex
].empty() && type
== "single") {
2935 setSelection(doc
, normalizeSelection(ranges
.slice(0, ourIndex
).concat(ranges
.slice(ourIndex
+ 1)), 0));
2938 replaceOneSelection(doc
, ourIndex
, ourRange
, sel_mouse
);
2941 var lastPos
= start
;
2942 function extendTo(pos
) {
2943 if (cmp(lastPos
, pos
) == 0) return;
2946 if (type
== "rect") {
2947 var ranges
= [], tabSize
= cm
.options
.tabSize
;
2948 var startCol
= countColumn(getLine(doc
, start
.line
).text
, start
.ch
, tabSize
);
2949 var posCol
= countColumn(getLine(doc
, pos
.line
).text
, pos
.ch
, tabSize
);
2950 var left
= Math
.min(startCol
, posCol
), right
= Math
.max(startCol
, posCol
);
2951 for (var line
= Math
.min(start
.line
, pos
.line
), end
= Math
.min(cm
.lastLine(), Math
.max(start
.line
, pos
.line
));
2952 line
<= end
; line
++) {
2953 var text
= getLine(doc
, line
).text
, leftPos
= findColumn(text
, left
, tabSize
);
2955 ranges
.push(new Range(Pos(line
, leftPos
), Pos(line
, leftPos
)));
2956 else if (text
.length
> leftPos
)
2957 ranges
.push(new Range(Pos(line
, leftPos
), Pos(line
, findColumn(text
, right
, tabSize
))));
2959 if (!ranges
.length
) ranges
.push(new Range(start
, start
));
2960 setSelection(doc
, normalizeSelection(startSel
.ranges
.slice(0, ourIndex
).concat(ranges
), ourIndex
),
2961 {origin
: "*mouse", scroll
: false});
2962 cm
.scrollIntoView(pos
);
2964 var oldRange
= ourRange
;
2965 var anchor
= oldRange
.anchor
, head
= pos
;
2966 if (type
!= "single") {
2967 if (type
== "double")
2968 var range
= cm
.findWordAt(pos
);
2970 var range
= new Range(Pos(pos
.line
, 0), clipPos(doc
, Pos(pos
.line
+ 1, 0)));
2971 if (cmp(range
.anchor
, anchor
) > 0) {
2973 anchor
= minPos(oldRange
.from(), range
.anchor
);
2975 head
= range
.anchor
;
2976 anchor
= maxPos(oldRange
.to(), range
.head
);
2979 var ranges
= startSel
.ranges
.slice(0);
2980 ranges
[ourIndex
] = new Range(clipPos(doc
, anchor
), head
);
2981 setSelection(doc
, normalizeSelection(ranges
, ourIndex
), sel_mouse
);
2985 var editorSize
= display
.wrapper
.getBoundingClientRect();
2986 // Used to ensure timeout re-tries don't fire when another extend
2987 // happened in the meantime (clearTimeout isn't reliable -- at
2988 // least on Chrome, the timeouts still happen even when cleared,
2989 // if the clear happens after their scheduled firing time).
2992 function extend(e
) {
2993 var curCount
= ++counter
;
2994 var cur
= posFromMouse(cm
, e
, true, type
== "rect");
2996 if (cmp(cur
, lastPos
) != 0) {
2999 var visible
= visibleLines(display
, doc
);
3000 if (cur
.line
>= visible
.to
|| cur
.line
< visible
.from)
3001 setTimeout(operation(cm
, function(){if (counter
== curCount
) extend(e
);}), 150);
3003 var outside
= e
.clientY
< editorSize
.top
? -20 : e
.clientY
> editorSize
.bottom
? 20 : 0;
3004 if (outside
) setTimeout(operation(cm
, function() {
3005 if (counter
!= curCount
) return;
3006 display
.scroller
.scrollTop
+= outside
;
3014 e_preventDefault(e
);
3016 off(document
, "mousemove", move);
3017 off(document
, "mouseup", up
);
3018 doc
.history
.lastSelOrigin
= null;
3021 var move = operation(cm
, function(e
) {
3022 if (!e_button(e
)) done(e
);
3025 var up
= operation(cm
, done
);
3026 on(document
, "mousemove", move);
3027 on(document
, "mouseup", up
);
3030 // Determines whether an event happened in the gutter, and fires the
3031 // handlers for the corresponding event.
3032 function gutterEvent(cm
, e
, type
, prevent
, signalfn
) {
3033 try { var mX
= e
.clientX
, mY
= e
.clientY
; }
3034 catch(e
) { return false; }
3035 if (mX
>= Math
.floor(cm
.display
.gutters
.getBoundingClientRect().right
)) return false;
3036 if (prevent
) e_preventDefault(e
);
3038 var display
= cm
.display
;
3039 var lineBox
= display
.lineDiv
.getBoundingClientRect();
3041 if (mY
> lineBox
.bottom
|| !hasHandler(cm
, type
)) return e_defaultPrevented(e
);
3042 mY
-= lineBox
.top
- display
.viewOffset
;
3044 for (var i
= 0; i
< cm
.options
.gutters
.length
; ++i
) {
3045 var g
= display
.gutters
.childNodes
[i
];
3046 if (g
&& g
.getBoundingClientRect().right
>= mX
) {
3047 var line
= lineAtHeight(cm
.doc
, mY
);
3048 var gutter
= cm
.options
.gutters
[i
];
3049 signalfn(cm
, type
, cm
, line
, gutter
, e
);
3050 return e_defaultPrevented(e
);
3055 function clickInGutter(cm
, e
) {
3056 return gutterEvent(cm
, e
, "gutterClick", true, signalLater
);
3059 // Kludge to work around strange IE behavior where it'll sometimes
3060 // re-fire a series of drag-related events right after the drop (#1551)
3063 function onDrop(e
) {
3065 if (signalDOMEvent(cm
, e
) || eventInWidget(cm
.display
, e
))
3067 e_preventDefault(e
);
3068 if (ie
) lastDrop
= +new Date
;
3069 var pos
= posFromMouse(cm
, e
, true), files
= e
.dataTransfer
.files
;
3070 if (!pos
|| isReadOnly(cm
)) return;
3071 // Might be a file drop, in which case we simply extract the text
3073 if (files
&& files
.length
&& window
.FileReader
&& window
.File
) {
3074 var n
= files
.length
, text
= Array(n
), read
= 0;
3075 var loadFile = function(file
, i
) {
3076 var reader
= new FileReader
;
3077 reader
.onload
= operation(cm
, function() {
3078 text
[i
] = reader
.result
;
3080 pos
= clipPos(cm
.doc
, pos
);
3081 var change
= {from: pos
, to
: pos
, text
: splitLines(text
.join("\n")), origin
: "paste"};
3082 makeChange(cm
.doc
, change
);
3083 setSelectionReplaceHistory(cm
.doc
, simpleSelection(pos
, changeEnd(change
)));
3086 reader
.readAsText(file
);
3088 for (var i
= 0; i
< n
; ++i
) loadFile(files
[i
], i
);
3089 } else { // Normal drop
3090 // Don't do a replace if the drop happened inside of the selected text.
3091 if (cm
.state
.draggingText
&& cm
.doc
.sel
.contains(pos
) > -1) {
3092 cm
.state
.draggingText(e
);
3093 // Ensure the editor is re-focused
3094 setTimeout(bind(focusInput
, cm
), 20);
3098 var text
= e
.dataTransfer
.getData("Text");
3100 if (cm
.state
.draggingText
&& !(mac
? e
.metaKey
: e
.ctrlKey
))
3101 var selected
= cm
.listSelections();
3102 setSelectionNoUndo(cm
.doc
, simpleSelection(pos
, pos
));
3103 if (selected
) for (var i
= 0; i
< selected
.length
; ++i
)
3104 replaceRange(cm
.doc
, "", selected
[i
].anchor
, selected
[i
].head
, "drag");
3105 cm
.replaceSelection(text
, "around", "paste");
3113 function onDragStart(cm
, e
) {
3114 if (ie
&& (!cm
.state
.draggingText
|| +new Date
- lastDrop
< 100)) { e_stop(e
); return; }
3115 if (signalDOMEvent(cm
, e
) || eventInWidget(cm
.display
, e
)) return;
3117 e
.dataTransfer
.setData("Text", cm
.getSelection());
3119 // Use dummy image instead of default browsers image.
3120 // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
3121 if (e
.dataTransfer
.setDragImage
&& !safari
) {
3122 var img
= elt("img", null, null, "position: fixed; left: 0; top: 0;");
3123 img
.src
= "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
3125 img
.width
= img
.height
= 1;
3126 cm
.display
.wrapper
.appendChild(img
);
3127 // Force a relayout, or Opera won't use our image for some obscure reason
3128 img
._top
= img
.offsetTop
;
3130 e
.dataTransfer
.setDragImage(img
, 0, 0);
3131 if (presto
) img
.parentNode
.removeChild(img
);
3137 // Sync the scrollable area and scrollbars, ensure the viewport
3138 // covers the visible area.
3139 function setScrollTop(cm
, val
) {
3140 if (Math
.abs(cm
.doc
.scrollTop
- val
) < 2) return;
3141 cm
.doc
.scrollTop
= val
;
3142 if (!gecko
) updateDisplaySimple(cm
, {top
: val
});
3143 if (cm
.display
.scroller
.scrollTop
!= val
) cm
.display
.scroller
.scrollTop
= val
;
3144 cm
.display
.scrollbars
.setScrollTop(val
);
3145 if (gecko
) updateDisplaySimple(cm
);
3146 startWorker(cm
, 100);
3148 // Sync scroller and scrollbar, ensure the gutter elements are
3150 function setScrollLeft(cm
, val
, isScroller
) {
3151 if (isScroller
? val
== cm
.doc
.scrollLeft
: Math
.abs(cm
.doc
.scrollLeft
- val
) < 2) return;
3152 val
= Math
.min(val
, cm
.display
.scroller
.scrollWidth
- cm
.display
.scroller
.clientWidth
);
3153 cm
.doc
.scrollLeft
= val
;
3154 alignHorizontally(cm
);
3155 if (cm
.display
.scroller
.scrollLeft
!= val
) cm
.display
.scroller
.scrollLeft
= val
;
3156 cm
.display
.scrollbars
.setScrollLeft(val
);
3159 // Since the delta values reported on mouse wheel events are
3160 // unstandardized between browsers and even browser versions, and
3161 // generally horribly unpredictable, this code starts by measuring
3162 // the scroll effect that the first few mouse wheel events have,
3163 // and, from that, detects the way it can convert deltas to pixel
3164 // offsets afterwards.
3166 // The reason we want to know the amount a wheel event will scroll
3167 // is that it gives us a chance to update the display before the
3168 // actual scrolling happens, reducing flickering.
3170 var wheelSamples
= 0, wheelPixelsPerUnit
= null;
3171 // Fill in a browser-detected starting value on browsers where we
3172 // know one. These don't have to be accurate -- the result of them
3173 // being wrong would just be a slight flicker on the first wheel
3174 // scroll (if it is large enough).
3175 if (ie
) wheelPixelsPerUnit
= -.53;
3176 else if (gecko
) wheelPixelsPerUnit
= 15;
3177 else if (chrome
) wheelPixelsPerUnit
= -.7;
3178 else if (safari
) wheelPixelsPerUnit
= -1/3;
3180 var wheelEventDelta = function(e
) {
3181 var dx
= e
.wheelDeltaX
, dy
= e
.wheelDeltaY
;
3182 if (dx
== null && e
.detail
&& e
.axis
== e
.HORIZONTAL_AXIS
) dx
= e
.detail
;
3183 if (dy
== null && e
.detail
&& e
.axis
== e
.VERTICAL_AXIS
) dy
= e
.detail
;
3184 else if (dy
== null) dy
= e
.wheelDelta
;
3185 return {x
: dx
, y
: dy
};
3187 CodeMirror
.wheelEventPixels = function(e
) {
3188 var delta
= wheelEventDelta(e
);
3189 delta
.x
*= wheelPixelsPerUnit
;
3190 delta
.y
*= wheelPixelsPerUnit
;
3194 function onScrollWheel(cm
, e
) {
3195 var delta
= wheelEventDelta(e
), dx
= delta
.x
, dy
= delta
.y
;
3197 var display
= cm
.display
, scroll
= display
.scroller
;
3198 // Quit if there's nothing to scroll here
3199 if (!(dx
&& scroll
.scrollWidth
> scroll
.clientWidth
||
3200 dy
&& scroll
.scrollHeight
> scroll
.clientHeight
)) return;
3202 // Webkit browsers on OS X abort momentum scrolls when the target
3203 // of the scroll event is removed from the scrollable element.
3204 // This hack (see related code in patchDisplay) makes sure the
3205 // element is kept around.
3206 if (dy
&& mac
&& webkit
) {
3207 outer
: for (var cur
= e
.target
, view
= display
.view
; cur
!= scroll
; cur
= cur
.parentNode
) {
3208 for (var i
= 0; i
< view
.length
; i
++) {
3209 if (view
[i
].node
== cur
) {
3210 cm
.display
.currentWheelTarget
= cur
;
3217 // On some browsers, horizontal scrolling will cause redraws to
3218 // happen before the gutter has been realigned, causing it to
3219 // wriggle around in a most unseemly way. When we have an
3220 // estimated pixels/delta value, we just handle horizontal
3221 // scrolling entirely here. It'll be slightly off from native, but
3222 // better than glitching out.
3223 if (dx
&& !gecko
&& !presto
&& wheelPixelsPerUnit
!= null) {
3225 setScrollTop(cm
, Math
.max(0, Math
.min(scroll
.scrollTop
+ dy
* wheelPixelsPerUnit
, scroll
.scrollHeight
- scroll
.clientHeight
)));
3226 setScrollLeft(cm
, Math
.max(0, Math
.min(scroll
.scrollLeft
+ dx
* wheelPixelsPerUnit
, scroll
.scrollWidth
- scroll
.clientWidth
)));
3227 e_preventDefault(e
);
3228 display
.wheelStartX
= null; // Abort measurement, if in progress
3232 // 'Project' the visible viewport to cover the area that is being
3233 // scrolled into view (if we know enough to estimate it).
3234 if (dy
&& wheelPixelsPerUnit
!= null) {
3235 var pixels
= dy
* wheelPixelsPerUnit
;
3236 var top
= cm
.doc
.scrollTop
, bot
= top
+ display
.wrapper
.clientHeight
;
3237 if (pixels
< 0) top
= Math
.max(0, top
+ pixels
- 50);
3238 else bot
= Math
.min(cm
.doc
.height
, bot
+ pixels
+ 50);
3239 updateDisplaySimple(cm
, {top
: top
, bottom
: bot
});
3242 if (wheelSamples
< 20) {
3243 if (display
.wheelStartX
== null) {
3244 display
.wheelStartX
= scroll
.scrollLeft
; display
.wheelStartY
= scroll
.scrollTop
;
3245 display
.wheelDX
= dx
; display
.wheelDY
= dy
;
3246 setTimeout(function() {
3247 if (display
.wheelStartX
== null) return;
3248 var movedX
= scroll
.scrollLeft
- display
.wheelStartX
;
3249 var movedY
= scroll
.scrollTop
- display
.wheelStartY
;
3250 var sample
= (movedY
&& display
.wheelDY
&& movedY
/ display
.wheelDY
) ||
3251 (movedX
&& display
.wheelDX
&& movedX
/ display
.wheelDX
);
3252 display
.wheelStartX
= display
.wheelStartY
= null;
3253 if (!sample
) return;
3254 wheelPixelsPerUnit
= (wheelPixelsPerUnit
* wheelSamples
+ sample
) / (wheelSamples
+ 1);
3258 display
.wheelDX
+= dx
; display
.wheelDY
+= dy
;
3265 // Run a handler that was bound to a key.
3266 function doHandleBinding(cm
, bound
, dropShift
) {
3267 if (typeof bound
== "string") {
3268 bound
= commands
[bound
];
3269 if (!bound
) return false;
3271 // Ensure previous input has been read, so that the handler sees a
3272 // consistent view of the document
3273 if (cm
.display
.pollingFast
&& readInput(cm
)) cm
.display
.pollingFast
= false;
3274 var prevShift
= cm
.display
.shift
, done
= false;
3276 if (isReadOnly(cm
)) cm
.state
.suppressEdits
= true;
3277 if (dropShift
) cm
.display
.shift
= false;
3278 done
= bound(cm
) != Pass
;
3280 cm
.display
.shift
= prevShift
;
3281 cm
.state
.suppressEdits
= false;
3286 function lookupKeyForEditor(cm
, name
, handle
) {
3287 for (var i
= 0; i
< cm
.state
.keyMaps
.length
; i
++) {
3288 var result
= lookupKey(name
, cm
.state
.keyMaps
[i
], handle
, cm
);
3289 if (result
) return result
;
3291 return (cm
.options
.extraKeys
&& lookupKey(name
, cm
.options
.extraKeys
, handle
, cm
))
3292 || lookupKey(name
, cm
.options
.keyMap
, handle
, cm
);
3295 var stopSeq
= new Delayed
;
3296 function dispatchKey(cm
, name
, e
, handle
) {
3297 var seq
= cm
.state
.keySeq
;
3299 if (isModifierKey(name
)) return "handled";
3300 stopSeq
.set(50, function() {
3301 if (cm
.state
.keySeq
== seq
) {
3302 cm
.state
.keySeq
= null;
3306 name
= seq
+ " " + name
;
3308 var result
= lookupKeyForEditor(cm
, name
, handle
);
3310 if (result
== "multi")
3311 cm
.state
.keySeq
= name
;
3312 if (result
== "handled")
3313 signalLater(cm
, "keyHandled", cm
, name
, e
);
3315 if (result
== "handled" || result
== "multi") {
3316 e_preventDefault(e
);
3320 if (seq
&& !result
&& /\'$/.test(name
)) {
3321 e_preventDefault(e
);
3327 // Handle a key from the keydown event.
3328 function handleKeyBinding(cm
, e
) {
3329 var name
= keyName(e
, true);
3330 if (!name
) return false;
3332 if (e
.shiftKey
&& !cm
.state
.keySeq
) {
3333 // First try to resolve full name (including 'Shift-'). Failing
3334 // that, see if there is a cursor-motion command (starting with
3335 // 'go') bound to the keyname without 'Shift-'.
3336 return dispatchKey(cm
, "Shift-" + name
, e
, function(b
) {return doHandleBinding(cm
, b
, true);})
3337 || dispatchKey(cm
, name
, e
, function(b
) {
3338 if (typeof b
== "string" ? /^go[A-Z]/.test(b
) : b
.motion
)
3339 return doHandleBinding(cm
, b
);
3342 return dispatchKey(cm
, name
, e
, function(b
) { return doHandleBinding(cm
, b
); });
3346 // Handle a key from the keypress event
3347 function handleCharBinding(cm
, e
, ch
) {
3348 return dispatchKey(cm
, "'" + ch
+ "'", e
,
3349 function(b
) { return doHandleBinding(cm
, b
, true); });
3352 var lastStoppedKey
= null;
3353 function onKeyDown(e
) {
3356 if (signalDOMEvent(cm
, e
)) return;
3357 // IE does strange things with escape.
3358 if (ie
&& ie_version
< 11 && e
.keyCode
== 27) e
.returnValue
= false;
3359 var code
= e
.keyCode
;
3360 cm
.display
.shift
= code
== 16 || e
.shiftKey
;
3361 var handled
= handleKeyBinding(cm
, e
);
3363 lastStoppedKey
= handled
? code
: null;
3364 // Opera has no cut event... we try to at least catch the key combo
3365 if (!handled
&& code
== 88 && !hasCopyEvent
&& (mac
? e
.metaKey
: e
.ctrlKey
))
3366 cm
.replaceSelection("", null, "cut");
3369 // Turn mouse into crosshair when Alt is held on Mac.
3370 if (code
== 18 && !/\bCodeMirror-crosshair\b/.test(cm
.display
.lineDiv
.className
))
3374 function showCrossHair(cm
) {
3375 var lineDiv
= cm
.display
.lineDiv
;
3376 addClass(lineDiv
, "CodeMirror-crosshair");
3379 if (e
.keyCode
== 18 || !e
.altKey
) {
3380 rmClass(lineDiv
, "CodeMirror-crosshair");
3381 off(document
, "keyup", up
);
3382 off(document
, "mouseover", up
);
3385 on(document
, "keyup", up
);
3386 on(document
, "mouseover", up
);
3389 function onKeyUp(e
) {
3390 if (e
.keyCode
== 16) this.doc
.sel
.shift
= false;
3391 signalDOMEvent(this, e
);
3394 function onKeyPress(e
) {
3396 if (signalDOMEvent(cm
, e
) || e
.ctrlKey
&& !e
.altKey
|| mac
&& e
.metaKey
) return;
3397 var keyCode
= e
.keyCode
, charCode
= e
.charCode
;
3398 if (presto
&& keyCode
== lastStoppedKey
) {lastStoppedKey
= null; e_preventDefault(e
); return;}
3399 if (((presto
&& (!e
.which
|| e
.which
< 10)) || khtml
) && handleKeyBinding(cm
, e
)) return;
3400 var ch
= String
.fromCharCode(charCode
== null ? keyCode
: charCode
);
3401 if (handleCharBinding(cm
, e
, ch
)) return;
3402 if (ie
&& ie_version
>= 9) cm
.display
.inputHasSelection
= null;
3406 // FOCUS/BLUR EVENTS
3408 function onFocus(cm
) {
3409 if (cm
.options
.readOnly
== "nocursor") return;
3410 if (!cm
.state
.focused
) {
3411 signal(cm
, "focus", cm
);
3412 cm
.state
.focused
= true;
3413 addClass(cm
.display
.wrapper
, "CodeMirror-focused");
3414 // The prevInput test prevents this from firing when a context
3415 // menu is closed (since the resetInput would kill the
3416 // select-all detection hack)
3417 if (!cm
.curOp
&& cm
.display
.selForContextMenu
!= cm
.doc
.sel
) {
3419 if (webkit
) setTimeout(bind(resetInput
, cm
, true), 0); // Issue #1730
3425 function onBlur(cm
) {
3426 if (cm
.state
.focused
) {
3427 signal(cm
, "blur", cm
);
3428 cm
.state
.focused
= false;
3429 rmClass(cm
.display
.wrapper
, "CodeMirror-focused");
3431 clearInterval(cm
.display
.blinker
);
3432 setTimeout(function() {if (!cm
.state
.focused
) cm
.display
.shift
= false;}, 150);
3435 // CONTEXT MENU HANDLING
3437 // To make the context menu work, we need to briefly unhide the
3438 // textarea (making it as unobtrusive as possible) to let the
3439 // right-click take effect on it.
3440 function onContextMenu(cm
, e
) {
3441 if (signalDOMEvent(cm
, e
, "contextmenu")) return;
3442 var display
= cm
.display
;
3443 if (eventInWidget(display
, e
) || contextMenuInGutter(cm
, e
)) return;
3445 var pos
= posFromMouse(cm
, e
), scrollPos
= display
.scroller
.scrollTop
;
3446 if (!pos
|| presto
) return; // Opera is difficult.
3448 // Reset the current text selection only if the click is done outside of the selection
3449 // and 'resetSelectionOnContextMenu' option is true.
3450 var reset
= cm
.options
.resetSelectionOnContextMenu
;
3451 if (reset
&& cm
.doc
.sel
.contains(pos
) == -1)
3452 operation(cm
, setSelection
)(cm
.doc
, simpleSelection(pos
), sel_dontScroll
);
3454 var oldCSS
= display
.input
.style
.cssText
;
3455 display
.inputDiv
.style
.position
= "absolute";
3456 display
.input
.style
.cssText
= "position: fixed; width: 30px; height: 30px; top: " + (e
.clientY
- 5) +
3457 "px; left: " + (e
.clientX
- 5) + "px; z-index: 1000; background: " +
3458 (ie
? "rgba(255, 255, 255, .05)" : "transparent") +
3459 "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
3460 if (webkit
) var oldScrollY
= window
.scrollY
; // Work around Chrome issue (#2712)
3462 if (webkit
) window
.scrollTo(null, oldScrollY
);
3464 // Adds "Select all" to context menu in FF
3465 if (!cm
.somethingSelected()) display
.input
.value
= display
.prevInput
= " ";
3466 display
.contextMenuPending
= true;
3467 display
.selForContextMenu
= cm
.doc
.sel
;
3468 clearTimeout(display
.detectingSelectAll
);
3470 // Select-all will be greyed out if there's nothing to select, so
3471 // this adds a zero-width space so that we can later check whether
3473 function prepareSelectAllHack() {
3474 if (display
.input
.selectionStart
!= null) {
3475 var selected
= cm
.somethingSelected();
3476 var extval
= display
.input
.value
= "\u200b" + (selected
? display
.input
.value
: "");
3477 display
.prevInput
= selected
? "" : "\u200b";
3478 display
.input
.selectionStart
= 1; display
.input
.selectionEnd
= extval
.length
;
3479 // Re-set this, in case some other handler touched the
3480 // selection in the meantime.
3481 display
.selForContextMenu
= cm
.doc
.sel
;
3485 display
.contextMenuPending
= false;
3486 display
.inputDiv
.style
.position
= "relative";
3487 display
.input
.style
.cssText
= oldCSS
;
3488 if (ie
&& ie_version
< 9) display
.scrollbars
.setScrollTop(display
.scroller
.scrollTop
= scrollPos
);
3491 // Try to detect the user choosing select-all
3492 if (display
.input
.selectionStart
!= null) {
3493 if (!ie
|| (ie
&& ie_version
< 9)) prepareSelectAllHack();
3494 var i
= 0, poll = function() {
3495 if (display
.selForContextMenu
== cm
.doc
.sel
&& display
.input
.selectionStart
== 0)
3496 operation(cm
, commands
.selectAll
)(cm
);
3497 else if (i
++ < 10) display
.detectingSelectAll
= setTimeout(poll
, 500);
3498 else resetInput(cm
);
3500 display
.detectingSelectAll
= setTimeout(poll
, 200);
3504 if (ie
&& ie_version
>= 9) prepareSelectAllHack();
3505 if (captureRightClick
) {
3507 var mouseup = function() {
3508 off(window
, "mouseup", mouseup
);
3509 setTimeout(rehide
, 20);
3511 on(window
, "mouseup", mouseup
);
3513 setTimeout(rehide
, 50);
3517 function contextMenuInGutter(cm
, e
) {
3518 if (!hasHandler(cm
, "gutterContextMenu")) return false;
3519 return gutterEvent(cm
, e
, "gutterContextMenu", false, signal
);
3524 // Compute the position of the end of a change (its 'to' property
3525 // refers to the pre-change end).
3526 var changeEnd
= CodeMirror
.changeEnd = function(change
) {
3527 if (!change
.text
) return change
.to
;
3528 return Pos(change
.from.line
+ change
.text
.length
- 1,
3529 lst(change
.text
).length
+ (change
.text
.length
== 1 ? change
.from.ch
: 0));
3532 // Adjust a position to refer to the post-change position of the
3533 // same text, or the end of the change if the change covers it.
3534 function adjustForChange(pos
, change
) {
3535 if (cmp(pos
, change
.from) < 0) return pos
;
3536 if (cmp(pos
, change
.to
) <= 0) return changeEnd(change
);
3538 var line
= pos
.line
+ change
.text
.length
- (change
.to
.line
- change
.from.line
) - 1, ch
= pos
.ch
;
3539 if (pos
.line
== change
.to
.line
) ch
+= changeEnd(change
).ch
- change
.to
.ch
;
3540 return Pos(line
, ch
);
3543 function computeSelAfterChange(doc
, change
) {
3545 for (var i
= 0; i
< doc
.sel
.ranges
.length
; i
++) {
3546 var range
= doc
.sel
.ranges
[i
];
3547 out
.push(new Range(adjustForChange(range
.anchor
, change
),
3548 adjustForChange(range
.head
, change
)));
3550 return normalizeSelection(out
, doc
.sel
.primIndex
);
3553 function offsetPos(pos
, old
, nw
) {
3554 if (pos
.line
== old
.line
)
3555 return Pos(nw
.line
, pos
.ch
- old
.ch
+ nw
.ch
);
3557 return Pos(nw
.line
+ (pos
.line
- old
.line
), pos
.ch
);
3560 // Used by replaceSelections to allow moving the selection to the
3561 // start or around the replaced test. Hint may be "start" or "around".
3562 function computeReplacedSel(doc
, changes
, hint
) {
3564 var oldPrev
= Pos(doc
.first
, 0), newPrev
= oldPrev
;
3565 for (var i
= 0; i
< changes
.length
; i
++) {
3566 var change
= changes
[i
];
3567 var from = offsetPos(change
.from, oldPrev
, newPrev
);
3568 var to
= offsetPos(changeEnd(change
), oldPrev
, newPrev
);
3569 oldPrev
= change
.to
;
3571 if (hint
== "around") {
3572 var range
= doc
.sel
.ranges
[i
], inv
= cmp(range
.head
, range
.anchor
) < 0;
3573 out
[i
] = new Range(inv
? to
: from, inv
? from : to
);
3575 out
[i
] = new Range(from, from);
3578 return new Selection(out
, doc
.sel
.primIndex
);
3581 // Allow "beforeChange" event handlers to influence a change
3582 function filterChange(doc
, change
, update
) {
3588 origin
: change
.origin
,
3589 cancel: function() { this.canceled
= true; }
3591 if (update
) obj
.update = function(from, to
, text
, origin
) {
3592 if (from) this.from = clipPos(doc
, from);
3593 if (to
) this.to
= clipPos(doc
, to
);
3594 if (text
) this.text
= text
;
3595 if (origin
!== undefined) this.origin
= origin
;
3597 signal(doc
, "beforeChange", doc
, obj
);
3598 if (doc
.cm
) signal(doc
.cm
, "beforeChange", doc
.cm
, obj
);
3600 if (obj
.canceled
) return null;
3601 return {from: obj
.from, to
: obj
.to
, text
: obj
.text
, origin
: obj
.origin
};
3604 // Apply a change to a document, and add it to the document's
3605 // history, and propagating it to all linked documents.
3606 function makeChange(doc
, change
, ignoreReadOnly
) {
3608 if (!doc
.cm
.curOp
) return operation(doc
.cm
, makeChange
)(doc
, change
, ignoreReadOnly
);
3609 if (doc
.cm
.state
.suppressEdits
) return;
3612 if (hasHandler(doc
, "beforeChange") || doc
.cm
&& hasHandler(doc
.cm
, "beforeChange")) {
3613 change
= filterChange(doc
, change
, true);
3614 if (!change
) return;
3617 // Possibly split or suppress the update based on the presence
3618 // of read-only spans in its range.
3619 var split
= sawReadOnlySpans
&& !ignoreReadOnly
&& removeReadOnlyRanges(doc
, change
.from, change
.to
);
3621 for (var i
= split
.length
- 1; i
>= 0; --i
)
3622 makeChangeInner(doc
, {from: split
[i
].from, to
: split
[i
].to
, text
: i
? [""] : change
.text
});
3624 makeChangeInner(doc
, change
);
3628 function makeChangeInner(doc
, change
) {
3629 if (change
.text
.length
== 1 && change
.text
[0] == "" && cmp(change
.from, change
.to
) == 0) return;
3630 var selAfter
= computeSelAfterChange(doc
, change
);
3631 addChangeToHistory(doc
, change
, selAfter
, doc
.cm
? doc
.cm
.curOp
.id
: NaN
);
3633 makeChangeSingleDoc(doc
, change
, selAfter
, stretchSpansOverChange(doc
, change
));
3636 linkedDocs(doc
, function(doc
, sharedHist
) {
3637 if (!sharedHist
&& indexOf(rebased
, doc
.history
) == -1) {
3638 rebaseHist(doc
.history
, change
);
3639 rebased
.push(doc
.history
);
3641 makeChangeSingleDoc(doc
, change
, null, stretchSpansOverChange(doc
, change
));
3645 // Revert a change stored in a document's history.
3646 function makeChangeFromHistory(doc
, type
, allowSelectionOnly
) {
3647 if (doc
.cm
&& doc
.cm
.state
.suppressEdits
) return;
3649 var hist
= doc
.history
, event
, selAfter
= doc
.sel
;
3650 var source
= type
== "undo" ? hist
.done
: hist
.undone
, dest
= type
== "undo" ? hist
.undone
: hist
.done
;
3652 // Verify that there is a useable event (so that ctrl-z won't
3653 // needlessly clear selection events)
3654 for (var i
= 0; i
< source
.length
; i
++) {
3656 if (allowSelectionOnly
? event
.ranges
&& !event
.equals(doc
.sel
) : !event
.ranges
)
3659 if (i
== source
.length
) return;
3660 hist
.lastOrigin
= hist
.lastSelOrigin
= null;
3663 event
= source
.pop();
3665 pushSelectionToHistory(event
, dest
);
3666 if (allowSelectionOnly
&& !event
.equals(doc
.sel
)) {
3667 setSelection(doc
, event
, {clearRedo
: false});
3675 // Build up a reverse change object to add to the opposite history
3676 // stack (redo when undoing, and vice versa).
3677 var antiChanges
= [];
3678 pushSelectionToHistory(selAfter
, dest
);
3679 dest
.push({changes
: antiChanges
, generation
: hist
.generation
});
3680 hist
.generation
= event
.generation
|| ++hist
.maxGeneration
;
3682 var filter
= hasHandler(doc
, "beforeChange") || doc
.cm
&& hasHandler(doc
.cm
, "beforeChange");
3684 for (var i
= event
.changes
.length
- 1; i
>= 0; --i
) {
3685 var change
= event
.changes
[i
];
3686 change
.origin
= type
;
3687 if (filter
&& !filterChange(doc
, change
, false)) {
3692 antiChanges
.push(historyChangeFromChange(doc
, change
));
3694 var after
= i
? computeSelAfterChange(doc
, change
) : lst(source
);
3695 makeChangeSingleDoc(doc
, change
, after
, mergeOldSpans(doc
, change
));
3696 if (!i
&& doc
.cm
) doc
.cm
.scrollIntoView({from: change
.from, to
: changeEnd(change
)});
3699 // Propagate to the linked documents
3700 linkedDocs(doc
, function(doc
, sharedHist
) {
3701 if (!sharedHist
&& indexOf(rebased
, doc
.history
) == -1) {
3702 rebaseHist(doc
.history
, change
);
3703 rebased
.push(doc
.history
);
3705 makeChangeSingleDoc(doc
, change
, null, mergeOldSpans(doc
, change
));
3710 // Sub-views need their line numbers shifted when text is added
3711 // above or below them in the parent document.
3712 function shiftDoc(doc
, distance
) {
3713 if (distance
== 0) return;
3714 doc
.first
+= distance
;
3715 doc
.sel
= new Selection(map(doc
.sel
.ranges
, function(range
) {
3716 return new Range(Pos(range
.anchor
.line
+ distance
, range
.anchor
.ch
),
3717 Pos(range
.head
.line
+ distance
, range
.head
.ch
));
3718 }), doc
.sel
.primIndex
);
3720 regChange(doc
.cm
, doc
.first
, doc
.first
- distance
, distance
);
3721 for (var d
= doc
.cm
.display
, l
= d
.viewFrom
; l
< d
.viewTo
; l
++)
3722 regLineChange(doc
.cm
, l
, "gutter");
3726 // More lower-level change function, handling only a single document
3727 // (not linked ones).
3728 function makeChangeSingleDoc(doc
, change
, selAfter
, spans
) {
3729 if (doc
.cm
&& !doc
.cm
.curOp
)
3730 return operation(doc
.cm
, makeChangeSingleDoc
)(doc
, change
, selAfter
, spans
);
3732 if (change
.to
.line
< doc
.first
) {
3733 shiftDoc(doc
, change
.text
.length
- 1 - (change
.to
.line
- change
.from.line
));
3736 if (change
.from.line
> doc
.lastLine()) return;
3738 // Clip the change to the size of this doc
3739 if (change
.from.line
< doc
.first
) {
3740 var shift
= change
.text
.length
- 1 - (doc
.first
- change
.from.line
);
3741 shiftDoc(doc
, shift
);
3742 change
= {from: Pos(doc
.first
, 0), to
: Pos(change
.to
.line
+ shift
, change
.to
.ch
),
3743 text
: [lst(change
.text
)], origin
: change
.origin
};
3745 var last
= doc
.lastLine();
3746 if (change
.to
.line
> last
) {
3747 change
= {from: change
.from, to
: Pos(last
, getLine(doc
, last
).text
.length
),
3748 text
: [change
.text
[0]], origin
: change
.origin
};
3751 change
.removed
= getBetween(doc
, change
.from, change
.to
);
3753 if (!selAfter
) selAfter
= computeSelAfterChange(doc
, change
);
3754 if (doc
.cm
) makeChangeSingleDocInEditor(doc
.cm
, change
, spans
);
3755 else updateDoc(doc
, change
, spans
);
3756 setSelectionNoUndo(doc
, selAfter
, sel_dontScroll
);
3759 // Handle the interaction of a change to a document with the editor
3760 // that this document is part of.
3761 function makeChangeSingleDocInEditor(cm
, change
, spans
) {
3762 var doc
= cm
.doc
, display
= cm
.display
, from = change
.from, to
= change
.to
;
3764 var recomputeMaxLength
= false, checkWidthStart
= from.line
;
3765 if (!cm
.options
.lineWrapping
) {
3766 checkWidthStart
= lineNo(visualLine(getLine(doc
, from.line
)));
3767 doc
.iter(checkWidthStart
, to
.line
+ 1, function(line
) {
3768 if (line
== display
.maxLine
) {
3769 recomputeMaxLength
= true;
3775 if (doc
.sel
.contains(change
.from, change
.to
) > -1)
3776 signalCursorActivity(cm
);
3778 updateDoc(doc
, change
, spans
, estimateHeight(cm
));
3780 if (!cm
.options
.lineWrapping
) {
3781 doc
.iter(checkWidthStart
, from.line
+ change
.text
.length
, function(line
) {
3782 var len
= lineLength(line
);
3783 if (len
> display
.maxLineLength
) {
3784 display
.maxLine
= line
;
3785 display
.maxLineLength
= len
;
3786 display
.maxLineChanged
= true;
3787 recomputeMaxLength
= false;
3790 if (recomputeMaxLength
) cm
.curOp
.updateMaxLine
= true;
3793 // Adjust frontier, schedule worker
3794 doc
.frontier
= Math
.min(doc
.frontier
, from.line
);
3795 startWorker(cm
, 400);
3797 var lendiff
= change
.text
.length
- (to
.line
- from.line
) - 1;
3798 // Remember that these lines changed, for updating the display
3801 else if (from.line
== to
.line
&& change
.text
.length
== 1 && !isWholeLineUpdate(cm
.doc
, change
))
3802 regLineChange(cm
, from.line
, "text");
3804 regChange(cm
, from.line
, to
.line
+ 1, lendiff
);
3806 var changesHandler
= hasHandler(cm
, "changes"), changeHandler
= hasHandler(cm
, "change");
3807 if (changeHandler
|| changesHandler
) {
3811 removed
: change
.removed
,
3812 origin
: change
.origin
3814 if (changeHandler
) signalLater(cm
, "change", cm
, obj
);
3815 if (changesHandler
) (cm
.curOp
.changeObjs
|| (cm
.curOp
.changeObjs
= [])).push(obj
);
3817 cm
.display
.selForContextMenu
= null;
3820 function replaceRange(doc
, code
, from, to
, origin
) {
3822 if (cmp(to
, from) < 0) { var tmp
= to
; to
= from; from = tmp
; }
3823 if (typeof code
== "string") code
= splitLines(code
);
3824 makeChange(doc
, {from: from, to
: to
, text
: code
, origin
: origin
});
3827 // SCROLLING THINGS INTO VIEW
3829 // If an editor sits on the top or bottom of the window, partially
3830 // scrolled out of view, this ensures that the cursor is visible.
3831 function maybeScrollWindow(cm
, coords
) {
3832 if (signalDOMEvent(cm
, "scrollCursorIntoView")) return;
3834 var display
= cm
.display
, box
= display
.sizer
.getBoundingClientRect(), doScroll
= null;
3835 if (coords
.top
+ box
.top
< 0) doScroll
= true;
3836 else if (coords
.bottom
+ box
.top
> (window
.innerHeight
|| document
.documentElement
.clientHeight
)) doScroll
= false;
3837 if (doScroll
!= null && !phantom
) {
3838 var scrollNode
= elt("div", "\u200b", null, "position: absolute; top: " +
3839 (coords
.top
- display
.viewOffset
- paddingTop(cm
.display
)) + "px; height: " +
3840 (coords
.bottom
- coords
.top
+ scrollGap(cm
) + display
.barHeight
) + "px; left: " +
3841 coords
.left
+ "px; width: 2px;");
3842 cm
.display
.lineSpace
.appendChild(scrollNode
);
3843 scrollNode
.scrollIntoView(doScroll
);
3844 cm
.display
.lineSpace
.removeChild(scrollNode
);
3848 // Scroll a given position into view (immediately), verifying that
3849 // it actually became visible (as line heights are accurately
3850 // measured, the position of something may 'drift' during drawing).
3851 function scrollPosIntoView(cm
, pos
, end
, margin
) {
3852 if (margin
== null) margin
= 0;
3853 for (var limit
= 0; limit
< 5; limit
++) {
3854 var changed
= false, coords
= cursorCoords(cm
, pos
);
3855 var endCoords
= !end
|| end
== pos
? coords
: cursorCoords(cm
, end
);
3856 var scrollPos
= calculateScrollPos(cm
, Math
.min(coords
.left
, endCoords
.left
),
3857 Math
.min(coords
.top
, endCoords
.top
) - margin
,
3858 Math
.max(coords
.left
, endCoords
.left
),
3859 Math
.max(coords
.bottom
, endCoords
.bottom
) + margin
);
3860 var startTop
= cm
.doc
.scrollTop
, startLeft
= cm
.doc
.scrollLeft
;
3861 if (scrollPos
.scrollTop
!= null) {
3862 setScrollTop(cm
, scrollPos
.scrollTop
);
3863 if (Math
.abs(cm
.doc
.scrollTop
- startTop
) > 1) changed
= true;
3865 if (scrollPos
.scrollLeft
!= null) {
3866 setScrollLeft(cm
, scrollPos
.scrollLeft
);
3867 if (Math
.abs(cm
.doc
.scrollLeft
- startLeft
) > 1) changed
= true;
3869 if (!changed
) break;
3874 // Scroll a given set of coordinates into view (immediately).
3875 function scrollIntoView(cm
, x1
, y1
, x2
, y2
) {
3876 var scrollPos
= calculateScrollPos(cm
, x1
, y1
, x2
, y2
);
3877 if (scrollPos
.scrollTop
!= null) setScrollTop(cm
, scrollPos
.scrollTop
);
3878 if (scrollPos
.scrollLeft
!= null) setScrollLeft(cm
, scrollPos
.scrollLeft
);
3881 // Calculate a new scroll position needed to scroll the given
3882 // rectangle into view. Returns an object with scrollTop and
3883 // scrollLeft properties. When these are undefined, the
3884 // vertical/horizontal position does not need to be adjusted.
3885 function calculateScrollPos(cm
, x1
, y1
, x2
, y2
) {
3886 var display
= cm
.display
, snapMargin
= textHeight(cm
.display
);
3888 var screentop
= cm
.curOp
&& cm
.curOp
.scrollTop
!= null ? cm
.curOp
.scrollTop
: display
.scroller
.scrollTop
;
3889 var screen
= displayHeight(cm
), result
= {};
3890 if (y2
- y1
> screen
) y2
= y1
+ screen
;
3891 var docBottom
= cm
.doc
.height
+ paddingVert(display
);
3892 var atTop
= y1
< snapMargin
, atBottom
= y2
> docBottom
- snapMargin
;
3893 if (y1
< screentop
) {
3894 result
.scrollTop
= atTop
? 0 : y1
;
3895 } else if (y2
> screentop
+ screen
) {
3896 var newTop
= Math
.min(y1
, (atBottom
? docBottom
: y2
) - screen
);
3897 if (newTop
!= screentop
) result
.scrollTop
= newTop
;
3900 var screenleft
= cm
.curOp
&& cm
.curOp
.scrollLeft
!= null ? cm
.curOp
.scrollLeft
: display
.scroller
.scrollLeft
;
3901 var screenw
= displayWidth(cm
) - (cm
.options
.fixedGutter
? display
.gutters
.offsetWidth
: 0);
3902 var tooWide
= x2
- x1
> screenw
;
3903 if (tooWide
) x2
= x1
+ screenw
;
3905 result
.scrollLeft
= 0;
3906 else if (x1
< screenleft
)
3907 result
.scrollLeft
= Math
.max(0, x1
- (tooWide
? 0 : 10));
3908 else if (x2
> screenw
+ screenleft
- 3)
3909 result
.scrollLeft
= x2
+ (tooWide
? 0 : 10) - screenw
;
3913 // Store a relative adjustment to the scroll position in the current
3914 // operation (to be applied when the operation finishes).
3915 function addToScrollPos(cm
, left
, top
) {
3916 if (left
!= null || top
!= null) resolveScrollToPos(cm
);
3918 cm
.curOp
.scrollLeft
= (cm
.curOp
.scrollLeft
== null ? cm
.doc
.scrollLeft
: cm
.curOp
.scrollLeft
) + left
;
3920 cm
.curOp
.scrollTop
= (cm
.curOp
.scrollTop
== null ? cm
.doc
.scrollTop
: cm
.curOp
.scrollTop
) + top
;
3923 // Make sure that at the end of the operation the current cursor is
3925 function ensureCursorVisible(cm
) {
3926 resolveScrollToPos(cm
);
3927 var cur
= cm
.getCursor(), from = cur
, to
= cur
;
3928 if (!cm
.options
.lineWrapping
) {
3929 from = cur
.ch
? Pos(cur
.line
, cur
.ch
- 1) : cur
;
3930 to
= Pos(cur
.line
, cur
.ch
+ 1);
3932 cm
.curOp
.scrollToPos
= {from: from, to
: to
, margin
: cm
.options
.cursorScrollMargin
, isCursor
: true};
3935 // When an operation has its scrollToPos property set, and another
3936 // scroll action is applied before the end of the operation, this
3937 // 'simulates' scrolling that position into view in a cheap way, so
3938 // that the effect of intermediate scroll commands is not ignored.
3939 function resolveScrollToPos(cm
) {
3940 var range
= cm
.curOp
.scrollToPos
;
3942 cm
.curOp
.scrollToPos
= null;
3943 var from = estimateCoords(cm
, range
.from), to
= estimateCoords(cm
, range
.to
);
3944 var sPos
= calculateScrollPos(cm
, Math
.min(from.left
, to
.left
),
3945 Math
.min(from.top
, to
.top
) - range
.margin
,
3946 Math
.max(from.right
, to
.right
),
3947 Math
.max(from.bottom
, to
.bottom
) + range
.margin
);
3948 cm
.scrollTo(sPos
.scrollLeft
, sPos
.scrollTop
);
3954 // Indent the given line. The how parameter can be "smart",
3955 // "add"/null, "subtract", or "prev". When aggressive is false
3956 // (typically set to true for forced single-line indents), empty
3957 // lines are not indented, and places where the mode returns Pass
3959 function indentLine(cm
, n
, how
, aggressive
) {
3960 var doc
= cm
.doc
, state
;
3961 if (how
== null) how
= "add";
3962 if (how
== "smart") {
3963 // Fall back to "prev" when the mode doesn't have an indentation
3965 if (!doc
.mode
.indent
) how
= "prev";
3966 else state
= getStateBefore(cm
, n
);
3969 var tabSize
= cm
.options
.tabSize
;
3970 var line
= getLine(doc
, n
), curSpace
= countColumn(line
.text
, null, tabSize
);
3971 if (line
.stateAfter
) line
.stateAfter
= null;
3972 var curSpaceString
= line
.text
.match(/^\s*/)[0], indentation
;
3973 if (!aggressive
&& !/\S/.test(line
.text
)) {
3976 } else if (how
== "smart") {
3977 indentation
= doc
.mode
.indent(state
, line
.text
.slice(curSpaceString
.length
), line
.text
);
3978 if (indentation
== Pass
|| indentation
> 150) {
3979 if (!aggressive
) return;
3983 if (how
== "prev") {
3984 if (n
> doc
.first
) indentation
= countColumn(getLine(doc
, n
-1).text
, null, tabSize
);
3985 else indentation
= 0;
3986 } else if (how
== "add") {
3987 indentation
= curSpace
+ cm
.options
.indentUnit
;
3988 } else if (how
== "subtract") {
3989 indentation
= curSpace
- cm
.options
.indentUnit
;
3990 } else if (typeof how
== "number") {
3991 indentation
= curSpace
+ how
;
3993 indentation
= Math
.max(0, indentation
);
3995 var indentString
= "", pos
= 0;
3996 if (cm
.options
.indentWithTabs
)
3997 for (var i
= Math
.floor(indentation
/ tabSize
); i
; --i
) {pos
+= tabSize
; indentString
+= "\t";}
3998 if (pos
< indentation
) indentString
+= spaceStr(indentation
- pos
);
4000 if (indentString
!= curSpaceString
) {
4001 replaceRange(doc
, indentString
, Pos(n
, 0), Pos(n
, curSpaceString
.length
), "+input");
4003 // Ensure that, if the cursor was in the whitespace at the start
4004 // of the line, it is moved to the end of that space.
4005 for (var i
= 0; i
< doc
.sel
.ranges
.length
; i
++) {
4006 var range
= doc
.sel
.ranges
[i
];
4007 if (range
.head
.line
== n
&& range
.head
.ch
< curSpaceString
.length
) {
4008 var pos
= Pos(n
, curSpaceString
.length
);
4009 replaceOneSelection(doc
, i
, new Range(pos
, pos
));
4014 line
.stateAfter
= null;
4017 // Utility for applying a change to a line by handle or number,
4018 // returning the number and optionally registering the line as
4020 function changeLine(doc
, handle
, changeType
, op
) {
4021 var no
= handle
, line
= handle
;
4022 if (typeof handle
== "number") line
= getLine(doc
, clipLine(doc
, handle
));
4023 else no
= lineNo(handle
);
4024 if (no
== null) return null;
4025 if (op(line
, no
) && doc
.cm
) regLineChange(doc
.cm
, no
, changeType
);
4029 // Helper for deleting text near the selection(s), used to implement
4030 // backspace, delete, and similar functionality.
4031 function deleteNearSelection(cm
, compute
) {
4032 var ranges
= cm
.doc
.sel
.ranges
, kill
= [];
4033 // Build up a set of ranges to kill first, merging overlapping
4035 for (var i
= 0; i
< ranges
.length
; i
++) {
4036 var toKill
= compute(ranges
[i
]);
4037 while (kill
.length
&& cmp(toKill
.from, lst(kill
).to
) <= 0) {
4038 var replaced
= kill
.pop();
4039 if (cmp(replaced
.from, toKill
.from) < 0) {
4040 toKill
.from = replaced
.from;
4046 // Next, remove those actual ranges.
4047 runInOp(cm
, function() {
4048 for (var i
= kill
.length
- 1; i
>= 0; i
--)
4049 replaceRange(cm
.doc
, "", kill
[i
].from, kill
[i
].to
, "+delete");
4050 ensureCursorVisible(cm
);
4054 // Used for horizontal relative motion. Dir is -1 or 1 (left or
4055 // right), unit can be "char", "column" (like char, but doesn't
4056 // cross line boundaries), "word" (across next word), or "group" (to
4057 // the start of next group of word or non-word-non-whitespace
4058 // chars). The visually param controls whether, in right-to-left
4059 // text, direction 1 means to move towards the next index in the
4060 // string, or towards the character to the right of the current
4061 // position. The resulting position will have a hitSide=true
4062 // property if it reached the end of the document.
4063 function findPosH(doc
, pos
, dir
, unit
, visually
) {
4064 var line
= pos
.line
, ch
= pos
.ch
, origDir
= dir
;
4065 var lineObj
= getLine(doc
, line
);
4066 var possible
= true;
4067 function findNextLine() {
4069 if (l
< doc
.first
|| l
>= doc
.first
+ doc
.size
) return (possible
= false);
4071 return lineObj
= getLine(doc
, l
);
4073 function moveOnce(boundToLine
) {
4074 var next
= (visually
? moveVisually
: moveLogically
)(lineObj
, ch
, dir
, true);
4076 if (!boundToLine
&& findNextLine()) {
4077 if (visually
) ch
= (dir
< 0 ? lineRight
: lineLeft
)(lineObj
);
4078 else ch
= dir
< 0 ? lineObj
.text
.length
: 0;
4079 } else return (possible
= false);
4084 if (unit
== "char") moveOnce();
4085 else if (unit
== "column") moveOnce(true);
4086 else if (unit
== "word" || unit
== "group") {
4087 var sawType
= null, group
= unit
== "group";
4088 var helper
= doc
.cm
&& doc
.cm
.getHelper(pos
, "wordChars");
4089 for (var first
= true;; first
= false) {
4090 if (dir
< 0 && !moveOnce(!first
)) break;
4091 var cur
= lineObj
.text
.charAt(ch
) || "\n";
4092 var type
= isWordChar(cur
, helper
) ? "w"
4093 : group
&& cur
== "\n" ? "n"
4094 : !group
|| /\s/.test(cur
) ? null
4096 if (group
&& !first
&& !type
) type
= "s";
4097 if (sawType
&& sawType
!= type
) {
4098 if (dir
< 0) {dir
= 1; moveOnce();}
4102 if (type
) sawType
= type
;
4103 if (dir
> 0 && !moveOnce(!first
)) break;
4106 var result
= skipAtomic(doc
, Pos(line
, ch
), origDir
, true);
4107 if (!possible
) result
.hitSide
= true;
4111 // For relative vertical movement. Dir may be -1 or 1. Unit can be
4112 // "page" or "line". The resulting position will have a hitSide=true
4113 // property if it reached the end of the document.
4114 function findPosV(cm
, pos
, dir
, unit
) {
4115 var doc
= cm
.doc
, x
= pos
.left
, y
;
4116 if (unit
== "page") {
4117 var pageSize
= Math
.min(cm
.display
.wrapper
.clientHeight
, window
.innerHeight
|| document
.documentElement
.clientHeight
);
4118 y
= pos
.top
+ dir
* (pageSize
- (dir
< 0 ? 1.5 : .5) * textHeight(cm
.display
));
4119 } else if (unit
== "line") {
4120 y
= dir
> 0 ? pos
.bottom
+ 3 : pos
.top
- 3;
4123 var target
= coordsChar(cm
, x
, y
);
4124 if (!target
.outside
) break;
4125 if (dir
< 0 ? y
<= 0 : y
>= doc
.height
) { target
.hitSide
= true; break; }
4133 // The publicly visible API. Note that methodOp(f) means
4134 // 'wrap f in an operation, performed on its `this` parameter'.
4136 // This is not the complete set of editor methods. Most of the
4137 // methods defined on the Doc type are also injected into
4138 // CodeMirror.prototype, for backwards compatibility and
4141 CodeMirror
.prototype = {
4142 constructor: CodeMirror
,
4143 focus: function(){window
.focus(); focusInput(this); fastPoll(this);},
4145 setOption: function(option
, value
) {
4146 var options
= this.options
, old
= options
[option
];
4147 if (options
[option
] == value
&& option
!= "mode") return;
4148 options
[option
] = value
;
4149 if (optionHandlers
.hasOwnProperty(option
))
4150 operation(this, optionHandlers
[option
])(this, value
, old
);
4153 getOption: function(option
) {return this.options
[option
];},
4154 getDoc: function() {return this.doc
;},
4156 addKeyMap: function(map
, bottom
) {
4157 this.state
.keyMaps
[bottom
? "push" : "unshift"](getKeyMap(map
));
4159 removeKeyMap: function(map
) {
4160 var maps
= this.state
.keyMaps
;
4161 for (var i
= 0; i
< maps
.length
; ++i
)
4162 if (maps
[i
] == map
|| maps
[i
].name
== map
) {
4168 addOverlay
: methodOp(function(spec
, options
) {
4169 var mode
= spec
.token
? spec
: CodeMirror
.getMode(this.options
, spec
);
4170 if (mode
.startState
) throw new Error("Overlays may not be stateful.");
4171 this.state
.overlays
.push({mode
: mode
, modeSpec
: spec
, opaque
: options
&& options
.opaque
});
4172 this.state
.modeGen
++;
4175 removeOverlay
: methodOp(function(spec
) {
4176 var overlays
= this.state
.overlays
;
4177 for (var i
= 0; i
< overlays
.length
; ++i
) {
4178 var cur
= overlays
[i
].modeSpec
;
4179 if (cur
== spec
|| typeof spec
== "string" && cur
.name
== spec
) {
4180 overlays
.splice(i
, 1);
4181 this.state
.modeGen
++;
4188 indentLine
: methodOp(function(n
, dir
, aggressive
) {
4189 if (typeof dir
!= "string" && typeof dir
!= "number") {
4190 if (dir
== null) dir
= this.options
.smartIndent
? "smart" : "prev";
4191 else dir
= dir
? "add" : "subtract";
4193 if (isLine(this.doc
, n
)) indentLine(this, n
, dir
, aggressive
);
4195 indentSelection
: methodOp(function(how
) {
4196 var ranges
= this.doc
.sel
.ranges
, end
= -1;
4197 for (var i
= 0; i
< ranges
.length
; i
++) {
4198 var range
= ranges
[i
];
4199 if (!range
.empty()) {
4200 var from = range
.from(), to
= range
.to();
4201 var start
= Math
.max(end
, from.line
);
4202 end
= Math
.min(this.lastLine(), to
.line
- (to
.ch
? 0 : 1)) + 1;
4203 for (var j
= start
; j
< end
; ++j
)
4204 indentLine(this, j
, how
);
4205 var newRanges
= this.doc
.sel
.ranges
;
4206 if (from.ch
== 0 && ranges
.length
== newRanges
.length
&& newRanges
[i
].from().ch
> 0)
4207 replaceOneSelection(this.doc
, i
, new Range(from, newRanges
[i
].to()), sel_dontScroll
);
4208 } else if (range
.head
.line
> end
) {
4209 indentLine(this, range
.head
.line
, how
, true);
4210 end
= range
.head
.line
;
4211 if (i
== this.doc
.sel
.primIndex
) ensureCursorVisible(this);
4216 // Fetch the parser token for a given character. Useful for hacks
4217 // that want to inspect the mode state (say, for completion).
4218 getTokenAt: function(pos
, precise
) {
4219 return takeToken(this, pos
, precise
);
4222 getLineTokens: function(line
, precise
) {
4223 return takeToken(this, Pos(line
), precise
, true);
4226 getTokenTypeAt: function(pos
) {
4227 pos
= clipPos(this.doc
, pos
);
4228 var styles
= getLineStyles(this, getLine(this.doc
, pos
.line
));
4229 var before
= 0, after
= (styles
.length
- 1) / 2, ch
= pos
.ch
;
4231 if (ch
== 0) type
= styles
[2];
4233 var mid
= (before
+ after
) >> 1;
4234 if ((mid
? styles
[mid
* 2 - 1] : 0) >= ch
) after
= mid
;
4235 else if (styles
[mid
* 2 + 1] < ch
) before
= mid
+ 1;
4236 else { type
= styles
[mid
* 2 + 2]; break; }
4238 var cut
= type
? type
.indexOf("cm-overlay ") : -1;
4239 return cut
< 0 ? type
: cut
== 0 ? null : type
.slice(0, cut
- 1);
4242 getModeAt: function(pos
) {
4243 var mode
= this.doc
.mode
;
4244 if (!mode
.innerMode
) return mode
;
4245 return CodeMirror
.innerMode(mode
, this.getTokenAt(pos
).state
).mode
;
4248 getHelper: function(pos
, type
) {
4249 return this.getHelpers(pos
, type
)[0];
4252 getHelpers: function(pos
, type
) {
4254 if (!helpers
.hasOwnProperty(type
)) return helpers
;
4255 var help
= helpers
[type
], mode
= this.getModeAt(pos
);
4256 if (typeof mode
[type
] == "string") {
4257 if (help
[mode
[type
]]) found
.push(help
[mode
[type
]]);
4258 } else if (mode
[type
]) {
4259 for (var i
= 0; i
< mode
[type
].length
; i
++) {
4260 var val
= help
[mode
[type
][i
]];
4261 if (val
) found
.push(val
);
4263 } else if (mode
.helperType
&& help
[mode
.helperType
]) {
4264 found
.push(help
[mode
.helperType
]);
4265 } else if (help
[mode
.name
]) {
4266 found
.push(help
[mode
.name
]);
4268 for (var i
= 0; i
< help
._global
.length
; i
++) {
4269 var cur
= help
._global
[i
];
4270 if (cur
.pred(mode
, this) && indexOf(found
, cur
.val
) == -1)
4271 found
.push(cur
.val
);
4276 getStateAfter: function(line
, precise
) {
4278 line
= clipLine(doc
, line
== null ? doc
.first
+ doc
.size
- 1: line
);
4279 return getStateBefore(this, line
+ 1, precise
);
4282 cursorCoords: function(start
, mode
) {
4283 var pos
, range
= this.doc
.sel
.primary();
4284 if (start
== null) pos
= range
.head
;
4285 else if (typeof start
== "object") pos
= clipPos(this.doc
, start
);
4286 else pos
= start
? range
.from() : range
.to();
4287 return cursorCoords(this, pos
, mode
|| "page");
4290 charCoords: function(pos
, mode
) {
4291 return charCoords(this, clipPos(this.doc
, pos
), mode
|| "page");
4294 coordsChar: function(coords
, mode
) {
4295 coords
= fromCoordSystem(this, coords
, mode
|| "page");
4296 return coordsChar(this, coords
.left
, coords
.top
);
4299 lineAtHeight: function(height
, mode
) {
4300 height
= fromCoordSystem(this, {top
: height
, left
: 0}, mode
|| "page").top
;
4301 return lineAtHeight(this.doc
, height
+ this.display
.viewOffset
);
4303 heightAtLine: function(line
, mode
) {
4304 var end
= false, last
= this.doc
.first
+ this.doc
.size
- 1;
4305 if (line
< this.doc
.first
) line
= this.doc
.first
;
4306 else if (line
> last
) { line
= last
; end
= true; }
4307 var lineObj
= getLine(this.doc
, line
);
4308 return intoCoordSystem(this, lineObj
, {top
: 0, left
: 0}, mode
|| "page").top
+
4309 (end
? this.doc
.height
- heightAtLine(lineObj
) : 0);
4312 defaultTextHeight: function() { return textHeight(this.display
); },
4313 defaultCharWidth: function() { return charWidth(this.display
); },
4315 setGutterMarker
: methodOp(function(line
, gutterID
, value
) {
4316 return changeLine(this.doc
, line
, "gutter", function(line
) {
4317 var markers
= line
.gutterMarkers
|| (line
.gutterMarkers
= {});
4318 markers
[gutterID
] = value
;
4319 if (!value
&& isEmpty(markers
)) line
.gutterMarkers
= null;
4324 clearGutter
: methodOp(function(gutterID
) {
4325 var cm
= this, doc
= cm
.doc
, i
= doc
.first
;
4326 doc
.iter(function(line
) {
4327 if (line
.gutterMarkers
&& line
.gutterMarkers
[gutterID
]) {
4328 line
.gutterMarkers
[gutterID
] = null;
4329 regLineChange(cm
, i
, "gutter");
4330 if (isEmpty(line
.gutterMarkers
)) line
.gutterMarkers
= null;
4336 addLineWidget
: methodOp(function(handle
, node
, options
) {
4337 return addLineWidget(this, handle
, node
, options
);
4340 removeLineWidget: function(widget
) { widget
.clear(); },
4342 lineInfo: function(line
) {
4343 if (typeof line
== "number") {
4344 if (!isLine(this.doc
, line
)) return null;
4346 line
= getLine(this.doc
, line
);
4347 if (!line
) return null;
4349 var n
= lineNo(line
);
4350 if (n
== null) return null;
4352 return {line
: n
, handle
: line
, text
: line
.text
, gutterMarkers
: line
.gutterMarkers
,
4353 textClass
: line
.textClass
, bgClass
: line
.bgClass
, wrapClass
: line
.wrapClass
,
4354 widgets
: line
.widgets
};
4357 getViewport: function() { return {from: this.display
.viewFrom
, to
: this.display
.viewTo
};},
4359 addWidget: function(pos
, node
, scroll
, vert
, horiz
) {
4360 var display
= this.display
;
4361 pos
= cursorCoords(this, clipPos(this.doc
, pos
));
4362 var top
= pos
.bottom
, left
= pos
.left
;
4363 node
.style
.position
= "absolute";
4364 node
.setAttribute("cm-ignore-events", "true");
4365 display
.sizer
.appendChild(node
);
4366 if (vert
== "over") {
4368 } else if (vert
== "above" || vert
== "near") {
4369 var vspace
= Math
.max(display
.wrapper
.clientHeight
, this.doc
.height
),
4370 hspace
= Math
.max(display
.sizer
.clientWidth
, display
.lineSpace
.clientWidth
);
4371 // Default to positioning above (if specified and possible); otherwise default to positioning below
4372 if ((vert
== 'above' || pos
.bottom
+ node
.offsetHeight
> vspace
) && pos
.top
> node
.offsetHeight
)
4373 top
= pos
.top
- node
.offsetHeight
;
4374 else if (pos
.bottom
+ node
.offsetHeight
<= vspace
)
4376 if (left
+ node
.offsetWidth
> hspace
)
4377 left
= hspace
- node
.offsetWidth
;
4379 node
.style
.top
= top
+ "px";
4380 node
.style
.left
= node
.style
.right
= "";
4381 if (horiz
== "right") {
4382 left
= display
.sizer
.clientWidth
- node
.offsetWidth
;
4383 node
.style
.right
= "0px";
4385 if (horiz
== "left") left
= 0;
4386 else if (horiz
== "middle") left
= (display
.sizer
.clientWidth
- node
.offsetWidth
) / 2;
4387 node
.style
.left
= left
+ "px";
4390 scrollIntoView(this, left
, top
, left
+ node
.offsetWidth
, top
+ node
.offsetHeight
);
4393 triggerOnKeyDown
: methodOp(onKeyDown
),
4394 triggerOnKeyPress
: methodOp(onKeyPress
),
4395 triggerOnKeyUp
: onKeyUp
,
4397 execCommand: function(cmd
) {
4398 if (commands
.hasOwnProperty(cmd
))
4399 return commands
[cmd
](this);
4402 findPosH: function(from, amount
, unit
, visually
) {
4404 if (amount
< 0) { dir
= -1; amount
= -amount
; }
4405 for (var i
= 0, cur
= clipPos(this.doc
, from); i
< amount
; ++i
) {
4406 cur
= findPosH(this.doc
, cur
, dir
, unit
, visually
);
4407 if (cur
.hitSide
) break;
4412 moveH
: methodOp(function(dir
, unit
) {
4414 cm
.extendSelectionsBy(function(range
) {
4415 if (cm
.display
.shift
|| cm
.doc
.extend
|| range
.empty())
4416 return findPosH(cm
.doc
, range
.head
, dir
, unit
, cm
.options
.rtlMoveVisually
);
4418 return dir
< 0 ? range
.from() : range
.to();
4422 deleteH
: methodOp(function(dir
, unit
) {
4423 var sel
= this.doc
.sel
, doc
= this.doc
;
4424 if (sel
.somethingSelected())
4425 doc
.replaceSelection("", null, "+delete");
4427 deleteNearSelection(this, function(range
) {
4428 var other
= findPosH(doc
, range
.head
, dir
, unit
, false);
4429 return dir
< 0 ? {from: other
, to
: range
.head
} : {from: range
.head
, to
: other
};
4433 findPosV: function(from, amount
, unit
, goalColumn
) {
4434 var dir
= 1, x
= goalColumn
;
4435 if (amount
< 0) { dir
= -1; amount
= -amount
; }
4436 for (var i
= 0, cur
= clipPos(this.doc
, from); i
< amount
; ++i
) {
4437 var coords
= cursorCoords(this, cur
, "div");
4438 if (x
== null) x
= coords
.left
;
4439 else coords
.left
= x
;
4440 cur
= findPosV(this, coords
, dir
, unit
);
4441 if (cur
.hitSide
) break;
4446 moveV
: methodOp(function(dir
, unit
) {
4447 var cm
= this, doc
= this.doc
, goals
= [];
4448 var collapse
= !cm
.display
.shift
&& !doc
.extend
&& doc
.sel
.somethingSelected();
4449 doc
.extendSelectionsBy(function(range
) {
4451 return dir
< 0 ? range
.from() : range
.to();
4452 var headPos
= cursorCoords(cm
, range
.head
, "div");
4453 if (range
.goalColumn
!= null) headPos
.left
= range
.goalColumn
;
4454 goals
.push(headPos
.left
);
4455 var pos
= findPosV(cm
, headPos
, dir
, unit
);
4456 if (unit
== "page" && range
== doc
.sel
.primary())
4457 addToScrollPos(cm
, null, charCoords(cm
, pos
, "div").top
- headPos
.top
);
4460 if (goals
.length
) for (var i
= 0; i
< doc
.sel
.ranges
.length
; i
++)
4461 doc
.sel
.ranges
[i
].goalColumn
= goals
[i
];
4464 // Find the word at the given position (as returned by coordsChar).
4465 findWordAt: function(pos
) {
4466 var doc
= this.doc
, line
= getLine(doc
, pos
.line
).text
;
4467 var start
= pos
.ch
, end
= pos
.ch
;
4469 var helper
= this.getHelper(pos
, "wordChars");
4470 if ((pos
.xRel
< 0 || end
== line
.length
) && start
) --start
; else ++end
;
4471 var startChar
= line
.charAt(start
);
4472 var check
= isWordChar(startChar
, helper
)
4473 ? function(ch
) { return isWordChar(ch
, helper
); }
4474 : /\s/.test(startChar
) ? function(ch
) {return /\s/.test(ch
);}
4475 : function(ch
) {return !/\s/.test(ch
) && !isWordChar(ch
);};
4476 while (start
> 0 && check(line
.charAt(start
- 1))) --start
;
4477 while (end
< line
.length
&& check(line
.charAt(end
))) ++end
;
4479 return new Range(Pos(pos
.line
, start
), Pos(pos
.line
, end
));
4482 toggleOverwrite: function(value
) {
4483 if (value
!= null && value
== this.state
.overwrite
) return;
4484 if (this.state
.overwrite
= !this.state
.overwrite
)
4485 addClass(this.display
.cursorDiv
, "CodeMirror-overwrite");
4487 rmClass(this.display
.cursorDiv
, "CodeMirror-overwrite");
4489 signal(this, "overwriteToggle", this, this.state
.overwrite
);
4491 hasFocus: function() { return activeElt() == this.display
.input
; },
4493 scrollTo
: methodOp(function(x
, y
) {
4494 if (x
!= null || y
!= null) resolveScrollToPos(this);
4495 if (x
!= null) this.curOp
.scrollLeft
= x
;
4496 if (y
!= null) this.curOp
.scrollTop
= y
;
4498 getScrollInfo: function() {
4499 var scroller
= this.display
.scroller
;
4500 return {left
: scroller
.scrollLeft
, top
: scroller
.scrollTop
,
4501 height
: scroller
.scrollHeight
- scrollGap(this) - this.display
.barHeight
,
4502 width
: scroller
.scrollWidth
- scrollGap(this) - this.display
.barWidth
,
4503 clientHeight
: displayHeight(this), clientWidth
: displayWidth(this)};
4506 scrollIntoView
: methodOp(function(range
, margin
) {
4507 if (range
== null) {
4508 range
= {from: this.doc
.sel
.primary().head
, to
: null};
4509 if (margin
== null) margin
= this.options
.cursorScrollMargin
;
4510 } else if (typeof range
== "number") {
4511 range
= {from: Pos(range
, 0), to
: null};
4512 } else if (range
.from == null) {
4513 range
= {from: range
, to
: null};
4515 if (!range
.to
) range
.to
= range
.from;
4516 range
.margin
= margin
|| 0;
4518 if (range
.from.line
!= null) {
4519 resolveScrollToPos(this);
4520 this.curOp
.scrollToPos
= range
;
4522 var sPos
= calculateScrollPos(this, Math
.min(range
.from.left
, range
.to
.left
),
4523 Math
.min(range
.from.top
, range
.to
.top
) - range
.margin
,
4524 Math
.max(range
.from.right
, range
.to
.right
),
4525 Math
.max(range
.from.bottom
, range
.to
.bottom
) + range
.margin
);
4526 this.scrollTo(sPos
.scrollLeft
, sPos
.scrollTop
);
4530 setSize
: methodOp(function(width
, height
) {
4532 function interpret(val
) {
4533 return typeof val
== "number" || /^\d+$/.test(String(val
)) ? val
+ "px" : val
;
4535 if (width
!= null) cm
.display
.wrapper
.style
.width
= interpret(width
);
4536 if (height
!= null) cm
.display
.wrapper
.style
.height
= interpret(height
);
4537 if (cm
.options
.lineWrapping
) clearLineMeasurementCache(this);
4538 var lineNo
= cm
.display
.viewFrom
;
4539 cm
.doc
.iter(lineNo
, cm
.display
.viewTo
, function(line
) {
4540 if (line
.widgets
) for (var i
= 0; i
< line
.widgets
.length
; i
++)
4541 if (line
.widgets
[i
].noHScroll
) { regLineChange(cm
, lineNo
, "widget"); break; }
4544 cm
.curOp
.forceUpdate
= true;
4545 signal(cm
, "refresh", this);
4548 operation: function(f
){return runInOp(this, f
);},
4550 refresh
: methodOp(function() {
4551 var oldHeight
= this.display
.cachedTextHeight
;
4553 this.curOp
.forceUpdate
= true;
4555 this.scrollTo(this.doc
.scrollLeft
, this.doc
.scrollTop
);
4556 updateGutterSpace(this);
4557 if (oldHeight
== null || Math
.abs(oldHeight
- textHeight(this.display
)) > .5)
4558 estimateLineHeights(this);
4559 signal(this, "refresh", this);
4562 swapDoc
: methodOp(function(doc
) {
4565 attachDoc(this, doc
);
4568 this.scrollTo(doc
.scrollLeft
, doc
.scrollTop
);
4569 this.curOp
.forceScroll
= true;
4570 signalLater(this, "swapDoc", this, old
);
4574 getInputField: function(){return this.display
.input
;},
4575 getWrapperElement: function(){return this.display
.wrapper
;},
4576 getScrollerElement: function(){return this.display
.scroller
;},
4577 getGutterElement: function(){return this.display
.gutters
;}
4579 eventMixin(CodeMirror
);
4583 // The default configuration options.
4584 var defaults
= CodeMirror
.defaults
= {};
4585 // Functions to run when options are changed.
4586 var optionHandlers
= CodeMirror
.optionHandlers
= {};
4588 function option(name
, deflt
, handle
, notOnInit
) {
4589 CodeMirror
.defaults
[name
] = deflt
;
4590 if (handle
) optionHandlers
[name
] =
4591 notOnInit
? function(cm
, val
, old
) {if (old
!= Init
) handle(cm
, val
, old
);} : handle
;
4594 // Passed to option handlers when there is no old value.
4595 var Init
= CodeMirror
.Init
= {toString: function(){return "CodeMirror.Init";}};
4597 // These two are, on init, called from the constructor because they
4598 // have to be initialized before the editor can start at all.
4599 option("value", "", function(cm
, val
) {
4602 option("mode", null, function(cm
, val
) {
4603 cm
.doc
.modeOption
= val
;
4607 option("indentUnit", 2, loadMode
, true);
4608 option("indentWithTabs", false);
4609 option("smartIndent", true);
4610 option("tabSize", 4, function(cm
) {
4615 option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm
, val
) {
4616 cm
.options
.specialChars
= new RegExp(val
.source
+ (val
.test("\t") ? "" : "|\t"), "g");
4619 option("specialCharPlaceholder", defaultSpecialCharPlaceholder
, function(cm
) {cm
.refresh();}, true);
4620 option("electricChars", true);
4621 option("rtlMoveVisually", !windows
);
4622 option("wholeLineUpdateBefore", true);
4624 option("theme", "default", function(cm
) {
4628 option("keyMap", "default", function(cm
, val
, old
) {
4629 var next
= getKeyMap(val
);
4630 var prev
= old
!= CodeMirror
.Init
&& getKeyMap(old
);
4631 if (prev
&& prev
.detach
) prev
.detach(cm
, next
);
4632 if (next
.attach
) next
.attach(cm
, prev
|| null);
4634 option("extraKeys", null);
4636 option("lineWrapping", false, wrappingChanged
, true);
4637 option("gutters", [], function(cm
) {
4638 setGuttersForLineNumbers(cm
.options
);
4641 option("fixedGutter", true, function(cm
, val
) {
4642 cm
.display
.gutters
.style
.left
= val
? compensateForHScroll(cm
.display
) + "px" : "0";
4645 option("coverGutterNextToScrollbar", false, function(cm
) {updateScrollbars(cm
);}, true);
4646 option("scrollbarStyle", "native", function(cm
) {
4648 updateScrollbars(cm
);
4649 cm
.display
.scrollbars
.setScrollTop(cm
.doc
.scrollTop
);
4650 cm
.display
.scrollbars
.setScrollLeft(cm
.doc
.scrollLeft
);
4652 option("lineNumbers", false, function(cm
) {
4653 setGuttersForLineNumbers(cm
.options
);
4656 option("firstLineNumber", 1, guttersChanged
, true);
4657 option("lineNumberFormatter", function(integer
) {return integer
;}, guttersChanged
, true);
4658 option("showCursorWhenSelecting", false, updateSelection
, true);
4660 option("resetSelectionOnContextMenu", true);
4662 option("readOnly", false, function(cm
, val
) {
4663 if (val
== "nocursor") {
4665 cm
.display
.input
.blur();
4666 cm
.display
.disabled
= true;
4668 cm
.display
.disabled
= false;
4669 if (!val
) resetInput(cm
);
4672 option("disableInput", false, function(cm
, val
) {if (!val
) resetInput(cm
);}, true);
4673 option("dragDrop", true);
4675 option("cursorBlinkRate", 530);
4676 option("cursorScrollMargin", 0);
4677 option("cursorHeight", 1, updateSelection
, true);
4678 option("singleCursorHeightPerLine", true, updateSelection
, true);
4679 option("workTime", 100);
4680 option("workDelay", 100);
4681 option("flattenSpans", true, resetModeState
, true);
4682 option("addModeClass", false, resetModeState
, true);
4683 option("pollInterval", 100);
4684 option("undoDepth", 200, function(cm
, val
){cm
.doc
.history
.undoDepth
= val
;});
4685 option("historyEventDelay", 1250);
4686 option("viewportMargin", 10, function(cm
){cm
.refresh();}, true);
4687 option("maxHighlightLength", 10000, resetModeState
, true);
4688 option("moveInputWithCursor", true, function(cm
, val
) {
4689 if (!val
) cm
.display
.inputDiv
.style
.top
= cm
.display
.inputDiv
.style
.left
= 0;
4692 option("tabindex", null, function(cm
, val
) {
4693 cm
.display
.input
.tabIndex
= val
|| "";
4695 option("autofocus", null);
4697 // MODE DEFINITION AND QUERYING
4699 // Known modes, by name and by MIME
4700 var modes
= CodeMirror
.modes
= {}, mimeModes
= CodeMirror
.mimeModes
= {};
4702 // Extra arguments are stored as the mode's dependencies, which is
4703 // used by (legacy) mechanisms like loadmode.js to automatically
4704 // load a mode. (Preferred mechanism is the require/define calls.)
4705 CodeMirror
.defineMode = function(name
, mode
) {
4706 if (!CodeMirror
.defaults
.mode
&& name
!= "null") CodeMirror
.defaults
.mode
= name
;
4707 if (arguments
.length
> 2)
4708 mode
.dependencies
= Array
.prototype.slice
.call(arguments
, 2);
4712 CodeMirror
.defineMIME = function(mime
, spec
) {
4713 mimeModes
[mime
] = spec
;
4716 // Given a MIME type, a {name, ...options} config object, or a name
4717 // string, return a mode config object.
4718 CodeMirror
.resolveMode = function(spec
) {
4719 if (typeof spec
== "string" && mimeModes
.hasOwnProperty(spec
)) {
4720 spec
= mimeModes
[spec
];
4721 } else if (spec
&& typeof spec
.name
== "string" && mimeModes
.hasOwnProperty(spec
.name
)) {
4722 var found
= mimeModes
[spec
.name
];
4723 if (typeof found
== "string") found
= {name
: found
};
4724 spec
= createObj(found
, spec
);
4725 spec
.name
= found
.name
;
4726 } else if (typeof spec
== "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec
)) {
4727 return CodeMirror
.resolveMode("application/xml");
4729 if (typeof spec
== "string") return {name
: spec
};
4730 else return spec
|| {name
: "null"};
4733 // Given a mode spec (anything that resolveMode accepts), find and
4734 // initialize an actual mode object.
4735 CodeMirror
.getMode = function(options
, spec
) {
4736 var spec
= CodeMirror
.resolveMode(spec
);
4737 var mfactory
= modes
[spec
.name
];
4738 if (!mfactory
) return CodeMirror
.getMode(options
, "text/plain");
4739 var modeObj
= mfactory(options
, spec
);
4740 if (modeExtensions
.hasOwnProperty(spec
.name
)) {
4741 var exts
= modeExtensions
[spec
.name
];
4742 for (var prop
in exts
) {
4743 if (!exts
.hasOwnProperty(prop
)) continue;
4744 if (modeObj
.hasOwnProperty(prop
)) modeObj
["_" + prop
] = modeObj
[prop
];
4745 modeObj
[prop
] = exts
[prop
];
4748 modeObj
.name
= spec
.name
;
4749 if (spec
.helperType
) modeObj
.helperType
= spec
.helperType
;
4750 if (spec
.modeProps
) for (var prop
in spec
.modeProps
)
4751 modeObj
[prop
] = spec
.modeProps
[prop
];
4756 // Minimal default mode.
4757 CodeMirror
.defineMode("null", function() {
4758 return {token: function(stream
) {stream
.skipToEnd();}};
4760 CodeMirror
.defineMIME("text/plain", "null");
4762 // This can be used to attach properties to mode objects from
4763 // outside the actual mode definition.
4764 var modeExtensions
= CodeMirror
.modeExtensions
= {};
4765 CodeMirror
.extendMode = function(mode
, properties
) {
4766 var exts
= modeExtensions
.hasOwnProperty(mode
) ? modeExtensions
[mode
] : (modeExtensions
[mode
] = {});
4767 copyObj(properties
, exts
);
4772 CodeMirror
.defineExtension = function(name
, func
) {
4773 CodeMirror
.prototype[name
] = func
;
4775 CodeMirror
.defineDocExtension = function(name
, func
) {
4776 Doc
.prototype[name
] = func
;
4778 CodeMirror
.defineOption
= option
;
4781 CodeMirror
.defineInitHook = function(f
) {initHooks
.push(f
);};
4783 var helpers
= CodeMirror
.helpers
= {};
4784 CodeMirror
.registerHelper = function(type
, name
, value
) {
4785 if (!helpers
.hasOwnProperty(type
)) helpers
[type
] = CodeMirror
[type
] = {_global
: []};
4786 helpers
[type
][name
] = value
;
4788 CodeMirror
.registerGlobalHelper = function(type
, name
, predicate
, value
) {
4789 CodeMirror
.registerHelper(type
, name
, value
);
4790 helpers
[type
]._global
.push({pred
: predicate
, val
: value
});
4793 // MODE STATE HANDLING
4795 // Utility functions for working with state. Exported because nested
4796 // modes need to do this for their inner modes.
4798 var copyState
= CodeMirror
.copyState = function(mode
, state
) {
4799 if (state
=== true) return state
;
4800 if (mode
.copyState
) return mode
.copyState(state
);
4802 for (var n
in state
) {
4804 if (val
instanceof Array
) val
= val
.concat([]);
4810 var startState
= CodeMirror
.startState = function(mode
, a1
, a2
) {
4811 return mode
.startState
? mode
.startState(a1
, a2
) : true;
4814 // Given a mode and a state (for that mode), find the inner mode and
4815 // state at the position that the state refers to.
4816 CodeMirror
.innerMode = function(mode
, state
) {
4817 while (mode
.innerMode
) {
4818 var info
= mode
.innerMode(state
);
4819 if (!info
|| info
.mode
== mode
) break;
4823 return info
|| {mode
: mode
, state
: state
};
4826 // STANDARD COMMANDS
4828 // Commands are parameter-less actions that can be performed on an
4829 // editor, mostly used for keybindings.
4830 var commands
= CodeMirror
.commands
= {
4831 selectAll: function(cm
) {cm
.setSelection(Pos(cm
.firstLine(), 0), Pos(cm
.lastLine()), sel_dontScroll
);},
4832 singleSelection: function(cm
) {
4833 cm
.setSelection(cm
.getCursor("anchor"), cm
.getCursor("head"), sel_dontScroll
);
4835 killLine: function(cm
) {
4836 deleteNearSelection(cm
, function(range
) {
4837 if (range
.empty()) {
4838 var len
= getLine(cm
.doc
, range
.head
.line
).text
.length
;
4839 if (range
.head
.ch
== len
&& range
.head
.line
< cm
.lastLine())
4840 return {from: range
.head
, to
: Pos(range
.head
.line
+ 1, 0)};
4842 return {from: range
.head
, to
: Pos(range
.head
.line
, len
)};
4844 return {from: range
.from(), to
: range
.to()};
4848 deleteLine: function(cm
) {
4849 deleteNearSelection(cm
, function(range
) {
4850 return {from: Pos(range
.from().line
, 0),
4851 to
: clipPos(cm
.doc
, Pos(range
.to().line
+ 1, 0))};
4854 delLineLeft: function(cm
) {
4855 deleteNearSelection(cm
, function(range
) {
4856 return {from: Pos(range
.from().line
, 0), to
: range
.from()};
4859 delWrappedLineLeft: function(cm
) {
4860 deleteNearSelection(cm
, function(range
) {
4861 var top
= cm
.charCoords(range
.head
, "div").top
+ 5;
4862 var leftPos
= cm
.coordsChar({left
: 0, top
: top
}, "div");
4863 return {from: leftPos
, to
: range
.from()};
4866 delWrappedLineRight: function(cm
) {
4867 deleteNearSelection(cm
, function(range
) {
4868 var top
= cm
.charCoords(range
.head
, "div").top
+ 5;
4869 var rightPos
= cm
.coordsChar({left
: cm
.display
.lineDiv
.offsetWidth
+ 100, top
: top
}, "div");
4870 return {from: range
.from(), to
: rightPos
};
4873 undo: function(cm
) {cm
.undo();},
4874 redo: function(cm
) {cm
.redo();},
4875 undoSelection: function(cm
) {cm
.undoSelection();},
4876 redoSelection: function(cm
) {cm
.redoSelection();},
4877 goDocStart: function(cm
) {cm
.extendSelection(Pos(cm
.firstLine(), 0));},
4878 goDocEnd: function(cm
) {cm
.extendSelection(Pos(cm
.lastLine()));},
4879 goLineStart: function(cm
) {
4880 cm
.extendSelectionsBy(function(range
) { return lineStart(cm
, range
.head
.line
); },
4881 {origin
: "+move", bias
: 1});
4883 goLineStartSmart: function(cm
) {
4884 cm
.extendSelectionsBy(function(range
) {
4885 return lineStartSmart(cm
, range
.head
);
4886 }, {origin
: "+move", bias
: 1});
4888 goLineEnd: function(cm
) {
4889 cm
.extendSelectionsBy(function(range
) { return lineEnd(cm
, range
.head
.line
); },
4890 {origin
: "+move", bias
: -1});
4892 goLineRight: function(cm
) {
4893 cm
.extendSelectionsBy(function(range
) {
4894 var top
= cm
.charCoords(range
.head
, "div").top
+ 5;
4895 return cm
.coordsChar({left
: cm
.display
.lineDiv
.offsetWidth
+ 100, top
: top
}, "div");
4898 goLineLeft: function(cm
) {
4899 cm
.extendSelectionsBy(function(range
) {
4900 var top
= cm
.charCoords(range
.head
, "div").top
+ 5;
4901 return cm
.coordsChar({left
: 0, top
: top
}, "div");
4904 goLineLeftSmart: function(cm
) {
4905 cm
.extendSelectionsBy(function(range
) {
4906 var top
= cm
.charCoords(range
.head
, "div").top
+ 5;
4907 var pos
= cm
.coordsChar({left
: 0, top
: top
}, "div");
4908 if (pos
.ch
< cm
.getLine(pos
.line
).search(/\S/)) return lineStartSmart(cm
, range
.head
);
4912 goLineUp: function(cm
) {cm
.moveV(-1, "line");},
4913 goLineDown: function(cm
) {cm
.moveV(1, "line");},
4914 goPageUp: function(cm
) {cm
.moveV(-1, "page");},
4915 goPageDown: function(cm
) {cm
.moveV(1, "page");},
4916 goCharLeft: function(cm
) {cm
.moveH(-1, "char");},
4917 goCharRight: function(cm
) {cm
.moveH(1, "char");},
4918 goColumnLeft: function(cm
) {cm
.moveH(-1, "column");},
4919 goColumnRight: function(cm
) {cm
.moveH(1, "column");},
4920 goWordLeft: function(cm
) {cm
.moveH(-1, "word");},
4921 goGroupRight: function(cm
) {cm
.moveH(1, "group");},
4922 goGroupLeft: function(cm
) {cm
.moveH(-1, "group");},
4923 goWordRight: function(cm
) {cm
.moveH(1, "word");},
4924 delCharBefore: function(cm
) {cm
.deleteH(-1, "char");},
4925 delCharAfter: function(cm
) {cm
.deleteH(1, "char");},
4926 delWordBefore: function(cm
) {cm
.deleteH(-1, "word");},
4927 delWordAfter: function(cm
) {cm
.deleteH(1, "word");},
4928 delGroupBefore: function(cm
) {cm
.deleteH(-1, "group");},
4929 delGroupAfter: function(cm
) {cm
.deleteH(1, "group");},
4930 indentAuto: function(cm
) {cm
.indentSelection("smart");},
4931 indentMore: function(cm
) {cm
.indentSelection("add");},
4932 indentLess: function(cm
) {cm
.indentSelection("subtract");},
4933 insertTab: function(cm
) {cm
.replaceSelection("\t");},
4934 insertSoftTab: function(cm
) {
4935 var spaces
= [], ranges
= cm
.listSelections(), tabSize
= cm
.options
.tabSize
;
4936 for (var i
= 0; i
< ranges
.length
; i
++) {
4937 var pos
= ranges
[i
].from();
4938 var col
= countColumn(cm
.getLine(pos
.line
), pos
.ch
, tabSize
);
4939 spaces
.push(new Array(tabSize
- col
% tabSize
+ 1).join(" "));
4941 cm
.replaceSelections(spaces
);
4943 defaultTab: function(cm
) {
4944 if (cm
.somethingSelected()) cm
.indentSelection("add");
4945 else cm
.execCommand("insertTab");
4947 transposeChars: function(cm
) {
4948 runInOp(cm
, function() {
4949 var ranges
= cm
.listSelections(), newSel
= [];
4950 for (var i
= 0; i
< ranges
.length
; i
++) {
4951 var cur
= ranges
[i
].head
, line
= getLine(cm
.doc
, cur
.line
).text
;
4953 if (cur
.ch
== line
.length
) cur
= new Pos(cur
.line
, cur
.ch
- 1);
4955 cur
= new Pos(cur
.line
, cur
.ch
+ 1);
4956 cm
.replaceRange(line
.charAt(cur
.ch
- 1) + line
.charAt(cur
.ch
- 2),
4957 Pos(cur
.line
, cur
.ch
- 2), cur
, "+transpose");
4958 } else if (cur
.line
> cm
.doc
.first
) {
4959 var prev
= getLine(cm
.doc
, cur
.line
- 1).text
;
4961 cm
.replaceRange(line
.charAt(0) + "\n" + prev
.charAt(prev
.length
- 1),
4962 Pos(cur
.line
- 1, prev
.length
- 1), Pos(cur
.line
, 1), "+transpose");
4965 newSel
.push(new Range(cur
, cur
));
4967 cm
.setSelections(newSel
);
4970 newlineAndIndent: function(cm
) {
4971 runInOp(cm
, function() {
4972 var len
= cm
.listSelections().length
;
4973 for (var i
= 0; i
< len
; i
++) {
4974 var range
= cm
.listSelections()[i
];
4975 cm
.replaceRange("\n", range
.anchor
, range
.head
, "+input");
4976 cm
.indentLine(range
.from().line
+ 1, null, true);
4977 ensureCursorVisible(cm
);
4981 toggleOverwrite: function(cm
) {cm
.toggleOverwrite();}
4987 var keyMap
= CodeMirror
.keyMap
= {};
4990 "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
4991 "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
4992 "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
4993 "Tab": "defaultTab", "Shift-Tab": "indentAuto",
4994 "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
4995 "Esc": "singleSelection"
4997 // Note that the save and find-related commands aren't defined by
4998 // default. User code or addons can define them. Unknown commands
4999 // are simply ignored.
5000 keyMap
.pcDefault
= {
5001 "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
5002 "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
5003 "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
5004 "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
5005 "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
5006 "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
5007 "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
5008 fallthrough
: "basic"
5010 // Very basic readline/emacs-style bindings, which are standard on Mac.
5012 "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
5013 "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
5014 "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
5015 "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
5017 keyMap
.macDefault
= {
5018 "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
5019 "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
5020 "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
5021 "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
5022 "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
5023 "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
5024 "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
5025 fallthrough
: ["basic", "emacsy"]
5027 keyMap
["default"] = mac
? keyMap
.macDefault
: keyMap
.pcDefault
;
5031 function normalizeKeyName(name
) {
5032 var parts
= name
.split(/-(?!$)/), name
= parts
[parts
.length
- 1];
5033 var alt
, ctrl
, shift
, cmd
;
5034 for (var i
= 0; i
< parts
.length
- 1; i
++) {
5036 if (/^(cmd|meta|m)$/i.test(mod
)) cmd
= true;
5037 else if (/^a(lt)?$/i.test(mod
)) alt
= true;
5038 else if (/^(c|ctrl|control)$/i.test(mod
)) ctrl
= true;
5039 else if (/^s(hift)$/i.test(mod
)) shift
= true;
5040 else throw new Error("Unrecognized modifier name: " + mod
);
5042 if (alt
) name
= "Alt-" + name
;
5043 if (ctrl
) name
= "Ctrl-" + name
;
5044 if (cmd
) name
= "Cmd-" + name
;
5045 if (shift
) name
= "Shift-" + name
;
5049 // This is a kludge to keep keymaps mostly working as raw objects
5050 // (backwards compatibility) while at the same time support features
5051 // like normalization and multi-stroke key bindings. It compiles a
5052 // new normalized keymap, and then updates the old object to reflect
5054 CodeMirror
.normalizeKeyMap = function(keymap
) {
5056 for (var keyname
in keymap
) if (keymap
.hasOwnProperty(keyname
)) {
5057 var value
= keymap
[keyname
];
5058 if (/^(name|fallthrough|(de|at)tach)$/.test(keyname
)) continue;
5059 if (value
== "...") { delete keymap
[keyname
]; continue; }
5061 var keys
= map(keyname
.split(" "), normalizeKeyName
);
5062 for (var i
= 0; i
< keys
.length
; i
++) {
5064 if (i
== keys
.length
- 1) {
5068 name
= keys
.slice(0, i
+ 1).join(" ");
5071 var prev
= copy
[name
];
5072 if (!prev
) copy
[name
] = val
;
5073 else if (prev
!= val
) throw new Error("Inconsistent bindings for " + name
);
5075 delete keymap
[keyname
];
5077 for (var prop
in copy
) keymap
[prop
] = copy
[prop
];
5081 var lookupKey
= CodeMirror
.lookupKey = function(key
, map
, handle
, context
) {
5082 map
= getKeyMap(map
);
5083 var found
= map
.call
? map
.call(key
, context
) : map
[key
];
5084 if (found
=== false) return "nothing";
5085 if (found
=== "...") return "multi";
5086 if (found
!= null && handle(found
)) return "handled";
5088 if (map
.fallthrough
) {
5089 if (Object
.prototype.toString
.call(map
.fallthrough
) != "[object Array]")
5090 return lookupKey(key
, map
.fallthrough
, handle
, context
);
5091 for (var i
= 0; i
< map
.fallthrough
.length
; i
++) {
5092 var result
= lookupKey(key
, map
.fallthrough
[i
], handle
, context
);
5093 if (result
) return result
;
5098 // Modifier key presses don't count as 'real' key presses for the
5099 // purpose of keymap fallthrough.
5100 var isModifierKey
= CodeMirror
.isModifierKey = function(value
) {
5101 var name
= typeof value
== "string" ? value
: keyNames
[value
.keyCode
];
5102 return name
== "Ctrl" || name
== "Alt" || name
== "Shift" || name
== "Mod";
5105 // Look up the name of a key as indicated by an event object.
5106 var keyName
= CodeMirror
.keyName = function(event
, noShift
) {
5107 if (presto
&& event
.keyCode
== 34 && event
["char"]) return false;
5108 var base
= keyNames
[event
.keyCode
], name
= base
;
5109 if (name
== null || event
.altGraphKey
) return false;
5110 if (event
.altKey
&& base
!= "Alt") name
= "Alt-" + name
;
5111 if ((flipCtrlCmd
? event
.metaKey
: event
.ctrlKey
) && base
!= "Ctrl") name
= "Ctrl-" + name
;
5112 if ((flipCtrlCmd
? event
.ctrlKey
: event
.metaKey
) && base
!= "Cmd") name
= "Cmd-" + name
;
5113 if (!noShift
&& event
.shiftKey
&& base
!= "Shift") name
= "Shift-" + name
;
5117 function getKeyMap(val
) {
5118 return typeof val
== "string" ? keyMap
[val
] : val
;
5123 CodeMirror
.fromTextArea = function(textarea
, options
) {
5124 if (!options
) options
= {};
5125 options
.value
= textarea
.value
;
5126 if (!options
.tabindex
&& textarea
.tabindex
)
5127 options
.tabindex
= textarea
.tabindex
;
5128 if (!options
.placeholder
&& textarea
.placeholder
)
5129 options
.placeholder
= textarea
.placeholder
;
5130 // Set autofocus to true if this textarea is focused, or if it has
5131 // autofocus and no other element is focused.
5132 if (options
.autofocus
== null) {
5133 var hasFocus
= activeElt();
5134 options
.autofocus
= hasFocus
== textarea
||
5135 textarea
.getAttribute("autofocus") != null && hasFocus
== document
.body
;
5138 function save() {textarea
.value
= cm
.getValue();}
5139 if (textarea
.form
) {
5140 on(textarea
.form
, "submit", save
);
5141 // Deplorable hack to make the submit method do the right thing.
5142 if (!options
.leaveSubmitMethodAlone
) {
5143 var form
= textarea
.form
, realSubmit
= form
.submit
;
5145 var wrappedSubmit
= form
.submit = function() {
5147 form
.submit
= realSubmit
;
5149 form
.submit
= wrappedSubmit
;
5155 textarea
.style
.display
= "none";
5156 var cm
= CodeMirror(function(node
) {
5157 textarea
.parentNode
.insertBefore(node
, textarea
.nextSibling
);
5160 cm
.getTextArea = function() { return textarea
; };
5161 cm
.toTextArea = function() {
5162 cm
.toTextArea
= isNaN
; // Prevent this from being ran twice
5164 textarea
.parentNode
.removeChild(cm
.getWrapperElement());
5165 textarea
.style
.display
= "";
5166 if (textarea
.form
) {
5167 off(textarea
.form
, "submit", save
);
5168 if (typeof textarea
.form
.submit
== "function")
5169 textarea
.form
.submit
= realSubmit
;
5177 // Fed to the mode parsers, provides helper functions to make
5178 // parsers more succinct.
5180 var StringStream
= CodeMirror
.StringStream = function(string
, tabSize
) {
5181 this.pos
= this.start
= 0;
5182 this.string
= string
;
5183 this.tabSize
= tabSize
|| 8;
5184 this.lastColumnPos
= this.lastColumnValue
= 0;
5188 StringStream
.prototype = {
5189 eol: function() {return this.pos
>= this.string
.length
;},
5190 sol: function() {return this.pos
== this.lineStart
;},
5191 peek: function() {return this.string
.charAt(this.pos
) || undefined;},
5193 if (this.pos
< this.string
.length
)
5194 return this.string
.charAt(this.pos
++);
5196 eat: function(match
) {
5197 var ch
= this.string
.charAt(this.pos
);
5198 if (typeof match
== "string") var ok
= ch
== match
;
5199 else var ok
= ch
&& (match
.test
? match
.test(ch
) : match(ch
));
5200 if (ok
) {++this.pos
; return ch
;}
5202 eatWhile: function(match
) {
5203 var start
= this.pos
;
5204 while (this.eat(match
)){}
5205 return this.pos
> start
;
5207 eatSpace: function() {
5208 var start
= this.pos
;
5209 while (/[\s\u00a0]/.test(this.string
.charAt(this.pos
))) ++this.pos
;
5210 return this.pos
> start
;
5212 skipToEnd: function() {this.pos
= this.string
.length
;},
5213 skipTo: function(ch
) {
5214 var found
= this.string
.indexOf(ch
, this.pos
);
5215 if (found
> -1) {this.pos
= found
; return true;}
5217 backUp: function(n
) {this.pos
-= n
;},
5218 column: function() {
5219 if (this.lastColumnPos
< this.start
) {
5220 this.lastColumnValue
= countColumn(this.string
, this.start
, this.tabSize
, this.lastColumnPos
, this.lastColumnValue
);
5221 this.lastColumnPos
= this.start
;
5223 return this.lastColumnValue
- (this.lineStart
? countColumn(this.string
, this.lineStart
, this.tabSize
) : 0);
5225 indentation: function() {
5226 return countColumn(this.string
, null, this.tabSize
) -
5227 (this.lineStart
? countColumn(this.string
, this.lineStart
, this.tabSize
) : 0);
5229 match: function(pattern
, consume
, caseInsensitive
) {
5230 if (typeof pattern
== "string") {
5231 var cased = function(str
) {return caseInsensitive
? str
.toLowerCase() : str
;};
5232 var substr
= this.string
.substr(this.pos
, pattern
.length
);
5233 if (cased(substr
) == cased(pattern
)) {
5234 if (consume
!== false) this.pos
+= pattern
.length
;
5238 var match
= this.string
.slice(this.pos
).match(pattern
);
5239 if (match
&& match
.index
> 0) return null;
5240 if (match
&& consume
!== false) this.pos
+= match
[0].length
;
5244 current: function(){return this.string
.slice(this.start
, this.pos
);},
5245 hideFirstChars: function(n
, inner
) {
5246 this.lineStart
+= n
;
5247 try { return inner(); }
5248 finally { this.lineStart
-= n
; }
5254 // Created with markText and setBookmark methods. A TextMarker is a
5255 // handle that can be used to clear or find a marked position in the
5256 // document. Line objects hold arrays (markedSpans) containing
5257 // {from, to, marker} object pointing to such marker objects, and
5258 // indicating that such a marker is present on that line. Multiple
5259 // lines may point to the same marker when it spans across lines.
5260 // The spans will have null for their from/to properties when the
5261 // marker continues beyond the start/end of the line. Markers have
5262 // links back to the lines they currently touch.
5264 var TextMarker
= CodeMirror
.TextMarker = function(doc
, type
) {
5269 eventMixin(TextMarker
);
5271 // Clear the marker.
5272 TextMarker
.prototype.clear = function() {
5273 if (this.explicitlyCleared
) return;
5274 var cm
= this.doc
.cm
, withOp
= cm
&& !cm
.curOp
;
5275 if (withOp
) startOperation(cm
);
5276 if (hasHandler(this, "clear")) {
5277 var found
= this.find();
5278 if (found
) signalLater(this, "clear", found
.from, found
.to
);
5280 var min
= null, max
= null;
5281 for (var i
= 0; i
< this.lines
.length
; ++i
) {
5282 var line
= this.lines
[i
];
5283 var span
= getMarkedSpanFor(line
.markedSpans
, this);
5284 if (cm
&& !this.collapsed
) regLineChange(cm
, lineNo(line
), "text");
5286 if (span
.to
!= null) max
= lineNo(line
);
5287 if (span
.from != null) min
= lineNo(line
);
5289 line
.markedSpans
= removeMarkedSpan(line
.markedSpans
, span
);
5290 if (span
.from == null && this.collapsed
&& !lineIsHidden(this.doc
, line
) && cm
)
5291 updateLineHeight(line
, textHeight(cm
.display
));
5293 if (cm
&& this.collapsed
&& !cm
.options
.lineWrapping
) for (var i
= 0; i
< this.lines
.length
; ++i
) {
5294 var visual
= visualLine(this.lines
[i
]), len
= lineLength(visual
);
5295 if (len
> cm
.display
.maxLineLength
) {
5296 cm
.display
.maxLine
= visual
;
5297 cm
.display
.maxLineLength
= len
;
5298 cm
.display
.maxLineChanged
= true;
5302 if (min
!= null && cm
&& this.collapsed
) regChange(cm
, min
, max
+ 1);
5303 this.lines
.length
= 0;
5304 this.explicitlyCleared
= true;
5305 if (this.atomic
&& this.doc
.cantEdit
) {
5306 this.doc
.cantEdit
= false;
5307 if (cm
) reCheckSelection(cm
.doc
);
5309 if (cm
) signalLater(cm
, "markerCleared", cm
, this);
5310 if (withOp
) endOperation(cm
);
5311 if (this.parent
) this.parent
.clear();
5314 // Find the position of the marker in the document. Returns a {from,
5315 // to} object by default. Side can be passed to get a specific side
5316 // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
5317 // Pos objects returned contain a line object, rather than a line
5318 // number (used to prevent looking up the same line twice).
5319 TextMarker
.prototype.find = function(side
, lineObj
) {
5320 if (side
== null && this.type
== "bookmark") side
= 1;
5322 for (var i
= 0; i
< this.lines
.length
; ++i
) {
5323 var line
= this.lines
[i
];
5324 var span
= getMarkedSpanFor(line
.markedSpans
, this);
5325 if (span
.from != null) {
5326 from = Pos(lineObj
? line
: lineNo(line
), span
.from);
5327 if (side
== -1) return from;
5329 if (span
.to
!= null) {
5330 to
= Pos(lineObj
? line
: lineNo(line
), span
.to
);
5331 if (side
== 1) return to
;
5334 return from && {from: from, to
: to
};
5337 // Signals that the marker's widget changed, and surrounding layout
5338 // should be recomputed.
5339 TextMarker
.prototype.changed = function() {
5340 var pos
= this.find(-1, true), widget
= this, cm
= this.doc
.cm
;
5341 if (!pos
|| !cm
) return;
5342 runInOp(cm
, function() {
5343 var line
= pos
.line
, lineN
= lineNo(pos
.line
);
5344 var view
= findViewForLine(cm
, lineN
);
5346 clearLineMeasurementCacheFor(view
);
5347 cm
.curOp
.selectionChanged
= cm
.curOp
.forceUpdate
= true;
5349 cm
.curOp
.updateMaxLine
= true;
5350 if (!lineIsHidden(widget
.doc
, line
) && widget
.height
!= null) {
5351 var oldHeight
= widget
.height
;
5352 widget
.height
= null;
5353 var dHeight
= widgetHeight(widget
) - oldHeight
;
5355 updateLineHeight(line
, line
.height
+ dHeight
);
5360 TextMarker
.prototype.attachLine = function(line
) {
5361 if (!this.lines
.length
&& this.doc
.cm
) {
5362 var op
= this.doc
.cm
.curOp
;
5363 if (!op
.maybeHiddenMarkers
|| indexOf(op
.maybeHiddenMarkers
, this) == -1)
5364 (op
.maybeUnhiddenMarkers
|| (op
.maybeUnhiddenMarkers
= [])).push(this);
5366 this.lines
.push(line
);
5368 TextMarker
.prototype.detachLine = function(line
) {
5369 this.lines
.splice(indexOf(this.lines
, line
), 1);
5370 if (!this.lines
.length
&& this.doc
.cm
) {
5371 var op
= this.doc
.cm
.curOp
;
5372 (op
.maybeHiddenMarkers
|| (op
.maybeHiddenMarkers
= [])).push(this);
5376 // Collapsed markers have unique ids, in order to be able to order
5377 // them, which is needed for uniquely determining an outer marker
5378 // when they overlap (they may nest, but not partially overlap).
5379 var nextMarkerId
= 0;
5381 // Create a marker, wire it up to the right lines, and
5382 function markText(doc
, from, to
, options
, type
) {
5383 // Shared markers (across linked documents) are handled separately
5384 // (markTextShared will call out to this again, once per
5386 if (options
&& options
.shared
) return markTextShared(doc
, from, to
, options
, type
);
5387 // Ensure we are in an operation.
5388 if (doc
.cm
&& !doc
.cm
.curOp
) return operation(doc
.cm
, markText
)(doc
, from, to
, options
, type
);
5390 var marker
= new TextMarker(doc
, type
), diff
= cmp(from, to
);
5391 if (options
) copyObj(options
, marker
, false);
5392 // Don't connect empty markers unless clearWhenEmpty is false
5393 if (diff
> 0 || diff
== 0 && marker
.clearWhenEmpty
!== false)
5395 if (marker
.replacedWith
) {
5396 // Showing up as a widget implies collapsed (widget replaces text)
5397 marker
.collapsed
= true;
5398 marker
.widgetNode
= elt("span", [marker
.replacedWith
], "CodeMirror-widget");
5399 if (!options
.handleMouseEvents
) marker
.widgetNode
.setAttribute("cm-ignore-events", "true");
5400 if (options
.insertLeft
) marker
.widgetNode
.insertLeft
= true;
5402 if (marker
.collapsed
) {
5403 if (conflictingCollapsedRange(doc
, from.line
, from, to
, marker
) ||
5404 from.line
!= to
.line
&& conflictingCollapsedRange(doc
, to
.line
, from, to
, marker
))
5405 throw new Error("Inserting collapsed marker partially overlapping an existing one");
5406 sawCollapsedSpans
= true;
5409 if (marker
.addToHistory
)
5410 addChangeToHistory(doc
, {from: from, to
: to
, origin
: "markText"}, doc
.sel
, NaN
);
5412 var curLine
= from.line
, cm
= doc
.cm
, updateMaxLine
;
5413 doc
.iter(curLine
, to
.line
+ 1, function(line
) {
5414 if (cm
&& marker
.collapsed
&& !cm
.options
.lineWrapping
&& visualLine(line
) == cm
.display
.maxLine
)
5415 updateMaxLine
= true;
5416 if (marker
.collapsed
&& curLine
!= from.line
) updateLineHeight(line
, 0);
5417 addMarkedSpan(line
, new MarkedSpan(marker
,
5418 curLine
== from.line
? from.ch
: null,
5419 curLine
== to
.line
? to
.ch
: null));
5422 // lineIsHidden depends on the presence of the spans, so needs a second pass
5423 if (marker
.collapsed
) doc
.iter(from.line
, to
.line
+ 1, function(line
) {
5424 if (lineIsHidden(doc
, line
)) updateLineHeight(line
, 0);
5427 if (marker
.clearOnEnter
) on(marker
, "beforeCursorEnter", function() { marker
.clear(); });
5429 if (marker
.readOnly
) {
5430 sawReadOnlySpans
= true;
5431 if (doc
.history
.done
.length
|| doc
.history
.undone
.length
)
5434 if (marker
.collapsed
) {
5435 marker
.id
= ++nextMarkerId
;
5436 marker
.atomic
= true;
5439 // Sync editor state
5440 if (updateMaxLine
) cm
.curOp
.updateMaxLine
= true;
5441 if (marker
.collapsed
)
5442 regChange(cm
, from.line
, to
.line
+ 1);
5443 else if (marker
.className
|| marker
.title
|| marker
.startStyle
|| marker
.endStyle
|| marker
.css
)
5444 for (var i
= from.line
; i
<= to
.line
; i
++) regLineChange(cm
, i
, "text");
5445 if (marker
.atomic
) reCheckSelection(cm
.doc
);
5446 signalLater(cm
, "markerAdded", cm
, marker
);
5451 // SHARED TEXTMARKERS
5453 // A shared marker spans multiple linked documents. It is
5454 // implemented as a meta-marker-object controlling multiple normal
5456 var SharedTextMarker
= CodeMirror
.SharedTextMarker = function(markers
, primary
) {
5457 this.markers
= markers
;
5458 this.primary
= primary
;
5459 for (var i
= 0; i
< markers
.length
; ++i
)
5460 markers
[i
].parent
= this;
5462 eventMixin(SharedTextMarker
);
5464 SharedTextMarker
.prototype.clear = function() {
5465 if (this.explicitlyCleared
) return;
5466 this.explicitlyCleared
= true;
5467 for (var i
= 0; i
< this.markers
.length
; ++i
)
5468 this.markers
[i
].clear();
5469 signalLater(this, "clear");
5471 SharedTextMarker
.prototype.find = function(side
, lineObj
) {
5472 return this.primary
.find(side
, lineObj
);
5475 function markTextShared(doc
, from, to
, options
, type
) {
5476 options
= copyObj(options
);
5477 options
.shared
= false;
5478 var markers
= [markText(doc
, from, to
, options
, type
)], primary
= markers
[0];
5479 var widget
= options
.widgetNode
;
5480 linkedDocs(doc
, function(doc
) {
5481 if (widget
) options
.widgetNode
= widget
.cloneNode(true);
5482 markers
.push(markText(doc
, clipPos(doc
, from), clipPos(doc
, to
), options
, type
));
5483 for (var i
= 0; i
< doc
.linked
.length
; ++i
)
5484 if (doc
.linked
[i
].isParent
) return;
5485 primary
= lst(markers
);
5487 return new SharedTextMarker(markers
, primary
);
5490 function findSharedMarkers(doc
) {
5491 return doc
.findMarks(Pos(doc
.first
, 0), doc
.clipPos(Pos(doc
.lastLine())),
5492 function(m
) { return m
.parent
; });
5495 function copySharedMarkers(doc
, markers
) {
5496 for (var i
= 0; i
< markers
.length
; i
++) {
5497 var marker
= markers
[i
], pos
= marker
.find();
5498 var mFrom
= doc
.clipPos(pos
.from), mTo
= doc
.clipPos(pos
.to
);
5499 if (cmp(mFrom
, mTo
)) {
5500 var subMark
= markText(doc
, mFrom
, mTo
, marker
.primary
, marker
.primary
.type
);
5501 marker
.markers
.push(subMark
);
5502 subMark
.parent
= marker
;
5507 function detachSharedMarkers(markers
) {
5508 for (var i
= 0; i
< markers
.length
; i
++) {
5509 var marker
= markers
[i
], linked
= [marker
.primary
.doc
];;
5510 linkedDocs(marker
.primary
.doc
, function(d
) { linked
.push(d
); });
5511 for (var j
= 0; j
< marker
.markers
.length
; j
++) {
5512 var subMarker
= marker
.markers
[j
];
5513 if (indexOf(linked
, subMarker
.doc
) == -1) {
5514 subMarker
.parent
= null;
5515 marker
.markers
.splice(j
--, 1);
5523 function MarkedSpan(marker
, from, to
) {
5524 this.marker
= marker
;
5525 this.from = from; this.to
= to
;
5528 // Search an array of spans for a span matching the given marker.
5529 function getMarkedSpanFor(spans
, marker
) {
5530 if (spans
) for (var i
= 0; i
< spans
.length
; ++i
) {
5531 var span
= spans
[i
];
5532 if (span
.marker
== marker
) return span
;
5535 // Remove a span from an array, returning undefined if no spans are
5536 // left (we don't store arrays for lines without spans).
5537 function removeMarkedSpan(spans
, span
) {
5538 for (var r
, i
= 0; i
< spans
.length
; ++i
)
5539 if (spans
[i
] != span
) (r
|| (r
= [])).push(spans
[i
]);
5542 // Add a span to a line.
5543 function addMarkedSpan(line
, span
) {
5544 line
.markedSpans
= line
.markedSpans
? line
.markedSpans
.concat([span
]) : [span
];
5545 span
.marker
.attachLine(line
);
5548 // Used for the algorithm that adjusts markers for a change in the
5549 // document. These functions cut an array of spans at a given
5550 // character position, returning an array of remaining chunks (or
5551 // undefined if nothing remains).
5552 function markedSpansBefore(old
, startCh
, isInsert
) {
5553 if (old
) for (var i
= 0, nw
; i
< old
.length
; ++i
) {
5554 var span
= old
[i
], marker
= span
.marker
;
5555 var startsBefore
= span
.from == null || (marker
.inclusiveLeft
? span
.from <= startCh
: span
.from < startCh
);
5556 if (startsBefore
|| span
.from == startCh
&& marker
.type
== "bookmark" && (!isInsert
|| !span
.marker
.insertLeft
)) {
5557 var endsAfter
= span
.to
== null || (marker
.inclusiveRight
? span
.to
>= startCh
: span
.to
> startCh
);
5558 (nw
|| (nw
= [])).push(new MarkedSpan(marker
, span
.from, endsAfter
? null : span
.to
));
5563 function markedSpansAfter(old
, endCh
, isInsert
) {
5564 if (old
) for (var i
= 0, nw
; i
< old
.length
; ++i
) {
5565 var span
= old
[i
], marker
= span
.marker
;
5566 var endsAfter
= span
.to
== null || (marker
.inclusiveRight
? span
.to
>= endCh
: span
.to
> endCh
);
5567 if (endsAfter
|| span
.from == endCh
&& marker
.type
== "bookmark" && (!isInsert
|| span
.marker
.insertLeft
)) {
5568 var startsBefore
= span
.from == null || (marker
.inclusiveLeft
? span
.from <= endCh
: span
.from < endCh
);
5569 (nw
|| (nw
= [])).push(new MarkedSpan(marker
, startsBefore
? null : span
.from - endCh
,
5570 span
.to
== null ? null : span
.to
- endCh
));
5576 // Given a change object, compute the new set of marker spans that
5577 // cover the line in which the change took place. Removes spans
5578 // entirely within the change, reconnects spans belonging to the
5579 // same marker that appear on both sides of the change, and cuts off
5580 // spans partially within the change. Returns an array of span
5581 // arrays with one element for each line in (after) the change.
5582 function stretchSpansOverChange(doc
, change
) {
5583 if (change
.full
) return null;
5584 var oldFirst
= isLine(doc
, change
.from.line
) && getLine(doc
, change
.from.line
).markedSpans
;
5585 var oldLast
= isLine(doc
, change
.to
.line
) && getLine(doc
, change
.to
.line
).markedSpans
;
5586 if (!oldFirst
&& !oldLast
) return null;
5588 var startCh
= change
.from.ch
, endCh
= change
.to
.ch
, isInsert
= cmp(change
.from, change
.to
) == 0;
5589 // Get the spans that 'stick out' on both sides
5590 var first
= markedSpansBefore(oldFirst
, startCh
, isInsert
);
5591 var last
= markedSpansAfter(oldLast
, endCh
, isInsert
);
5593 // Next, merge those two ends
5594 var sameLine
= change
.text
.length
== 1, offset
= lst(change
.text
).length
+ (sameLine
? startCh
: 0);
5596 // Fix up .to properties of first
5597 for (var i
= 0; i
< first
.length
; ++i
) {
5598 var span
= first
[i
];
5599 if (span
.to
== null) {
5600 var found
= getMarkedSpanFor(last
, span
.marker
);
5601 if (!found
) span
.to
= startCh
;
5602 else if (sameLine
) span
.to
= found
.to
== null ? null : found
.to
+ offset
;
5607 // Fix up .from in last (or move them into first in case of sameLine)
5608 for (var i
= 0; i
< last
.length
; ++i
) {
5610 if (span
.to
!= null) span
.to
+= offset
;
5611 if (span
.from == null) {
5612 var found
= getMarkedSpanFor(first
, span
.marker
);
5615 if (sameLine
) (first
|| (first
= [])).push(span
);
5618 span
.from += offset
;
5619 if (sameLine
) (first
|| (first
= [])).push(span
);
5623 // Make sure we didn't create any zero-length spans
5624 if (first
) first
= clearEmptySpans(first
);
5625 if (last
&& last
!= first
) last
= clearEmptySpans(last
);
5627 var newMarkers
= [first
];
5629 // Fill gap with whole-line-spans
5630 var gap
= change
.text
.length
- 2, gapMarkers
;
5631 if (gap
> 0 && first
)
5632 for (var i
= 0; i
< first
.length
; ++i
)
5633 if (first
[i
].to
== null)
5634 (gapMarkers
|| (gapMarkers
= [])).push(new MarkedSpan(first
[i
].marker
, null, null));
5635 for (var i
= 0; i
< gap
; ++i
)
5636 newMarkers
.push(gapMarkers
);
5637 newMarkers
.push(last
);
5642 // Remove spans that are empty and don't have a clearWhenEmpty
5644 function clearEmptySpans(spans
) {
5645 for (var i
= 0; i
< spans
.length
; ++i
) {
5646 var span
= spans
[i
];
5647 if (span
.from != null && span
.from == span
.to
&& span
.marker
.clearWhenEmpty
!== false)
5648 spans
.splice(i
--, 1);
5650 if (!spans
.length
) return null;
5654 // Used for un/re-doing changes from the history. Combines the
5655 // result of computing the existing spans with the set of spans that
5656 // existed in the history (so that deleting around a span and then
5657 // undoing brings back the span).
5658 function mergeOldSpans(doc
, change
) {
5659 var old
= getOldSpans(doc
, change
);
5660 var stretched
= stretchSpansOverChange(doc
, change
);
5661 if (!old
) return stretched
;
5662 if (!stretched
) return old
;
5664 for (var i
= 0; i
< old
.length
; ++i
) {
5665 var oldCur
= old
[i
], stretchCur
= stretched
[i
];
5666 if (oldCur
&& stretchCur
) {
5667 spans
: for (var j
= 0; j
< stretchCur
.length
; ++j
) {
5668 var span
= stretchCur
[j
];
5669 for (var k
= 0; k
< oldCur
.length
; ++k
)
5670 if (oldCur
[k
].marker
== span
.marker
) continue spans
;
5673 } else if (stretchCur
) {
5674 old
[i
] = stretchCur
;
5680 // Used to 'clip' out readOnly ranges when making a change.
5681 function removeReadOnlyRanges(doc
, from, to
) {
5683 doc
.iter(from.line
, to
.line
+ 1, function(line
) {
5684 if (line
.markedSpans
) for (var i
= 0; i
< line
.markedSpans
.length
; ++i
) {
5685 var mark
= line
.markedSpans
[i
].marker
;
5686 if (mark
.readOnly
&& (!markers
|| indexOf(markers
, mark
) == -1))
5687 (markers
|| (markers
= [])).push(mark
);
5690 if (!markers
) return null;
5691 var parts
= [{from: from, to
: to
}];
5692 for (var i
= 0; i
< markers
.length
; ++i
) {
5693 var mk
= markers
[i
], m
= mk
.find(0);
5694 for (var j
= 0; j
< parts
.length
; ++j
) {
5696 if (cmp(p
.to
, m
.from) < 0 || cmp(p
.from, m
.to
) > 0) continue;
5697 var newParts
= [j
, 1], dfrom
= cmp(p
.from, m
.from), dto
= cmp(p
.to
, m
.to
);
5698 if (dfrom
< 0 || !mk
.inclusiveLeft
&& !dfrom
)
5699 newParts
.push({from: p
.from, to
: m
.from});
5700 if (dto
> 0 || !mk
.inclusiveRight
&& !dto
)
5701 newParts
.push({from: m
.to
, to
: p
.to
});
5702 parts
.splice
.apply(parts
, newParts
);
5703 j
+= newParts
.length
- 1;
5709 // Connect or disconnect spans from a line.
5710 function detachMarkedSpans(line
) {
5711 var spans
= line
.markedSpans
;
5713 for (var i
= 0; i
< spans
.length
; ++i
)
5714 spans
[i
].marker
.detachLine(line
);
5715 line
.markedSpans
= null;
5717 function attachMarkedSpans(line
, spans
) {
5719 for (var i
= 0; i
< spans
.length
; ++i
)
5720 spans
[i
].marker
.attachLine(line
);
5721 line
.markedSpans
= spans
;
5724 // Helpers used when computing which overlapping collapsed span
5725 // counts as the larger one.
5726 function extraLeft(marker
) { return marker
.inclusiveLeft
? -1 : 0; }
5727 function extraRight(marker
) { return marker
.inclusiveRight
? 1 : 0; }
5729 // Returns a number indicating which of two overlapping collapsed
5730 // spans is larger (and thus includes the other). Falls back to
5731 // comparing ids when the spans cover exactly the same range.
5732 function compareCollapsedMarkers(a
, b
) {
5733 var lenDiff
= a
.lines
.length
- b
.lines
.length
;
5734 if (lenDiff
!= 0) return lenDiff
;
5735 var aPos
= a
.find(), bPos
= b
.find();
5736 var fromCmp
= cmp(aPos
.from, bPos
.from) || extraLeft(a
) - extraLeft(b
);
5737 if (fromCmp
) return -fromCmp
;
5738 var toCmp
= cmp(aPos
.to
, bPos
.to
) || extraRight(a
) - extraRight(b
);
5739 if (toCmp
) return toCmp
;
5743 // Find out whether a line ends or starts in a collapsed span. If
5744 // so, return the marker for that span.
5745 function collapsedSpanAtSide(line
, start
) {
5746 var sps
= sawCollapsedSpans
&& line
.markedSpans
, found
;
5747 if (sps
) for (var sp
, i
= 0; i
< sps
.length
; ++i
) {
5749 if (sp
.marker
.collapsed
&& (start
? sp
.from : sp
.to
) == null &&
5750 (!found
|| compareCollapsedMarkers(found
, sp
.marker
) < 0))
5755 function collapsedSpanAtStart(line
) { return collapsedSpanAtSide(line
, true); }
5756 function collapsedSpanAtEnd(line
) { return collapsedSpanAtSide(line
, false); }
5758 // Test whether there exists a collapsed span that partially
5759 // overlaps (covers the start or end, but not both) of a new span.
5760 // Such overlap is not allowed.
5761 function conflictingCollapsedRange(doc
, lineNo
, from, to
, marker
) {
5762 var line
= getLine(doc
, lineNo
);
5763 var sps
= sawCollapsedSpans
&& line
.markedSpans
;
5764 if (sps
) for (var i
= 0; i
< sps
.length
; ++i
) {
5766 if (!sp
.marker
.collapsed
) continue;
5767 var found
= sp
.marker
.find(0);
5768 var fromCmp
= cmp(found
.from, from) || extraLeft(sp
.marker
) - extraLeft(marker
);
5769 var toCmp
= cmp(found
.to
, to
) || extraRight(sp
.marker
) - extraRight(marker
);
5770 if (fromCmp
>= 0 && toCmp
<= 0 || fromCmp
<= 0 && toCmp
>= 0) continue;
5771 if (fromCmp
<= 0 && (cmp(found
.to
, from) > 0 || (sp
.marker
.inclusiveRight
&& marker
.inclusiveLeft
)) ||
5772 fromCmp
>= 0 && (cmp(found
.from, to
) < 0 || (sp
.marker
.inclusiveLeft
&& marker
.inclusiveRight
)))
5777 // A visual line is a line as drawn on the screen. Folding, for
5778 // example, can cause multiple logical lines to appear on the same
5779 // visual line. This finds the start of the visual line that the
5780 // given line is part of (usually that is the line itself).
5781 function visualLine(line
) {
5783 while (merged
= collapsedSpanAtStart(line
))
5784 line
= merged
.find(-1, true).line
;
5788 // Returns an array of logical lines that continue the visual line
5789 // started by the argument, or undefined if there are no such lines.
5790 function visualLineContinued(line
) {
5792 while (merged
= collapsedSpanAtEnd(line
)) {
5793 line
= merged
.find(1, true).line
;
5794 (lines
|| (lines
= [])).push(line
);
5799 // Get the line number of the start of the visual line that the
5800 // given line number is part of.
5801 function visualLineNo(doc
, lineN
) {
5802 var line
= getLine(doc
, lineN
), vis
= visualLine(line
);
5803 if (line
== vis
) return lineN
;
5806 // Get the line number of the start of the next visual line after
5808 function visualLineEndNo(doc
, lineN
) {
5809 if (lineN
> doc
.lastLine()) return lineN
;
5810 var line
= getLine(doc
, lineN
), merged
;
5811 if (!lineIsHidden(doc
, line
)) return lineN
;
5812 while (merged
= collapsedSpanAtEnd(line
))
5813 line
= merged
.find(1, true).line
;
5814 return lineNo(line
) + 1;
5817 // Compute whether a line is hidden. Lines count as hidden when they
5818 // are part of a visual line that starts with another line, or when
5819 // they are entirely covered by collapsed, non-widget span.
5820 function lineIsHidden(doc
, line
) {
5821 var sps
= sawCollapsedSpans
&& line
.markedSpans
;
5822 if (sps
) for (var sp
, i
= 0; i
< sps
.length
; ++i
) {
5824 if (!sp
.marker
.collapsed
) continue;
5825 if (sp
.from == null) return true;
5826 if (sp
.marker
.widgetNode
) continue;
5827 if (sp
.from == 0 && sp
.marker
.inclusiveLeft
&& lineIsHiddenInner(doc
, line
, sp
))
5831 function lineIsHiddenInner(doc
, line
, span
) {
5832 if (span
.to
== null) {
5833 var end
= span
.marker
.find(1, true);
5834 return lineIsHiddenInner(doc
, end
.line
, getMarkedSpanFor(end
.line
.markedSpans
, span
.marker
));
5836 if (span
.marker
.inclusiveRight
&& span
.to
== line
.text
.length
)
5838 for (var sp
, i
= 0; i
< line
.markedSpans
.length
; ++i
) {
5839 sp
= line
.markedSpans
[i
];
5840 if (sp
.marker
.collapsed
&& !sp
.marker
.widgetNode
&& sp
.from == span
.to
&&
5841 (sp
.to
== null || sp
.to
!= span
.from) &&
5842 (sp
.marker
.inclusiveLeft
|| span
.marker
.inclusiveRight
) &&
5843 lineIsHiddenInner(doc
, line
, sp
)) return true;
5849 // Line widgets are block elements displayed above or below a line.
5851 var LineWidget
= CodeMirror
.LineWidget = function(cm
, node
, options
) {
5852 if (options
) for (var opt
in options
) if (options
.hasOwnProperty(opt
))
5853 this[opt
] = options
[opt
];
5857 eventMixin(LineWidget
);
5859 function adjustScrollWhenAboveVisible(cm
, line
, diff
) {
5860 if (heightAtLine(line
) < ((cm
.curOp
&& cm
.curOp
.scrollTop
) || cm
.doc
.scrollTop
))
5861 addToScrollPos(cm
, null, diff
);
5864 LineWidget
.prototype.clear = function() {
5865 var cm
= this.cm
, ws
= this.line
.widgets
, line
= this.line
, no
= lineNo(line
);
5866 if (no
== null || !ws
) return;
5867 for (var i
= 0; i
< ws
.length
; ++i
) if (ws
[i
] == this) ws
.splice(i
--, 1);
5868 if (!ws
.length
) line
.widgets
= null;
5869 var height
= widgetHeight(this);
5870 runInOp(cm
, function() {
5871 adjustScrollWhenAboveVisible(cm
, line
, -height
);
5872 regLineChange(cm
, no
, "widget");
5873 updateLineHeight(line
, Math
.max(0, line
.height
- height
));
5876 LineWidget
.prototype.changed = function() {
5877 var oldH
= this.height
, cm
= this.cm
, line
= this.line
;
5879 var diff
= widgetHeight(this) - oldH
;
5881 runInOp(cm
, function() {
5882 cm
.curOp
.forceUpdate
= true;
5883 adjustScrollWhenAboveVisible(cm
, line
, diff
);
5884 updateLineHeight(line
, line
.height
+ diff
);
5888 function widgetHeight(widget
) {
5889 if (widget
.height
!= null) return widget
.height
;
5890 if (!contains(document
.body
, widget
.node
)) {
5891 var parentStyle
= "position: relative;";
5892 if (widget
.coverGutter
)
5893 parentStyle
+= "margin-left: -" + widget
.cm
.display
.gutters
.offsetWidth
+ "px;";
5894 if (widget
.noHScroll
)
5895 parentStyle
+= "width: " + widget
.cm
.display
.wrapper
.clientWidth
+ "px;";
5896 removeChildrenAndAdd(widget
.cm
.display
.measure
, elt("div", [widget
.node
], null, parentStyle
));
5898 return widget
.height
= widget
.node
.offsetHeight
;
5901 function addLineWidget(cm
, handle
, node
, options
) {
5902 var widget
= new LineWidget(cm
, node
, options
);
5903 if (widget
.noHScroll
) cm
.display
.alignWidgets
= true;
5904 changeLine(cm
.doc
, handle
, "widget", function(line
) {
5905 var widgets
= line
.widgets
|| (line
.widgets
= []);
5906 if (widget
.insertAt
== null) widgets
.push(widget
);
5907 else widgets
.splice(Math
.min(widgets
.length
- 1, Math
.max(0, widget
.insertAt
)), 0, widget
);
5909 if (!lineIsHidden(cm
.doc
, line
)) {
5910 var aboveVisible
= heightAtLine(line
) < cm
.doc
.scrollTop
;
5911 updateLineHeight(line
, line
.height
+ widgetHeight(widget
));
5912 if (aboveVisible
) addToScrollPos(cm
, null, widget
.height
);
5913 cm
.curOp
.forceUpdate
= true;
5920 // LINE DATA STRUCTURE
5922 // Line objects. These hold state related to a line, including
5923 // highlighting info (the styles array).
5924 var Line
= CodeMirror
.Line = function(text
, markedSpans
, estimateHeight
) {
5926 attachMarkedSpans(this, markedSpans
);
5927 this.height
= estimateHeight
? estimateHeight(this) : 1;
5930 Line
.prototype.lineNo = function() { return lineNo(this); };
5932 // Change the content (text, markers) of a line. Automatically
5933 // invalidates cached information and tries to re-estimate the
5935 function updateLine(line
, text
, markedSpans
, estimateHeight
) {
5937 if (line
.stateAfter
) line
.stateAfter
= null;
5938 if (line
.styles
) line
.styles
= null;
5939 if (line
.order
!= null) line
.order
= null;
5940 detachMarkedSpans(line
);
5941 attachMarkedSpans(line
, markedSpans
);
5942 var estHeight
= estimateHeight
? estimateHeight(line
) : 1;
5943 if (estHeight
!= line
.height
) updateLineHeight(line
, estHeight
);
5946 // Detach a line from the document tree and its markers.
5947 function cleanUpLine(line
) {
5949 detachMarkedSpans(line
);
5952 function extractLineClasses(type
, output
) {
5953 if (type
) for (;;) {
5954 var lineClass
= type
.match(/(?:^|\s+)line-(background-)?(\S+)/);
5955 if (!lineClass
) break;
5956 type
= type
.slice(0, lineClass
.index
) + type
.slice(lineClass
.index
+ lineClass
[0].length
);
5957 var prop
= lineClass
[1] ? "bgClass" : "textClass";
5958 if (output
[prop
] == null)
5959 output
[prop
] = lineClass
[2];
5960 else if (!(new RegExp("(?:^|\s)" + lineClass
[2] + "(?:$|\s)")).test(output
[prop
]))
5961 output
[prop
] += " " + lineClass
[2];
5966 function callBlankLine(mode
, state
) {
5967 if (mode
.blankLine
) return mode
.blankLine(state
);
5968 if (!mode
.innerMode
) return;
5969 var inner
= CodeMirror
.innerMode(mode
, state
);
5970 if (inner
.mode
.blankLine
) return inner
.mode
.blankLine(inner
.state
);
5973 function readToken(mode
, stream
, state
, inner
) {
5974 for (var i
= 0; i
< 10; i
++) {
5975 if (inner
) inner
[0] = CodeMirror
.innerMode(mode
, state
).mode
;
5976 var style
= mode
.token(stream
, state
);
5977 if (stream
.pos
> stream
.start
) return style
;
5979 throw new Error("Mode " + mode
.name
+ " failed to advance stream.");
5982 // Utility for getTokenAt and getLineTokens
5983 function takeToken(cm
, pos
, precise
, asArray
) {
5984 function getObj(copy
) {
5985 return {start
: stream
.start
, end
: stream
.pos
,
5986 string
: stream
.current(),
5987 type
: style
|| null,
5988 state
: copy
? copyState(doc
.mode
, state
) : state
};
5991 var doc
= cm
.doc
, mode
= doc
.mode
, style
;
5992 pos
= clipPos(doc
, pos
);
5993 var line
= getLine(doc
, pos
.line
), state
= getStateBefore(cm
, pos
.line
, precise
);
5994 var stream
= new StringStream(line
.text
, cm
.options
.tabSize
), tokens
;
5995 if (asArray
) tokens
= [];
5996 while ((asArray
|| stream
.pos
< pos
.ch
) && !stream
.eol()) {
5997 stream
.start
= stream
.pos
;
5998 style
= readToken(mode
, stream
, state
);
5999 if (asArray
) tokens
.push(getObj(true));
6001 return asArray
? tokens
: getObj();
6004 // Run the given mode's parser over a line, calling f for each token.
6005 function runMode(cm
, text
, mode
, state
, f
, lineClasses
, forceToEnd
) {
6006 var flattenSpans
= mode
.flattenSpans
;
6007 if (flattenSpans
== null) flattenSpans
= cm
.options
.flattenSpans
;
6008 var curStart
= 0, curStyle
= null;
6009 var stream
= new StringStream(text
, cm
.options
.tabSize
), style
;
6010 var inner
= cm
.options
.addModeClass
&& [null];
6011 if (text
== "") extractLineClasses(callBlankLine(mode
, state
), lineClasses
);
6012 while (!stream
.eol()) {
6013 if (stream
.pos
> cm
.options
.maxHighlightLength
) {
6014 flattenSpans
= false;
6015 if (forceToEnd
) processLine(cm
, text
, state
, stream
.pos
);
6016 stream
.pos
= text
.length
;
6019 style
= extractLineClasses(readToken(mode
, stream
, state
, inner
), lineClasses
);
6022 var mName
= inner
[0].name
;
6023 if (mName
) style
= "m-" + (style
? mName
+ " " + style
: mName
);
6025 if (!flattenSpans
|| curStyle
!= style
) {
6026 while (curStart
< stream
.start
) {
6027 curStart
= Math
.min(stream
.start
, curStart
+ 50000);
6028 f(curStart
, curStyle
);
6032 stream
.start
= stream
.pos
;
6034 while (curStart
< stream
.pos
) {
6035 // Webkit seems to refuse to render text nodes longer than 57444 characters
6036 var pos
= Math
.min(stream
.pos
, curStart
+ 50000);
6042 // Compute a style array (an array starting with a mode generation
6043 // -- for invalidation -- followed by pairs of end positions and
6044 // style strings), which is used to highlight the tokens on the
6046 function highlightLine(cm
, line
, state
, forceToEnd
) {
6047 // A styles array always starts with a number identifying the
6048 // mode/overlays that it is based on (for easy invalidation).
6049 var st
= [cm
.state
.modeGen
], lineClasses
= {};
6050 // Compute the base array of styles
6051 runMode(cm
, line
.text
, cm
.doc
.mode
, state
, function(end
, style
) {
6052 st
.push(end
, style
);
6053 }, lineClasses
, forceToEnd
);
6055 // Run overlays, adjust style array.
6056 for (var o
= 0; o
< cm
.state
.overlays
.length
; ++o
) {
6057 var overlay
= cm
.state
.overlays
[o
], i
= 1, at
= 0;
6058 runMode(cm
, line
.text
, overlay
.mode
, true, function(end
, style
) {
6060 // Ensure there's a token end at the current position, and that i points at it
6064 st
.splice(i
, 1, end
, st
[i
+1], i_end
);
6066 at
= Math
.min(end
, i_end
);
6069 if (overlay
.opaque
) {
6070 st
.splice(start
, i
- start
, end
, "cm-overlay " + style
);
6073 for (; start
< i
; start
+= 2) {
6074 var cur
= st
[start
+1];
6075 st
[start
+1] = (cur
? cur
+ " " : "") + "cm-overlay " + style
;
6081 return {styles
: st
, classes
: lineClasses
.bgClass
|| lineClasses
.textClass
? lineClasses
: null};
6084 function getLineStyles(cm
, line
, updateFrontier
) {
6085 if (!line
.styles
|| line
.styles
[0] != cm
.state
.modeGen
) {
6086 var result
= highlightLine(cm
, line
, line
.stateAfter
= getStateBefore(cm
, lineNo(line
)));
6087 line
.styles
= result
.styles
;
6088 if (result
.classes
) line
.styleClasses
= result
.classes
;
6089 else if (line
.styleClasses
) line
.styleClasses
= null;
6090 if (updateFrontier
=== cm
.doc
.frontier
) cm
.doc
.frontier
++;
6095 // Lightweight form of highlight -- proceed over this line and
6096 // update state, but don't save a style array. Used for lines that
6097 // aren't currently visible.
6098 function processLine(cm
, text
, state
, startAt
) {
6099 var mode
= cm
.doc
.mode
;
6100 var stream
= new StringStream(text
, cm
.options
.tabSize
);
6101 stream
.start
= stream
.pos
= startAt
|| 0;
6102 if (text
== "") callBlankLine(mode
, state
);
6103 while (!stream
.eol() && stream
.pos
<= cm
.options
.maxHighlightLength
) {
6104 readToken(mode
, stream
, state
);
6105 stream
.start
= stream
.pos
;
6109 // Convert a style as returned by a mode (either null, or a string
6110 // containing one or more styles) to a CSS style. This is cached,
6111 // and also looks for line-wide styles.
6112 var styleToClassCache
= {}, styleToClassCacheWithMode
= {};
6113 function interpretTokenStyle(style
, options
) {
6114 if (!style
|| /^\s*$/.test(style
)) return null;
6115 var cache
= options
.addModeClass
? styleToClassCacheWithMode
: styleToClassCache
;
6116 return cache
[style
] ||
6117 (cache
[style
] = style
.replace(/\S+/g, "cm-$&"));
6120 // Render the DOM representation of the text of a line. Also builds
6121 // up a 'line map', which points at the DOM nodes that represent
6122 // specific stretches of text, and is used by the measuring code.
6123 // The returned object contains the DOM node, this map, and
6124 // information about line-wide styles that were set by the mode.
6125 function buildLineContent(cm
, lineView
) {
6126 // The padding-right forces the element to have a 'border', which
6127 // is needed on Webkit to be able to get line-level bounding
6128 // rectangles for it (in measureChar).
6129 var content
= elt("span", null, null, webkit
? "padding-right: .1px" : null);
6130 var builder
= {pre
: elt("pre", [content
]), content
: content
, col
: 0, pos
: 0, cm
: cm
};
6131 lineView
.measure
= {};
6133 // Iterate over the logical lines that make up this visual line.
6134 for (var i
= 0; i
<= (lineView
.rest
? lineView
.rest
.length
: 0); i
++) {
6135 var line
= i
? lineView
.rest
[i
- 1] : lineView
.line
, order
;
6137 builder
.addToken
= buildToken
;
6138 // Optionally wire in some hacks into the token-rendering
6139 // algorithm, to deal with browser quirks.
6140 if ((ie
|| webkit
) && cm
.getOption("lineWrapping"))
6141 builder
.addToken
= buildTokenSplitSpaces(builder
.addToken
);
6142 if (hasBadBidiRects(cm
.display
.measure
) && (order
= getOrder(line
)))
6143 builder
.addToken
= buildTokenBadBidi(builder
.addToken
, order
);
6145 var allowFrontierUpdate
= lineView
!= cm
.display
.externalMeasured
&& lineNo(line
);
6146 insertLineContent(line
, builder
, getLineStyles(cm
, line
, allowFrontierUpdate
));
6147 if (line
.styleClasses
) {
6148 if (line
.styleClasses
.bgClass
)
6149 builder
.bgClass
= joinClasses(line
.styleClasses
.bgClass
, builder
.bgClass
|| "");
6150 if (line
.styleClasses
.textClass
)
6151 builder
.textClass
= joinClasses(line
.styleClasses
.textClass
, builder
.textClass
|| "");
6154 // Ensure at least a single node is present, for measuring.
6155 if (builder
.map
.length
== 0)
6156 builder
.map
.push(0, 0, builder
.content
.appendChild(zeroWidthElement(cm
.display
.measure
)));
6158 // Store the map and a cache object for the current logical line
6160 lineView
.measure
.map
= builder
.map
;
6161 lineView
.measure
.cache
= {};
6163 (lineView
.measure
.maps
|| (lineView
.measure
.maps
= [])).push(builder
.map
);
6164 (lineView
.measure
.caches
|| (lineView
.measure
.caches
= [])).push({});
6169 if (webkit
&& /\bcm-tab\b/.test(builder
.content
.lastChild
.className
))
6170 builder
.content
.className
= "cm-tab-wrap-hack";
6172 signal(cm
, "renderLine", cm
, lineView
.line
, builder
.pre
);
6173 if (builder
.pre
.className
)
6174 builder
.textClass
= joinClasses(builder
.pre
.className
, builder
.textClass
|| "");
6179 function defaultSpecialCharPlaceholder(ch
) {
6180 var token
= elt("span", "\u2022", "cm-invalidchar");
6181 token
.title
= "\\u" + ch
.charCodeAt(0).toString(16);
6185 // Build up the DOM representation for a single token, and add it to
6186 // the line map. Takes care to render special characters separately.
6187 function buildToken(builder
, text
, style
, startStyle
, endStyle
, title
, css
) {
6189 var special
= builder
.cm
.options
.specialChars
, mustWrap
= false;
6190 if (!special
.test(text
)) {
6191 builder
.col
+= text
.length
;
6192 var content
= document
.createTextNode(text
);
6193 builder
.map
.push(builder
.pos
, builder
.pos
+ text
.length
, content
);
6194 if (ie
&& ie_version
< 9) mustWrap
= true;
6195 builder
.pos
+= text
.length
;
6197 var content
= document
.createDocumentFragment(), pos
= 0;
6199 special
.lastIndex
= pos
;
6200 var m
= special
.exec(text
);
6201 var skipped
= m
? m
.index
- pos
: text
.length
- pos
;
6203 var txt
= document
.createTextNode(text
.slice(pos
, pos
+ skipped
));
6204 if (ie
&& ie_version
< 9) content
.appendChild(elt("span", [txt
]));
6205 else content
.appendChild(txt
);
6206 builder
.map
.push(builder
.pos
, builder
.pos
+ skipped
, txt
);
6207 builder
.col
+= skipped
;
6208 builder
.pos
+= skipped
;
6213 var tabSize
= builder
.cm
.options
.tabSize
, tabWidth
= tabSize
- builder
.col
% tabSize
;
6214 var txt
= content
.appendChild(elt("span", spaceStr(tabWidth
), "cm-tab"));
6215 builder
.col
+= tabWidth
;
6217 var txt
= builder
.cm
.options
.specialCharPlaceholder(m
[0]);
6218 if (ie
&& ie_version
< 9) content
.appendChild(elt("span", [txt
]));
6219 else content
.appendChild(txt
);
6222 builder
.map
.push(builder
.pos
, builder
.pos
+ 1, txt
);
6226 if (style
|| startStyle
|| endStyle
|| mustWrap
|| css
) {
6227 var fullStyle
= style
|| "";
6228 if (startStyle
) fullStyle
+= startStyle
;
6229 if (endStyle
) fullStyle
+= endStyle
;
6230 var token
= elt("span", [content
], fullStyle
, css
);
6231 if (title
) token
.title
= title
;
6232 return builder
.content
.appendChild(token
);
6234 builder
.content
.appendChild(content
);
6237 function buildTokenSplitSpaces(inner
) {
6238 function split(old
) {
6240 for (var i
= 0; i
< old
.length
- 2; ++i
) out
+= i
% 2 ? " " : "\u00a0";
6244 return function(builder
, text
, style
, startStyle
, endStyle
, title
) {
6245 inner(builder
, text
.replace(/ {3,}/g
, split
), style
, startStyle
, endStyle
, title
);
6249 // Work around nonsense dimensions being reported for stretches of
6250 // right-to-left text.
6251 function buildTokenBadBidi(inner
, order
) {
6252 return function(builder
, text
, style
, startStyle
, endStyle
, title
) {
6253 style
= style
? style
+ " cm-force-border" : "cm-force-border";
6254 var start
= builder
.pos
, end
= start
+ text
.length
;
6256 // Find the part that overlaps with the start of this text
6257 for (var i
= 0; i
< order
.length
; i
++) {
6258 var part
= order
[i
];
6259 if (part
.to
> start
&& part
.from <= start
) break;
6261 if (part
.to
>= end
) return inner(builder
, text
, style
, startStyle
, endStyle
, title
);
6262 inner(builder
, text
.slice(0, part
.to
- start
), style
, startStyle
, null, title
);
6264 text
= text
.slice(part
.to
- start
);
6270 function buildCollapsedSpan(builder
, size
, marker
, ignoreWidget
) {
6271 var widget
= !ignoreWidget
&& marker
.widgetNode
;
6273 builder
.map
.push(builder
.pos
, builder
.pos
+ size
, widget
);
6274 builder
.content
.appendChild(widget
);
6276 builder
.pos
+= size
;
6279 // Outputs a number of spans to make up a line, taking highlighting
6280 // and marked text into account.
6281 function insertLineContent(line
, builder
, styles
) {
6282 var spans
= line
.markedSpans
, allText
= line
.text
, at
= 0;
6284 for (var i
= 1; i
< styles
.length
; i
+=2)
6285 builder
.addToken(builder
, allText
.slice(at
, at
= styles
[i
]), interpretTokenStyle(styles
[i
+1], builder
.cm
.options
));
6289 var len
= allText
.length
, pos
= 0, i
= 1, text
= "", style
, css
;
6290 var nextChange
= 0, spanStyle
, spanEndStyle
, spanStartStyle
, title
, collapsed
;
6292 if (nextChange
== pos
) { // Update current marker set
6293 spanStyle
= spanEndStyle
= spanStartStyle
= title
= css
= "";
6294 collapsed
= null; nextChange
= Infinity
;
6295 var foundBookmarks
= [];
6296 for (var j
= 0; j
< spans
.length
; ++j
) {
6297 var sp
= spans
[j
], m
= sp
.marker
;
6298 if (sp
.from <= pos
&& (sp
.to
== null || sp
.to
> pos
)) {
6299 if (sp
.to
!= null && nextChange
> sp
.to
) { nextChange
= sp
.to
; spanEndStyle
= ""; }
6300 if (m
.className
) spanStyle
+= " " + m
.className
;
6301 if (m
.css
) css
= m
.css
;
6302 if (m
.startStyle
&& sp
.from == pos
) spanStartStyle
+= " " + m
.startStyle
;
6303 if (m
.endStyle
&& sp
.to
== nextChange
) spanEndStyle
+= " " + m
.endStyle
;
6304 if (m
.title
&& !title
) title
= m
.title
;
6305 if (m
.collapsed
&& (!collapsed
|| compareCollapsedMarkers(collapsed
.marker
, m
) < 0))
6307 } else if (sp
.from > pos
&& nextChange
> sp
.from) {
6308 nextChange
= sp
.from;
6310 if (m
.type
== "bookmark" && sp
.from == pos
&& m
.widgetNode
) foundBookmarks
.push(m
);
6312 if (collapsed
&& (collapsed
.from || 0) == pos
) {
6313 buildCollapsedSpan(builder
, (collapsed
.to
== null ? len
+ 1 : collapsed
.to
) - pos
,
6314 collapsed
.marker
, collapsed
.from == null);
6315 if (collapsed
.to
== null) return;
6317 if (!collapsed
&& foundBookmarks
.length
) for (var j
= 0; j
< foundBookmarks
.length
; ++j
)
6318 buildCollapsedSpan(builder
, 0, foundBookmarks
[j
]);
6320 if (pos
>= len
) break;
6322 var upto
= Math
.min(len
, nextChange
);
6325 var end
= pos
+ text
.length
;
6327 var tokenText
= end
> upto
? text
.slice(0, upto
- pos
) : text
;
6328 builder
.addToken(builder
, tokenText
, style
? style
+ spanStyle
: spanStyle
,
6329 spanStartStyle
, pos
+ tokenText
.length
== nextChange
? spanEndStyle
: "", title
, css
);
6331 if (end
>= upto
) {text
= text
.slice(upto
- pos
); pos
= upto
; break;}
6333 spanStartStyle
= "";
6335 text
= allText
.slice(at
, at
= styles
[i
++]);
6336 style
= interpretTokenStyle(styles
[i
++], builder
.cm
.options
);
6341 // DOCUMENT DATA STRUCTURE
6343 // By default, updates that start and end at the beginning of a line
6344 // are treated specially, in order to make the association of line
6345 // widgets and marker elements with the text behave more intuitive.
6346 function isWholeLineUpdate(doc
, change
) {
6347 return change
.from.ch
== 0 && change
.to
.ch
== 0 && lst(change
.text
) == "" &&
6348 (!doc
.cm
|| doc
.cm
.options
.wholeLineUpdateBefore
);
6351 // Perform a change on the document data structure.
6352 function updateDoc(doc
, change
, markedSpans
, estimateHeight
) {
6353 function spansFor(n
) {return markedSpans
? markedSpans
[n
] : null;}
6354 function update(line
, text
, spans
) {
6355 updateLine(line
, text
, spans
, estimateHeight
);
6356 signalLater(line
, "change", line
, change
);
6358 function linesFor(start
, end
) {
6359 for (var i
= start
, result
= []; i
< end
; ++i
)
6360 result
.push(new Line(text
[i
], spansFor(i
), estimateHeight
));
6364 var from = change
.from, to
= change
.to
, text
= change
.text
;
6365 var firstLine
= getLine(doc
, from.line
), lastLine
= getLine(doc
, to
.line
);
6366 var lastText
= lst(text
), lastSpans
= spansFor(text
.length
- 1), nlines
= to
.line
- from.line
;
6368 // Adjust the line structure
6370 doc
.insert(0, linesFor(0, text
.length
));
6371 doc
.remove(text
.length
, doc
.size
- text
.length
);
6372 } else if (isWholeLineUpdate(doc
, change
)) {
6373 // This is a whole-line replace. Treated specially to make
6374 // sure line objects move the way they are supposed to.
6375 var added
= linesFor(0, text
.length
- 1);
6376 update(lastLine
, lastLine
.text
, lastSpans
);
6377 if (nlines
) doc
.remove(from.line
, nlines
);
6378 if (added
.length
) doc
.insert(from.line
, added
);
6379 } else if (firstLine
== lastLine
) {
6380 if (text
.length
== 1) {
6381 update(firstLine
, firstLine
.text
.slice(0, from.ch
) + lastText
+ firstLine
.text
.slice(to
.ch
), lastSpans
);
6383 var added
= linesFor(1, text
.length
- 1);
6384 added
.push(new Line(lastText
+ firstLine
.text
.slice(to
.ch
), lastSpans
, estimateHeight
));
6385 update(firstLine
, firstLine
.text
.slice(0, from.ch
) + text
[0], spansFor(0));
6386 doc
.insert(from.line
+ 1, added
);
6388 } else if (text
.length
== 1) {
6389 update(firstLine
, firstLine
.text
.slice(0, from.ch
) + text
[0] + lastLine
.text
.slice(to
.ch
), spansFor(0));
6390 doc
.remove(from.line
+ 1, nlines
);
6392 update(firstLine
, firstLine
.text
.slice(0, from.ch
) + text
[0], spansFor(0));
6393 update(lastLine
, lastText
+ lastLine
.text
.slice(to
.ch
), lastSpans
);
6394 var added
= linesFor(1, text
.length
- 1);
6395 if (nlines
> 1) doc
.remove(from.line
+ 1, nlines
- 1);
6396 doc
.insert(from.line
+ 1, added
);
6399 signalLater(doc
, "change", doc
, change
);
6402 // The document is represented as a BTree consisting of leaves, with
6403 // chunk of lines in them, and branches, with up to ten leaves or
6404 // other branch nodes below them. The top node is always a branch
6405 // node, and is the document object itself (meaning it has
6406 // additional methods and properties).
6408 // All nodes have parent links. The tree is used both to go from
6409 // line numbers to line objects, and to go from objects to numbers.
6410 // It also indexes by height, and is used to convert between height
6411 // and line object, and to find the total height of the document.
6413 // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
6415 function LeafChunk(lines
) {
6418 for (var i
= 0, height
= 0; i
< lines
.length
; ++i
) {
6419 lines
[i
].parent
= this;
6420 height
+= lines
[i
].height
;
6422 this.height
= height
;
6425 LeafChunk
.prototype = {
6426 chunkSize: function() { return this.lines
.length
; },
6427 // Remove the n lines at offset 'at'.
6428 removeInner: function(at
, n
) {
6429 for (var i
= at
, e
= at
+ n
; i
< e
; ++i
) {
6430 var line
= this.lines
[i
];
6431 this.height
-= line
.height
;
6433 signalLater(line
, "delete");
6435 this.lines
.splice(at
, n
);
6437 // Helper used to collapse a small branch into a single leaf.
6438 collapse: function(lines
) {
6439 lines
.push
.apply(lines
, this.lines
);
6441 // Insert the given array of lines at offset 'at', count them as
6442 // having the given height.
6443 insertInner: function(at
, lines
, height
) {
6444 this.height
+= height
;
6445 this.lines
= this.lines
.slice(0, at
).concat(lines
).concat(this.lines
.slice(at
));
6446 for (var i
= 0; i
< lines
.length
; ++i
) lines
[i
].parent
= this;
6448 // Used to iterate over a part of the tree.
6449 iterN: function(at
, n
, op
) {
6450 for (var e
= at
+ n
; at
< e
; ++at
)
6451 if (op(this.lines
[at
])) return true;
6455 function BranchChunk(children
) {
6456 this.children
= children
;
6457 var size
= 0, height
= 0;
6458 for (var i
= 0; i
< children
.length
; ++i
) {
6459 var ch
= children
[i
];
6460 size
+= ch
.chunkSize(); height
+= ch
.height
;
6464 this.height
= height
;
6468 BranchChunk
.prototype = {
6469 chunkSize: function() { return this.size
; },
6470 removeInner: function(at
, n
) {
6472 for (var i
= 0; i
< this.children
.length
; ++i
) {
6473 var child
= this.children
[i
], sz
= child
.chunkSize();
6475 var rm
= Math
.min(n
, sz
- at
), oldHeight
= child
.height
;
6476 child
.removeInner(at
, rm
);
6477 this.height
-= oldHeight
- child
.height
;
6478 if (sz
== rm
) { this.children
.splice(i
--, 1); child
.parent
= null; }
6479 if ((n
-= rm
) == 0) break;
6483 // If the result is smaller than 25 lines, ensure that it is a
6484 // single leaf node.
6485 if (this.size
- n
< 25 &&
6486 (this.children
.length
> 1 || !(this.children
[0] instanceof LeafChunk
))) {
6488 this.collapse(lines
);
6489 this.children
= [new LeafChunk(lines
)];
6490 this.children
[0].parent
= this;
6493 collapse: function(lines
) {
6494 for (var i
= 0; i
< this.children
.length
; ++i
) this.children
[i
].collapse(lines
);
6496 insertInner: function(at
, lines
, height
) {
6497 this.size
+= lines
.length
;
6498 this.height
+= height
;
6499 for (var i
= 0; i
< this.children
.length
; ++i
) {
6500 var child
= this.children
[i
], sz
= child
.chunkSize();
6502 child
.insertInner(at
, lines
, height
);
6503 if (child
.lines
&& child
.lines
.length
> 50) {
6504 while (child
.lines
.length
> 50) {
6505 var spilled
= child
.lines
.splice(child
.lines
.length
- 25, 25);
6506 var newleaf
= new LeafChunk(spilled
);
6507 child
.height
-= newleaf
.height
;
6508 this.children
.splice(i
+ 1, 0, newleaf
);
6509 newleaf
.parent
= this;
6518 // When a node has grown, check whether it should be split.
6519 maybeSpill: function() {
6520 if (this.children
.length
<= 10) return;
6523 var spilled
= me
.children
.splice(me
.children
.length
- 5, 5);
6524 var sibling
= new BranchChunk(spilled
);
6525 if (!me
.parent
) { // Become the parent node
6526 var copy
= new BranchChunk(me
.children
);
6528 me
.children
= [copy
, sibling
];
6531 me
.size
-= sibling
.size
;
6532 me
.height
-= sibling
.height
;
6533 var myIndex
= indexOf(me
.parent
.children
, me
);
6534 me
.parent
.children
.splice(myIndex
+ 1, 0, sibling
);
6536 sibling
.parent
= me
.parent
;
6537 } while (me
.children
.length
> 10);
6538 me
.parent
.maybeSpill();
6540 iterN: function(at
, n
, op
) {
6541 for (var i
= 0; i
< this.children
.length
; ++i
) {
6542 var child
= this.children
[i
], sz
= child
.chunkSize();
6544 var used
= Math
.min(n
, sz
- at
);
6545 if (child
.iterN(at
, used
, op
)) return true;
6546 if ((n
-= used
) == 0) break;
6554 var Doc
= CodeMirror
.Doc = function(text
, mode
, firstLine
) {
6555 if (!(this instanceof Doc
)) return new Doc(text
, mode
, firstLine
);
6556 if (firstLine
== null) firstLine
= 0;
6558 BranchChunk
.call(this, [new LeafChunk([new Line("", null)])]);
6559 this.first
= firstLine
;
6560 this.scrollTop
= this.scrollLeft
= 0;
6561 this.cantEdit
= false;
6562 this.cleanGeneration
= 1;
6563 this.frontier
= firstLine
;
6564 var start
= Pos(firstLine
, 0);
6565 this.sel
= simpleSelection(start
);
6566 this.history
= new History(null);
6567 this.id
= ++nextDocId
;
6568 this.modeOption
= mode
;
6570 if (typeof text
== "string") text
= splitLines(text
);
6571 updateDoc(this, {from: start
, to
: start
, text
: text
});
6572 setSelection(this, simpleSelection(start
), sel_dontScroll
);
6575 Doc
.prototype = createObj(BranchChunk
.prototype, {
6577 // Iterate over the document. Supports two forms -- with only one
6578 // argument, it calls that for each line in the document. With
6579 // three, it iterates over the range given by the first two (with
6580 // the second being non-inclusive).
6581 iter: function(from, to
, op
) {
6582 if (op
) this.iterN(from - this.first
, to
- from, op
);
6583 else this.iterN(this.first
, this.first
+ this.size
, from);
6586 // Non-public interface for adding and removing lines.
6587 insert: function(at
, lines
) {
6589 for (var i
= 0; i
< lines
.length
; ++i
) height
+= lines
[i
].height
;
6590 this.insertInner(at
- this.first
, lines
, height
);
6592 remove: function(at
, n
) { this.removeInner(at
- this.first
, n
); },
6594 // From here, the methods are part of the public interface. Most
6595 // are also available from CodeMirror (editor) instances.
6597 getValue: function(lineSep
) {
6598 var lines
= getLines(this, this.first
, this.first
+ this.size
);
6599 if (lineSep
=== false) return lines
;
6600 return lines
.join(lineSep
|| "\n");
6602 setValue
: docMethodOp(function(code
) {
6603 var top
= Pos(this.first
, 0), last
= this.first
+ this.size
- 1;
6604 makeChange(this, {from: top
, to
: Pos(last
, getLine(this, last
).text
.length
),
6605 text
: splitLines(code
), origin
: "setValue", full
: true}, true);
6606 setSelection(this, simpleSelection(top
));
6608 replaceRange: function(code
, from, to
, origin
) {
6609 from = clipPos(this, from);
6610 to
= to
? clipPos(this, to
) : from;
6611 replaceRange(this, code
, from, to
, origin
);
6613 getRange: function(from, to
, lineSep
) {
6614 var lines
= getBetween(this, clipPos(this, from), clipPos(this, to
));
6615 if (lineSep
=== false) return lines
;
6616 return lines
.join(lineSep
|| "\n");
6619 getLine: function(line
) {var l
= this.getLineHandle(line
); return l
&& l
.text
;},
6621 getLineHandle: function(line
) {if (isLine(this, line
)) return getLine(this, line
);},
6622 getLineNumber: function(line
) {return lineNo(line
);},
6624 getLineHandleVisualStart: function(line
) {
6625 if (typeof line
== "number") line
= getLine(this, line
);
6626 return visualLine(line
);
6629 lineCount: function() {return this.size
;},
6630 firstLine: function() {return this.first
;},
6631 lastLine: function() {return this.first
+ this.size
- 1;},
6633 clipPos: function(pos
) {return clipPos(this, pos
);},
6635 getCursor: function(start
) {
6636 var range
= this.sel
.primary(), pos
;
6637 if (start
== null || start
== "head") pos
= range
.head
;
6638 else if (start
== "anchor") pos
= range
.anchor
;
6639 else if (start
== "end" || start
== "to" || start
=== false) pos
= range
.to();
6640 else pos
= range
.from();
6643 listSelections: function() { return this.sel
.ranges
; },
6644 somethingSelected: function() {return this.sel
.somethingSelected();},
6646 setCursor
: docMethodOp(function(line
, ch
, options
) {
6647 setSimpleSelection(this, clipPos(this, typeof line
== "number" ? Pos(line
, ch
|| 0) : line
), null, options
);
6649 setSelection
: docMethodOp(function(anchor
, head
, options
) {
6650 setSimpleSelection(this, clipPos(this, anchor
), clipPos(this, head
|| anchor
), options
);
6652 extendSelection
: docMethodOp(function(head
, other
, options
) {
6653 extendSelection(this, clipPos(this, head
), other
&& clipPos(this, other
), options
);
6655 extendSelections
: docMethodOp(function(heads
, options
) {
6656 extendSelections(this, clipPosArray(this, heads
, options
));
6658 extendSelectionsBy
: docMethodOp(function(f
, options
) {
6659 extendSelections(this, map(this.sel
.ranges
, f
), options
);
6661 setSelections
: docMethodOp(function(ranges
, primary
, options
) {
6662 if (!ranges
.length
) return;
6663 for (var i
= 0, out
= []; i
< ranges
.length
; i
++)
6664 out
[i
] = new Range(clipPos(this, ranges
[i
].anchor
),
6665 clipPos(this, ranges
[i
].head
));
6666 if (primary
== null) primary
= Math
.min(ranges
.length
- 1, this.sel
.primIndex
);
6667 setSelection(this, normalizeSelection(out
, primary
), options
);
6669 addSelection
: docMethodOp(function(anchor
, head
, options
) {
6670 var ranges
= this.sel
.ranges
.slice(0);
6671 ranges
.push(new Range(clipPos(this, anchor
), clipPos(this, head
|| anchor
)));
6672 setSelection(this, normalizeSelection(ranges
, ranges
.length
- 1), options
);
6675 getSelection: function(lineSep
) {
6676 var ranges
= this.sel
.ranges
, lines
;
6677 for (var i
= 0; i
< ranges
.length
; i
++) {
6678 var sel
= getBetween(this, ranges
[i
].from(), ranges
[i
].to());
6679 lines
= lines
? lines
.concat(sel
) : sel
;
6681 if (lineSep
=== false) return lines
;
6682 else return lines
.join(lineSep
|| "\n");
6684 getSelections: function(lineSep
) {
6685 var parts
= [], ranges
= this.sel
.ranges
;
6686 for (var i
= 0; i
< ranges
.length
; i
++) {
6687 var sel
= getBetween(this, ranges
[i
].from(), ranges
[i
].to());
6688 if (lineSep
!== false) sel
= sel
.join(lineSep
|| "\n");
6693 replaceSelection: function(code
, collapse
, origin
) {
6695 for (var i
= 0; i
< this.sel
.ranges
.length
; i
++)
6697 this.replaceSelections(dup
, collapse
, origin
|| "+input");
6699 replaceSelections
: docMethodOp(function(code
, collapse
, origin
) {
6700 var changes
= [], sel
= this.sel
;
6701 for (var i
= 0; i
< sel
.ranges
.length
; i
++) {
6702 var range
= sel
.ranges
[i
];
6703 changes
[i
] = {from: range
.from(), to
: range
.to(), text
: splitLines(code
[i
]), origin
: origin
};
6705 var newSel
= collapse
&& collapse
!= "end" && computeReplacedSel(this, changes
, collapse
);
6706 for (var i
= changes
.length
- 1; i
>= 0; i
--)
6707 makeChange(this, changes
[i
]);
6708 if (newSel
) setSelectionReplaceHistory(this, newSel
);
6709 else if (this.cm
) ensureCursorVisible(this.cm
);
6711 undo
: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
6712 redo
: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
6713 undoSelection
: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
6714 redoSelection
: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
6716 setExtending: function(val
) {this.extend
= val
;},
6717 getExtending: function() {return this.extend
;},
6719 historySize: function() {
6720 var hist
= this.history
, done
= 0, undone
= 0;
6721 for (var i
= 0; i
< hist
.done
.length
; i
++) if (!hist
.done
[i
].ranges
) ++done
;
6722 for (var i
= 0; i
< hist
.undone
.length
; i
++) if (!hist
.undone
[i
].ranges
) ++undone
;
6723 return {undo
: done
, redo
: undone
};
6725 clearHistory: function() {this.history
= new History(this.history
.maxGeneration
);},
6727 markClean: function() {
6728 this.cleanGeneration
= this.changeGeneration(true);
6730 changeGeneration: function(forceSplit
) {
6732 this.history
.lastOp
= this.history
.lastSelOp
= this.history
.lastOrigin
= null;
6733 return this.history
.generation
;
6735 isClean: function (gen
) {
6736 return this.history
.generation
== (gen
|| this.cleanGeneration
);
6739 getHistory: function() {
6740 return {done
: copyHistoryArray(this.history
.done
),
6741 undone
: copyHistoryArray(this.history
.undone
)};
6743 setHistory: function(histData
) {
6744 var hist
= this.history
= new History(this.history
.maxGeneration
);
6745 hist
.done
= copyHistoryArray(histData
.done
.slice(0), null, true);
6746 hist
.undone
= copyHistoryArray(histData
.undone
.slice(0), null, true);
6749 addLineClass
: docMethodOp(function(handle
, where
, cls
) {
6750 return changeLine(this, handle
, where
== "gutter" ? "gutter" : "class", function(line
) {
6751 var prop
= where
== "text" ? "textClass"
6752 : where
== "background" ? "bgClass"
6753 : where
== "gutter" ? "gutterClass" : "wrapClass";
6754 if (!line
[prop
]) line
[prop
] = cls
;
6755 else if (classTest(cls
).test(line
[prop
])) return false;
6756 else line
[prop
] += " " + cls
;
6760 removeLineClass
: docMethodOp(function(handle
, where
, cls
) {
6761 return changeLine(this, handle
, where
== "gutter" ? "gutter" : "class", function(line
) {
6762 var prop
= where
== "text" ? "textClass"
6763 : where
== "background" ? "bgClass"
6764 : where
== "gutter" ? "gutterClass" : "wrapClass";
6765 var cur
= line
[prop
];
6766 if (!cur
) return false;
6767 else if (cls
== null) line
[prop
] = null;
6769 var found
= cur
.match(classTest(cls
));
6770 if (!found
) return false;
6771 var end
= found
.index
+ found
[0].length
;
6772 line
[prop
] = cur
.slice(0, found
.index
) + (!found
.index
|| end
== cur
.length
? "" : " ") + cur
.slice(end
) || null;
6778 markText: function(from, to
, options
) {
6779 return markText(this, clipPos(this, from), clipPos(this, to
), options
, "range");
6781 setBookmark: function(pos
, options
) {
6782 var realOpts
= {replacedWith
: options
&& (options
.nodeType
== null ? options
.widget
: options
),
6783 insertLeft
: options
&& options
.insertLeft
,
6784 clearWhenEmpty
: false, shared
: options
&& options
.shared
};
6785 pos
= clipPos(this, pos
);
6786 return markText(this, pos
, pos
, realOpts
, "bookmark");
6788 findMarksAt: function(pos
) {
6789 pos
= clipPos(this, pos
);
6790 var markers
= [], spans
= getLine(this, pos
.line
).markedSpans
;
6791 if (spans
) for (var i
= 0; i
< spans
.length
; ++i
) {
6792 var span
= spans
[i
];
6793 if ((span
.from == null || span
.from <= pos
.ch
) &&
6794 (span
.to
== null || span
.to
>= pos
.ch
))
6795 markers
.push(span
.marker
.parent
|| span
.marker
);
6799 findMarks: function(from, to
, filter
) {
6800 from = clipPos(this, from); to
= clipPos(this, to
);
6801 var found
= [], lineNo
= from.line
;
6802 this.iter(from.line
, to
.line
+ 1, function(line
) {
6803 var spans
= line
.markedSpans
;
6804 if (spans
) for (var i
= 0; i
< spans
.length
; i
++) {
6805 var span
= spans
[i
];
6806 if (!(lineNo
== from.line
&& from.ch
> span
.to
||
6807 span
.from == null && lineNo
!= from.line
||
6808 lineNo
== to
.line
&& span
.from > to
.ch
) &&
6809 (!filter
|| filter(span
.marker
)))
6810 found
.push(span
.marker
.parent
|| span
.marker
);
6816 getAllMarks: function() {
6818 this.iter(function(line
) {
6819 var sps
= line
.markedSpans
;
6820 if (sps
) for (var i
= 0; i
< sps
.length
; ++i
)
6821 if (sps
[i
].from != null) markers
.push(sps
[i
].marker
);
6826 posFromIndex: function(off
) {
6827 var ch
, lineNo
= this.first
;
6828 this.iter(function(line
) {
6829 var sz
= line
.text
.length
+ 1;
6830 if (sz
> off
) { ch
= off
; return true; }
6834 return clipPos(this, Pos(lineNo
, ch
));
6836 indexFromPos: function (coords
) {
6837 coords
= clipPos(this, coords
);
6838 var index
= coords
.ch
;
6839 if (coords
.line
< this.first
|| coords
.ch
< 0) return 0;
6840 this.iter(this.first
, coords
.line
, function (line
) {
6841 index
+= line
.text
.length
+ 1;
6846 copy: function(copyHistory
) {
6847 var doc
= new Doc(getLines(this, this.first
, this.first
+ this.size
), this.modeOption
, this.first
);
6848 doc
.scrollTop
= this.scrollTop
; doc
.scrollLeft
= this.scrollLeft
;
6852 doc
.history
.undoDepth
= this.history
.undoDepth
;
6853 doc
.setHistory(this.getHistory());
6858 linkedDoc: function(options
) {
6859 if (!options
) options
= {};
6860 var from = this.first
, to
= this.first
+ this.size
;
6861 if (options
.from != null && options
.from > from) from = options
.from;
6862 if (options
.to
!= null && options
.to
< to
) to
= options
.to
;
6863 var copy
= new Doc(getLines(this, from, to
), options
.mode
|| this.modeOption
, from);
6864 if (options
.sharedHist
) copy
.history
= this.history
;
6865 (this.linked
|| (this.linked
= [])).push({doc
: copy
, sharedHist
: options
.sharedHist
});
6866 copy
.linked
= [{doc
: this, isParent
: true, sharedHist
: options
.sharedHist
}];
6867 copySharedMarkers(copy
, findSharedMarkers(this));
6870 unlinkDoc: function(other
) {
6871 if (other
instanceof CodeMirror
) other
= other
.doc
;
6872 if (this.linked
) for (var i
= 0; i
< this.linked
.length
; ++i
) {
6873 var link
= this.linked
[i
];
6874 if (link
.doc
!= other
) continue;
6875 this.linked
.splice(i
, 1);
6876 other
.unlinkDoc(this);
6877 detachSharedMarkers(findSharedMarkers(this));
6880 // If the histories were shared, split them again
6881 if (other
.history
== this.history
) {
6882 var splitIds
= [other
.id
];
6883 linkedDocs(other
, function(doc
) {splitIds
.push(doc
.id
);}, true);
6884 other
.history
= new History(null);
6885 other
.history
.done
= copyHistoryArray(this.history
.done
, splitIds
);
6886 other
.history
.undone
= copyHistoryArray(this.history
.undone
, splitIds
);
6889 iterLinkedDocs: function(f
) {linkedDocs(this, f
);},
6891 getMode: function() {return this.mode
;},
6892 getEditor: function() {return this.cm
;}
6896 Doc
.prototype.eachLine
= Doc
.prototype.iter
;
6898 // Set up methods on CodeMirror's prototype to redirect to the editor's document.
6899 var dontDelegate
= "iter insert remove copy getEditor".split(" ");
6900 for (var prop
in Doc
.prototype) if (Doc
.prototype.hasOwnProperty(prop
) && indexOf(dontDelegate
, prop
) < 0)
6901 CodeMirror
.prototype[prop
] = (function(method
) {
6902 return function() {return method
.apply(this.doc
, arguments
);};
6903 })(Doc
.prototype[prop
]);
6907 // Call f for all linked documents.
6908 function linkedDocs(doc
, f
, sharedHistOnly
) {
6909 function propagate(doc
, skip
, sharedHist
) {
6910 if (doc
.linked
) for (var i
= 0; i
< doc
.linked
.length
; ++i
) {
6911 var rel
= doc
.linked
[i
];
6912 if (rel
.doc
== skip
) continue;
6913 var shared
= sharedHist
&& rel
.sharedHist
;
6914 if (sharedHistOnly
&& !shared
) continue;
6916 propagate(rel
.doc
, doc
, shared
);
6919 propagate(doc
, null, true);
6922 // Attach a document to an editor.
6923 function attachDoc(cm
, doc
) {
6924 if (doc
.cm
) throw new Error("This document is already in use.");
6927 estimateLineHeights(cm
);
6929 if (!cm
.options
.lineWrapping
) findMaxLine(cm
);
6930 cm
.options
.mode
= doc
.modeOption
;
6936 // Find the line object corresponding to the given line number.
6937 function getLine(doc
, n
) {
6939 if (n
< 0 || n
>= doc
.size
) throw new Error("There is no line " + (n
+ doc
.first
) + " in the document.");
6940 for (var chunk
= doc
; !chunk
.lines
;) {
6941 for (var i
= 0;; ++i
) {
6942 var child
= chunk
.children
[i
], sz
= child
.chunkSize();
6943 if (n
< sz
) { chunk
= child
; break; }
6947 return chunk
.lines
[n
];
6950 // Get the part of a document between two positions, as an array of
6952 function getBetween(doc
, start
, end
) {
6953 var out
= [], n
= start
.line
;
6954 doc
.iter(start
.line
, end
.line
+ 1, function(line
) {
6955 var text
= line
.text
;
6956 if (n
== end
.line
) text
= text
.slice(0, end
.ch
);
6957 if (n
== start
.line
) text
= text
.slice(start
.ch
);
6963 // Get the lines between from and to, as array of strings.
6964 function getLines(doc
, from, to
) {
6966 doc
.iter(from, to
, function(line
) { out
.push(line
.text
); });
6970 // Update the height of a line, propagating the height change
6971 // upwards to parent nodes.
6972 function updateLineHeight(line
, height
) {
6973 var diff
= height
- line
.height
;
6974 if (diff
) for (var n
= line
; n
; n
= n
.parent
) n
.height
+= diff
;
6977 // Given a line object, find its line number by walking up through
6978 // its parent links.
6979 function lineNo(line
) {
6980 if (line
.parent
== null) return null;
6981 var cur
= line
.parent
, no
= indexOf(cur
.lines
, line
);
6982 for (var chunk
= cur
.parent
; chunk
; cur
= chunk
, chunk
= chunk
.parent
) {
6983 for (var i
= 0;; ++i
) {
6984 if (chunk
.children
[i
] == cur
) break;
6985 no
+= chunk
.children
[i
].chunkSize();
6988 return no
+ cur
.first
;
6991 // Find the line at the given vertical position, using the height
6992 // information in the document tree.
6993 function lineAtHeight(chunk
, h
) {
6994 var n
= chunk
.first
;
6996 for (var i
= 0; i
< chunk
.children
.length
; ++i
) {
6997 var child
= chunk
.children
[i
], ch
= child
.height
;
6998 if (h
< ch
) { chunk
= child
; continue outer
; }
7000 n
+= child
.chunkSize();
7003 } while (!chunk
.lines
);
7004 for (var i
= 0; i
< chunk
.lines
.length
; ++i
) {
7005 var line
= chunk
.lines
[i
], lh
= line
.height
;
7013 // Find the height above the given line.
7014 function heightAtLine(lineObj
) {
7015 lineObj
= visualLine(lineObj
);
7017 var h
= 0, chunk
= lineObj
.parent
;
7018 for (var i
= 0; i
< chunk
.lines
.length
; ++i
) {
7019 var line
= chunk
.lines
[i
];
7020 if (line
== lineObj
) break;
7021 else h
+= line
.height
;
7023 for (var p
= chunk
.parent
; p
; chunk
= p
, p
= chunk
.parent
) {
7024 for (var i
= 0; i
< p
.children
.length
; ++i
) {
7025 var cur
= p
.children
[i
];
7026 if (cur
== chunk
) break;
7027 else h
+= cur
.height
;
7033 // Get the bidi ordering for the given line (and cache it). Returns
7034 // false for lines that are fully left-to-right, and an array of
7035 // BidiSpan objects otherwise.
7036 function getOrder(line
) {
7037 var order
= line
.order
;
7038 if (order
== null) order
= line
.order
= bidiOrdering(line
.text
);
7044 function History(startGen
) {
7045 // Arrays of change events and selections. Doing something adds an
7046 // event to done and clears undo. Undoing moves events from done
7047 // to undone, redoing moves them in the other direction.
7048 this.done
= []; this.undone
= [];
7049 this.undoDepth
= Infinity
;
7050 // Used to track when changes can be merged into a single undo
7052 this.lastModTime
= this.lastSelTime
= 0;
7053 this.lastOp
= this.lastSelOp
= null;
7054 this.lastOrigin
= this.lastSelOrigin
= null;
7055 // Used by the isClean() method
7056 this.generation
= this.maxGeneration
= startGen
|| 1;
7059 // Create a history change event from an updateDoc-style change
7061 function historyChangeFromChange(doc
, change
) {
7062 var histChange
= {from: copyPos(change
.from), to
: changeEnd(change
), text
: getBetween(doc
, change
.from, change
.to
)};
7063 attachLocalSpans(doc
, histChange
, change
.from.line
, change
.to
.line
+ 1);
7064 linkedDocs(doc
, function(doc
) {attachLocalSpans(doc
, histChange
, change
.from.line
, change
.to
.line
+ 1);}, true);
7068 // Pop all selection events off the end of a history array. Stop at
7070 function clearSelectionEvents(array
) {
7071 while (array
.length
) {
7072 var last
= lst(array
);
7073 if (last
.ranges
) array
.pop();
7078 // Find the top change event in the history. Pop off selection
7079 // events that are in the way.
7080 function lastChangeEvent(hist
, force
) {
7082 clearSelectionEvents(hist
.done
);
7083 return lst(hist
.done
);
7084 } else if (hist
.done
.length
&& !lst(hist
.done
).ranges
) {
7085 return lst(hist
.done
);
7086 } else if (hist
.done
.length
> 1 && !hist
.done
[hist
.done
.length
- 2].ranges
) {
7088 return lst(hist
.done
);
7092 // Register a change in the history. Merges changes that are within
7093 // a single operation, ore are close together with an origin that
7094 // allows merging (starting with "+") into a single event.
7095 function addChangeToHistory(doc
, change
, selAfter
, opId
) {
7096 var hist
= doc
.history
;
7097 hist
.undone
.length
= 0;
7098 var time
= +new Date
, cur
;
7100 if ((hist
.lastOp
== opId
||
7101 hist
.lastOrigin
== change
.origin
&& change
.origin
&&
7102 ((change
.origin
.charAt(0) == "+" && doc
.cm
&& hist
.lastModTime
> time
- doc
.cm
.options
.historyEventDelay
) ||
7103 change
.origin
.charAt(0) == "*")) &&
7104 (cur
= lastChangeEvent(hist
, hist
.lastOp
== opId
))) {
7105 // Merge this change into the last event
7106 var last
= lst(cur
.changes
);
7107 if (cmp(change
.from, change
.to
) == 0 && cmp(change
.from, last
.to
) == 0) {
7108 // Optimized case for simple insertion -- don't want to add
7109 // new changesets for every character typed
7110 last
.to
= changeEnd(change
);
7112 // Add new sub-event
7113 cur
.changes
.push(historyChangeFromChange(doc
, change
));
7116 // Can not be merged, start a new event.
7117 var before
= lst(hist
.done
);
7118 if (!before
|| !before
.ranges
)
7119 pushSelectionToHistory(doc
.sel
, hist
.done
);
7120 cur
= {changes
: [historyChangeFromChange(doc
, change
)],
7121 generation
: hist
.generation
};
7122 hist
.done
.push(cur
);
7123 while (hist
.done
.length
> hist
.undoDepth
) {
7125 if (!hist
.done
[0].ranges
) hist
.done
.shift();
7128 hist
.done
.push(selAfter
);
7129 hist
.generation
= ++hist
.maxGeneration
;
7130 hist
.lastModTime
= hist
.lastSelTime
= time
;
7131 hist
.lastOp
= hist
.lastSelOp
= opId
;
7132 hist
.lastOrigin
= hist
.lastSelOrigin
= change
.origin
;
7134 if (!last
) signal(doc
, "historyAdded");
7137 function selectionEventCanBeMerged(doc
, origin
, prev
, sel
) {
7138 var ch
= origin
.charAt(0);
7141 prev
.ranges
.length
== sel
.ranges
.length
&&
7142 prev
.somethingSelected() == sel
.somethingSelected() &&
7143 new Date
- doc
.history
.lastSelTime
<= (doc
.cm
? doc
.cm
.options
.historyEventDelay
: 500);
7146 // Called whenever the selection changes, sets the new selection as
7147 // the pending selection in the history, and pushes the old pending
7148 // selection into the 'done' array when it was significantly
7149 // different (in number of selected ranges, emptiness, or time).
7150 function addSelectionToHistory(doc
, sel
, opId
, options
) {
7151 var hist
= doc
.history
, origin
= options
&& options
.origin
;
7153 // A new event is started when the previous origin does not match
7154 // the current, or the origins don't allow matching. Origins
7155 // starting with * are always merged, those starting with + are
7156 // merged when similar and close together in time.
7157 if (opId
== hist
.lastSelOp
||
7158 (origin
&& hist
.lastSelOrigin
== origin
&&
7159 (hist
.lastModTime
== hist
.lastSelTime
&& hist
.lastOrigin
== origin
||
7160 selectionEventCanBeMerged(doc
, origin
, lst(hist
.done
), sel
))))
7161 hist
.done
[hist
.done
.length
- 1] = sel
;
7163 pushSelectionToHistory(sel
, hist
.done
);
7165 hist
.lastSelTime
= +new Date
;
7166 hist
.lastSelOrigin
= origin
;
7167 hist
.lastSelOp
= opId
;
7168 if (options
&& options
.clearRedo
!== false)
7169 clearSelectionEvents(hist
.undone
);
7172 function pushSelectionToHistory(sel
, dest
) {
7173 var top
= lst(dest
);
7174 if (!(top
&& top
.ranges
&& top
.equals(sel
)))
7178 // Used to store marked span information in the history.
7179 function attachLocalSpans(doc
, change
, from, to
) {
7180 var existing
= change
["spans_" + doc
.id
], n
= 0;
7181 doc
.iter(Math
.max(doc
.first
, from), Math
.min(doc
.first
+ doc
.size
, to
), function(line
) {
7182 if (line
.markedSpans
)
7183 (existing
|| (existing
= change
["spans_" + doc
.id
] = {}))[n
] = line
.markedSpans
;
7188 // When un/re-doing restores text containing marked spans, those
7189 // that have been explicitly cleared should not be restored.
7190 function removeClearedSpans(spans
) {
7191 if (!spans
) return null;
7192 for (var i
= 0, out
; i
< spans
.length
; ++i
) {
7193 if (spans
[i
].marker
.explicitlyCleared
) { if (!out
) out
= spans
.slice(0, i
); }
7194 else if (out
) out
.push(spans
[i
]);
7196 return !out
? spans
: out
.length
? out
: null;
7199 // Retrieve and filter the old marked spans stored in a change event.
7200 function getOldSpans(doc
, change
) {
7201 var found
= change
["spans_" + doc
.id
];
7202 if (!found
) return null;
7203 for (var i
= 0, nw
= []; i
< change
.text
.length
; ++i
)
7204 nw
.push(removeClearedSpans(found
[i
]));
7208 // Used both to provide a JSON-safe object in .getHistory, and, when
7209 // detaching a document, to split the history in two
7210 function copyHistoryArray(events
, newGroup
, instantiateSel
) {
7211 for (var i
= 0, copy
= []; i
< events
.length
; ++i
) {
7212 var event
= events
[i
];
7214 copy
.push(instantiateSel
? Selection
.prototype.deepCopy
.call(event
) : event
);
7217 var changes
= event
.changes
, newChanges
= [];
7218 copy
.push({changes
: newChanges
});
7219 for (var j
= 0; j
< changes
.length
; ++j
) {
7220 var change
= changes
[j
], m
;
7221 newChanges
.push({from: change
.from, to
: change
.to
, text
: change
.text
});
7222 if (newGroup
) for (var prop
in change
) if (m
= prop
.match(/^spans_(\d+)$/)) {
7223 if (indexOf(newGroup
, Number(m
[1])) > -1) {
7224 lst(newChanges
)[prop
] = change
[prop
];
7225 delete change
[prop
];
7233 // Rebasing/resetting history to deal with externally-sourced changes
7235 function rebaseHistSelSingle(pos
, from, to
, diff
) {
7236 if (to
< pos
.line
) {
7238 } else if (from < pos
.line
) {
7244 // Tries to rebase an array of history events given a change in the
7245 // document. If the change touches the same lines as the event, the
7246 // event, and everything 'behind' it, is discarded. If the change is
7247 // before the event, the event's positions are updated. Uses a
7248 // copy-on-write scheme for the positions, to avoid having to
7249 // reallocate them all on every rebase, but also avoid problems with
7250 // shared position objects being unsafely updated.
7251 function rebaseHistArray(array
, from, to
, diff
) {
7252 for (var i
= 0; i
< array
.length
; ++i
) {
7253 var sub
= array
[i
], ok
= true;
7255 if (!sub
.copied
) { sub
= array
[i
] = sub
.deepCopy(); sub
.copied
= true; }
7256 for (var j
= 0; j
< sub
.ranges
.length
; j
++) {
7257 rebaseHistSelSingle(sub
.ranges
[j
].anchor
, from, to
, diff
);
7258 rebaseHistSelSingle(sub
.ranges
[j
].head
, from, to
, diff
);
7262 for (var j
= 0; j
< sub
.changes
.length
; ++j
) {
7263 var cur
= sub
.changes
[j
];
7264 if (to
< cur
.from.line
) {
7265 cur
.from = Pos(cur
.from.line
+ diff
, cur
.from.ch
);
7266 cur
.to
= Pos(cur
.to
.line
+ diff
, cur
.to
.ch
);
7267 } else if (from <= cur
.to
.line
) {
7273 array
.splice(0, i
+ 1);
7279 function rebaseHist(hist
, change
) {
7280 var from = change
.from.line
, to
= change
.to
.line
, diff
= change
.text
.length
- (to
- from) - 1;
7281 rebaseHistArray(hist
.done
, from, to
, diff
);
7282 rebaseHistArray(hist
.undone
, from, to
, diff
);
7287 // Due to the fact that we still support jurassic IE versions, some
7288 // compatibility wrappers are needed.
7290 var e_preventDefault
= CodeMirror
.e_preventDefault = function(e
) {
7291 if (e
.preventDefault
) e
.preventDefault();
7292 else e
.returnValue
= false;
7294 var e_stopPropagation
= CodeMirror
.e_stopPropagation = function(e
) {
7295 if (e
.stopPropagation
) e
.stopPropagation();
7296 else e
.cancelBubble
= true;
7298 function e_defaultPrevented(e
) {
7299 return e
.defaultPrevented
!= null ? e
.defaultPrevented
: e
.returnValue
== false;
7301 var e_stop
= CodeMirror
.e_stop = function(e
) {e_preventDefault(e
); e_stopPropagation(e
);};
7303 function e_target(e
) {return e
.target
|| e
.srcElement
;}
7304 function e_button(e
) {
7307 if (e
.button
& 1) b
= 1;
7308 else if (e
.button
& 2) b
= 3;
7309 else if (e
.button
& 4) b
= 2;
7311 if (mac
&& e
.ctrlKey
&& b
== 1) b
= 3;
7317 // Lightweight event framework. on/off also work on DOM nodes,
7318 // registering native DOM handlers.
7320 var on
= CodeMirror
.on = function(emitter
, type
, f
) {
7321 if (emitter
.addEventListener
)
7322 emitter
.addEventListener(type
, f
, false);
7323 else if (emitter
.attachEvent
)
7324 emitter
.attachEvent("on" + type
, f
);
7326 var map
= emitter
._handlers
|| (emitter
._handlers
= {});
7327 var arr
= map
[type
] || (map
[type
] = []);
7332 var off
= CodeMirror
.off = function(emitter
, type
, f
) {
7333 if (emitter
.removeEventListener
)
7334 emitter
.removeEventListener(type
, f
, false);
7335 else if (emitter
.detachEvent
)
7336 emitter
.detachEvent("on" + type
, f
);
7338 var arr
= emitter
._handlers
&& emitter
._handlers
[type
];
7340 for (var i
= 0; i
< arr
.length
; ++i
)
7341 if (arr
[i
] == f
) { arr
.splice(i
, 1); break; }
7345 var signal
= CodeMirror
.signal = function(emitter
, type
/*, values...*/) {
7346 var arr
= emitter
._handlers
&& emitter
._handlers
[type
];
7348 var args
= Array
.prototype.slice
.call(arguments
, 2);
7349 for (var i
= 0; i
< arr
.length
; ++i
) arr
[i
].apply(null, args
);
7352 var orphanDelayedCallbacks
= null;
7354 // Often, we want to signal events at a point where we are in the
7355 // middle of some work, but don't want the handler to start calling
7356 // other methods on the editor, which might be in an inconsistent
7357 // state or simply not expect any other events to happen.
7358 // signalLater looks whether there are any handlers, and schedules
7359 // them to be executed when the last operation ends, or, if no
7360 // operation is active, when a timeout fires.
7361 function signalLater(emitter
, type
/*, values...*/) {
7362 var arr
= emitter
._handlers
&& emitter
._handlers
[type
];
7364 var args
= Array
.prototype.slice
.call(arguments
, 2), list
;
7365 if (operationGroup
) {
7366 list
= operationGroup
.delayedCallbacks
;
7367 } else if (orphanDelayedCallbacks
) {
7368 list
= orphanDelayedCallbacks
;
7370 list
= orphanDelayedCallbacks
= [];
7371 setTimeout(fireOrphanDelayed
, 0);
7373 function bnd(f
) {return function(){f
.apply(null, args
);};};
7374 for (var i
= 0; i
< arr
.length
; ++i
)
7375 list
.push(bnd(arr
[i
]));
7378 function fireOrphanDelayed() {
7379 var delayed
= orphanDelayedCallbacks
;
7380 orphanDelayedCallbacks
= null;
7381 for (var i
= 0; i
< delayed
.length
; ++i
) delayed
[i
]();
7384 // The DOM events that CodeMirror handles can be overridden by
7385 // registering a (non-DOM) handler on the editor for the event name,
7386 // and preventDefault-ing the event in that handler.
7387 function signalDOMEvent(cm
, e
, override
) {
7388 if (typeof e
== "string")
7389 e
= {type
: e
, preventDefault: function() { this.defaultPrevented
= true; }};
7390 signal(cm
, override
|| e
.type
, cm
, e
);
7391 return e_defaultPrevented(e
) || e
.codemirrorIgnore
;
7394 function signalCursorActivity(cm
) {
7395 var arr
= cm
._handlers
&& cm
._handlers
.cursorActivity
;
7397 var set = cm
.curOp
.cursorActivityHandlers
|| (cm
.curOp
.cursorActivityHandlers
= []);
7398 for (var i
= 0; i
< arr
.length
; ++i
) if (indexOf(set, arr
[i
]) == -1)
7402 function hasHandler(emitter
, type
) {
7403 var arr
= emitter
._handlers
&& emitter
._handlers
[type
];
7404 return arr
&& arr
.length
> 0;
7407 // Add on and off methods to a constructor's prototype, to make
7408 // registering events on such objects more convenient.
7409 function eventMixin(ctor
) {
7410 ctor
.prototype.on = function(type
, f
) {on(this, type
, f
);};
7411 ctor
.prototype.off = function(type
, f
) {off(this, type
, f
);};
7416 // Number of pixels added to scroller and sizer to hide scrollbar
7417 var scrollerGap
= 30;
7419 // Returned or thrown by various protocols to signal 'I'm not
7421 var Pass
= CodeMirror
.Pass
= {toString: function(){return "CodeMirror.Pass";}};
7423 // Reused option objects for setSelection & friends
7424 var sel_dontScroll
= {scroll
: false}, sel_mouse
= {origin
: "*mouse"}, sel_move
= {origin
: "+move"};
7426 function Delayed() {this.id
= null;}
7427 Delayed
.prototype.set = function(ms
, f
) {
7428 clearTimeout(this.id
);
7429 this.id
= setTimeout(f
, ms
);
7432 // Counts the column offset in a string, taking tabs into account.
7433 // Used mostly to find indentation.
7434 var countColumn
= CodeMirror
.countColumn = function(string
, end
, tabSize
, startIndex
, startValue
) {
7436 end
= string
.search(/[^\s\u00a0]/);
7437 if (end
== -1) end
= string
.length
;
7439 for (var i
= startIndex
|| 0, n
= startValue
|| 0;;) {
7440 var nextTab
= string
.indexOf("\t", i
);
7441 if (nextTab
< 0 || nextTab
>= end
)
7442 return n
+ (end
- i
);
7444 n
+= tabSize
- (n
% tabSize
);
7449 // The inverse of countColumn -- find the offset that corresponds to
7450 // a particular column.
7451 function findColumn(string
, goal
, tabSize
) {
7452 for (var pos
= 0, col
= 0;;) {
7453 var nextTab
= string
.indexOf("\t", pos
);
7454 if (nextTab
== -1) nextTab
= string
.length
;
7455 var skipped
= nextTab
- pos
;
7456 if (nextTab
== string
.length
|| col
+ skipped
>= goal
)
7457 return pos
+ Math
.min(skipped
, goal
- col
);
7458 col
+= nextTab
- pos
;
7459 col
+= tabSize
- (col
% tabSize
);
7461 if (col
>= goal
) return pos
;
7465 var spaceStrs
= [""];
7466 function spaceStr(n
) {
7467 while (spaceStrs
.length
<= n
)
7468 spaceStrs
.push(lst(spaceStrs
) + " ");
7469 return spaceStrs
[n
];
7472 function lst(arr
) { return arr
[arr
.length
-1]; }
7474 var selectInput = function(node
) { node
.select(); };
7475 if (ios
) // Mobile Safari apparently has a bug where select() is broken.
7476 selectInput = function(node
) { node
.selectionStart
= 0; node
.selectionEnd
= node
.value
.length
; };
7477 else if (ie
) // Suppress mysterious IE10 errors
7478 selectInput = function(node
) { try { node
.select(); } catch(_e
) {} };
7480 function indexOf(array
, elt
) {
7481 for (var i
= 0; i
< array
.length
; ++i
)
7482 if (array
[i
] == elt
) return i
;
7485 function map(array
, f
) {
7487 for (var i
= 0; i
< array
.length
; i
++) out
[i
] = f(array
[i
], i
);
7491 function createObj(base
, props
) {
7493 if (Object
.create
) {
7494 inst
= Object
.create(base
);
7496 var ctor = function() {};
7497 ctor
.prototype = base
;
7500 if (props
) copyObj(props
, inst
);
7504 function copyObj(obj
, target
, overwrite
) {
7505 if (!target
) target
= {};
7506 for (var prop
in obj
)
7507 if (obj
.hasOwnProperty(prop
) && (overwrite
!== false || !target
.hasOwnProperty(prop
)))
7508 target
[prop
] = obj
[prop
];
7513 var args
= Array
.prototype.slice
.call(arguments
, 1);
7514 return function(){return f
.apply(null, args
);};
7517 var nonASCIISingleCaseWordChar
= /[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
7518 var isWordCharBasic
= CodeMirror
.isWordChar = function(ch
) {
7519 return /\w/.test(ch
) || ch
> "\x80" &&
7520 (ch
.toUpperCase() != ch
.toLowerCase() || nonASCIISingleCaseWordChar
.test(ch
));
7522 function isWordChar(ch
, helper
) {
7523 if (!helper
) return isWordCharBasic(ch
);
7524 if (helper
.source
.indexOf("\\w") > -1 && isWordCharBasic(ch
)) return true;
7525 return helper
.test(ch
);
7528 function isEmpty(obj
) {
7529 for (var n
in obj
) if (obj
.hasOwnProperty(n
) && obj
[n
]) return false;
7533 // Extending unicode characters. A series of a non-extending char +
7534 // any number of extending chars is treated as a single unit as far
7535 // as editing and measuring is concerned. This is not fully correct,
7536 // since some scripts/fonts/browsers also treat other configurations
7537 // of code points as a group.
7538 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]/;
7539 function isExtendingChar(ch
) { return ch
.charCodeAt(0) >= 768 && extendingChars
.test(ch
); }
7543 function elt(tag
, content
, className
, style
) {
7544 var e
= document
.createElement(tag
);
7545 if (className
) e
.className
= className
;
7546 if (style
) e
.style
.cssText
= style
;
7547 if (typeof content
== "string") e
.appendChild(document
.createTextNode(content
));
7548 else if (content
) for (var i
= 0; i
< content
.length
; ++i
) e
.appendChild(content
[i
]);
7553 if (document
.createRange
) range = function(node
, start
, end
) {
7554 var r
= document
.createRange();
7555 r
.setEnd(node
, end
);
7556 r
.setStart(node
, start
);
7559 else range = function(node
, start
, end
) {
7560 var r
= document
.body
.createTextRange();
7561 try { r
.moveToElementText(node
.parentNode
); }
7562 catch(e
) { return r
; }
7564 r
.moveEnd("character", end
);
7565 r
.moveStart("character", start
);
7569 function removeChildren(e
) {
7570 for (var count
= e
.childNodes
.length
; count
> 0; --count
)
7571 e
.removeChild(e
.firstChild
);
7575 function removeChildrenAndAdd(parent
, e
) {
7576 return removeChildren(parent
).appendChild(e
);
7579 function contains(parent
, child
) {
7580 if (parent
.contains
)
7581 return parent
.contains(child
);
7582 while (child
= child
.parentNode
)
7583 if (child
== parent
) return true;
7586 function activeElt() { return document
.activeElement
; }
7587 // Older versions of IE throws unspecified error when touching
7588 // document.activeElement in some cases (during loading, in iframe)
7589 if (ie
&& ie_version
< 11) activeElt = function() {
7590 try { return document
.activeElement
; }
7591 catch(e
) { return document
.body
; }
7594 function classTest(cls
) { return new RegExp("(^|\\s)" + cls
+ "(?:$|\\s)\\s*"); }
7595 var rmClass
= CodeMirror
.rmClass = function(node
, cls
) {
7596 var current
= node
.className
;
7597 var match
= classTest(cls
).exec(current
);
7599 var after
= current
.slice(match
.index
+ match
[0].length
);
7600 node
.className
= current
.slice(0, match
.index
) + (after
? match
[1] + after
: "");
7603 var addClass
= CodeMirror
.addClass = function(node
, cls
) {
7604 var current
= node
.className
;
7605 if (!classTest(cls
).test(current
)) node
.className
+= (current
? " " : "") + cls
;
7607 function joinClasses(a
, b
) {
7608 var as
= a
.split(" ");
7609 for (var i
= 0; i
< as
.length
; i
++)
7610 if (as
[i
] && !classTest(as
[i
]).test(b
)) b
+= " " + as
[i
];
7614 // WINDOW-WIDE EVENTS
7616 // These must be handled carefully, because naively registering a
7617 // handler for each editor will cause the editors to never be
7618 // garbage collected.
7620 function forEachCodeMirror(f
) {
7621 if (!document
.body
.getElementsByClassName
) return;
7622 var byClass
= document
.body
.getElementsByClassName("CodeMirror");
7623 for (var i
= 0; i
< byClass
.length
; i
++) {
7624 var cm
= byClass
[i
].CodeMirror
;
7629 var globalsRegistered
= false;
7630 function ensureGlobalHandlers() {
7631 if (globalsRegistered
) return;
7632 registerGlobalHandlers();
7633 globalsRegistered
= true;
7635 function registerGlobalHandlers() {
7636 // When the window resizes, we need to refresh active editors.
7638 on(window
, "resize", function() {
7639 if (resizeTimer
== null) resizeTimer
= setTimeout(function() {
7641 forEachCodeMirror(onResize
);
7644 // When the window loses focus, we want to show the editor as blurred
7645 on(window
, "blur", function() {
7646 forEachCodeMirror(onBlur
);
7650 // FEATURE DETECTION
7652 // Detect drag-and-drop
7653 var dragAndDrop = function() {
7654 // There is *some* kind of drag-and-drop support in IE6-8, but I
7655 // couldn't get it to work yet.
7656 if (ie
&& ie_version
< 9) return false;
7657 var div
= elt('div');
7658 return "draggable" in div
|| "dragDrop" in div
;
7662 function zeroWidthElement(measure
) {
7663 if (zwspSupported
== null) {
7664 var test
= elt("span", "\u200b");
7665 removeChildrenAndAdd(measure
, elt("span", [test
, document
.createTextNode("x")]));
7666 if (measure
.firstChild
.offsetHeight
!= 0)
7667 zwspSupported
= test
.offsetWidth
<= 1 && test
.offsetHeight
> 2 && !(ie
&& ie_version
< 8);
7669 if (zwspSupported
) return elt("span", "\u200b");
7670 else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
7673 // Feature-detect IE's crummy client rect reporting for bidi text
7675 function hasBadBidiRects(measure
) {
7676 if (badBidiRects
!= null) return badBidiRects
;
7677 var txt
= removeChildrenAndAdd(measure
, document
.createTextNode("A\u062eA"));
7678 var r0
= range(txt
, 0, 1).getBoundingClientRect();
7679 if (!r0
|| r0
.left
== r0
.right
) return false; // Safari returns null in some cases (#2780)
7680 var r1
= range(txt
, 1, 2).getBoundingClientRect();
7681 return badBidiRects
= (r1
.right
- r0
.right
< 3);
7684 // See if "".split is the broken IE version, if so, provide an
7685 // alternative way to split lines.
7686 var splitLines
= CodeMirror
.splitLines
= "\n\nb".split(/\n/).length
!= 3 ? function(string
) {
7687 var pos
= 0, result
= [], l
= string
.length
;
7689 var nl
= string
.indexOf("\n", pos
);
7690 if (nl
== -1) nl
= string
.length
;
7691 var line
= string
.slice(pos
, string
.charAt(nl
- 1) == "\r" ? nl
- 1 : nl
);
7692 var rt
= line
.indexOf("\r");
7694 result
.push(line
.slice(0, rt
));
7702 } : function(string
){return string
.split(/\r\n?|\n/);};
7704 var hasSelection
= window
.getSelection
? function(te
) {
7705 try { return te
.selectionStart
!= te
.selectionEnd
; }
7706 catch(e
) { return false; }
7708 try {var range
= te
.ownerDocument
.selection
.createRange();}
7710 if (!range
|| range
.parentElement() != te
) return false;
7711 return range
.compareEndPoints("StartToEnd", range
) != 0;
7714 var hasCopyEvent
= (function() {
7716 if ("oncopy" in e
) return true;
7717 e
.setAttribute("oncopy", "return;");
7718 return typeof e
.oncopy
== "function";
7721 var badZoomedRects
= null;
7722 function hasBadZoomedRects(measure
) {
7723 if (badZoomedRects
!= null) return badZoomedRects
;
7724 var node
= removeChildrenAndAdd(measure
, elt("span", "x"));
7725 var normal
= node
.getBoundingClientRect();
7726 var fromRange
= range(node
, 0, 1).getBoundingClientRect();
7727 return badZoomedRects
= Math
.abs(normal
.left
- fromRange
.left
) > 1;
7732 var keyNames
= {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
7733 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
7734 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
7735 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete",
7736 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
7737 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
7738 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"};
7739 CodeMirror
.keyNames
= keyNames
;
7742 for (var i
= 0; i
< 10; i
++) keyNames
[i
+ 48] = keyNames
[i
+ 96] = String(i
);
7744 for (var i
= 65; i
<= 90; i
++) keyNames
[i
] = String
.fromCharCode(i
);
7746 for (var i
= 1; i
<= 12; i
++) keyNames
[i
+ 111] = keyNames
[i
+ 63235] = "F" + i
;
7751 function iterateBidiSections(order
, from, to
, f
) {
7752 if (!order
) return f(from, to
, "ltr");
7754 for (var i
= 0; i
< order
.length
; ++i
) {
7755 var part
= order
[i
];
7756 if (part
.from < to
&& part
.to
> from || from == to
&& part
.to
== from) {
7757 f(Math
.max(part
.from, from), Math
.min(part
.to
, to
), part
.level
== 1 ? "rtl" : "ltr");
7761 if (!found
) f(from, to
, "ltr");
7764 function bidiLeft(part
) { return part
.level
% 2 ? part
.to
: part
.from; }
7765 function bidiRight(part
) { return part
.level
% 2 ? part
.from : part
.to
; }
7767 function lineLeft(line
) { var order
= getOrder(line
); return order
? bidiLeft(order
[0]) : 0; }
7768 function lineRight(line
) {
7769 var order
= getOrder(line
);
7770 if (!order
) return line
.text
.length
;
7771 return bidiRight(lst(order
));
7774 function lineStart(cm
, lineN
) {
7775 var line
= getLine(cm
.doc
, lineN
);
7776 var visual
= visualLine(line
);
7777 if (visual
!= line
) lineN
= lineNo(visual
);
7778 var order
= getOrder(visual
);
7779 var ch
= !order
? 0 : order
[0].level
% 2 ? lineRight(visual
) : lineLeft(visual
);
7780 return Pos(lineN
, ch
);
7782 function lineEnd(cm
, lineN
) {
7783 var merged
, line
= getLine(cm
.doc
, lineN
);
7784 while (merged
= collapsedSpanAtEnd(line
)) {
7785 line
= merged
.find(1, true).line
;
7788 var order
= getOrder(line
);
7789 var ch
= !order
? line
.text
.length
: order
[0].level
% 2 ? lineLeft(line
) : lineRight(line
);
7790 return Pos(lineN
== null ? lineNo(line
) : lineN
, ch
);
7792 function lineStartSmart(cm
, pos
) {
7793 var start
= lineStart(cm
, pos
.line
);
7794 var line
= getLine(cm
.doc
, start
.line
);
7795 var order
= getOrder(line
);
7796 if (!order
|| order
[0].level
== 0) {
7797 var firstNonWS
= Math
.max(0, line
.text
.search(/\S/));
7798 var inWS
= pos
.line
== start
.line
&& pos
.ch
<= firstNonWS
&& pos
.ch
;
7799 return Pos(start
.line
, inWS
? 0 : firstNonWS
);
7804 function compareBidiLevel(order
, a
, b
) {
7805 var linedir
= order
[0].level
;
7806 if (a
== linedir
) return true;
7807 if (b
== linedir
) return false;
7811 function getBidiPartAt(order
, pos
) {
7813 for (var i
= 0, found
; i
< order
.length
; ++i
) {
7815 if (cur
.from < pos
&& cur
.to
> pos
) return i
;
7816 if ((cur
.from == pos
|| cur
.to
== pos
)) {
7817 if (found
== null) {
7819 } else if (compareBidiLevel(order
, cur
.level
, order
[found
].level
)) {
7820 if (cur
.from != cur
.to
) bidiOther
= found
;
7823 if (cur
.from != cur
.to
) bidiOther
= i
;
7831 function moveInLine(line
, pos
, dir
, byUnit
) {
7832 if (!byUnit
) return pos
+ dir
;
7834 while (pos
> 0 && isExtendingChar(line
.text
.charAt(pos
)));
7838 // This is needed in order to move 'visually' through bi-directional
7839 // text -- i.e., pressing left should make the cursor go left, even
7840 // when in RTL text. The tricky part is the 'jumps', where RTL and
7841 // LTR text touch each other. This often requires the cursor offset
7842 // to move more than one unit, in order to visually move one unit.
7843 function moveVisually(line
, start
, dir
, byUnit
) {
7844 var bidi
= getOrder(line
);
7845 if (!bidi
) return moveLogically(line
, start
, dir
, byUnit
);
7846 var pos
= getBidiPartAt(bidi
, start
), part
= bidi
[pos
];
7847 var target
= moveInLine(line
, start
, part
.level
% 2 ? -dir
: dir
, byUnit
);
7850 if (target
> part
.from && target
< part
.to
) return target
;
7851 if (target
== part
.from || target
== part
.to
) {
7852 if (getBidiPartAt(bidi
, target
) == pos
) return target
;
7853 part
= bidi
[pos
+= dir
];
7854 return (dir
> 0) == part
.level
% 2 ? part
.to
: part
.from;
7856 part
= bidi
[pos
+= dir
];
7857 if (!part
) return null;
7858 if ((dir
> 0) == part
.level
% 2)
7859 target
= moveInLine(line
, part
.to
, -1, byUnit
);
7861 target
= moveInLine(line
, part
.from, 1, byUnit
);
7866 function moveLogically(line
, start
, dir
, byUnit
) {
7867 var target
= start
+ dir
;
7868 if (byUnit
) while (target
> 0 && isExtendingChar(line
.text
.charAt(target
))) target
+= dir
;
7869 return target
< 0 || target
> line
.text
.length
? null : target
;
7872 // Bidirectional ordering algorithm
7873 // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
7874 // that this (partially) implements.
7876 // One-char codes used for character types:
7877 // L (L): Left-to-Right
7878 // R (R): Right-to-Left
7879 // r (AL): Right-to-Left Arabic
7880 // 1 (EN): European Number
7881 // + (ES): European Number Separator
7882 // % (ET): European Number Terminator
7883 // n (AN): Arabic Number
7884 // , (CS): Common Number Separator
7885 // m (NSM): Non-Spacing Mark
7886 // b (BN): Boundary Neutral
7887 // s (B): Paragraph Separator
7888 // t (S): Segment Separator
7889 // w (WS): Whitespace
7890 // N (ON): Other Neutrals
7892 // Returns null if characters are ordered as they appear
7893 // (left-to-right), or an array of sections ({from, to, level}
7894 // objects) in the order in which they occur visually.
7895 var bidiOrdering
= (function() {
7896 // Character types for codepoints 0 to 0xff
7897 var lowTypes
= "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
7898 // Character types for codepoints 0x600 to 0x6ff
7899 var arabicTypes
= "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
7900 function charType(code
) {
7901 if (code
<= 0xf7) return lowTypes
.charAt(code
);
7902 else if (0x590 <= code
&& code
<= 0x5f4) return "R";
7903 else if (0x600 <= code
&& code
<= 0x6ed) return arabicTypes
.charAt(code
- 0x600);
7904 else if (0x6ee <= code
&& code
<= 0x8ac) return "r";
7905 else if (0x2000 <= code
&& code
<= 0x200b) return "w";
7906 else if (code
== 0x200c) return "b";
7910 var bidiRE
= /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
7911 var isNeutral
= /[stwN]/, isStrong
= /[LRr]/, countsAsLeft
= /[Lb1n]/, countsAsNum
= /[1n]/;
7912 // Browsers seem to always treat the boundaries of block elements as being L.
7913 var outerType
= "L";
7915 function BidiSpan(level
, from, to
) {
7917 this.from = from; this.to
= to
;
7920 return function(str
) {
7921 if (!bidiRE
.test(str
)) return false;
7922 var len
= str
.length
, types
= [];
7923 for (var i
= 0, type
; i
< len
; ++i
)
7924 types
.push(type
= charType(str
.charCodeAt(i
)));
7926 // W1. Examine each non-spacing mark (NSM) in the level run, and
7927 // change the type of the NSM to the type of the previous
7928 // character. If the NSM is at the start of the level run, it will
7929 // get the type of sor.
7930 for (var i
= 0, prev
= outerType
; i
< len
; ++i
) {
7931 var type
= types
[i
];
7932 if (type
== "m") types
[i
] = prev
;
7936 // W2. Search backwards from each instance of a European number
7937 // until the first strong type (R, L, AL, or sor) is found. If an
7938 // AL is found, change the type of the European number to Arabic
7940 // W3. Change all ALs to R.
7941 for (var i
= 0, cur
= outerType
; i
< len
; ++i
) {
7942 var type
= types
[i
];
7943 if (type
== "1" && cur
== "r") types
[i
] = "n";
7944 else if (isStrong
.test(type
)) { cur
= type
; if (type
== "r") types
[i
] = "R"; }
7947 // W4. A single European separator between two European numbers
7948 // changes to a European number. A single common separator between
7949 // two numbers of the same type changes to that type.
7950 for (var i
= 1, prev
= types
[0]; i
< len
- 1; ++i
) {
7951 var type
= types
[i
];
7952 if (type
== "+" && prev
== "1" && types
[i
+1] == "1") types
[i
] = "1";
7953 else if (type
== "," && prev
== types
[i
+1] &&
7954 (prev
== "1" || prev
== "n")) types
[i
] = prev
;
7958 // W5. A sequence of European terminators adjacent to European
7959 // numbers changes to all European numbers.
7960 // W6. Otherwise, separators and terminators change to Other
7962 for (var i
= 0; i
< len
; ++i
) {
7963 var type
= types
[i
];
7964 if (type
== ",") types
[i
] = "N";
7965 else if (type
== "%") {
7966 for (var end
= i
+ 1; end
< len
&& types
[end
] == "%"; ++end
) {}
7967 var replace
= (i
&& types
[i
-1] == "!") || (end
< len
&& types
[end
] == "1") ? "1" : "N";
7968 for (var j
= i
; j
< end
; ++j
) types
[j
] = replace
;
7973 // W7. Search backwards from each instance of a European number
7974 // until the first strong type (R, L, or sor) is found. If an L is
7975 // found, then change the type of the European number to L.
7976 for (var i
= 0, cur
= outerType
; i
< len
; ++i
) {
7977 var type
= types
[i
];
7978 if (cur
== "L" && type
== "1") types
[i
] = "L";
7979 else if (isStrong
.test(type
)) cur
= type
;
7982 // N1. A sequence of neutrals takes the direction of the
7983 // surrounding strong text if the text on both sides has the same
7984 // direction. European and Arabic numbers act as if they were R in
7985 // terms of their influence on neutrals. Start-of-level-run (sor)
7986 // and end-of-level-run (eor) are used at level run boundaries.
7987 // N2. Any remaining neutrals take the embedding direction.
7988 for (var i
= 0; i
< len
; ++i
) {
7989 if (isNeutral
.test(types
[i
])) {
7990 for (var end
= i
+ 1; end
< len
&& isNeutral
.test(types
[end
]); ++end
) {}
7991 var before
= (i
? types
[i
-1] : outerType
) == "L";
7992 var after
= (end
< len
? types
[end
] : outerType
) == "L";
7993 var replace
= before
|| after
? "L" : "R";
7994 for (var j
= i
; j
< end
; ++j
) types
[j
] = replace
;
7999 // Here we depart from the documented algorithm, in order to avoid
8000 // building up an actual levels array. Since there are only three
8001 // levels (0, 1, 2) in an implementation that doesn't take
8002 // explicit embedding into account, we can build up the order on
8003 // the fly, without following the level-based algorithm.
8005 for (var i
= 0; i
< len
;) {
8006 if (countsAsLeft
.test(types
[i
])) {
8008 for (++i
; i
< len
&& countsAsLeft
.test(types
[i
]); ++i
) {}
8009 order
.push(new BidiSpan(0, start
, i
));
8011 var pos
= i
, at
= order
.length
;
8012 for (++i
; i
< len
&& types
[i
] != "L"; ++i
) {}
8013 for (var j
= pos
; j
< i
;) {
8014 if (countsAsNum
.test(types
[j
])) {
8015 if (pos
< j
) order
.splice(at
, 0, new BidiSpan(1, pos
, j
));
8017 for (++j
; j
< i
&& countsAsNum
.test(types
[j
]); ++j
) {}
8018 order
.splice(at
, 0, new BidiSpan(2, nstart
, j
));
8022 if (pos
< i
) order
.splice(at
, 0, new BidiSpan(1, pos
, i
));
8025 if (order
[0].level
== 1 && (m
= str
.match(/^\s+/))) {
8026 order
[0].from = m
[0].length
;
8027 order
.unshift(new BidiSpan(0, 0, m
[0].length
));
8029 if (lst(order
).level
== 1 && (m
= str
.match(/\s+$/))) {
8030 lst(order
).to
-= m
[0].length
;
8031 order
.push(new BidiSpan(0, len
- m
[0].length
, len
));
8033 if (order
[0].level
!= lst(order
).level
)
8034 order
.push(new BidiSpan(order
[0].level
, len
, len
));
8042 CodeMirror
.version
= "4.12.0";