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