Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
malwaredllc
GitHub Repository: malwaredllc/byob
Path: blob/master/web-gui/buildyourownbotnet/assets/js/codemirror/lib/codemirror.js
1293 views
1
// CodeMirror version 3.21
2
//
3
// CodeMirror is the only global var we claim
4
window.CodeMirror = (function() {
5
"use strict";
6
7
// BROWSER SNIFFING
8
9
// Crude, but necessary to handle a number of hard-to-feature-detect
10
// bugs and behavior differences.
11
var gecko = /gecko\/\d/i.test(navigator.userAgent);
12
// IE11 currently doesn't count as 'ie', since it has almost none of
13
// the same bugs as earlier versions. Use ie_gt10 to handle
14
// incompatibilities in that version.
15
var old_ie = /MSIE \d/.test(navigator.userAgent);
16
var ie_lt8 = old_ie && (document.documentMode == null || document.documentMode < 8);
17
var ie_lt9 = old_ie && (document.documentMode == null || document.documentMode < 9);
18
var ie_gt10 = /Trident\/([7-9]|\d{2,})\./.test(navigator.userAgent);
19
var ie = old_ie || ie_gt10;
20
var webkit = /WebKit\//.test(navigator.userAgent);
21
var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
22
var chrome = /Chrome\//.test(navigator.userAgent);
23
var opera = /Opera\//.test(navigator.userAgent);
24
var safari = /Apple Computer/.test(navigator.vendor);
25
var khtml = /KHTML\//.test(navigator.userAgent);
26
var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent);
27
var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
28
var phantom = /PhantomJS/.test(navigator.userAgent);
29
30
var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
31
// This is woefully incomplete. Suggestions for alternative methods welcome.
32
var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
33
var mac = ios || /Mac/.test(navigator.platform);
34
var windows = /win/i.test(navigator.platform);
35
36
var opera_version = opera && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
37
if (opera_version) opera_version = Number(opera_version[1]);
38
if (opera_version && opera_version >= 15) { opera = false; webkit = true; }
39
// Some browsers use the wrong event properties to signal cmd/ctrl on OS X
40
var flipCtrlCmd = mac && (qtwebkit || opera && (opera_version == null || opera_version < 12.11));
41
var captureMiddleClick = gecko || (old_ie && !ie_lt9);
42
43
// Optimize some code when these features are not used
44
var sawReadOnlySpans = false, sawCollapsedSpans = false;
45
46
// CONSTRUCTOR
47
48
function CodeMirror(place, options) {
49
if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
50
51
this.options = options = options || {};
52
// Determine effective options based on given values and defaults.
53
for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt))
54
options[opt] = defaults[opt];
55
setGuttersForLineNumbers(options);
56
57
var docStart = typeof options.value == "string" ? 0 : options.value.first;
58
var display = this.display = makeDisplay(place, docStart);
59
display.wrapper.CodeMirror = this;
60
updateGutters(this);
61
if (options.autofocus && !mobile) focusInput(this);
62
63
this.state = {keyMaps: [],
64
overlays: [],
65
modeGen: 0,
66
overwrite: false, focused: false,
67
suppressEdits: false,
68
pasteIncoming: false, cutIncoming: false,
69
draggingText: false,
70
highlight: new Delayed()};
71
72
themeChanged(this);
73
if (options.lineWrapping)
74
this.display.wrapper.className += " CodeMirror-wrap";
75
76
var doc = options.value;
77
if (typeof doc == "string") doc = new Doc(options.value, options.mode);
78
operation(this, attachDoc)(this, doc);
79
80
// Override magic textarea content restore that IE sometimes does
81
// on our hidden textarea on reload
82
if (old_ie) setTimeout(bind(resetInput, this, true), 20);
83
84
registerEventHandlers(this);
85
// IE throws unspecified error in certain cases, when
86
// trying to access activeElement before onload
87
var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { }
88
if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20);
89
else onBlur(this);
90
91
operation(this, function() {
92
for (var opt in optionHandlers)
93
if (optionHandlers.propertyIsEnumerable(opt))
94
optionHandlers[opt](this, options[opt], Init);
95
for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
96
})();
97
}
98
99
// DISPLAY CONSTRUCTOR
100
101
function makeDisplay(place, docStart) {
102
var d = {};
103
104
var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none; font-size: 4px;");
105
if (webkit) input.style.width = "1000px";
106
else input.setAttribute("wrap", "off");
107
// if border: 0; -- iOS fails to open keyboard (issue #1287)
108
if (ios) input.style.border = "1px solid black";
109
input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false");
110
111
// Wraps and hides input textarea
112
d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
113
// The actual fake scrollbars.
114
d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar");
115
d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar");
116
d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
117
d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
118
// DIVs containing the selection and the actual code
119
d.lineDiv = elt("div", null, "CodeMirror-code");
120
d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
121
// Blinky cursor, and element used to ensure cursor fits at the end of a line
122
d.cursor = elt("div", "\u00a0", "CodeMirror-cursor");
123
// Secondary cursor, shown when on a 'jump' in bi-directional text
124
d.otherCursor = elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor");
125
// Used to measure text size
126
d.measure = elt("div", null, "CodeMirror-measure");
127
// Wraps everything that needs to exist inside the vertically-padded coordinate system
128
d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor],
129
null, "position: relative; outline: none");
130
// Moved around its parent to cover visible view
131
d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
132
// Set to the height of the text, causes scrolling
133
d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
134
// D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers
135
d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;");
136
// Will contain the gutters, if any
137
d.gutters = elt("div", null, "CodeMirror-gutters");
138
d.lineGutter = null;
139
// Provides scrolling
140
d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
141
d.scroller.setAttribute("tabIndex", "-1");
142
// The element in which the editor lives.
143
d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV,
144
d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
145
// Work around IE7 z-index bug
146
if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
147
if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper);
148
149
// Needed to hide big blue blinking cursor on Mobile Safari
150
if (ios) input.style.width = "0px";
151
if (!webkit) d.scroller.draggable = true;
152
// Needed to handle Tab key in KHTML
153
if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
154
// Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
155
else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px";
156
157
// Current visible range (may be bigger than the view window).
158
d.viewOffset = d.lastSizeC = 0;
159
d.showingFrom = d.showingTo = docStart;
160
161
// Used to only resize the line number gutter when necessary (when
162
// the amount of lines crosses a boundary that makes its width change)
163
d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
164
// See readInput and resetInput
165
d.prevInput = "";
166
// Set to true when a non-horizontal-scrolling widget is added. As
167
// an optimization, widget aligning is skipped when d is false.
168
d.alignWidgets = false;
169
// Flag that indicates whether we currently expect input to appear
170
// (after some event like 'keypress' or 'input') and are polling
171
// intensively.
172
d.pollingFast = false;
173
// Self-resetting timeout for the poller
174
d.poll = new Delayed();
175
176
d.cachedCharWidth = d.cachedTextHeight = null;
177
d.measureLineCache = [];
178
d.measureLineCachePos = 0;
179
180
// Tracks when resetInput has punted to just putting a short
181
// string instead of the (large) selection.
182
d.inaccurateSelection = false;
183
184
// Tracks the maximum line length so that the horizontal scrollbar
185
// can be kept static when scrolling.
186
d.maxLine = null;
187
d.maxLineLength = 0;
188
d.maxLineChanged = false;
189
190
// Used for measuring wheel scrolling granularity
191
d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
192
193
return d;
194
}
195
196
// STATE UPDATES
197
198
// Used to get the editor into a consistent state again when options change.
199
200
function loadMode(cm) {
201
cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
202
resetModeState(cm);
203
}
204
205
function resetModeState(cm) {
206
cm.doc.iter(function(line) {
207
if (line.stateAfter) line.stateAfter = null;
208
if (line.styles) line.styles = null;
209
});
210
cm.doc.frontier = cm.doc.first;
211
startWorker(cm, 100);
212
cm.state.modeGen++;
213
if (cm.curOp) regChange(cm);
214
}
215
216
function wrappingChanged(cm) {
217
if (cm.options.lineWrapping) {
218
cm.display.wrapper.className += " CodeMirror-wrap";
219
cm.display.sizer.style.minWidth = "";
220
} else {
221
cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", "");
222
computeMaxLength(cm);
223
}
224
estimateLineHeights(cm);
225
regChange(cm);
226
clearCaches(cm);
227
setTimeout(function(){updateScrollbars(cm);}, 100);
228
}
229
230
function estimateHeight(cm) {
231
var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
232
var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
233
return function(line) {
234
if (lineIsHidden(cm.doc, line))
235
return 0;
236
else if (wrapping)
237
return (Math.ceil(line.text.length / perLine) || 1) * th;
238
else
239
return th;
240
};
241
}
242
243
function estimateLineHeights(cm) {
244
var doc = cm.doc, est = estimateHeight(cm);
245
doc.iter(function(line) {
246
var estHeight = est(line);
247
if (estHeight != line.height) updateLineHeight(line, estHeight);
248
});
249
}
250
251
function keyMapChanged(cm) {
252
var map = keyMap[cm.options.keyMap], style = map.style;
253
cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
254
(style ? " cm-keymap-" + style : "");
255
}
256
257
function themeChanged(cm) {
258
cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
259
cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
260
clearCaches(cm);
261
}
262
263
function guttersChanged(cm) {
264
updateGutters(cm);
265
regChange(cm);
266
setTimeout(function(){alignHorizontally(cm);}, 20);
267
}
268
269
function updateGutters(cm) {
270
var gutters = cm.display.gutters, specs = cm.options.gutters;
271
removeChildren(gutters);
272
for (var i = 0; i < specs.length; ++i) {
273
var gutterClass = specs[i];
274
var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
275
if (gutterClass == "CodeMirror-linenumbers") {
276
cm.display.lineGutter = gElt;
277
gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
278
}
279
}
280
gutters.style.display = i ? "" : "none";
281
}
282
283
function lineLength(doc, line) {
284
if (line.height == 0) return 0;
285
var len = line.text.length, merged, cur = line;
286
while (merged = collapsedSpanAtStart(cur)) {
287
var found = merged.find();
288
cur = getLine(doc, found.from.line);
289
len += found.from.ch - found.to.ch;
290
}
291
cur = line;
292
while (merged = collapsedSpanAtEnd(cur)) {
293
var found = merged.find();
294
len -= cur.text.length - found.from.ch;
295
cur = getLine(doc, found.to.line);
296
len += cur.text.length - found.to.ch;
297
}
298
return len;
299
}
300
301
function computeMaxLength(cm) {
302
var d = cm.display, doc = cm.doc;
303
d.maxLine = getLine(doc, doc.first);
304
d.maxLineLength = lineLength(doc, d.maxLine);
305
d.maxLineChanged = true;
306
doc.iter(function(line) {
307
var len = lineLength(doc, line);
308
if (len > d.maxLineLength) {
309
d.maxLineLength = len;
310
d.maxLine = line;
311
}
312
});
313
}
314
315
// Make sure the gutters options contains the element
316
// "CodeMirror-linenumbers" when the lineNumbers option is true.
317
function setGuttersForLineNumbers(options) {
318
var found = indexOf(options.gutters, "CodeMirror-linenumbers");
319
if (found == -1 && options.lineNumbers) {
320
options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
321
} else if (found > -1 && !options.lineNumbers) {
322
options.gutters = options.gutters.slice(0);
323
options.gutters.splice(found, 1);
324
}
325
}
326
327
// SCROLLBARS
328
329
// Re-synchronize the fake scrollbars with the actual size of the
330
// content. Optionally force a scrollTop.
331
function updateScrollbars(cm) {
332
var d = cm.display, docHeight = cm.doc.height;
333
var totalHeight = docHeight + paddingVert(d);
334
d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px";
335
d.gutters.style.height = Math.max(totalHeight, d.scroller.clientHeight - scrollerCutOff) + "px";
336
var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight);
337
var needsH = d.scroller.scrollWidth > (d.scroller.clientWidth + 1);
338
var needsV = scrollHeight > (d.scroller.clientHeight + 1);
339
if (needsV) {
340
d.scrollbarV.style.display = "block";
341
d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
342
d.scrollbarV.firstChild.style.height =
343
(scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px";
344
} else {
345
d.scrollbarV.style.display = "";
346
d.scrollbarV.firstChild.style.height = "0";
347
}
348
if (needsH) {
349
d.scrollbarH.style.display = "block";
350
d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
351
d.scrollbarH.firstChild.style.width =
352
(d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px";
353
} else {
354
d.scrollbarH.style.display = "";
355
d.scrollbarH.firstChild.style.width = "0";
356
}
357
if (needsH && needsV) {
358
d.scrollbarFiller.style.display = "block";
359
d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
360
} else d.scrollbarFiller.style.display = "";
361
if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
362
d.gutterFiller.style.display = "block";
363
d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px";
364
d.gutterFiller.style.width = d.gutters.offsetWidth + "px";
365
} else d.gutterFiller.style.display = "";
366
367
if (mac_geLion && scrollbarWidth(d.measure) === 0) {
368
d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px";
369
d.scrollbarV.style.pointerEvents = d.scrollbarH.style.pointerEvents = "none";
370
}
371
}
372
373
function visibleLines(display, doc, viewPort) {
374
var top = display.scroller.scrollTop, height = display.wrapper.clientHeight;
375
if (typeof viewPort == "number") top = viewPort;
376
else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;}
377
top = Math.floor(top - paddingTop(display));
378
var bottom = Math.ceil(top + height);
379
return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)};
380
}
381
382
// LINE NUMBERS
383
384
function alignHorizontally(cm) {
385
var display = cm.display;
386
if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
387
var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
388
var gutterW = display.gutters.offsetWidth, l = comp + "px";
389
for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) {
390
for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l;
391
}
392
if (cm.options.fixedGutter)
393
display.gutters.style.left = (comp + gutterW) + "px";
394
}
395
396
function maybeUpdateLineNumberWidth(cm) {
397
if (!cm.options.lineNumbers) return false;
398
var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
399
if (last.length != display.lineNumChars) {
400
var test = display.measure.appendChild(elt("div", [elt("div", last)],
401
"CodeMirror-linenumber CodeMirror-gutter-elt"));
402
var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
403
display.lineGutter.style.width = "";
404
display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
405
display.lineNumWidth = display.lineNumInnerWidth + padding;
406
display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
407
display.lineGutter.style.width = display.lineNumWidth + "px";
408
return true;
409
}
410
return false;
411
}
412
413
function lineNumberFor(options, i) {
414
return String(options.lineNumberFormatter(i + options.firstLineNumber));
415
}
416
function compensateForHScroll(display) {
417
return getRect(display.scroller).left - getRect(display.sizer).left;
418
}
419
420
// DISPLAY DRAWING
421
422
function updateDisplay(cm, changes, viewPort, forced) {
423
var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo, updated;
424
var visible = visibleLines(cm.display, cm.doc, viewPort);
425
for (var first = true;; first = false) {
426
var oldWidth = cm.display.scroller.clientWidth;
427
if (!updateDisplayInner(cm, changes, visible, forced)) break;
428
updated = true;
429
changes = [];
430
updateSelection(cm);
431
updateScrollbars(cm);
432
if (first && cm.options.lineWrapping && oldWidth != cm.display.scroller.clientWidth) {
433
forced = true;
434
continue;
435
}
436
forced = false;
437
438
// Clip forced viewport to actual scrollable area
439
if (viewPort)
440
viewPort = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight,
441
typeof viewPort == "number" ? viewPort : viewPort.top);
442
visible = visibleLines(cm.display, cm.doc, viewPort);
443
if (visible.from >= cm.display.showingFrom && visible.to <= cm.display.showingTo)
444
break;
445
}
446
447
if (updated) {
448
signalLater(cm, "update", cm);
449
if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo)
450
signalLater(cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo);
451
}
452
return updated;
453
}
454
455
// Uses a set of changes plus the current scroll position to
456
// determine which DOM updates have to be made, and makes the
457
// updates.
458
function updateDisplayInner(cm, changes, visible, forced) {
459
var display = cm.display, doc = cm.doc;
460
if (!display.wrapper.offsetWidth) {
461
display.showingFrom = display.showingTo = doc.first;
462
display.viewOffset = 0;
463
return;
464
}
465
466
// Bail out if the visible area is already rendered and nothing changed.
467
if (!forced && changes.length == 0 &&
468
visible.from > display.showingFrom && visible.to < display.showingTo)
469
return;
470
471
if (maybeUpdateLineNumberWidth(cm))
472
changes = [{from: doc.first, to: doc.first + doc.size}];
473
var gutterW = display.sizer.style.marginLeft = display.gutters.offsetWidth + "px";
474
display.scrollbarH.style.left = cm.options.fixedGutter ? gutterW : "0";
475
476
// Used to determine which lines need their line numbers updated
477
var positionsChangedFrom = Infinity;
478
if (cm.options.lineNumbers)
479
for (var i = 0; i < changes.length; ++i)
480
if (changes[i].diff && changes[i].from < positionsChangedFrom) { positionsChangedFrom = changes[i].from; }
481
482
var end = doc.first + doc.size;
483
var from = Math.max(visible.from - cm.options.viewportMargin, doc.first);
484
var to = Math.min(end, visible.to + cm.options.viewportMargin);
485
if (display.showingFrom < from && from - display.showingFrom < 20) from = Math.max(doc.first, display.showingFrom);
486
if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(end, display.showingTo);
487
if (sawCollapsedSpans) {
488
from = lineNo(visualLine(doc, getLine(doc, from)));
489
while (to < end && lineIsHidden(doc, getLine(doc, to))) ++to;
490
}
491
492
// Create a range of theoretically intact lines, and punch holes
493
// in that using the change info.
494
var intact = [{from: Math.max(display.showingFrom, doc.first),
495
to: Math.min(display.showingTo, end)}];
496
if (intact[0].from >= intact[0].to) intact = [];
497
else intact = computeIntact(intact, changes);
498
// When merged lines are present, we might have to reduce the
499
// intact ranges because changes in continued fragments of the
500
// intact lines do require the lines to be redrawn.
501
if (sawCollapsedSpans)
502
for (var i = 0; i < intact.length; ++i) {
503
var range = intact[i], merged;
504
while (merged = collapsedSpanAtEnd(getLine(doc, range.to - 1))) {
505
var newTo = merged.find().from.line;
506
if (newTo > range.from) range.to = newTo;
507
else { intact.splice(i--, 1); break; }
508
}
509
}
510
511
// Clip off the parts that won't be visible
512
var intactLines = 0;
513
for (var i = 0; i < intact.length; ++i) {
514
var range = intact[i];
515
if (range.from < from) range.from = from;
516
if (range.to > to) range.to = to;
517
if (range.from >= range.to) intact.splice(i--, 1);
518
else intactLines += range.to - range.from;
519
}
520
if (!forced && intactLines == to - from && from == display.showingFrom && to == display.showingTo) {
521
updateViewOffset(cm);
522
return;
523
}
524
intact.sort(function(a, b) {return a.from - b.from;});
525
526
// Avoid crashing on IE's "unspecified error" when in iframes
527
try {
528
var focused = document.activeElement;
529
} catch(e) {}
530
if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none";
531
patchDisplay(cm, from, to, intact, positionsChangedFrom);
532
display.lineDiv.style.display = "";
533
if (focused && document.activeElement != focused && focused.offsetHeight) focused.focus();
534
535
var different = from != display.showingFrom || to != display.showingTo ||
536
display.lastSizeC != display.wrapper.clientHeight;
537
// This is just a bogus formula that detects when the editor is
538
// resized or the font size changes.
539
if (different) {
540
display.lastSizeC = display.wrapper.clientHeight;
541
startWorker(cm, 400);
542
}
543
display.showingFrom = from; display.showingTo = to;
544
545
display.gutters.style.height = "";
546
updateHeightsInViewport(cm);
547
updateViewOffset(cm);
548
549
return true;
550
}
551
552
function updateHeightsInViewport(cm) {
553
var display = cm.display;
554
var prevBottom = display.lineDiv.offsetTop;
555
for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) {
556
if (ie_lt8) {
557
var bot = node.offsetTop + node.offsetHeight;
558
height = bot - prevBottom;
559
prevBottom = bot;
560
} else {
561
var box = getRect(node);
562
height = box.bottom - box.top;
563
}
564
var diff = node.lineObj.height - height;
565
if (height < 2) height = textHeight(display);
566
if (diff > .001 || diff < -.001) {
567
updateLineHeight(node.lineObj, height);
568
var widgets = node.lineObj.widgets;
569
if (widgets) for (var i = 0; i < widgets.length; ++i)
570
widgets[i].height = widgets[i].node.offsetHeight;
571
}
572
}
573
}
574
575
function updateViewOffset(cm) {
576
var off = cm.display.viewOffset = heightAtLine(cm, getLine(cm.doc, cm.display.showingFrom));
577
// Position the mover div to align with the current virtual scroll position
578
cm.display.mover.style.top = off + "px";
579
}
580
581
function computeIntact(intact, changes) {
582
for (var i = 0, l = changes.length || 0; i < l; ++i) {
583
var change = changes[i], intact2 = [], diff = change.diff || 0;
584
for (var j = 0, l2 = intact.length; j < l2; ++j) {
585
var range = intact[j];
586
if (change.to <= range.from && change.diff) {
587
intact2.push({from: range.from + diff, to: range.to + diff});
588
} else if (change.to <= range.from || change.from >= range.to) {
589
intact2.push(range);
590
} else {
591
if (change.from > range.from)
592
intact2.push({from: range.from, to: change.from});
593
if (change.to < range.to)
594
intact2.push({from: change.to + diff, to: range.to + diff});
595
}
596
}
597
intact = intact2;
598
}
599
return intact;
600
}
601
602
function getDimensions(cm) {
603
var d = cm.display, left = {}, width = {};
604
for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
605
left[cm.options.gutters[i]] = n.offsetLeft;
606
width[cm.options.gutters[i]] = n.offsetWidth;
607
}
608
return {fixedPos: compensateForHScroll(d),
609
gutterTotalWidth: d.gutters.offsetWidth,
610
gutterLeft: left,
611
gutterWidth: width,
612
wrapperWidth: d.wrapper.clientWidth};
613
}
614
615
function patchDisplay(cm, from, to, intact, updateNumbersFrom) {
616
var dims = getDimensions(cm);
617
var display = cm.display, lineNumbers = cm.options.lineNumbers;
618
if (!intact.length && (!webkit || !cm.display.currentWheelTarget))
619
removeChildren(display.lineDiv);
620
var container = display.lineDiv, cur = container.firstChild;
621
622
function rm(node) {
623
var next = node.nextSibling;
624
if (webkit && mac && cm.display.currentWheelTarget == node) {
625
node.style.display = "none";
626
node.lineObj = null;
627
} else {
628
node.parentNode.removeChild(node);
629
}
630
return next;
631
}
632
633
var nextIntact = intact.shift(), lineN = from;
634
cm.doc.iter(from, to, function(line) {
635
if (nextIntact && nextIntact.to == lineN) nextIntact = intact.shift();
636
if (lineIsHidden(cm.doc, line)) {
637
if (line.height != 0) updateLineHeight(line, 0);
638
if (line.widgets && cur && cur.previousSibling) for (var i = 0; i < line.widgets.length; ++i) {
639
var w = line.widgets[i];
640
if (w.showIfHidden) {
641
var prev = cur.previousSibling;
642
if (/pre/i.test(prev.nodeName)) {
643
var wrap = elt("div", null, null, "position: relative");
644
prev.parentNode.replaceChild(wrap, prev);
645
wrap.appendChild(prev);
646
prev = wrap;
647
}
648
var wnode = prev.appendChild(elt("div", [w.node], "CodeMirror-linewidget"));
649
if (!w.handleMouseEvents) wnode.ignoreEvents = true;
650
positionLineWidget(w, wnode, prev, dims);
651
}
652
}
653
} else if (nextIntact && nextIntact.from <= lineN && nextIntact.to > lineN) {
654
// This line is intact. Skip to the actual node. Update its
655
// line number if needed.
656
while (cur.lineObj != line) cur = rm(cur);
657
if (lineNumbers && updateNumbersFrom <= lineN && cur.lineNumber)
658
setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineN));
659
cur = cur.nextSibling;
660
} else {
661
// For lines with widgets, make an attempt to find and reuse
662
// the existing element, so that widgets aren't needlessly
663
// removed and re-inserted into the dom
664
if (line.widgets) for (var j = 0, search = cur, reuse; search && j < 20; ++j, search = search.nextSibling)
665
if (search.lineObj == line && /div/i.test(search.nodeName)) { reuse = search; break; }
666
// This line needs to be generated.
667
var lineNode = buildLineElement(cm, line, lineN, dims, reuse);
668
if (lineNode != reuse) {
669
container.insertBefore(lineNode, cur);
670
} else {
671
while (cur != reuse) cur = rm(cur);
672
cur = cur.nextSibling;
673
}
674
675
lineNode.lineObj = line;
676
}
677
++lineN;
678
});
679
while (cur) cur = rm(cur);
680
}
681
682
function buildLineElement(cm, line, lineNo, dims, reuse) {
683
var built = buildLineContent(cm, line), lineElement = built.pre;
684
var markers = line.gutterMarkers, display = cm.display, wrap;
685
686
var bgClass = built.bgClass ? built.bgClass + " " + (line.bgClass || "") : line.bgClass;
687
if (!cm.options.lineNumbers && !markers && !bgClass && !line.wrapClass && !line.widgets)
688
return lineElement;
689
690
// Lines with gutter elements, widgets or a background class need
691
// to be wrapped again, and have the extra elements added to the
692
// wrapper div
693
694
if (reuse) {
695
reuse.alignable = null;
696
var isOk = true, widgetsSeen = 0, insertBefore = null;
697
for (var n = reuse.firstChild, next; n; n = next) {
698
next = n.nextSibling;
699
if (!/\bCodeMirror-linewidget\b/.test(n.className)) {
700
reuse.removeChild(n);
701
} else {
702
for (var i = 0; i < line.widgets.length; ++i) {
703
var widget = line.widgets[i];
704
if (widget.node == n.firstChild) {
705
if (!widget.above && !insertBefore) insertBefore = n;
706
positionLineWidget(widget, n, reuse, dims);
707
++widgetsSeen;
708
break;
709
}
710
}
711
if (i == line.widgets.length) { isOk = false; break; }
712
}
713
}
714
reuse.insertBefore(lineElement, insertBefore);
715
if (isOk && widgetsSeen == line.widgets.length) {
716
wrap = reuse;
717
reuse.className = line.wrapClass || "";
718
}
719
}
720
if (!wrap) {
721
wrap = elt("div", null, line.wrapClass, "position: relative");
722
wrap.appendChild(lineElement);
723
}
724
// Kludge to make sure the styled element lies behind the selection (by z-index)
725
if (bgClass)
726
wrap.insertBefore(elt("div", null, bgClass + " CodeMirror-linebackground"), wrap.firstChild);
727
if (cm.options.lineNumbers || markers) {
728
var gutterWrap = wrap.insertBefore(elt("div", null, "CodeMirror-gutter-wrapper", "position: absolute; left: " +
729
(cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"),
730
lineElement);
731
if (cm.options.fixedGutter) (wrap.alignable || (wrap.alignable = [])).push(gutterWrap);
732
if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
733
wrap.lineNumber = gutterWrap.appendChild(
734
elt("div", lineNumberFor(cm.options, lineNo),
735
"CodeMirror-linenumber CodeMirror-gutter-elt",
736
"left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
737
+ display.lineNumInnerWidth + "px"));
738
if (markers)
739
for (var k = 0; k < cm.options.gutters.length; ++k) {
740
var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
741
if (found)
742
gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
743
dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
744
}
745
}
746
if (ie_lt8) wrap.style.zIndex = 2;
747
if (line.widgets && wrap != reuse) for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
748
var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
749
if (!widget.handleMouseEvents) node.ignoreEvents = true;
750
positionLineWidget(widget, node, wrap, dims);
751
if (widget.above)
752
wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement);
753
else
754
wrap.appendChild(node);
755
signalLater(widget, "redraw");
756
}
757
return wrap;
758
}
759
760
function positionLineWidget(widget, node, wrap, dims) {
761
if (widget.noHScroll) {
762
(wrap.alignable || (wrap.alignable = [])).push(node);
763
var width = dims.wrapperWidth;
764
node.style.left = dims.fixedPos + "px";
765
if (!widget.coverGutter) {
766
width -= dims.gutterTotalWidth;
767
node.style.paddingLeft = dims.gutterTotalWidth + "px";
768
}
769
node.style.width = width + "px";
770
}
771
if (widget.coverGutter) {
772
node.style.zIndex = 5;
773
node.style.position = "relative";
774
if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
775
}
776
}
777
778
// SELECTION / CURSOR
779
780
function updateSelection(cm) {
781
var display = cm.display;
782
var collapsed = posEq(cm.doc.sel.from, cm.doc.sel.to);
783
if (collapsed || cm.options.showCursorWhenSelecting)
784
updateSelectionCursor(cm);
785
else
786
display.cursor.style.display = display.otherCursor.style.display = "none";
787
if (!collapsed)
788
updateSelectionRange(cm);
789
else
790
display.selectionDiv.style.display = "none";
791
792
// Move the hidden textarea near the cursor to prevent scrolling artifacts
793
if (cm.options.moveInputWithCursor) {
794
var headPos = cursorCoords(cm, cm.doc.sel.head, "div");
795
var wrapOff = getRect(display.wrapper), lineOff = getRect(display.lineDiv);
796
display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
797
headPos.top + lineOff.top - wrapOff.top)) + "px";
798
display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
799
headPos.left + lineOff.left - wrapOff.left)) + "px";
800
}
801
}
802
803
// No selection, plain cursor
804
function updateSelectionCursor(cm) {
805
var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div");
806
display.cursor.style.left = pos.left + "px";
807
display.cursor.style.top = pos.top + "px";
808
display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
809
display.cursor.style.display = "";
810
811
if (pos.other) {
812
display.otherCursor.style.display = "";
813
display.otherCursor.style.left = pos.other.left + "px";
814
display.otherCursor.style.top = pos.other.top + "px";
815
display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
816
} else { display.otherCursor.style.display = "none"; }
817
}
818
819
// Highlight selection
820
function updateSelectionRange(cm) {
821
var display = cm.display, doc = cm.doc, sel = cm.doc.sel;
822
var fragment = document.createDocumentFragment();
823
var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display);
824
825
function add(left, top, width, bottom) {
826
if (top < 0) top = 0;
827
fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
828
"px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) +
829
"px; height: " + (bottom - top) + "px"));
830
}
831
832
function drawForLine(line, fromArg, toArg) {
833
var lineObj = getLine(doc, line);
834
var lineLen = lineObj.text.length;
835
var start, end;
836
function coords(ch, bias) {
837
return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
838
}
839
840
iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
841
var leftPos = coords(from, "left"), rightPos, left, right;
842
if (from == to) {
843
rightPos = leftPos;
844
left = right = leftPos.left;
845
} else {
846
rightPos = coords(to - 1, "right");
847
if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
848
left = leftPos.left;
849
right = rightPos.right;
850
}
851
if (fromArg == null && from == 0) left = pl;
852
if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
853
add(left, leftPos.top, null, leftPos.bottom);
854
left = pl;
855
if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
856
}
857
if (toArg == null && to == lineLen) right = clientWidth;
858
if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
859
start = leftPos;
860
if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
861
end = rightPos;
862
if (left < pl + 1) left = pl;
863
add(left, rightPos.top, right - left, rightPos.bottom);
864
});
865
return {start: start, end: end};
866
}
867
868
if (sel.from.line == sel.to.line) {
869
drawForLine(sel.from.line, sel.from.ch, sel.to.ch);
870
} else {
871
var fromLine = getLine(doc, sel.from.line), toLine = getLine(doc, sel.to.line);
872
var singleVLine = visualLine(doc, fromLine) == visualLine(doc, toLine);
873
var leftEnd = drawForLine(sel.from.line, sel.from.ch, singleVLine ? fromLine.text.length : null).end;
874
var rightStart = drawForLine(sel.to.line, singleVLine ? 0 : null, sel.to.ch).start;
875
if (singleVLine) {
876
if (leftEnd.top < rightStart.top - 2) {
877
add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
878
add(pl, rightStart.top, rightStart.left, rightStart.bottom);
879
} else {
880
add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
881
}
882
}
883
if (leftEnd.bottom < rightStart.top)
884
add(pl, leftEnd.bottom, null, rightStart.top);
885
}
886
887
removeChildrenAndAdd(display.selectionDiv, fragment);
888
display.selectionDiv.style.display = "";
889
}
890
891
// Cursor-blinking
892
function restartBlink(cm) {
893
if (!cm.state.focused) return;
894
var display = cm.display;
895
clearInterval(display.blinker);
896
var on = true;
897
display.cursor.style.visibility = display.otherCursor.style.visibility = "";
898
if (cm.options.cursorBlinkRate > 0)
899
display.blinker = setInterval(function() {
900
display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden";
901
}, cm.options.cursorBlinkRate);
902
}
903
904
// HIGHLIGHT WORKER
905
906
function startWorker(cm, time) {
907
if (cm.doc.mode.startState && cm.doc.frontier < cm.display.showingTo)
908
cm.state.highlight.set(time, bind(highlightWorker, cm));
909
}
910
911
function highlightWorker(cm) {
912
var doc = cm.doc;
913
if (doc.frontier < doc.first) doc.frontier = doc.first;
914
if (doc.frontier >= cm.display.showingTo) return;
915
var end = +new Date + cm.options.workTime;
916
var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
917
var changed = [], prevChange;
918
doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.showingTo + 500), function(line) {
919
if (doc.frontier >= cm.display.showingFrom) { // Visible
920
var oldStyles = line.styles;
921
line.styles = highlightLine(cm, line, state, true);
922
var ischange = !oldStyles || oldStyles.length != line.styles.length;
923
for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
924
if (ischange) {
925
if (prevChange && prevChange.end == doc.frontier) prevChange.end++;
926
else changed.push(prevChange = {start: doc.frontier, end: doc.frontier + 1});
927
}
928
line.stateAfter = copyState(doc.mode, state);
929
} else {
930
processLine(cm, line.text, state);
931
line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
932
}
933
++doc.frontier;
934
if (+new Date > end) {
935
startWorker(cm, cm.options.workDelay);
936
return true;
937
}
938
});
939
if (changed.length)
940
operation(cm, function() {
941
for (var i = 0; i < changed.length; ++i)
942
regChange(this, changed[i].start, changed[i].end);
943
})();
944
}
945
946
// Finds the line to start with when starting a parse. Tries to
947
// find a line with a stateAfter, so that it can start with a
948
// valid state. If that fails, it returns the line with the
949
// smallest indentation, which tends to need the least context to
950
// parse correctly.
951
function findStartLine(cm, n, precise) {
952
var minindent, minline, doc = cm.doc;
953
var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
954
for (var search = n; search > lim; --search) {
955
if (search <= doc.first) return doc.first;
956
var line = getLine(doc, search - 1);
957
if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
958
var indented = countColumn(line.text, null, cm.options.tabSize);
959
if (minline == null || minindent > indented) {
960
minline = search - 1;
961
minindent = indented;
962
}
963
}
964
return minline;
965
}
966
967
function getStateBefore(cm, n, precise) {
968
var doc = cm.doc, display = cm.display;
969
if (!doc.mode.startState) return true;
970
var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
971
if (!state) state = startState(doc.mode);
972
else state = copyState(doc.mode, state);
973
doc.iter(pos, n, function(line) {
974
processLine(cm, line.text, state);
975
var save = pos == n - 1 || pos % 5 == 0 || pos >= display.showingFrom && pos < display.showingTo;
976
line.stateAfter = save ? copyState(doc.mode, state) : null;
977
++pos;
978
});
979
if (precise) doc.frontier = pos;
980
return state;
981
}
982
983
// POSITION MEASUREMENT
984
985
function paddingTop(display) {return display.lineSpace.offsetTop;}
986
function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
987
function paddingLeft(display) {
988
var e = removeChildrenAndAdd(display.measure, elt("pre", null, null, "text-align: left")).appendChild(elt("span", "x"));
989
return e.offsetLeft;
990
}
991
992
function measureChar(cm, line, ch, data, bias) {
993
var dir = -1;
994
data = data || measureLine(cm, line);
995
if (data.crude) {
996
var left = data.left + ch * data.width;
997
return {left: left, right: left + data.width, top: data.top, bottom: data.bottom};
998
}
999
1000
for (var pos = ch;; pos += dir) {
1001
var r = data[pos];
1002
if (r) break;
1003
if (dir < 0 && pos == 0) dir = 1;
1004
}
1005
bias = pos > ch ? "left" : pos < ch ? "right" : bias;
1006
if (bias == "left" && r.leftSide) r = r.leftSide;
1007
else if (bias == "right" && r.rightSide) r = r.rightSide;
1008
return {left: pos < ch ? r.right : r.left,
1009
right: pos > ch ? r.left : r.right,
1010
top: r.top,
1011
bottom: r.bottom};
1012
}
1013
1014
function findCachedMeasurement(cm, line) {
1015
var cache = cm.display.measureLineCache;
1016
for (var i = 0; i < cache.length; ++i) {
1017
var memo = cache[i];
1018
if (memo.text == line.text && memo.markedSpans == line.markedSpans &&
1019
cm.display.scroller.clientWidth == memo.width &&
1020
memo.classes == line.textClass + "|" + line.wrapClass)
1021
return memo;
1022
}
1023
}
1024
1025
function clearCachedMeasurement(cm, line) {
1026
var exists = findCachedMeasurement(cm, line);
1027
if (exists) exists.text = exists.measure = exists.markedSpans = null;
1028
}
1029
1030
function measureLine(cm, line) {
1031
// First look in the cache
1032
var cached = findCachedMeasurement(cm, line);
1033
if (cached) return cached.measure;
1034
1035
// Failing that, recompute and store result in cache
1036
var measure = measureLineInner(cm, line);
1037
var cache = cm.display.measureLineCache;
1038
var memo = {text: line.text, width: cm.display.scroller.clientWidth,
1039
markedSpans: line.markedSpans, measure: measure,
1040
classes: line.textClass + "|" + line.wrapClass};
1041
if (cache.length == 16) cache[++cm.display.measureLineCachePos % 16] = memo;
1042
else cache.push(memo);
1043
return measure;
1044
}
1045
1046
function measureLineInner(cm, line) {
1047
if (!cm.options.lineWrapping && line.text.length >= cm.options.crudeMeasuringFrom)
1048
return crudelyMeasureLine(cm, line);
1049
1050
var display = cm.display, measure = emptyArray(line.text.length);
1051
var pre = buildLineContent(cm, line, measure, true).pre;
1052
1053
// IE does not cache element positions of inline elements between
1054
// calls to getBoundingClientRect. This makes the loop below,
1055
// which gathers the positions of all the characters on the line,
1056
// do an amount of layout work quadratic to the number of
1057
// characters. When line wrapping is off, we try to improve things
1058
// by first subdividing the line into a bunch of inline blocks, so
1059
// that IE can reuse most of the layout information from caches
1060
// for those blocks. This does interfere with line wrapping, so it
1061
// doesn't work when wrapping is on, but in that case the
1062
// situation is slightly better, since IE does cache line-wrapping
1063
// information and only recomputes per-line.
1064
if (old_ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) {
1065
var fragment = document.createDocumentFragment();
1066
var chunk = 10, n = pre.childNodes.length;
1067
for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) {
1068
var wrap = elt("div", null, null, "display: inline-block");
1069
for (var j = 0; j < chunk && n; ++j) {
1070
wrap.appendChild(pre.firstChild);
1071
--n;
1072
}
1073
fragment.appendChild(wrap);
1074
}
1075
pre.appendChild(fragment);
1076
}
1077
1078
removeChildrenAndAdd(display.measure, pre);
1079
1080
var outer = getRect(display.lineDiv);
1081
var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight;
1082
// Work around an IE7/8 bug where it will sometimes have randomly
1083
// replaced our pre with a clone at this point.
1084
if (ie_lt9 && display.measure.first != pre)
1085
removeChildrenAndAdd(display.measure, pre);
1086
1087
function measureRect(rect) {
1088
var top = rect.top - outer.top, bot = rect.bottom - outer.top;
1089
if (bot > maxBot) bot = maxBot;
1090
if (top < 0) top = 0;
1091
for (var i = vranges.length - 2; i >= 0; i -= 2) {
1092
var rtop = vranges[i], rbot = vranges[i+1];
1093
if (rtop > bot || rbot < top) continue;
1094
if (rtop <= top && rbot >= bot ||
1095
top <= rtop && bot >= rbot ||
1096
Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) {
1097
vranges[i] = Math.min(top, rtop);
1098
vranges[i+1] = Math.max(bot, rbot);
1099
break;
1100
}
1101
}
1102
if (i < 0) { i = vranges.length; vranges.push(top, bot); }
1103
return {left: rect.left - outer.left,
1104
right: rect.right - outer.left,
1105
top: i, bottom: null};
1106
}
1107
function finishRect(rect) {
1108
rect.bottom = vranges[rect.top+1];
1109
rect.top = vranges[rect.top];
1110
}
1111
1112
for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) {
1113
var node = cur, rect = null;
1114
// A widget might wrap, needs special care
1115
if (/\bCodeMirror-widget\b/.test(cur.className) && cur.getClientRects) {
1116
if (cur.firstChild.nodeType == 1) node = cur.firstChild;
1117
var rects = node.getClientRects();
1118
if (rects.length > 1) {
1119
rect = data[i] = measureRect(rects[0]);
1120
rect.rightSide = measureRect(rects[rects.length - 1]);
1121
}
1122
}
1123
if (!rect) rect = data[i] = measureRect(getRect(node));
1124
if (cur.measureRight) rect.right = getRect(cur.measureRight).left - outer.left;
1125
if (cur.leftSide) rect.leftSide = measureRect(getRect(cur.leftSide));
1126
}
1127
removeChildren(cm.display.measure);
1128
for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) {
1129
finishRect(cur);
1130
if (cur.leftSide) finishRect(cur.leftSide);
1131
if (cur.rightSide) finishRect(cur.rightSide);
1132
}
1133
return data;
1134
}
1135
1136
function crudelyMeasureLine(cm, line) {
1137
var copy = new Line(line.text.slice(0, 100), null);
1138
if (line.textClass) copy.textClass = line.textClass;
1139
var measure = measureLineInner(cm, copy);
1140
var left = measureChar(cm, copy, 0, measure, "left");
1141
var right = measureChar(cm, copy, 99, measure, "right");
1142
return {crude: true, top: left.top, left: left.left, bottom: left.bottom, width: (right.right - left.left) / 100};
1143
}
1144
1145
function measureLineWidth(cm, line) {
1146
var hasBadSpan = false;
1147
if (line.markedSpans) for (var i = 0; i < line.markedSpans; ++i) {
1148
var sp = line.markedSpans[i];
1149
if (sp.collapsed && (sp.to == null || sp.to == line.text.length)) hasBadSpan = true;
1150
}
1151
var cached = !hasBadSpan && findCachedMeasurement(cm, line);
1152
if (cached || line.text.length >= cm.options.crudeMeasuringFrom)
1153
return measureChar(cm, line, line.text.length, cached && cached.measure, "right").right;
1154
1155
var pre = buildLineContent(cm, line, null, true).pre;
1156
var end = pre.appendChild(zeroWidthElement(cm.display.measure));
1157
removeChildrenAndAdd(cm.display.measure, pre);
1158
return getRect(end).right - getRect(cm.display.lineDiv).left;
1159
}
1160
1161
function clearCaches(cm) {
1162
cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0;
1163
cm.display.cachedCharWidth = cm.display.cachedTextHeight = null;
1164
if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
1165
cm.display.lineNumChars = null;
1166
}
1167
1168
function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
1169
function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
1170
1171
// Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page"
1172
function intoCoordSystem(cm, lineObj, rect, context) {
1173
if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
1174
var size = widgetHeight(lineObj.widgets[i]);
1175
rect.top += size; rect.bottom += size;
1176
}
1177
if (context == "line") return rect;
1178
if (!context) context = "local";
1179
var yOff = heightAtLine(cm, lineObj);
1180
if (context == "local") yOff += paddingTop(cm.display);
1181
else yOff -= cm.display.viewOffset;
1182
if (context == "page" || context == "window") {
1183
var lOff = getRect(cm.display.lineSpace);
1184
yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
1185
var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
1186
rect.left += xOff; rect.right += xOff;
1187
}
1188
rect.top += yOff; rect.bottom += yOff;
1189
return rect;
1190
}
1191
1192
// Context may be "window", "page", "div", or "local"/null
1193
// Result is in "div" coords
1194
function fromCoordSystem(cm, coords, context) {
1195
if (context == "div") return coords;
1196
var left = coords.left, top = coords.top;
1197
// First move into "page" coordinate system
1198
if (context == "page") {
1199
left -= pageScrollX();
1200
top -= pageScrollY();
1201
} else if (context == "local" || !context) {
1202
var localBox = getRect(cm.display.sizer);
1203
left += localBox.left;
1204
top += localBox.top;
1205
}
1206
1207
var lineSpaceBox = getRect(cm.display.lineSpace);
1208
return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
1209
}
1210
1211
function charCoords(cm, pos, context, lineObj, bias) {
1212
if (!lineObj) lineObj = getLine(cm.doc, pos.line);
1213
return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, null, bias), context);
1214
}
1215
1216
function cursorCoords(cm, pos, context, lineObj, measurement) {
1217
lineObj = lineObj || getLine(cm.doc, pos.line);
1218
if (!measurement) measurement = measureLine(cm, lineObj);
1219
function get(ch, right) {
1220
var m = measureChar(cm, lineObj, ch, measurement, right ? "right" : "left");
1221
if (right) m.left = m.right; else m.right = m.left;
1222
return intoCoordSystem(cm, lineObj, m, context);
1223
}
1224
function getBidi(ch, partPos) {
1225
var part = order[partPos], right = part.level % 2;
1226
if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
1227
part = order[--partPos];
1228
ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
1229
right = true;
1230
} else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
1231
part = order[++partPos];
1232
ch = bidiLeft(part) - part.level % 2;
1233
right = false;
1234
}
1235
if (right && ch == part.to && ch > part.from) return get(ch - 1);
1236
return get(ch, right);
1237
}
1238
var order = getOrder(lineObj), ch = pos.ch;
1239
if (!order) return get(ch);
1240
var partPos = getBidiPartAt(order, ch);
1241
var val = getBidi(ch, partPos);
1242
if (bidiOther != null) val.other = getBidi(ch, bidiOther);
1243
return val;
1244
}
1245
1246
function PosWithInfo(line, ch, outside, xRel) {
1247
var pos = new Pos(line, ch);
1248
pos.xRel = xRel;
1249
if (outside) pos.outside = true;
1250
return pos;
1251
}
1252
1253
// Coords must be lineSpace-local
1254
function coordsChar(cm, x, y) {
1255
var doc = cm.doc;
1256
y += cm.display.viewOffset;
1257
if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
1258
var lineNo = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
1259
if (lineNo > last)
1260
return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
1261
if (x < 0) x = 0;
1262
1263
for (;;) {
1264
var lineObj = getLine(doc, lineNo);
1265
var found = coordsCharInner(cm, lineObj, lineNo, x, y);
1266
var merged = collapsedSpanAtEnd(lineObj);
1267
var mergedPos = merged && merged.find();
1268
if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
1269
lineNo = mergedPos.to.line;
1270
else
1271
return found;
1272
}
1273
}
1274
1275
function coordsCharInner(cm, lineObj, lineNo, x, y) {
1276
var innerOff = y - heightAtLine(cm, lineObj);
1277
var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
1278
var measurement = measureLine(cm, lineObj);
1279
1280
function getX(ch) {
1281
var sp = cursorCoords(cm, Pos(lineNo, ch), "line",
1282
lineObj, measurement);
1283
wrongLine = true;
1284
if (innerOff > sp.bottom) return sp.left - adjust;
1285
else if (innerOff < sp.top) return sp.left + adjust;
1286
else wrongLine = false;
1287
return sp.left;
1288
}
1289
1290
var bidi = getOrder(lineObj), dist = lineObj.text.length;
1291
var from = lineLeft(lineObj), to = lineRight(lineObj);
1292
var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
1293
1294
if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
1295
// Do a binary search between these bounds.
1296
for (;;) {
1297
if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
1298
var ch = x < fromX || x - fromX <= toX - x ? from : to;
1299
var xDiff = x - (ch == from ? fromX : toX);
1300
while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
1301
var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
1302
xDiff < 0 ? -1 : xDiff ? 1 : 0);
1303
return pos;
1304
}
1305
var step = Math.ceil(dist / 2), middle = from + step;
1306
if (bidi) {
1307
middle = from;
1308
for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
1309
}
1310
var middleX = getX(middle);
1311
if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
1312
else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
1313
}
1314
}
1315
1316
var measureText;
1317
function textHeight(display) {
1318
if (display.cachedTextHeight != null) return display.cachedTextHeight;
1319
if (measureText == null) {
1320
measureText = elt("pre");
1321
// Measure a bunch of lines, for browsers that compute
1322
// fractional heights.
1323
for (var i = 0; i < 49; ++i) {
1324
measureText.appendChild(document.createTextNode("x"));
1325
measureText.appendChild(elt("br"));
1326
}
1327
measureText.appendChild(document.createTextNode("x"));
1328
}
1329
removeChildrenAndAdd(display.measure, measureText);
1330
var height = measureText.offsetHeight / 50;
1331
if (height > 3) display.cachedTextHeight = height;
1332
removeChildren(display.measure);
1333
return height || 1;
1334
}
1335
1336
function charWidth(display) {
1337
if (display.cachedCharWidth != null) return display.cachedCharWidth;
1338
var anchor = elt("span", "x");
1339
var pre = elt("pre", [anchor]);
1340
removeChildrenAndAdd(display.measure, pre);
1341
var width = anchor.offsetWidth;
1342
if (width > 2) display.cachedCharWidth = width;
1343
return width || 10;
1344
}
1345
1346
// OPERATIONS
1347
1348
// Operations are used to wrap changes in such a way that each
1349
// change won't have to update the cursor and display (which would
1350
// be awkward, slow, and error-prone), but instead updates are
1351
// batched and then all combined and executed at once.
1352
1353
var nextOpId = 0;
1354
function startOperation(cm) {
1355
cm.curOp = {
1356
// An array of ranges of lines that have to be updated. See
1357
// updateDisplay.
1358
changes: [],
1359
forceUpdate: false,
1360
updateInput: null,
1361
userSelChange: null,
1362
textChanged: null,
1363
selectionChanged: false,
1364
cursorActivity: false,
1365
updateMaxLine: false,
1366
updateScrollPos: false,
1367
id: ++nextOpId
1368
};
1369
if (!delayedCallbackDepth++) delayedCallbacks = [];
1370
}
1371
1372
function endOperation(cm) {
1373
var op = cm.curOp, doc = cm.doc, display = cm.display;
1374
cm.curOp = null;
1375
1376
if (op.updateMaxLine) computeMaxLength(cm);
1377
if (display.maxLineChanged && !cm.options.lineWrapping && display.maxLine) {
1378
var width = measureLineWidth(cm, display.maxLine);
1379
display.sizer.style.minWidth = Math.max(0, width + 3 + scrollerCutOff) + "px";
1380
display.maxLineChanged = false;
1381
var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + display.sizer.offsetWidth - display.scroller.clientWidth);
1382
if (maxScrollLeft < doc.scrollLeft && !op.updateScrollPos)
1383
setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true);
1384
}
1385
var newScrollPos, updated;
1386
if (op.updateScrollPos) {
1387
newScrollPos = op.updateScrollPos;
1388
} else if (op.selectionChanged && display.scroller.clientHeight) { // don't rescroll if not visible
1389
var coords = cursorCoords(cm, doc.sel.head);
1390
newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom);
1391
}
1392
if (op.changes.length || op.forceUpdate || newScrollPos && newScrollPos.scrollTop != null) {
1393
updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop, op.forceUpdate);
1394
if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop;
1395
}
1396
if (!updated && op.selectionChanged) updateSelection(cm);
1397
if (op.updateScrollPos) {
1398
var top = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, newScrollPos.scrollTop));
1399
var left = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, newScrollPos.scrollLeft));
1400
display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = top;
1401
display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = left;
1402
alignHorizontally(cm);
1403
if (op.scrollToPos)
1404
scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos.from),
1405
clipPos(cm.doc, op.scrollToPos.to), op.scrollToPos.margin);
1406
} else if (newScrollPos) {
1407
scrollCursorIntoView(cm);
1408
}
1409
if (op.selectionChanged) restartBlink(cm);
1410
1411
if (cm.state.focused && op.updateInput)
1412
resetInput(cm, op.userSelChange);
1413
1414
var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
1415
if (hidden) for (var i = 0; i < hidden.length; ++i)
1416
if (!hidden[i].lines.length) signal(hidden[i], "hide");
1417
if (unhidden) for (var i = 0; i < unhidden.length; ++i)
1418
if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
1419
1420
var delayed;
1421
if (!--delayedCallbackDepth) {
1422
delayed = delayedCallbacks;
1423
delayedCallbacks = null;
1424
}
1425
if (op.textChanged)
1426
signal(cm, "change", cm, op.textChanged);
1427
if (op.cursorActivity) signal(cm, "cursorActivity", cm);
1428
if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i]();
1429
}
1430
1431
// Wraps a function in an operation. Returns the wrapped function.
1432
function operation(cm1, f) {
1433
return function() {
1434
var cm = cm1 || this, withOp = !cm.curOp;
1435
if (withOp) startOperation(cm);
1436
try { var result = f.apply(cm, arguments); }
1437
finally { if (withOp) endOperation(cm); }
1438
return result;
1439
};
1440
}
1441
function docOperation(f) {
1442
return function() {
1443
var withOp = this.cm && !this.cm.curOp, result;
1444
if (withOp) startOperation(this.cm);
1445
try { result = f.apply(this, arguments); }
1446
finally { if (withOp) endOperation(this.cm); }
1447
return result;
1448
};
1449
}
1450
function runInOp(cm, f) {
1451
var withOp = !cm.curOp, result;
1452
if (withOp) startOperation(cm);
1453
try { result = f(); }
1454
finally { if (withOp) endOperation(cm); }
1455
return result;
1456
}
1457
1458
function regChange(cm, from, to, lendiff) {
1459
if (from == null) from = cm.doc.first;
1460
if (to == null) to = cm.doc.first + cm.doc.size;
1461
cm.curOp.changes.push({from: from, to: to, diff: lendiff});
1462
}
1463
1464
// INPUT HANDLING
1465
1466
function slowPoll(cm) {
1467
if (cm.display.pollingFast) return;
1468
cm.display.poll.set(cm.options.pollInterval, function() {
1469
readInput(cm);
1470
if (cm.state.focused) slowPoll(cm);
1471
});
1472
}
1473
1474
function fastPoll(cm) {
1475
var missed = false;
1476
cm.display.pollingFast = true;
1477
function p() {
1478
var changed = readInput(cm);
1479
if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
1480
else {cm.display.pollingFast = false; slowPoll(cm);}
1481
}
1482
cm.display.poll.set(20, p);
1483
}
1484
1485
// prevInput is a hack to work with IME. If we reset the textarea
1486
// on every change, that breaks IME. So we look for changes
1487
// compared to the previous content instead. (Modern browsers have
1488
// events that indicate IME taking place, but these are not widely
1489
// supported or compatible enough yet to rely on.)
1490
function readInput(cm) {
1491
var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc, sel = doc.sel;
1492
if (!cm.state.focused || hasSelection(input) || isReadOnly(cm) || cm.options.disableInput) return false;
1493
if (cm.state.pasteIncoming && cm.state.fakedLastChar) {
1494
input.value = input.value.substring(0, input.value.length - 1);
1495
cm.state.fakedLastChar = false;
1496
}
1497
var text = input.value;
1498
if (text == prevInput && posEq(sel.from, sel.to)) return false;
1499
if (ie && !ie_lt9 && cm.display.inputHasSelection === text) {
1500
resetInput(cm, true);
1501
return false;
1502
}
1503
1504
var withOp = !cm.curOp;
1505
if (withOp) startOperation(cm);
1506
sel.shift = false;
1507
var same = 0, l = Math.min(prevInput.length, text.length);
1508
while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
1509
var from = sel.from, to = sel.to;
1510
var inserted = text.slice(same);
1511
if (same < prevInput.length)
1512
from = Pos(from.line, from.ch - (prevInput.length - same));
1513
else if (cm.state.overwrite && posEq(from, to) && !cm.state.pasteIncoming)
1514
to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + inserted.length));
1515
1516
var updateInput = cm.curOp.updateInput;
1517
var changeEvent = {from: from, to: to, text: splitLines(inserted),
1518
origin: cm.state.pasteIncoming ? "paste" : cm.state.cutIncoming ? "cut" : "+input"};
1519
makeChange(cm.doc, changeEvent, "end");
1520
cm.curOp.updateInput = updateInput;
1521
signalLater(cm, "inputRead", cm, changeEvent);
1522
if (inserted && !cm.state.pasteIncoming && cm.options.electricChars &&
1523
cm.options.smartIndent && sel.head.ch < 100) {
1524
var electric = cm.getModeAt(sel.head).electricChars;
1525
if (electric) for (var i = 0; i < electric.length; i++)
1526
if (inserted.indexOf(electric.charAt(i)) > -1) {
1527
indentLine(cm, sel.head.line, "smart");
1528
break;
1529
}
1530
}
1531
1532
if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = "";
1533
else cm.display.prevInput = text;
1534
if (withOp) endOperation(cm);
1535
cm.state.pasteIncoming = cm.state.cutIncoming = false;
1536
return true;
1537
}
1538
1539
function resetInput(cm, user) {
1540
var minimal, selected, doc = cm.doc;
1541
if (!posEq(doc.sel.from, doc.sel.to)) {
1542
cm.display.prevInput = "";
1543
minimal = hasCopyEvent &&
1544
(doc.sel.to.line - doc.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000);
1545
var content = minimal ? "-" : selected || cm.getSelection();
1546
cm.display.input.value = content;
1547
if (cm.state.focused) selectInput(cm.display.input);
1548
if (ie && !ie_lt9) cm.display.inputHasSelection = content;
1549
} else if (user) {
1550
cm.display.prevInput = cm.display.input.value = "";
1551
if (ie && !ie_lt9) cm.display.inputHasSelection = null;
1552
}
1553
cm.display.inaccurateSelection = minimal;
1554
}
1555
1556
function focusInput(cm) {
1557
if (cm.options.readOnly != "nocursor" && (!mobile || document.activeElement != cm.display.input))
1558
cm.display.input.focus();
1559
}
1560
1561
function isReadOnly(cm) {
1562
return cm.options.readOnly || cm.doc.cantEdit;
1563
}
1564
1565
// EVENT HANDLERS
1566
1567
function registerEventHandlers(cm) {
1568
var d = cm.display;
1569
on(d.scroller, "mousedown", operation(cm, onMouseDown));
1570
if (old_ie)
1571
on(d.scroller, "dblclick", operation(cm, function(e) {
1572
if (signalDOMEvent(cm, e)) return;
1573
var pos = posFromMouse(cm, e);
1574
if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
1575
e_preventDefault(e);
1576
var word = findWordAt(getLine(cm.doc, pos.line).text, pos);
1577
extendSelection(cm.doc, word.from, word.to);
1578
}));
1579
else
1580
on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
1581
on(d.lineSpace, "selectstart", function(e) {
1582
if (!eventInWidget(d, e)) e_preventDefault(e);
1583
});
1584
// Gecko browsers fire contextmenu *after* opening the menu, at
1585
// which point we can't mess with it anymore. Context menu is
1586
// handled in onMouseDown for Gecko.
1587
if (!captureMiddleClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
1588
1589
on(d.scroller, "scroll", function() {
1590
if (d.scroller.clientHeight) {
1591
setScrollTop(cm, d.scroller.scrollTop);
1592
setScrollLeft(cm, d.scroller.scrollLeft, true);
1593
signal(cm, "scroll", cm);
1594
}
1595
});
1596
on(d.scrollbarV, "scroll", function() {
1597
if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop);
1598
});
1599
on(d.scrollbarH, "scroll", function() {
1600
if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft);
1601
});
1602
1603
on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
1604
on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
1605
1606
function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); }
1607
on(d.scrollbarH, "mousedown", reFocus);
1608
on(d.scrollbarV, "mousedown", reFocus);
1609
// Prevent wrapper from ever scrolling
1610
on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
1611
1612
var resizeTimer;
1613
function onResize() {
1614
if (resizeTimer == null) resizeTimer = setTimeout(function() {
1615
resizeTimer = null;
1616
// Might be a text scaling operation, clear size caches.
1617
d.cachedCharWidth = d.cachedTextHeight = knownScrollbarWidth = null;
1618
clearCaches(cm);
1619
runInOp(cm, bind(regChange, cm));
1620
}, 100);
1621
}
1622
on(window, "resize", onResize);
1623
// Above handler holds on to the editor and its data structures.
1624
// Here we poll to unregister it when the editor is no longer in
1625
// the document, so that it can be garbage-collected.
1626
function unregister() {
1627
for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNode) {}
1628
if (p) setTimeout(unregister, 5000);
1629
else off(window, "resize", onResize);
1630
}
1631
setTimeout(unregister, 5000);
1632
1633
on(d.input, "keyup", operation(cm, function(e) {
1634
if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
1635
if (e.keyCode == 16) cm.doc.sel.shift = false;
1636
}));
1637
on(d.input, "input", function() {
1638
if (ie && !ie_lt9 && cm.display.inputHasSelection) cm.display.inputHasSelection = null;
1639
fastPoll(cm);
1640
});
1641
on(d.input, "keydown", operation(cm, onKeyDown));
1642
on(d.input, "keypress", operation(cm, onKeyPress));
1643
on(d.input, "focus", bind(onFocus, cm));
1644
on(d.input, "blur", bind(onBlur, cm));
1645
1646
function drag_(e) {
1647
if (signalDOMEvent(cm, e) || cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return;
1648
e_stop(e);
1649
}
1650
if (cm.options.dragDrop) {
1651
on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
1652
on(d.scroller, "dragenter", drag_);
1653
on(d.scroller, "dragover", drag_);
1654
on(d.scroller, "drop", operation(cm, onDrop));
1655
}
1656
on(d.scroller, "paste", function(e) {
1657
if (eventInWidget(d, e)) return;
1658
focusInput(cm);
1659
fastPoll(cm);
1660
});
1661
on(d.input, "paste", function() {
1662
// Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206
1663
// Add a char to the end of textarea before paste occur so that
1664
// selection doesn't span to the end of textarea.
1665
if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) {
1666
var start = d.input.selectionStart, end = d.input.selectionEnd;
1667
d.input.value += "$";
1668
d.input.selectionStart = start;
1669
d.input.selectionEnd = end;
1670
cm.state.fakedLastChar = true;
1671
}
1672
cm.state.pasteIncoming = true;
1673
fastPoll(cm);
1674
});
1675
1676
function prepareCopy(e) {
1677
if (d.inaccurateSelection) {
1678
d.prevInput = "";
1679
d.inaccurateSelection = false;
1680
d.input.value = cm.getSelection();
1681
selectInput(d.input);
1682
}
1683
if (e.type == "cut") cm.state.cutIncoming = true;
1684
}
1685
on(d.input, "cut", prepareCopy);
1686
on(d.input, "copy", prepareCopy);
1687
1688
// Needed to handle Tab key in KHTML
1689
if (khtml) on(d.sizer, "mouseup", function() {
1690
if (document.activeElement == d.input) d.input.blur();
1691
focusInput(cm);
1692
});
1693
}
1694
1695
function eventInWidget(display, e) {
1696
for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
1697
if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true;
1698
}
1699
}
1700
1701
function posFromMouse(cm, e, liberal) {
1702
var display = cm.display;
1703
if (!liberal) {
1704
var target = e_target(e);
1705
if (target == display.scrollbarH || target == display.scrollbarH.firstChild ||
1706
target == display.scrollbarV || target == display.scrollbarV.firstChild ||
1707
target == display.scrollbarFiller || target == display.gutterFiller) return null;
1708
}
1709
var x, y, space = getRect(display.lineSpace);
1710
// Fails unpredictably on IE[67] when mouse is dragged around quickly.
1711
try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
1712
return coordsChar(cm, x - space.left, y - space.top);
1713
}
1714
1715
var lastClick, lastDoubleClick;
1716
function onMouseDown(e) {
1717
if (signalDOMEvent(this, e)) return;
1718
var cm = this, display = cm.display, doc = cm.doc, sel = doc.sel;
1719
sel.shift = e.shiftKey;
1720
1721
if (eventInWidget(display, e)) {
1722
if (!webkit) {
1723
display.scroller.draggable = false;
1724
setTimeout(function(){display.scroller.draggable = true;}, 100);
1725
}
1726
return;
1727
}
1728
if (clickInGutter(cm, e)) return;
1729
var start = posFromMouse(cm, e);
1730
1731
switch (e_button(e)) {
1732
case 3:
1733
if (captureMiddleClick) onContextMenu.call(cm, cm, e);
1734
return;
1735
case 2:
1736
if (webkit) cm.state.lastMiddleDown = +new Date;
1737
if (start) extendSelection(cm.doc, start);
1738
setTimeout(bind(focusInput, cm), 20);
1739
e_preventDefault(e);
1740
return;
1741
}
1742
// For button 1, if it was clicked inside the editor
1743
// (posFromMouse returning non-null), we have to adjust the
1744
// selection.
1745
if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;}
1746
1747
if (!cm.state.focused) onFocus(cm);
1748
1749
var now = +new Date, type = "single";
1750
if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
1751
type = "triple";
1752
e_preventDefault(e);
1753
setTimeout(bind(focusInput, cm), 20);
1754
selectLine(cm, start.line);
1755
} else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
1756
type = "double";
1757
lastDoubleClick = {time: now, pos: start};
1758
e_preventDefault(e);
1759
var word = findWordAt(getLine(doc, start.line).text, start);
1760
extendSelection(cm.doc, word.from, word.to);
1761
} else { lastClick = {time: now, pos: start}; }
1762
1763
var last = start;
1764
if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) &&
1765
!posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") {
1766
var dragEnd = operation(cm, function(e2) {
1767
if (webkit) display.scroller.draggable = false;
1768
cm.state.draggingText = false;
1769
off(document, "mouseup", dragEnd);
1770
off(display.scroller, "drop", dragEnd);
1771
if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
1772
e_preventDefault(e2);
1773
extendSelection(cm.doc, start);
1774
focusInput(cm);
1775
// Work around unexplainable focus problem in IE9 (#2127)
1776
if (old_ie && !ie_lt9)
1777
setTimeout(function() {document.body.focus(); focusInput(cm);}, 20);
1778
}
1779
});
1780
// Let the drag handler handle this.
1781
if (webkit) display.scroller.draggable = true;
1782
cm.state.draggingText = dragEnd;
1783
// IE's approach to draggable
1784
if (display.scroller.dragDrop) display.scroller.dragDrop();
1785
on(document, "mouseup", dragEnd);
1786
on(display.scroller, "drop", dragEnd);
1787
return;
1788
}
1789
e_preventDefault(e);
1790
if (type == "single") extendSelection(cm.doc, clipPos(doc, start));
1791
1792
var startstart = sel.from, startend = sel.to, lastPos = start;
1793
1794
function doSelect(cur) {
1795
if (posEq(lastPos, cur)) return;
1796
lastPos = cur;
1797
1798
if (type == "single") {
1799
extendSelection(cm.doc, clipPos(doc, start), cur);
1800
return;
1801
}
1802
1803
startstart = clipPos(doc, startstart);
1804
startend = clipPos(doc, startend);
1805
if (type == "double") {
1806
var word = findWordAt(getLine(doc, cur.line).text, cur);
1807
if (posLess(cur, startstart)) extendSelection(cm.doc, word.from, startend);
1808
else extendSelection(cm.doc, startstart, word.to);
1809
} else if (type == "triple") {
1810
if (posLess(cur, startstart)) extendSelection(cm.doc, startend, clipPos(doc, Pos(cur.line, 0)));
1811
else extendSelection(cm.doc, startstart, clipPos(doc, Pos(cur.line + 1, 0)));
1812
}
1813
}
1814
1815
var editorSize = getRect(display.wrapper);
1816
// Used to ensure timeout re-tries don't fire when another extend
1817
// happened in the meantime (clearTimeout isn't reliable -- at
1818
// least on Chrome, the timeouts still happen even when cleared,
1819
// if the clear happens after their scheduled firing time).
1820
var counter = 0;
1821
1822
function extend(e) {
1823
var curCount = ++counter;
1824
var cur = posFromMouse(cm, e, true);
1825
if (!cur) return;
1826
if (!posEq(cur, last)) {
1827
if (!cm.state.focused) onFocus(cm);
1828
last = cur;
1829
doSelect(cur);
1830
var visible = visibleLines(display, doc);
1831
if (cur.line >= visible.to || cur.line < visible.from)
1832
setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
1833
} else {
1834
var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
1835
if (outside) setTimeout(operation(cm, function() {
1836
if (counter != curCount) return;
1837
display.scroller.scrollTop += outside;
1838
extend(e);
1839
}), 50);
1840
}
1841
}
1842
1843
function done(e) {
1844
counter = Infinity;
1845
e_preventDefault(e);
1846
focusInput(cm);
1847
off(document, "mousemove", move);
1848
off(document, "mouseup", up);
1849
}
1850
1851
var move = operation(cm, function(e) {
1852
if (!old_ie && !e_button(e)) done(e);
1853
else extend(e);
1854
});
1855
var up = operation(cm, done);
1856
on(document, "mousemove", move);
1857
on(document, "mouseup", up);
1858
}
1859
1860
function gutterEvent(cm, e, type, prevent, signalfn) {
1861
try { var mX = e.clientX, mY = e.clientY; }
1862
catch(e) { return false; }
1863
if (mX >= Math.floor(getRect(cm.display.gutters).right)) return false;
1864
if (prevent) e_preventDefault(e);
1865
1866
var display = cm.display;
1867
var lineBox = getRect(display.lineDiv);
1868
1869
if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
1870
mY -= lineBox.top - display.viewOffset;
1871
1872
for (var i = 0; i < cm.options.gutters.length; ++i) {
1873
var g = display.gutters.childNodes[i];
1874
if (g && getRect(g).right >= mX) {
1875
var line = lineAtHeight(cm.doc, mY);
1876
var gutter = cm.options.gutters[i];
1877
signalfn(cm, type, cm, line, gutter, e);
1878
return e_defaultPrevented(e);
1879
}
1880
}
1881
}
1882
1883
function contextMenuInGutter(cm, e) {
1884
if (!hasHandler(cm, "gutterContextMenu")) return false;
1885
return gutterEvent(cm, e, "gutterContextMenu", false, signal);
1886
}
1887
1888
function clickInGutter(cm, e) {
1889
return gutterEvent(cm, e, "gutterClick", true, signalLater);
1890
}
1891
1892
// Kludge to work around strange IE behavior where it'll sometimes
1893
// re-fire a series of drag-related events right after the drop (#1551)
1894
var lastDrop = 0;
1895
1896
function onDrop(e) {
1897
var cm = this;
1898
if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e) || (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))))
1899
return;
1900
e_preventDefault(e);
1901
if (ie) lastDrop = +new Date;
1902
var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
1903
if (!pos || isReadOnly(cm)) return;
1904
if (files && files.length && window.FileReader && window.File) {
1905
var n = files.length, text = Array(n), read = 0;
1906
var loadFile = function(file, i) {
1907
var reader = new FileReader;
1908
reader.onload = function() {
1909
text[i] = reader.result;
1910
if (++read == n) {
1911
pos = clipPos(cm.doc, pos);
1912
makeChange(cm.doc, {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}, "around");
1913
}
1914
};
1915
reader.readAsText(file);
1916
};
1917
for (var i = 0; i < n; ++i) loadFile(files[i], i);
1918
} else {
1919
// Don't do a replace if the drop happened inside of the selected text.
1920
if (cm.state.draggingText && !(posLess(pos, cm.doc.sel.from) || posLess(cm.doc.sel.to, pos))) {
1921
cm.state.draggingText(e);
1922
// Ensure the editor is re-focused
1923
setTimeout(bind(focusInput, cm), 20);
1924
return;
1925
}
1926
try {
1927
var text = e.dataTransfer.getData("Text");
1928
if (text) {
1929
var curFrom = cm.doc.sel.from, curTo = cm.doc.sel.to;
1930
setSelection(cm.doc, pos, pos);
1931
if (cm.state.draggingText) replaceRange(cm.doc, "", curFrom, curTo, "paste");
1932
cm.replaceSelection(text, null, "paste");
1933
focusInput(cm);
1934
}
1935
}
1936
catch(e){}
1937
}
1938
}
1939
1940
function onDragStart(cm, e) {
1941
if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
1942
if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
1943
1944
var txt = cm.getSelection();
1945
e.dataTransfer.setData("Text", txt);
1946
1947
// Use dummy image instead of default browsers image.
1948
// Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
1949
if (e.dataTransfer.setDragImage && !safari) {
1950
var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
1951
img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
1952
if (opera) {
1953
img.width = img.height = 1;
1954
cm.display.wrapper.appendChild(img);
1955
// Force a relayout, or Opera won't use our image for some obscure reason
1956
img._top = img.offsetTop;
1957
}
1958
e.dataTransfer.setDragImage(img, 0, 0);
1959
if (opera) img.parentNode.removeChild(img);
1960
}
1961
}
1962
1963
function setScrollTop(cm, val) {
1964
if (Math.abs(cm.doc.scrollTop - val) < 2) return;
1965
cm.doc.scrollTop = val;
1966
if (!gecko) updateDisplay(cm, [], val);
1967
if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
1968
if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
1969
if (gecko) updateDisplay(cm, []);
1970
startWorker(cm, 100);
1971
}
1972
function setScrollLeft(cm, val, isScroller) {
1973
if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
1974
val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
1975
cm.doc.scrollLeft = val;
1976
alignHorizontally(cm);
1977
if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
1978
if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
1979
}
1980
1981
// Since the delta values reported on mouse wheel events are
1982
// unstandardized between browsers and even browser versions, and
1983
// generally horribly unpredictable, this code starts by measuring
1984
// the scroll effect that the first few mouse wheel events have,
1985
// and, from that, detects the way it can convert deltas to pixel
1986
// offsets afterwards.
1987
//
1988
// The reason we want to know the amount a wheel event will scroll
1989
// is that it gives us a chance to update the display before the
1990
// actual scrolling happens, reducing flickering.
1991
1992
var wheelSamples = 0, wheelPixelsPerUnit = null;
1993
// Fill in a browser-detected starting value on browsers where we
1994
// know one. These don't have to be accurate -- the result of them
1995
// being wrong would just be a slight flicker on the first wheel
1996
// scroll (if it is large enough).
1997
if (old_ie) wheelPixelsPerUnit = -.53;
1998
else if (gecko) wheelPixelsPerUnit = 15;
1999
else if (chrome) wheelPixelsPerUnit = -.7;
2000
else if (safari) wheelPixelsPerUnit = -1/3;
2001
2002
function onScrollWheel(cm, e) {
2003
var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
2004
if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
2005
if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
2006
else if (dy == null) dy = e.wheelDelta;
2007
2008
var display = cm.display, scroll = display.scroller;
2009
// Quit if there's nothing to scroll here
2010
if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
2011
dy && scroll.scrollHeight > scroll.clientHeight)) return;
2012
2013
// Webkit browsers on OS X abort momentum scrolls when the target
2014
// of the scroll event is removed from the scrollable element.
2015
// This hack (see related code in patchDisplay) makes sure the
2016
// element is kept around.
2017
if (dy && mac && webkit) {
2018
for (var cur = e.target; cur != scroll; cur = cur.parentNode) {
2019
if (cur.lineObj) {
2020
cm.display.currentWheelTarget = cur;
2021
break;
2022
}
2023
}
2024
}
2025
2026
// On some browsers, horizontal scrolling will cause redraws to
2027
// happen before the gutter has been realigned, causing it to
2028
// wriggle around in a most unseemly way. When we have an
2029
// estimated pixels/delta value, we just handle horizontal
2030
// scrolling entirely here. It'll be slightly off from native, but
2031
// better than glitching out.
2032
if (dx && !gecko && !opera && wheelPixelsPerUnit != null) {
2033
if (dy)
2034
setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
2035
setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
2036
e_preventDefault(e);
2037
display.wheelStartX = null; // Abort measurement, if in progress
2038
return;
2039
}
2040
2041
if (dy && wheelPixelsPerUnit != null) {
2042
var pixels = dy * wheelPixelsPerUnit;
2043
var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
2044
if (pixels < 0) top = Math.max(0, top + pixels - 50);
2045
else bot = Math.min(cm.doc.height, bot + pixels + 50);
2046
updateDisplay(cm, [], {top: top, bottom: bot});
2047
}
2048
2049
if (wheelSamples < 20) {
2050
if (display.wheelStartX == null) {
2051
display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
2052
display.wheelDX = dx; display.wheelDY = dy;
2053
setTimeout(function() {
2054
if (display.wheelStartX == null) return;
2055
var movedX = scroll.scrollLeft - display.wheelStartX;
2056
var movedY = scroll.scrollTop - display.wheelStartY;
2057
var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
2058
(movedX && display.wheelDX && movedX / display.wheelDX);
2059
display.wheelStartX = display.wheelStartY = null;
2060
if (!sample) return;
2061
wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
2062
++wheelSamples;
2063
}, 200);
2064
} else {
2065
display.wheelDX += dx; display.wheelDY += dy;
2066
}
2067
}
2068
}
2069
2070
function doHandleBinding(cm, bound, dropShift) {
2071
if (typeof bound == "string") {
2072
bound = commands[bound];
2073
if (!bound) return false;
2074
}
2075
// Ensure previous input has been read, so that the handler sees a
2076
// consistent view of the document
2077
if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
2078
var doc = cm.doc, prevShift = doc.sel.shift, done = false;
2079
try {
2080
if (isReadOnly(cm)) cm.state.suppressEdits = true;
2081
if (dropShift) doc.sel.shift = false;
2082
done = bound(cm) != Pass;
2083
} finally {
2084
doc.sel.shift = prevShift;
2085
cm.state.suppressEdits = false;
2086
}
2087
return done;
2088
}
2089
2090
function allKeyMaps(cm) {
2091
var maps = cm.state.keyMaps.slice(0);
2092
if (cm.options.extraKeys) maps.push(cm.options.extraKeys);
2093
maps.push(cm.options.keyMap);
2094
return maps;
2095
}
2096
2097
var maybeTransition;
2098
function handleKeyBinding(cm, e) {
2099
// Handle auto keymap transitions
2100
var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
2101
clearTimeout(maybeTransition);
2102
if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
2103
if (getKeyMap(cm.options.keyMap) == startMap) {
2104
cm.options.keyMap = (next.call ? next.call(null, cm) : next);
2105
keyMapChanged(cm);
2106
}
2107
}, 50);
2108
2109
var name = keyName(e, true), handled = false;
2110
if (!name) return false;
2111
var keymaps = allKeyMaps(cm);
2112
2113
if (e.shiftKey) {
2114
// First try to resolve full name (including 'Shift-'). Failing
2115
// that, see if there is a cursor-motion command (starting with
2116
// 'go') bound to the keyname without 'Shift-'.
2117
handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);})
2118
|| lookupKey(name, keymaps, function(b) {
2119
if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
2120
return doHandleBinding(cm, b);
2121
});
2122
} else {
2123
handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); });
2124
}
2125
2126
if (handled) {
2127
e_preventDefault(e);
2128
restartBlink(cm);
2129
if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
2130
signalLater(cm, "keyHandled", cm, name, e);
2131
}
2132
return handled;
2133
}
2134
2135
function handleCharBinding(cm, e, ch) {
2136
var handled = lookupKey("'" + ch + "'", allKeyMaps(cm),
2137
function(b) { return doHandleBinding(cm, b, true); });
2138
if (handled) {
2139
e_preventDefault(e);
2140
restartBlink(cm);
2141
signalLater(cm, "keyHandled", cm, "'" + ch + "'", e);
2142
}
2143
return handled;
2144
}
2145
2146
var lastStoppedKey = null;
2147
function onKeyDown(e) {
2148
var cm = this;
2149
if (!cm.state.focused) onFocus(cm);
2150
if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
2151
if (old_ie && e.keyCode == 27) e.returnValue = false;
2152
var code = e.keyCode;
2153
// IE does strange things with escape.
2154
cm.doc.sel.shift = code == 16 || e.shiftKey;
2155
// First give onKeyEvent option a chance to handle this.
2156
var handled = handleKeyBinding(cm, e);
2157
if (opera) {
2158
lastStoppedKey = handled ? code : null;
2159
// Opera has no cut event... we try to at least catch the key combo
2160
if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
2161
cm.replaceSelection("");
2162
}
2163
}
2164
2165
function onKeyPress(e) {
2166
var cm = this;
2167
if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
2168
var keyCode = e.keyCode, charCode = e.charCode;
2169
if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
2170
if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
2171
var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
2172
if (handleCharBinding(cm, e, ch)) return;
2173
if (ie && !ie_lt9) cm.display.inputHasSelection = null;
2174
fastPoll(cm);
2175
}
2176
2177
function onFocus(cm) {
2178
if (cm.options.readOnly == "nocursor") return;
2179
if (!cm.state.focused) {
2180
signal(cm, "focus", cm);
2181
cm.state.focused = true;
2182
if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
2183
cm.display.wrapper.className += " CodeMirror-focused";
2184
if (!cm.curOp) {
2185
resetInput(cm, true);
2186
if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #1730
2187
}
2188
}
2189
slowPoll(cm);
2190
restartBlink(cm);
2191
}
2192
function onBlur(cm) {
2193
if (cm.state.focused) {
2194
signal(cm, "blur", cm);
2195
cm.state.focused = false;
2196
cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-focused", "");
2197
}
2198
clearInterval(cm.display.blinker);
2199
setTimeout(function() {if (!cm.state.focused) cm.doc.sel.shift = false;}, 150);
2200
}
2201
2202
var detectingSelectAll;
2203
function onContextMenu(cm, e) {
2204
if (signalDOMEvent(cm, e, "contextmenu")) return;
2205
var display = cm.display, sel = cm.doc.sel;
2206
if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return;
2207
2208
var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
2209
if (!pos || opera) return; // Opera is difficult.
2210
2211
// Reset the current text selection only if the click is done outside of the selection
2212
// and 'resetSelectionOnContextMenu' option is true.
2213
var reset = cm.options.resetSelectionOnContextMenu;
2214
if (reset && (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to)))
2215
operation(cm, setSelection)(cm.doc, pos, pos);
2216
2217
var oldCSS = display.input.style.cssText;
2218
display.inputDiv.style.position = "absolute";
2219
display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
2220
"px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: transparent; outline: none;" +
2221
"border-width: 0; outline: none; overflow: hidden; opacity: .05; -ms-opacity: .05; filter: alpha(opacity=5);";
2222
focusInput(cm);
2223
resetInput(cm, true);
2224
// Adds "Select all" to context menu in FF
2225
if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " ";
2226
2227
function prepareSelectAllHack() {
2228
if (display.input.selectionStart != null) {
2229
var extval = display.input.value = "\u200b" + (posEq(sel.from, sel.to) ? "" : display.input.value);
2230
display.prevInput = "\u200b";
2231
display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
2232
}
2233
}
2234
function rehide() {
2235
display.inputDiv.style.position = "relative";
2236
display.input.style.cssText = oldCSS;
2237
if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
2238
slowPoll(cm);
2239
2240
// Try to detect the user choosing select-all
2241
if (display.input.selectionStart != null) {
2242
if (!old_ie || ie_lt9) prepareSelectAllHack();
2243
clearTimeout(detectingSelectAll);
2244
var i = 0, poll = function(){
2245
if (display.prevInput == "\u200b" && display.input.selectionStart == 0)
2246
operation(cm, commands.selectAll)(cm);
2247
else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
2248
else resetInput(cm);
2249
};
2250
detectingSelectAll = setTimeout(poll, 200);
2251
}
2252
}
2253
2254
if (old_ie && !ie_lt9) prepareSelectAllHack();
2255
if (captureMiddleClick) {
2256
e_stop(e);
2257
var mouseup = function() {
2258
off(window, "mouseup", mouseup);
2259
setTimeout(rehide, 20);
2260
};
2261
on(window, "mouseup", mouseup);
2262
} else {
2263
setTimeout(rehide, 50);
2264
}
2265
}
2266
2267
// UPDATING
2268
2269
var changeEnd = CodeMirror.changeEnd = function(change) {
2270
if (!change.text) return change.to;
2271
return Pos(change.from.line + change.text.length - 1,
2272
lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
2273
};
2274
2275
// Make sure a position will be valid after the given change.
2276
function clipPostChange(doc, change, pos) {
2277
if (!posLess(change.from, pos)) return clipPos(doc, pos);
2278
var diff = (change.text.length - 1) - (change.to.line - change.from.line);
2279
if (pos.line > change.to.line + diff) {
2280
var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1;
2281
if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length);
2282
return clipToLen(pos, getLine(doc, preLine).text.length);
2283
}
2284
if (pos.line == change.to.line + diff)
2285
return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) +
2286
getLine(doc, change.to.line).text.length - change.to.ch);
2287
var inside = pos.line - change.from.line;
2288
return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch));
2289
}
2290
2291
// Hint can be null|"end"|"start"|"around"|{anchor,head}
2292
function computeSelAfterChange(doc, change, hint) {
2293
if (hint && typeof hint == "object") // Assumed to be {anchor, head} object
2294
return {anchor: clipPostChange(doc, change, hint.anchor),
2295
head: clipPostChange(doc, change, hint.head)};
2296
2297
if (hint == "start") return {anchor: change.from, head: change.from};
2298
2299
var end = changeEnd(change);
2300
if (hint == "around") return {anchor: change.from, head: end};
2301
if (hint == "end") return {anchor: end, head: end};
2302
2303
// hint is null, leave the selection alone as much as possible
2304
var adjustPos = function(pos) {
2305
if (posLess(pos, change.from)) return pos;
2306
if (!posLess(change.to, pos)) return end;
2307
2308
var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
2309
if (pos.line == change.to.line) ch += end.ch - change.to.ch;
2310
return Pos(line, ch);
2311
};
2312
return {anchor: adjustPos(doc.sel.anchor), head: adjustPos(doc.sel.head)};
2313
}
2314
2315
function filterChange(doc, change, update) {
2316
var obj = {
2317
canceled: false,
2318
from: change.from,
2319
to: change.to,
2320
text: change.text,
2321
origin: change.origin,
2322
cancel: function() { this.canceled = true; }
2323
};
2324
if (update) obj.update = function(from, to, text, origin) {
2325
if (from) this.from = clipPos(doc, from);
2326
if (to) this.to = clipPos(doc, to);
2327
if (text) this.text = text;
2328
if (origin !== undefined) this.origin = origin;
2329
};
2330
signal(doc, "beforeChange", doc, obj);
2331
if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
2332
2333
if (obj.canceled) return null;
2334
return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
2335
}
2336
2337
// Replace the range from from to to by the strings in replacement.
2338
// change is a {from, to, text [, origin]} object
2339
function makeChange(doc, change, selUpdate, ignoreReadOnly) {
2340
if (doc.cm) {
2341
if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, selUpdate, ignoreReadOnly);
2342
if (doc.cm.state.suppressEdits) return;
2343
}
2344
2345
if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
2346
change = filterChange(doc, change, true);
2347
if (!change) return;
2348
}
2349
2350
// Possibly split or suppress the update based on the presence
2351
// of read-only spans in its range.
2352
var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
2353
if (split) {
2354
for (var i = split.length - 1; i >= 1; --i)
2355
makeChangeNoReadonly(doc, {from: split[i].from, to: split[i].to, text: [""]});
2356
if (split.length)
2357
makeChangeNoReadonly(doc, {from: split[0].from, to: split[0].to, text: change.text}, selUpdate);
2358
} else {
2359
makeChangeNoReadonly(doc, change, selUpdate);
2360
}
2361
}
2362
2363
function makeChangeNoReadonly(doc, change, selUpdate) {
2364
if (change.text.length == 1 && change.text[0] == "" && posEq(change.from, change.to)) return;
2365
var selAfter = computeSelAfterChange(doc, change, selUpdate);
2366
addToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
2367
2368
makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
2369
var rebased = [];
2370
2371
linkedDocs(doc, function(doc, sharedHist) {
2372
if (!sharedHist && indexOf(rebased, doc.history) == -1) {
2373
rebaseHist(doc.history, change);
2374
rebased.push(doc.history);
2375
}
2376
makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
2377
});
2378
}
2379
2380
function makeChangeFromHistory(doc, type) {
2381
if (doc.cm && doc.cm.state.suppressEdits) return;
2382
2383
var hist = doc.history;
2384
var event = (type == "undo" ? hist.done : hist.undone).pop();
2385
if (!event) return;
2386
2387
var anti = {changes: [], anchorBefore: event.anchorAfter, headBefore: event.headAfter,
2388
anchorAfter: event.anchorBefore, headAfter: event.headBefore,
2389
generation: hist.generation};
2390
(type == "undo" ? hist.undone : hist.done).push(anti);
2391
hist.generation = event.generation || ++hist.maxGeneration;
2392
2393
var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
2394
2395
for (var i = event.changes.length - 1; i >= 0; --i) {
2396
var change = event.changes[i];
2397
change.origin = type;
2398
if (filter && !filterChange(doc, change, false)) {
2399
(type == "undo" ? hist.done : hist.undone).length = 0;
2400
return;
2401
}
2402
2403
anti.changes.push(historyChangeFromChange(doc, change));
2404
2405
var after = i ? computeSelAfterChange(doc, change, null)
2406
: {anchor: event.anchorBefore, head: event.headBefore};
2407
makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
2408
var rebased = [];
2409
2410
linkedDocs(doc, function(doc, sharedHist) {
2411
if (!sharedHist && indexOf(rebased, doc.history) == -1) {
2412
rebaseHist(doc.history, change);
2413
rebased.push(doc.history);
2414
}
2415
makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
2416
});
2417
}
2418
}
2419
2420
function shiftDoc(doc, distance) {
2421
function shiftPos(pos) {return Pos(pos.line + distance, pos.ch);}
2422
doc.first += distance;
2423
if (doc.cm) regChange(doc.cm, doc.first, doc.first, distance);
2424
doc.sel.head = shiftPos(doc.sel.head); doc.sel.anchor = shiftPos(doc.sel.anchor);
2425
doc.sel.from = shiftPos(doc.sel.from); doc.sel.to = shiftPos(doc.sel.to);
2426
}
2427
2428
function makeChangeSingleDoc(doc, change, selAfter, spans) {
2429
if (doc.cm && !doc.cm.curOp)
2430
return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
2431
2432
if (change.to.line < doc.first) {
2433
shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
2434
return;
2435
}
2436
if (change.from.line > doc.lastLine()) return;
2437
2438
// Clip the change to the size of this doc
2439
if (change.from.line < doc.first) {
2440
var shift = change.text.length - 1 - (doc.first - change.from.line);
2441
shiftDoc(doc, shift);
2442
change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
2443
text: [lst(change.text)], origin: change.origin};
2444
}
2445
var last = doc.lastLine();
2446
if (change.to.line > last) {
2447
change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
2448
text: [change.text[0]], origin: change.origin};
2449
}
2450
2451
change.removed = getBetween(doc, change.from, change.to);
2452
2453
if (!selAfter) selAfter = computeSelAfterChange(doc, change, null);
2454
if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans, selAfter);
2455
else updateDoc(doc, change, spans, selAfter);
2456
}
2457
2458
function makeChangeSingleDocInEditor(cm, change, spans, selAfter) {
2459
var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
2460
2461
var recomputeMaxLength = false, checkWidthStart = from.line;
2462
if (!cm.options.lineWrapping) {
2463
checkWidthStart = lineNo(visualLine(doc, getLine(doc, from.line)));
2464
doc.iter(checkWidthStart, to.line + 1, function(line) {
2465
if (line == display.maxLine) {
2466
recomputeMaxLength = true;
2467
return true;
2468
}
2469
});
2470
}
2471
2472
if (!posLess(doc.sel.head, change.from) && !posLess(change.to, doc.sel.head))
2473
cm.curOp.cursorActivity = true;
2474
2475
updateDoc(doc, change, spans, selAfter, estimateHeight(cm));
2476
2477
if (!cm.options.lineWrapping) {
2478
doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
2479
var len = lineLength(doc, line);
2480
if (len > display.maxLineLength) {
2481
display.maxLine = line;
2482
display.maxLineLength = len;
2483
display.maxLineChanged = true;
2484
recomputeMaxLength = false;
2485
}
2486
});
2487
if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
2488
}
2489
2490
// Adjust frontier, schedule worker
2491
doc.frontier = Math.min(doc.frontier, from.line);
2492
startWorker(cm, 400);
2493
2494
var lendiff = change.text.length - (to.line - from.line) - 1;
2495
// Remember that these lines changed, for updating the display
2496
regChange(cm, from.line, to.line + 1, lendiff);
2497
2498
if (hasHandler(cm, "change")) {
2499
var changeObj = {from: from, to: to,
2500
text: change.text,
2501
removed: change.removed,
2502
origin: change.origin};
2503
if (cm.curOp.textChanged) {
2504
for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {}
2505
cur.next = changeObj;
2506
} else cm.curOp.textChanged = changeObj;
2507
}
2508
}
2509
2510
function replaceRange(doc, code, from, to, origin) {
2511
if (!to) to = from;
2512
if (posLess(to, from)) { var tmp = to; to = from; from = tmp; }
2513
if (typeof code == "string") code = splitLines(code);
2514
makeChange(doc, {from: from, to: to, text: code, origin: origin}, null);
2515
}
2516
2517
// POSITION OBJECT
2518
2519
function Pos(line, ch) {
2520
if (!(this instanceof Pos)) return new Pos(line, ch);
2521
this.line = line; this.ch = ch;
2522
}
2523
CodeMirror.Pos = Pos;
2524
2525
function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
2526
function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
2527
function cmp(a, b) {return a.line - b.line || a.ch - b.ch;}
2528
function copyPos(x) {return Pos(x.line, x.ch);}
2529
2530
// SELECTION
2531
2532
function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
2533
function clipPos(doc, pos) {
2534
if (pos.line < doc.first) return Pos(doc.first, 0);
2535
var last = doc.first + doc.size - 1;
2536
if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
2537
return clipToLen(pos, getLine(doc, pos.line).text.length);
2538
}
2539
function clipToLen(pos, linelen) {
2540
var ch = pos.ch;
2541
if (ch == null || ch > linelen) return Pos(pos.line, linelen);
2542
else if (ch < 0) return Pos(pos.line, 0);
2543
else return pos;
2544
}
2545
function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
2546
2547
// If shift is held, this will move the selection anchor. Otherwise,
2548
// it'll set the whole selection.
2549
function extendSelection(doc, pos, other, bias) {
2550
if (doc.sel.shift || doc.sel.extend) {
2551
var anchor = doc.sel.anchor;
2552
if (other) {
2553
var posBefore = posLess(pos, anchor);
2554
if (posBefore != posLess(other, anchor)) {
2555
anchor = pos;
2556
pos = other;
2557
} else if (posBefore != posLess(pos, other)) {
2558
pos = other;
2559
}
2560
}
2561
setSelection(doc, anchor, pos, bias);
2562
} else {
2563
setSelection(doc, pos, other || pos, bias);
2564
}
2565
if (doc.cm) doc.cm.curOp.userSelChange = true;
2566
}
2567
2568
function filterSelectionChange(doc, anchor, head) {
2569
var obj = {anchor: anchor, head: head};
2570
signal(doc, "beforeSelectionChange", doc, obj);
2571
if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
2572
obj.anchor = clipPos(doc, obj.anchor); obj.head = clipPos(doc, obj.head);
2573
return obj;
2574
}
2575
2576
// Update the selection. Last two args are only used by
2577
// updateDoc, since they have to be expressed in the line
2578
// numbers before the update.
2579
function setSelection(doc, anchor, head, bias, checkAtomic) {
2580
if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) {
2581
var filtered = filterSelectionChange(doc, anchor, head);
2582
head = filtered.head;
2583
anchor = filtered.anchor;
2584
}
2585
2586
var sel = doc.sel;
2587
sel.goalColumn = null;
2588
if (bias == null) bias = posLess(head, sel.head) ? -1 : 1;
2589
// Skip over atomic spans.
2590
if (checkAtomic || !posEq(anchor, sel.anchor))
2591
anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push");
2592
if (checkAtomic || !posEq(head, sel.head))
2593
head = skipAtomic(doc, head, bias, checkAtomic != "push");
2594
2595
if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return;
2596
2597
sel.anchor = anchor; sel.head = head;
2598
var inv = posLess(head, anchor);
2599
sel.from = inv ? head : anchor;
2600
sel.to = inv ? anchor : head;
2601
2602
if (doc.cm)
2603
doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged =
2604
doc.cm.curOp.cursorActivity = true;
2605
2606
signalLater(doc, "cursorActivity", doc);
2607
}
2608
2609
function reCheckSelection(cm) {
2610
setSelection(cm.doc, cm.doc.sel.from, cm.doc.sel.to, null, "push");
2611
}
2612
2613
function skipAtomic(doc, pos, bias, mayClear) {
2614
var flipped = false, curPos = pos;
2615
var dir = bias || 1;
2616
doc.cantEdit = false;
2617
search: for (;;) {
2618
var line = getLine(doc, curPos.line);
2619
if (line.markedSpans) {
2620
for (var i = 0; i < line.markedSpans.length; ++i) {
2621
var sp = line.markedSpans[i], m = sp.marker;
2622
if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
2623
(sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
2624
if (mayClear) {
2625
signal(m, "beforeCursorEnter");
2626
if (m.explicitlyCleared) {
2627
if (!line.markedSpans) break;
2628
else {--i; continue;}
2629
}
2630
}
2631
if (!m.atomic) continue;
2632
var newPos = m.find()[dir < 0 ? "from" : "to"];
2633
if (posEq(newPos, curPos)) {
2634
newPos.ch += dir;
2635
if (newPos.ch < 0) {
2636
if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
2637
else newPos = null;
2638
} else if (newPos.ch > line.text.length) {
2639
if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
2640
else newPos = null;
2641
}
2642
if (!newPos) {
2643
if (flipped) {
2644
// Driven in a corner -- no valid cursor position found at all
2645
// -- try again *with* clearing, if we didn't already
2646
if (!mayClear) return skipAtomic(doc, pos, bias, true);
2647
// Otherwise, turn off editing until further notice, and return the start of the doc
2648
doc.cantEdit = true;
2649
return Pos(doc.first, 0);
2650
}
2651
flipped = true; newPos = pos; dir = -dir;
2652
}
2653
}
2654
curPos = newPos;
2655
continue search;
2656
}
2657
}
2658
}
2659
return curPos;
2660
}
2661
}
2662
2663
// SCROLLING
2664
2665
function scrollCursorIntoView(cm) {
2666
var coords = scrollPosIntoView(cm, cm.doc.sel.head, null, cm.options.cursorScrollMargin);
2667
if (!cm.state.focused) return;
2668
var display = cm.display, box = getRect(display.sizer), doScroll = null;
2669
if (coords.top + box.top < 0) doScroll = true;
2670
else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
2671
if (doScroll != null && !phantom) {
2672
var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
2673
(coords.top - display.viewOffset) + "px; height: " +
2674
(coords.bottom - coords.top + scrollerCutOff) + "px; left: " +
2675
coords.left + "px; width: 2px;");
2676
cm.display.lineSpace.appendChild(scrollNode);
2677
scrollNode.scrollIntoView(doScroll);
2678
cm.display.lineSpace.removeChild(scrollNode);
2679
}
2680
}
2681
2682
function scrollPosIntoView(cm, pos, end, margin) {
2683
if (margin == null) margin = 0;
2684
for (;;) {
2685
var changed = false, coords = cursorCoords(cm, pos);
2686
var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
2687
var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
2688
Math.min(coords.top, endCoords.top) - margin,
2689
Math.max(coords.left, endCoords.left),
2690
Math.max(coords.bottom, endCoords.bottom) + margin);
2691
var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
2692
if (scrollPos.scrollTop != null) {
2693
setScrollTop(cm, scrollPos.scrollTop);
2694
if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
2695
}
2696
if (scrollPos.scrollLeft != null) {
2697
setScrollLeft(cm, scrollPos.scrollLeft);
2698
if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
2699
}
2700
if (!changed) return coords;
2701
}
2702
}
2703
2704
function scrollIntoView(cm, x1, y1, x2, y2) {
2705
var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
2706
if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
2707
if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
2708
}
2709
2710
function calculateScrollPos(cm, x1, y1, x2, y2) {
2711
var display = cm.display, snapMargin = textHeight(cm.display);
2712
if (y1 < 0) y1 = 0;
2713
var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {};
2714
var docBottom = cm.doc.height + paddingVert(display);
2715
var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
2716
if (y1 < screentop) {
2717
result.scrollTop = atTop ? 0 : y1;
2718
} else if (y2 > screentop + screen) {
2719
var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
2720
if (newTop != screentop) result.scrollTop = newTop;
2721
}
2722
2723
var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft;
2724
x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
2725
var gutterw = display.gutters.offsetWidth;
2726
var atLeft = x1 < gutterw + 10;
2727
if (x1 < screenleft + gutterw || atLeft) {
2728
if (atLeft) x1 = 0;
2729
result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
2730
} else if (x2 > screenw + screenleft - 3) {
2731
result.scrollLeft = x2 + 10 - screenw;
2732
}
2733
return result;
2734
}
2735
2736
function updateScrollPos(cm, left, top) {
2737
cm.curOp.updateScrollPos = {scrollLeft: left == null ? cm.doc.scrollLeft : left,
2738
scrollTop: top == null ? cm.doc.scrollTop : top};
2739
}
2740
2741
function addToScrollPos(cm, left, top) {
2742
var pos = cm.curOp.updateScrollPos || (cm.curOp.updateScrollPos = {scrollLeft: cm.doc.scrollLeft, scrollTop: cm.doc.scrollTop});
2743
var scroll = cm.display.scroller;
2744
pos.scrollTop = Math.max(0, Math.min(scroll.scrollHeight - scroll.clientHeight, pos.scrollTop + top));
2745
pos.scrollLeft = Math.max(0, Math.min(scroll.scrollWidth - scroll.clientWidth, pos.scrollLeft + left));
2746
}
2747
2748
// API UTILITIES
2749
2750
function indentLine(cm, n, how, aggressive) {
2751
var doc = cm.doc;
2752
if (how == null) how = "add";
2753
if (how == "smart") {
2754
if (!cm.doc.mode.indent) how = "prev";
2755
else var state = getStateBefore(cm, n);
2756
}
2757
2758
var tabSize = cm.options.tabSize;
2759
var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
2760
var curSpaceString = line.text.match(/^\s*/)[0], indentation;
2761
if (!aggressive && !/\S/.test(line.text)) {
2762
indentation = 0;
2763
how = "not";
2764
} else if (how == "smart") {
2765
indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
2766
if (indentation == Pass) {
2767
if (!aggressive) return;
2768
how = "prev";
2769
}
2770
}
2771
if (how == "prev") {
2772
if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
2773
else indentation = 0;
2774
} else if (how == "add") {
2775
indentation = curSpace + cm.options.indentUnit;
2776
} else if (how == "subtract") {
2777
indentation = curSpace - cm.options.indentUnit;
2778
} else if (typeof how == "number") {
2779
indentation = curSpace + how;
2780
}
2781
indentation = Math.max(0, indentation);
2782
2783
var indentString = "", pos = 0;
2784
if (cm.options.indentWithTabs)
2785
for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
2786
if (pos < indentation) indentString += spaceStr(indentation - pos);
2787
2788
if (indentString != curSpaceString)
2789
replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
2790
else if (doc.sel.head.line == n && doc.sel.head.ch < curSpaceString.length)
2791
setSelection(doc, Pos(n, curSpaceString.length), Pos(n, curSpaceString.length), 1);
2792
line.stateAfter = null;
2793
}
2794
2795
function changeLine(cm, handle, op) {
2796
var no = handle, line = handle, doc = cm.doc;
2797
if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
2798
else no = lineNo(handle);
2799
if (no == null) return null;
2800
if (op(line, no)) regChange(cm, no, no + 1);
2801
else return null;
2802
return line;
2803
}
2804
2805
function findPosH(doc, pos, dir, unit, visually) {
2806
var line = pos.line, ch = pos.ch, origDir = dir;
2807
var lineObj = getLine(doc, line);
2808
var possible = true;
2809
function findNextLine() {
2810
var l = line + dir;
2811
if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
2812
line = l;
2813
return lineObj = getLine(doc, l);
2814
}
2815
function moveOnce(boundToLine) {
2816
var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
2817
if (next == null) {
2818
if (!boundToLine && findNextLine()) {
2819
if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
2820
else ch = dir < 0 ? lineObj.text.length : 0;
2821
} else return (possible = false);
2822
} else ch = next;
2823
return true;
2824
}
2825
2826
if (unit == "char") moveOnce();
2827
else if (unit == "column") moveOnce(true);
2828
else if (unit == "word" || unit == "group") {
2829
var sawType = null, group = unit == "group";
2830
for (var first = true;; first = false) {
2831
if (dir < 0 && !moveOnce(!first)) break;
2832
var cur = lineObj.text.charAt(ch) || "\n";
2833
var type = isWordChar(cur) ? "w"
2834
: !group ? null
2835
: /\s/.test(cur) ? null
2836
: "p";
2837
if (sawType && sawType != type) {
2838
if (dir < 0) {dir = 1; moveOnce();}
2839
break;
2840
}
2841
if (type) sawType = type;
2842
if (dir > 0 && !moveOnce(!first)) break;
2843
}
2844
}
2845
var result = skipAtomic(doc, Pos(line, ch), origDir, true);
2846
if (!possible) result.hitSide = true;
2847
return result;
2848
}
2849
2850
function findPosV(cm, pos, dir, unit) {
2851
var doc = cm.doc, x = pos.left, y;
2852
if (unit == "page") {
2853
var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
2854
y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
2855
} else if (unit == "line") {
2856
y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
2857
}
2858
for (;;) {
2859
var target = coordsChar(cm, x, y);
2860
if (!target.outside) break;
2861
if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
2862
y += dir * 5;
2863
}
2864
return target;
2865
}
2866
2867
function findWordAt(line, pos) {
2868
var start = pos.ch, end = pos.ch;
2869
if (line) {
2870
if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
2871
var startChar = line.charAt(start);
2872
var check = isWordChar(startChar) ? isWordChar
2873
: /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
2874
: function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
2875
while (start > 0 && check(line.charAt(start - 1))) --start;
2876
while (end < line.length && check(line.charAt(end))) ++end;
2877
}
2878
return {from: Pos(pos.line, start), to: Pos(pos.line, end)};
2879
}
2880
2881
function selectLine(cm, line) {
2882
extendSelection(cm.doc, Pos(line, 0), clipPos(cm.doc, Pos(line + 1, 0)));
2883
}
2884
2885
// PROTOTYPE
2886
2887
// The publicly visible API. Note that operation(null, f) means
2888
// 'wrap f in an operation, performed on its `this` parameter'
2889
2890
CodeMirror.prototype = {
2891
constructor: CodeMirror,
2892
focus: function(){window.focus(); focusInput(this); fastPoll(this);},
2893
2894
setOption: function(option, value) {
2895
var options = this.options, old = options[option];
2896
if (options[option] == value && option != "mode") return;
2897
options[option] = value;
2898
if (optionHandlers.hasOwnProperty(option))
2899
operation(this, optionHandlers[option])(this, value, old);
2900
},
2901
2902
getOption: function(option) {return this.options[option];},
2903
getDoc: function() {return this.doc;},
2904
2905
addKeyMap: function(map, bottom) {
2906
this.state.keyMaps[bottom ? "push" : "unshift"](map);
2907
},
2908
removeKeyMap: function(map) {
2909
var maps = this.state.keyMaps;
2910
for (var i = 0; i < maps.length; ++i)
2911
if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map)) {
2912
maps.splice(i, 1);
2913
return true;
2914
}
2915
},
2916
2917
addOverlay: operation(null, function(spec, options) {
2918
var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
2919
if (mode.startState) throw new Error("Overlays may not be stateful.");
2920
this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
2921
this.state.modeGen++;
2922
regChange(this);
2923
}),
2924
removeOverlay: operation(null, function(spec) {
2925
var overlays = this.state.overlays;
2926
for (var i = 0; i < overlays.length; ++i) {
2927
var cur = overlays[i].modeSpec;
2928
if (cur == spec || typeof spec == "string" && cur.name == spec) {
2929
overlays.splice(i, 1);
2930
this.state.modeGen++;
2931
regChange(this);
2932
return;
2933
}
2934
}
2935
}),
2936
2937
indentLine: operation(null, function(n, dir, aggressive) {
2938
if (typeof dir != "string" && typeof dir != "number") {
2939
if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
2940
else dir = dir ? "add" : "subtract";
2941
}
2942
if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
2943
}),
2944
indentSelection: operation(null, function(how) {
2945
var sel = this.doc.sel;
2946
if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how, true);
2947
var e = sel.to.line - (sel.to.ch ? 0 : 1);
2948
for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how);
2949
}),
2950
2951
// Fetch the parser token for a given character. Useful for hacks
2952
// that want to inspect the mode state (say, for completion).
2953
getTokenAt: function(pos, precise) {
2954
var doc = this.doc;
2955
pos = clipPos(doc, pos);
2956
var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode;
2957
var line = getLine(doc, pos.line);
2958
var stream = new StringStream(line.text, this.options.tabSize);
2959
while (stream.pos < pos.ch && !stream.eol()) {
2960
stream.start = stream.pos;
2961
var style = mode.token(stream, state);
2962
}
2963
return {start: stream.start,
2964
end: stream.pos,
2965
string: stream.current(),
2966
className: style || null, // Deprecated, use 'type' instead
2967
type: style || null,
2968
state: state};
2969
},
2970
2971
getTokenTypeAt: function(pos) {
2972
pos = clipPos(this.doc, pos);
2973
var styles = getLineStyles(this, getLine(this.doc, pos.line));
2974
var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
2975
if (ch == 0) return styles[2];
2976
for (;;) {
2977
var mid = (before + after) >> 1;
2978
if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
2979
else if (styles[mid * 2 + 1] < ch) before = mid + 1;
2980
else return styles[mid * 2 + 2];
2981
}
2982
},
2983
2984
getModeAt: function(pos) {
2985
var mode = this.doc.mode;
2986
if (!mode.innerMode) return mode;
2987
return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
2988
},
2989
2990
getHelper: function(pos, type) {
2991
return this.getHelpers(pos, type)[0];
2992
},
2993
2994
getHelpers: function(pos, type) {
2995
var found = [];
2996
if (!helpers.hasOwnProperty(type)) return helpers;
2997
var help = helpers[type], mode = this.getModeAt(pos);
2998
if (typeof mode[type] == "string") {
2999
if (help[mode[type]]) found.push(help[mode[type]]);
3000
} else if (mode[type]) {
3001
for (var i = 0; i < mode[type].length; i++) {
3002
var val = help[mode[type][i]];
3003
if (val) found.push(val);
3004
}
3005
} else if (mode.helperType && help[mode.helperType]) {
3006
found.push(help[mode.helperType]);
3007
} else if (help[mode.name]) {
3008
found.push(help[mode.name]);
3009
}
3010
for (var i = 0; i < help._global.length; i++) {
3011
var cur = help._global[i];
3012
if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
3013
found.push(cur.val);
3014
}
3015
return found;
3016
},
3017
3018
getStateAfter: function(line, precise) {
3019
var doc = this.doc;
3020
line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
3021
return getStateBefore(this, line + 1, precise);
3022
},
3023
3024
cursorCoords: function(start, mode) {
3025
var pos, sel = this.doc.sel;
3026
if (start == null) pos = sel.head;
3027
else if (typeof start == "object") pos = clipPos(this.doc, start);
3028
else pos = start ? sel.from : sel.to;
3029
return cursorCoords(this, pos, mode || "page");
3030
},
3031
3032
charCoords: function(pos, mode) {
3033
return charCoords(this, clipPos(this.doc, pos), mode || "page");
3034
},
3035
3036
coordsChar: function(coords, mode) {
3037
coords = fromCoordSystem(this, coords, mode || "page");
3038
return coordsChar(this, coords.left, coords.top);
3039
},
3040
3041
lineAtHeight: function(height, mode) {
3042
height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
3043
return lineAtHeight(this.doc, height + this.display.viewOffset);
3044
},
3045
heightAtLine: function(line, mode) {
3046
var end = false, last = this.doc.first + this.doc.size - 1;
3047
if (line < this.doc.first) line = this.doc.first;
3048
else if (line > last) { line = last; end = true; }
3049
var lineObj = getLine(this.doc, line);
3050
return intoCoordSystem(this, getLine(this.doc, line), {top: 0, left: 0}, mode || "page").top +
3051
(end ? lineObj.height : 0);
3052
},
3053
3054
defaultTextHeight: function() { return textHeight(this.display); },
3055
defaultCharWidth: function() { return charWidth(this.display); },
3056
3057
setGutterMarker: operation(null, function(line, gutterID, value) {
3058
return changeLine(this, line, function(line) {
3059
var markers = line.gutterMarkers || (line.gutterMarkers = {});
3060
markers[gutterID] = value;
3061
if (!value && isEmpty(markers)) line.gutterMarkers = null;
3062
return true;
3063
});
3064
}),
3065
3066
clearGutter: operation(null, function(gutterID) {
3067
var cm = this, doc = cm.doc, i = doc.first;
3068
doc.iter(function(line) {
3069
if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
3070
line.gutterMarkers[gutterID] = null;
3071
regChange(cm, i, i + 1);
3072
if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
3073
}
3074
++i;
3075
});
3076
}),
3077
3078
addLineClass: operation(null, function(handle, where, cls) {
3079
return changeLine(this, handle, function(line) {
3080
var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
3081
if (!line[prop]) line[prop] = cls;
3082
else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false;
3083
else line[prop] += " " + cls;
3084
return true;
3085
});
3086
}),
3087
3088
removeLineClass: operation(null, function(handle, where, cls) {
3089
return changeLine(this, handle, function(line) {
3090
var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
3091
var cur = line[prop];
3092
if (!cur) return false;
3093
else if (cls == null) line[prop] = null;
3094
else {
3095
var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)"));
3096
if (!found) return false;
3097
var end = found.index + found[0].length;
3098
line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
3099
}
3100
return true;
3101
});
3102
}),
3103
3104
addLineWidget: operation(null, function(handle, node, options) {
3105
return addLineWidget(this, handle, node, options);
3106
}),
3107
3108
removeLineWidget: function(widget) { widget.clear(); },
3109
3110
lineInfo: function(line) {
3111
if (typeof line == "number") {
3112
if (!isLine(this.doc, line)) return null;
3113
var n = line;
3114
line = getLine(this.doc, line);
3115
if (!line) return null;
3116
} else {
3117
var n = lineNo(line);
3118
if (n == null) return null;
3119
}
3120
return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
3121
textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
3122
widgets: line.widgets};
3123
},
3124
3125
getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};},
3126
3127
addWidget: function(pos, node, scroll, vert, horiz) {
3128
var display = this.display;
3129
pos = cursorCoords(this, clipPos(this.doc, pos));
3130
var top = pos.bottom, left = pos.left;
3131
node.style.position = "absolute";
3132
display.sizer.appendChild(node);
3133
if (vert == "over") {
3134
top = pos.top;
3135
} else if (vert == "above" || vert == "near") {
3136
var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
3137
hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
3138
// Default to positioning above (if specified and possible); otherwise default to positioning below
3139
if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
3140
top = pos.top - node.offsetHeight;
3141
else if (pos.bottom + node.offsetHeight <= vspace)
3142
top = pos.bottom;
3143
if (left + node.offsetWidth > hspace)
3144
left = hspace - node.offsetWidth;
3145
}
3146
node.style.top = top + "px";
3147
node.style.left = node.style.right = "";
3148
if (horiz == "right") {
3149
left = display.sizer.clientWidth - node.offsetWidth;
3150
node.style.right = "0px";
3151
} else {
3152
if (horiz == "left") left = 0;
3153
else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
3154
node.style.left = left + "px";
3155
}
3156
if (scroll)
3157
scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
3158
},
3159
3160
triggerOnKeyDown: operation(null, onKeyDown),
3161
3162
execCommand: function(cmd) {
3163
if (commands.hasOwnProperty(cmd))
3164
return commands[cmd](this);
3165
},
3166
3167
findPosH: function(from, amount, unit, visually) {
3168
var dir = 1;
3169
if (amount < 0) { dir = -1; amount = -amount; }
3170
for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
3171
cur = findPosH(this.doc, cur, dir, unit, visually);
3172
if (cur.hitSide) break;
3173
}
3174
return cur;
3175
},
3176
3177
moveH: operation(null, function(dir, unit) {
3178
var sel = this.doc.sel, pos;
3179
if (sel.shift || sel.extend || posEq(sel.from, sel.to))
3180
pos = findPosH(this.doc, sel.head, dir, unit, this.options.rtlMoveVisually);
3181
else
3182
pos = dir < 0 ? sel.from : sel.to;
3183
extendSelection(this.doc, pos, pos, dir);
3184
}),
3185
3186
deleteH: operation(null, function(dir, unit) {
3187
var sel = this.doc.sel;
3188
if (!posEq(sel.from, sel.to)) replaceRange(this.doc, "", sel.from, sel.to, "+delete");
3189
else replaceRange(this.doc, "", sel.from, findPosH(this.doc, sel.head, dir, unit, false), "+delete");
3190
this.curOp.userSelChange = true;
3191
}),
3192
3193
findPosV: function(from, amount, unit, goalColumn) {
3194
var dir = 1, x = goalColumn;
3195
if (amount < 0) { dir = -1; amount = -amount; }
3196
for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
3197
var coords = cursorCoords(this, cur, "div");
3198
if (x == null) x = coords.left;
3199
else coords.left = x;
3200
cur = findPosV(this, coords, dir, unit);
3201
if (cur.hitSide) break;
3202
}
3203
return cur;
3204
},
3205
3206
moveV: operation(null, function(dir, unit) {
3207
var sel = this.doc.sel, target, goal;
3208
if (sel.shift || sel.extend || posEq(sel.from, sel.to)) {
3209
var pos = cursorCoords(this, sel.head, "div");
3210
if (sel.goalColumn != null) pos.left = sel.goalColumn;
3211
target = findPosV(this, pos, dir, unit);
3212
if (unit == "page") addToScrollPos(this, 0, charCoords(this, target, "div").top - pos.top);
3213
goal = pos.left;
3214
} else {
3215
target = dir < 0 ? sel.from : sel.to;
3216
}
3217
extendSelection(this.doc, target, target, dir);
3218
if (goal != null) sel.goalColumn = goal;
3219
}),
3220
3221
toggleOverwrite: function(value) {
3222
if (value != null && value == this.state.overwrite) return;
3223
if (this.state.overwrite = !this.state.overwrite)
3224
this.display.cursor.className += " CodeMirror-overwrite";
3225
else
3226
this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", "");
3227
},
3228
hasFocus: function() { return this.state.focused; },
3229
3230
scrollTo: operation(null, function(x, y) {
3231
updateScrollPos(this, x, y);
3232
}),
3233
getScrollInfo: function() {
3234
var scroller = this.display.scroller, co = scrollerCutOff;
3235
return {left: scroller.scrollLeft, top: scroller.scrollTop,
3236
height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,
3237
clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};
3238
},
3239
3240
scrollIntoView: operation(null, function(range, margin) {
3241
if (range == null) range = {from: this.doc.sel.head, to: null};
3242
else if (typeof range == "number") range = {from: Pos(range, 0), to: null};
3243
else if (range.from == null) range = {from: range, to: null};
3244
if (!range.to) range.to = range.from;
3245
if (!margin) margin = 0;
3246
3247
var coords = range;
3248
if (range.from.line != null) {
3249
this.curOp.scrollToPos = {from: range.from, to: range.to, margin: margin};
3250
coords = {from: cursorCoords(this, range.from),
3251
to: cursorCoords(this, range.to)};
3252
}
3253
var sPos = calculateScrollPos(this, Math.min(coords.from.left, coords.to.left),
3254
Math.min(coords.from.top, coords.to.top) - margin,
3255
Math.max(coords.from.right, coords.to.right),
3256
Math.max(coords.from.bottom, coords.to.bottom) + margin);
3257
updateScrollPos(this, sPos.scrollLeft, sPos.scrollTop);
3258
}),
3259
3260
setSize: operation(null, function(width, height) {
3261
function interpret(val) {
3262
return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
3263
}
3264
if (width != null) this.display.wrapper.style.width = interpret(width);
3265
if (height != null) this.display.wrapper.style.height = interpret(height);
3266
if (this.options.lineWrapping)
3267
this.display.measureLineCache.length = this.display.measureLineCachePos = 0;
3268
this.curOp.forceUpdate = true;
3269
}),
3270
3271
operation: function(f){return runInOp(this, f);},
3272
3273
refresh: operation(null, function() {
3274
var badHeight = this.display.cachedTextHeight == null;
3275
clearCaches(this);
3276
updateScrollPos(this, this.doc.scrollLeft, this.doc.scrollTop);
3277
regChange(this);
3278
if (badHeight) estimateLineHeights(this);
3279
}),
3280
3281
swapDoc: operation(null, function(doc) {
3282
var old = this.doc;
3283
old.cm = null;
3284
attachDoc(this, doc);
3285
clearCaches(this);
3286
resetInput(this, true);
3287
updateScrollPos(this, doc.scrollLeft, doc.scrollTop);
3288
signalLater(this, "swapDoc", this, old);
3289
return old;
3290
}),
3291
3292
getInputField: function(){return this.display.input;},
3293
getWrapperElement: function(){return this.display.wrapper;},
3294
getScrollerElement: function(){return this.display.scroller;},
3295
getGutterElement: function(){return this.display.gutters;}
3296
};
3297
eventMixin(CodeMirror);
3298
3299
// OPTION DEFAULTS
3300
3301
var optionHandlers = CodeMirror.optionHandlers = {};
3302
3303
// The default configuration options.
3304
var defaults = CodeMirror.defaults = {};
3305
3306
function option(name, deflt, handle, notOnInit) {
3307
CodeMirror.defaults[name] = deflt;
3308
if (handle) optionHandlers[name] =
3309
notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
3310
}
3311
3312
var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
3313
3314
// These two are, on init, called from the constructor because they
3315
// have to be initialized before the editor can start at all.
3316
option("value", "", function(cm, val) {
3317
cm.setValue(val);
3318
}, true);
3319
option("mode", null, function(cm, val) {
3320
cm.doc.modeOption = val;
3321
loadMode(cm);
3322
}, true);
3323
3324
option("indentUnit", 2, loadMode, true);
3325
option("indentWithTabs", false);
3326
option("smartIndent", true);
3327
option("tabSize", 4, function(cm) {
3328
resetModeState(cm);
3329
clearCaches(cm);
3330
regChange(cm);
3331
}, true);
3332
option("specialChars", /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\ufeff]/g, function(cm, val) {
3333
cm.options.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
3334
cm.refresh();
3335
}, true);
3336
option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
3337
option("electricChars", true);
3338
option("rtlMoveVisually", !windows);
3339
option("wholeLineUpdateBefore", true);
3340
3341
option("theme", "default", function(cm) {
3342
themeChanged(cm);
3343
guttersChanged(cm);
3344
}, true);
3345
option("keyMap", "default", keyMapChanged);
3346
option("extraKeys", null);
3347
3348
option("onKeyEvent", null);
3349
option("onDragEvent", null);
3350
3351
option("lineWrapping", false, wrappingChanged, true);
3352
option("gutters", [], function(cm) {
3353
setGuttersForLineNumbers(cm.options);
3354
guttersChanged(cm);
3355
}, true);
3356
option("fixedGutter", true, function(cm, val) {
3357
cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
3358
cm.refresh();
3359
}, true);
3360
option("coverGutterNextToScrollbar", false, updateScrollbars, true);
3361
option("lineNumbers", false, function(cm) {
3362
setGuttersForLineNumbers(cm.options);
3363
guttersChanged(cm);
3364
}, true);
3365
option("firstLineNumber", 1, guttersChanged, true);
3366
option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
3367
option("showCursorWhenSelecting", false, updateSelection, true);
3368
3369
option("resetSelectionOnContextMenu", true);
3370
3371
option("readOnly", false, function(cm, val) {
3372
if (val == "nocursor") {
3373
onBlur(cm);
3374
cm.display.input.blur();
3375
cm.display.disabled = true;
3376
} else {
3377
cm.display.disabled = false;
3378
if (!val) resetInput(cm, true);
3379
}
3380
});
3381
option("disableInput", false, function(cm, val) {if (!val) resetInput(cm, true);}, true);
3382
option("dragDrop", true);
3383
3384
option("cursorBlinkRate", 530);
3385
option("cursorScrollMargin", 0);
3386
option("cursorHeight", 1);
3387
option("workTime", 100);
3388
option("workDelay", 100);
3389
option("flattenSpans", true, resetModeState, true);
3390
option("addModeClass", false, resetModeState, true);
3391
option("pollInterval", 100);
3392
option("undoDepth", 40, function(cm, val){cm.doc.history.undoDepth = val;});
3393
option("historyEventDelay", 500);
3394
option("viewportMargin", 10, function(cm){cm.refresh();}, true);
3395
option("maxHighlightLength", 10000, resetModeState, true);
3396
option("crudeMeasuringFrom", 10000);
3397
option("moveInputWithCursor", true, function(cm, val) {
3398
if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0;
3399
});
3400
3401
option("tabindex", null, function(cm, val) {
3402
cm.display.input.tabIndex = val || "";
3403
});
3404
option("autofocus", null);
3405
3406
// MODE DEFINITION AND QUERYING
3407
3408
// Known modes, by name and by MIME
3409
var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
3410
3411
CodeMirror.defineMode = function(name, mode) {
3412
if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
3413
if (arguments.length > 2) {
3414
mode.dependencies = [];
3415
for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
3416
}
3417
modes[name] = mode;
3418
};
3419
3420
CodeMirror.defineMIME = function(mime, spec) {
3421
mimeModes[mime] = spec;
3422
};
3423
3424
CodeMirror.resolveMode = function(spec) {
3425
if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
3426
spec = mimeModes[spec];
3427
} else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
3428
var found = mimeModes[spec.name];
3429
spec = createObj(found, spec);
3430
spec.name = found.name;
3431
} else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
3432
return CodeMirror.resolveMode("application/xml");
3433
}
3434
if (typeof spec == "string") return {name: spec};
3435
else return spec || {name: "null"};
3436
};
3437
3438
CodeMirror.getMode = function(options, spec) {
3439
var spec = CodeMirror.resolveMode(spec);
3440
var mfactory = modes[spec.name];
3441
if (!mfactory) return CodeMirror.getMode(options, "text/plain");
3442
var modeObj = mfactory(options, spec);
3443
if (modeExtensions.hasOwnProperty(spec.name)) {
3444
var exts = modeExtensions[spec.name];
3445
for (var prop in exts) {
3446
if (!exts.hasOwnProperty(prop)) continue;
3447
if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
3448
modeObj[prop] = exts[prop];
3449
}
3450
}
3451
modeObj.name = spec.name;
3452
if (spec.helperType) modeObj.helperType = spec.helperType;
3453
if (spec.modeProps) for (var prop in spec.modeProps)
3454
modeObj[prop] = spec.modeProps[prop];
3455
3456
return modeObj;
3457
};
3458
3459
CodeMirror.defineMode("null", function() {
3460
return {token: function(stream) {stream.skipToEnd();}};
3461
});
3462
CodeMirror.defineMIME("text/plain", "null");
3463
3464
var modeExtensions = CodeMirror.modeExtensions = {};
3465
CodeMirror.extendMode = function(mode, properties) {
3466
var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
3467
copyObj(properties, exts);
3468
};
3469
3470
// EXTENSIONS
3471
3472
CodeMirror.defineExtension = function(name, func) {
3473
CodeMirror.prototype[name] = func;
3474
};
3475
CodeMirror.defineDocExtension = function(name, func) {
3476
Doc.prototype[name] = func;
3477
};
3478
CodeMirror.defineOption = option;
3479
3480
var initHooks = [];
3481
CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
3482
3483
var helpers = CodeMirror.helpers = {};
3484
CodeMirror.registerHelper = function(type, name, value) {
3485
if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
3486
helpers[type][name] = value;
3487
};
3488
CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
3489
CodeMirror.registerHelper(type, name, value);
3490
helpers[type]._global.push({pred: predicate, val: value});
3491
};
3492
3493
// UTILITIES
3494
3495
CodeMirror.isWordChar = isWordChar;
3496
3497
// MODE STATE HANDLING
3498
3499
// Utility functions for working with state. Exported because modes
3500
// sometimes need to do this.
3501
function copyState(mode, state) {
3502
if (state === true) return state;
3503
if (mode.copyState) return mode.copyState(state);
3504
var nstate = {};
3505
for (var n in state) {
3506
var val = state[n];
3507
if (val instanceof Array) val = val.concat([]);
3508
nstate[n] = val;
3509
}
3510
return nstate;
3511
}
3512
CodeMirror.copyState = copyState;
3513
3514
function startState(mode, a1, a2) {
3515
return mode.startState ? mode.startState(a1, a2) : true;
3516
}
3517
CodeMirror.startState = startState;
3518
3519
CodeMirror.innerMode = function(mode, state) {
3520
while (mode.innerMode) {
3521
var info = mode.innerMode(state);
3522
if (!info || info.mode == mode) break;
3523
state = info.state;
3524
mode = info.mode;
3525
}
3526
return info || {mode: mode, state: state};
3527
};
3528
3529
// STANDARD COMMANDS
3530
3531
var commands = CodeMirror.commands = {
3532
selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()));},
3533
killLine: function(cm) {
3534
var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
3535
if (!sel && cm.getLine(from.line).length == from.ch)
3536
cm.replaceRange("", from, Pos(from.line + 1, 0), "+delete");
3537
else cm.replaceRange("", from, sel ? to : Pos(from.line), "+delete");
3538
},
3539
deleteLine: function(cm) {
3540
var l = cm.getCursor().line;
3541
cm.replaceRange("", Pos(l, 0), Pos(l), "+delete");
3542
},
3543
delLineLeft: function(cm) {
3544
var cur = cm.getCursor();
3545
cm.replaceRange("", Pos(cur.line, 0), cur, "+delete");
3546
},
3547
undo: function(cm) {cm.undo();},
3548
redo: function(cm) {cm.redo();},
3549
goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
3550
goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
3551
goLineStart: function(cm) {
3552
cm.extendSelection(lineStart(cm, cm.getCursor().line));
3553
},
3554
goLineStartSmart: function(cm) {
3555
var cur = cm.getCursor(), start = lineStart(cm, cur.line);
3556
var line = cm.getLineHandle(start.line);
3557
var order = getOrder(line);
3558
if (!order || order[0].level == 0) {
3559
var firstNonWS = Math.max(0, line.text.search(/\S/));
3560
var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch;
3561
cm.extendSelection(Pos(start.line, inWS ? 0 : firstNonWS));
3562
} else cm.extendSelection(start);
3563
},
3564
goLineEnd: function(cm) {
3565
cm.extendSelection(lineEnd(cm, cm.getCursor().line));
3566
},
3567
goLineRight: function(cm) {
3568
var top = cm.charCoords(cm.getCursor(), "div").top + 5;
3569
cm.extendSelection(cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"));
3570
},
3571
goLineLeft: function(cm) {
3572
var top = cm.charCoords(cm.getCursor(), "div").top + 5;
3573
cm.extendSelection(cm.coordsChar({left: 0, top: top}, "div"));
3574
},
3575
goLineUp: function(cm) {cm.moveV(-1, "line");},
3576
goLineDown: function(cm) {cm.moveV(1, "line");},
3577
goPageUp: function(cm) {cm.moveV(-1, "page");},
3578
goPageDown: function(cm) {cm.moveV(1, "page");},
3579
goCharLeft: function(cm) {cm.moveH(-1, "char");},
3580
goCharRight: function(cm) {cm.moveH(1, "char");},
3581
goColumnLeft: function(cm) {cm.moveH(-1, "column");},
3582
goColumnRight: function(cm) {cm.moveH(1, "column");},
3583
goWordLeft: function(cm) {cm.moveH(-1, "word");},
3584
goGroupRight: function(cm) {cm.moveH(1, "group");},
3585
goGroupLeft: function(cm) {cm.moveH(-1, "group");},
3586
goWordRight: function(cm) {cm.moveH(1, "word");},
3587
delCharBefore: function(cm) {cm.deleteH(-1, "char");},
3588
delCharAfter: function(cm) {cm.deleteH(1, "char");},
3589
delWordBefore: function(cm) {cm.deleteH(-1, "word");},
3590
delWordAfter: function(cm) {cm.deleteH(1, "word");},
3591
delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
3592
delGroupAfter: function(cm) {cm.deleteH(1, "group");},
3593
indentAuto: function(cm) {cm.indentSelection("smart");},
3594
indentMore: function(cm) {cm.indentSelection("add");},
3595
indentLess: function(cm) {cm.indentSelection("subtract");},
3596
insertTab: function(cm) {
3597
cm.replaceSelection("\t", "end", "+input");
3598
},
3599
defaultTab: function(cm) {
3600
if (cm.somethingSelected()) cm.indentSelection("add");
3601
else cm.replaceSelection("\t", "end", "+input");
3602
},
3603
transposeChars: function(cm) {
3604
var cur = cm.getCursor(), line = cm.getLine(cur.line);
3605
if (cur.ch > 0 && cur.ch < line.length - 1)
3606
cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
3607
Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1));
3608
},
3609
newlineAndIndent: function(cm) {
3610
operation(cm, function() {
3611
cm.replaceSelection("\n", "end", "+input");
3612
cm.indentLine(cm.getCursor().line, null, true);
3613
})();
3614
},
3615
toggleOverwrite: function(cm) {cm.toggleOverwrite();}
3616
};
3617
3618
// STANDARD KEYMAPS
3619
3620
var keyMap = CodeMirror.keyMap = {};
3621
keyMap.basic = {
3622
"Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
3623
"End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
3624
"Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
3625
"Tab": "defaultTab", "Shift-Tab": "indentAuto",
3626
"Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
3627
};
3628
// Note that the save and find-related commands aren't defined by
3629
// default. Unknown commands are simply ignored.
3630
keyMap.pcDefault = {
3631
"Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
3632
"Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
3633
"Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
3634
"Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
3635
"Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
3636
"Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
3637
fallthrough: "basic"
3638
};
3639
keyMap.macDefault = {
3640
"Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
3641
"Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
3642
"Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delGroupBefore",
3643
"Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
3644
"Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
3645
"Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft",
3646
fallthrough: ["basic", "emacsy"]
3647
};
3648
keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
3649
keyMap.emacsy = {
3650
"Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
3651
"Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
3652
"Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
3653
"Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
3654
};
3655
3656
// KEYMAP DISPATCH
3657
3658
function getKeyMap(val) {
3659
if (typeof val == "string") return keyMap[val];
3660
else return val;
3661
}
3662
3663
function lookupKey(name, maps, handle) {
3664
function lookup(map) {
3665
map = getKeyMap(map);
3666
var found = map[name];
3667
if (found === false) return "stop";
3668
if (found != null && handle(found)) return true;
3669
if (map.nofallthrough) return "stop";
3670
3671
var fallthrough = map.fallthrough;
3672
if (fallthrough == null) return false;
3673
if (Object.prototype.toString.call(fallthrough) != "[object Array]")
3674
return lookup(fallthrough);
3675
for (var i = 0, e = fallthrough.length; i < e; ++i) {
3676
var done = lookup(fallthrough[i]);
3677
if (done) return done;
3678
}
3679
return false;
3680
}
3681
3682
for (var i = 0; i < maps.length; ++i) {
3683
var done = lookup(maps[i]);
3684
if (done) return done != "stop";
3685
}
3686
}
3687
function isModifierKey(event) {
3688
var name = keyNames[event.keyCode];
3689
return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
3690
}
3691
function keyName(event, noShift) {
3692
if (opera && event.keyCode == 34 && event["char"]) return false;
3693
var name = keyNames[event.keyCode];
3694
if (name == null || event.altGraphKey) return false;
3695
if (event.altKey) name = "Alt-" + name;
3696
if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name;
3697
if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name;
3698
if (!noShift && event.shiftKey) name = "Shift-" + name;
3699
return name;
3700
}
3701
CodeMirror.lookupKey = lookupKey;
3702
CodeMirror.isModifierKey = isModifierKey;
3703
CodeMirror.keyName = keyName;
3704
3705
// FROMTEXTAREA
3706
3707
CodeMirror.fromTextArea = function(textarea, options) {
3708
if (!options) options = {};
3709
options.value = textarea.value;
3710
if (!options.tabindex && textarea.tabindex)
3711
options.tabindex = textarea.tabindex;
3712
if (!options.placeholder && textarea.placeholder)
3713
options.placeholder = textarea.placeholder;
3714
// Set autofocus to true if this textarea is focused, or if it has
3715
// autofocus and no other element is focused.
3716
if (options.autofocus == null) {
3717
var hasFocus = document.body;
3718
// doc.activeElement occasionally throws on IE
3719
try { hasFocus = document.activeElement; } catch(e) {}
3720
options.autofocus = hasFocus == textarea ||
3721
textarea.getAttribute("autofocus") != null && hasFocus == document.body;
3722
}
3723
3724
function save() {textarea.value = cm.getValue();}
3725
if (textarea.form) {
3726
on(textarea.form, "submit", save);
3727
// Deplorable hack to make the submit method do the right thing.
3728
if (!options.leaveSubmitMethodAlone) {
3729
var form = textarea.form, realSubmit = form.submit;
3730
try {
3731
var wrappedSubmit = form.submit = function() {
3732
save();
3733
form.submit = realSubmit;
3734
form.submit();
3735
form.submit = wrappedSubmit;
3736
};
3737
} catch(e) {}
3738
}
3739
}
3740
3741
textarea.style.display = "none";
3742
var cm = CodeMirror(function(node) {
3743
textarea.parentNode.insertBefore(node, textarea.nextSibling);
3744
}, options);
3745
cm.save = save;
3746
cm.getTextArea = function() { return textarea; };
3747
cm.toTextArea = function() {
3748
save();
3749
textarea.parentNode.removeChild(cm.getWrapperElement());
3750
textarea.style.display = "";
3751
if (textarea.form) {
3752
off(textarea.form, "submit", save);
3753
if (typeof textarea.form.submit == "function")
3754
textarea.form.submit = realSubmit;
3755
}
3756
};
3757
return cm;
3758
};
3759
3760
// STRING STREAM
3761
3762
// Fed to the mode parsers, provides helper functions to make
3763
// parsers more succinct.
3764
3765
// The character stream used by a mode's parser.
3766
function StringStream(string, tabSize) {
3767
this.pos = this.start = 0;
3768
this.string = string;
3769
this.tabSize = tabSize || 8;
3770
this.lastColumnPos = this.lastColumnValue = 0;
3771
this.lineStart = 0;
3772
}
3773
3774
StringStream.prototype = {
3775
eol: function() {return this.pos >= this.string.length;},
3776
sol: function() {return this.pos == this.lineStart;},
3777
peek: function() {return this.string.charAt(this.pos) || undefined;},
3778
next: function() {
3779
if (this.pos < this.string.length)
3780
return this.string.charAt(this.pos++);
3781
},
3782
eat: function(match) {
3783
var ch = this.string.charAt(this.pos);
3784
if (typeof match == "string") var ok = ch == match;
3785
else var ok = ch && (match.test ? match.test(ch) : match(ch));
3786
if (ok) {++this.pos; return ch;}
3787
},
3788
eatWhile: function(match) {
3789
var start = this.pos;
3790
while (this.eat(match)){}
3791
return this.pos > start;
3792
},
3793
eatSpace: function() {
3794
var start = this.pos;
3795
while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
3796
return this.pos > start;
3797
},
3798
skipToEnd: function() {this.pos = this.string.length;},
3799
skipTo: function(ch) {
3800
var found = this.string.indexOf(ch, this.pos);
3801
if (found > -1) {this.pos = found; return true;}
3802
},
3803
backUp: function(n) {this.pos -= n;},
3804
column: function() {
3805
if (this.lastColumnPos < this.start) {
3806
this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
3807
this.lastColumnPos = this.start;
3808
}
3809
return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
3810
},
3811
indentation: function() {
3812
return countColumn(this.string, null, this.tabSize) -
3813
(this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
3814
},
3815
match: function(pattern, consume, caseInsensitive) {
3816
if (typeof pattern == "string") {
3817
var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
3818
var substr = this.string.substr(this.pos, pattern.length);
3819
if (cased(substr) == cased(pattern)) {
3820
if (consume !== false) this.pos += pattern.length;
3821
return true;
3822
}
3823
} else {
3824
var match = this.string.slice(this.pos).match(pattern);
3825
if (match && match.index > 0) return null;
3826
if (match && consume !== false) this.pos += match[0].length;
3827
return match;
3828
}
3829
},
3830
current: function(){return this.string.slice(this.start, this.pos);},
3831
hideFirstChars: function(n, inner) {
3832
this.lineStart += n;
3833
try { return inner(); }
3834
finally { this.lineStart -= n; }
3835
}
3836
};
3837
CodeMirror.StringStream = StringStream;
3838
3839
// TEXTMARKERS
3840
3841
function TextMarker(doc, type) {
3842
this.lines = [];
3843
this.type = type;
3844
this.doc = doc;
3845
}
3846
CodeMirror.TextMarker = TextMarker;
3847
eventMixin(TextMarker);
3848
3849
TextMarker.prototype.clear = function() {
3850
if (this.explicitlyCleared) return;
3851
var cm = this.doc.cm, withOp = cm && !cm.curOp;
3852
if (withOp) startOperation(cm);
3853
if (hasHandler(this, "clear")) {
3854
var found = this.find();
3855
if (found) signalLater(this, "clear", found.from, found.to);
3856
}
3857
var min = null, max = null;
3858
for (var i = 0; i < this.lines.length; ++i) {
3859
var line = this.lines[i];
3860
var span = getMarkedSpanFor(line.markedSpans, this);
3861
if (span.to != null) max = lineNo(line);
3862
line.markedSpans = removeMarkedSpan(line.markedSpans, span);
3863
if (span.from != null)
3864
min = lineNo(line);
3865
else if (this.collapsed && !lineIsHidden(this.doc, line) && cm)
3866
updateLineHeight(line, textHeight(cm.display));
3867
}
3868
if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
3869
var visual = visualLine(cm.doc, this.lines[i]), len = lineLength(cm.doc, visual);
3870
if (len > cm.display.maxLineLength) {
3871
cm.display.maxLine = visual;
3872
cm.display.maxLineLength = len;
3873
cm.display.maxLineChanged = true;
3874
}
3875
}
3876
3877
if (min != null && cm) regChange(cm, min, max + 1);
3878
this.lines.length = 0;
3879
this.explicitlyCleared = true;
3880
if (this.atomic && this.doc.cantEdit) {
3881
this.doc.cantEdit = false;
3882
if (cm) reCheckSelection(cm);
3883
}
3884
if (withOp) endOperation(cm);
3885
};
3886
3887
TextMarker.prototype.find = function(bothSides) {
3888
var from, to;
3889
for (var i = 0; i < this.lines.length; ++i) {
3890
var line = this.lines[i];
3891
var span = getMarkedSpanFor(line.markedSpans, this);
3892
if (span.from != null || span.to != null) {
3893
var found = lineNo(line);
3894
if (span.from != null) from = Pos(found, span.from);
3895
if (span.to != null) to = Pos(found, span.to);
3896
}
3897
}
3898
if (this.type == "bookmark" && !bothSides) return from;
3899
return from && {from: from, to: to};
3900
};
3901
3902
TextMarker.prototype.changed = function() {
3903
var pos = this.find(), cm = this.doc.cm;
3904
if (!pos || !cm) return;
3905
if (this.type != "bookmark") pos = pos.from;
3906
var line = getLine(this.doc, pos.line);
3907
clearCachedMeasurement(cm, line);
3908
if (pos.line >= cm.display.showingFrom && pos.line < cm.display.showingTo) {
3909
for (var node = cm.display.lineDiv.firstChild; node; node = node.nextSibling) if (node.lineObj == line) {
3910
if (node.offsetHeight != line.height) updateLineHeight(line, node.offsetHeight);
3911
break;
3912
}
3913
runInOp(cm, function() {
3914
cm.curOp.selectionChanged = cm.curOp.forceUpdate = cm.curOp.updateMaxLine = true;
3915
});
3916
}
3917
};
3918
3919
TextMarker.prototype.attachLine = function(line) {
3920
if (!this.lines.length && this.doc.cm) {
3921
var op = this.doc.cm.curOp;
3922
if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
3923
(op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
3924
}
3925
this.lines.push(line);
3926
};
3927
TextMarker.prototype.detachLine = function(line) {
3928
this.lines.splice(indexOf(this.lines, line), 1);
3929
if (!this.lines.length && this.doc.cm) {
3930
var op = this.doc.cm.curOp;
3931
(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
3932
}
3933
};
3934
3935
var nextMarkerId = 0;
3936
3937
function markText(doc, from, to, options, type) {
3938
if (options && options.shared) return markTextShared(doc, from, to, options, type);
3939
if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
3940
3941
var marker = new TextMarker(doc, type);
3942
if (options) copyObj(options, marker);
3943
if (posLess(to, from) || posEq(from, to) && marker.clearWhenEmpty !== false)
3944
return marker;
3945
if (marker.replacedWith) {
3946
marker.collapsed = true;
3947
marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget");
3948
if (!options.handleMouseEvents) marker.replacedWith.ignoreEvents = true;
3949
}
3950
if (marker.collapsed) {
3951
if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
3952
from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
3953
throw new Error("Inserting collapsed marker partially overlapping an existing one");
3954
sawCollapsedSpans = true;
3955
}
3956
3957
if (marker.addToHistory)
3958
addToHistory(doc, {from: from, to: to, origin: "markText"},
3959
{head: doc.sel.head, anchor: doc.sel.anchor}, NaN);
3960
3961
var curLine = from.line, cm = doc.cm, updateMaxLine;
3962
doc.iter(curLine, to.line + 1, function(line) {
3963
if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(doc, line) == cm.display.maxLine)
3964
updateMaxLine = true;
3965
var span = {from: null, to: null, marker: marker};
3966
if (curLine == from.line) span.from = from.ch;
3967
if (curLine == to.line) span.to = to.ch;
3968
if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
3969
addMarkedSpan(line, span);
3970
++curLine;
3971
});
3972
if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
3973
if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
3974
});
3975
3976
if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
3977
3978
if (marker.readOnly) {
3979
sawReadOnlySpans = true;
3980
if (doc.history.done.length || doc.history.undone.length)
3981
doc.clearHistory();
3982
}
3983
if (marker.collapsed) {
3984
marker.id = ++nextMarkerId;
3985
marker.atomic = true;
3986
}
3987
if (cm) {
3988
if (updateMaxLine) cm.curOp.updateMaxLine = true;
3989
if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.collapsed)
3990
regChange(cm, from.line, to.line + 1);
3991
if (marker.atomic) reCheckSelection(cm);
3992
}
3993
return marker;
3994
}
3995
3996
// SHARED TEXTMARKERS
3997
3998
function SharedTextMarker(markers, primary) {
3999
this.markers = markers;
4000
this.primary = primary;
4001
for (var i = 0, me = this; i < markers.length; ++i) {
4002
markers[i].parent = this;
4003
on(markers[i], "clear", function(){me.clear();});
4004
}
4005
}
4006
CodeMirror.SharedTextMarker = SharedTextMarker;
4007
eventMixin(SharedTextMarker);
4008
4009
SharedTextMarker.prototype.clear = function() {
4010
if (this.explicitlyCleared) return;
4011
this.explicitlyCleared = true;
4012
for (var i = 0; i < this.markers.length; ++i)
4013
this.markers[i].clear();
4014
signalLater(this, "clear");
4015
};
4016
SharedTextMarker.prototype.find = function() {
4017
return this.primary.find();
4018
};
4019
4020
function markTextShared(doc, from, to, options, type) {
4021
options = copyObj(options);
4022
options.shared = false;
4023
var markers = [markText(doc, from, to, options, type)], primary = markers[0];
4024
var widget = options.replacedWith;
4025
linkedDocs(doc, function(doc) {
4026
if (widget) options.replacedWith = widget.cloneNode(true);
4027
markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
4028
for (var i = 0; i < doc.linked.length; ++i)
4029
if (doc.linked[i].isParent) return;
4030
primary = lst(markers);
4031
});
4032
return new SharedTextMarker(markers, primary);
4033
}
4034
4035
// TEXTMARKER SPANS
4036
4037
function getMarkedSpanFor(spans, marker) {
4038
if (spans) for (var i = 0; i < spans.length; ++i) {
4039
var span = spans[i];
4040
if (span.marker == marker) return span;
4041
}
4042
}
4043
function removeMarkedSpan(spans, span) {
4044
for (var r, i = 0; i < spans.length; ++i)
4045
if (spans[i] != span) (r || (r = [])).push(spans[i]);
4046
return r;
4047
}
4048
function addMarkedSpan(line, span) {
4049
line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
4050
span.marker.attachLine(line);
4051
}
4052
4053
function markedSpansBefore(old, startCh, isInsert) {
4054
if (old) for (var i = 0, nw; i < old.length; ++i) {
4055
var span = old[i], marker = span.marker;
4056
var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
4057
if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
4058
var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
4059
(nw || (nw = [])).push({from: span.from,
4060
to: endsAfter ? null : span.to,
4061
marker: marker});
4062
}
4063
}
4064
return nw;
4065
}
4066
4067
function markedSpansAfter(old, endCh, isInsert) {
4068
if (old) for (var i = 0, nw; i < old.length; ++i) {
4069
var span = old[i], marker = span.marker;
4070
var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
4071
if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
4072
var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
4073
(nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh,
4074
to: span.to == null ? null : span.to - endCh,
4075
marker: marker});
4076
}
4077
}
4078
return nw;
4079
}
4080
4081
function stretchSpansOverChange(doc, change) {
4082
var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
4083
var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
4084
if (!oldFirst && !oldLast) return null;
4085
4086
var startCh = change.from.ch, endCh = change.to.ch, isInsert = posEq(change.from, change.to);
4087
// Get the spans that 'stick out' on both sides
4088
var first = markedSpansBefore(oldFirst, startCh, isInsert);
4089
var last = markedSpansAfter(oldLast, endCh, isInsert);
4090
4091
// Next, merge those two ends
4092
var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
4093
if (first) {
4094
// Fix up .to properties of first
4095
for (var i = 0; i < first.length; ++i) {
4096
var span = first[i];
4097
if (span.to == null) {
4098
var found = getMarkedSpanFor(last, span.marker);
4099
if (!found) span.to = startCh;
4100
else if (sameLine) span.to = found.to == null ? null : found.to + offset;
4101
}
4102
}
4103
}
4104
if (last) {
4105
// Fix up .from in last (or move them into first in case of sameLine)
4106
for (var i = 0; i < last.length; ++i) {
4107
var span = last[i];
4108
if (span.to != null) span.to += offset;
4109
if (span.from == null) {
4110
var found = getMarkedSpanFor(first, span.marker);
4111
if (!found) {
4112
span.from = offset;
4113
if (sameLine) (first || (first = [])).push(span);
4114
}
4115
} else {
4116
span.from += offset;
4117
if (sameLine) (first || (first = [])).push(span);
4118
}
4119
}
4120
}
4121
// Make sure we didn't create any zero-length spans
4122
if (first) first = clearEmptySpans(first);
4123
if (last && last != first) last = clearEmptySpans(last);
4124
4125
var newMarkers = [first];
4126
if (!sameLine) {
4127
// Fill gap with whole-line-spans
4128
var gap = change.text.length - 2, gapMarkers;
4129
if (gap > 0 && first)
4130
for (var i = 0; i < first.length; ++i)
4131
if (first[i].to == null)
4132
(gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker});
4133
for (var i = 0; i < gap; ++i)
4134
newMarkers.push(gapMarkers);
4135
newMarkers.push(last);
4136
}
4137
return newMarkers;
4138
}
4139
4140
function clearEmptySpans(spans) {
4141
for (var i = 0; i < spans.length; ++i) {
4142
var span = spans[i];
4143
if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
4144
spans.splice(i--, 1);
4145
}
4146
if (!spans.length) return null;
4147
return spans;
4148
}
4149
4150
function mergeOldSpans(doc, change) {
4151
var old = getOldSpans(doc, change);
4152
var stretched = stretchSpansOverChange(doc, change);
4153
if (!old) return stretched;
4154
if (!stretched) return old;
4155
4156
for (var i = 0; i < old.length; ++i) {
4157
var oldCur = old[i], stretchCur = stretched[i];
4158
if (oldCur && stretchCur) {
4159
spans: for (var j = 0; j < stretchCur.length; ++j) {
4160
var span = stretchCur[j];
4161
for (var k = 0; k < oldCur.length; ++k)
4162
if (oldCur[k].marker == span.marker) continue spans;
4163
oldCur.push(span);
4164
}
4165
} else if (stretchCur) {
4166
old[i] = stretchCur;
4167
}
4168
}
4169
return old;
4170
}
4171
4172
function removeReadOnlyRanges(doc, from, to) {
4173
var markers = null;
4174
doc.iter(from.line, to.line + 1, function(line) {
4175
if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
4176
var mark = line.markedSpans[i].marker;
4177
if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
4178
(markers || (markers = [])).push(mark);
4179
}
4180
});
4181
if (!markers) return null;
4182
var parts = [{from: from, to: to}];
4183
for (var i = 0; i < markers.length; ++i) {
4184
var mk = markers[i], m = mk.find();
4185
for (var j = 0; j < parts.length; ++j) {
4186
var p = parts[j];
4187
if (posLess(p.to, m.from) || posLess(m.to, p.from)) continue;
4188
var newParts = [j, 1];
4189
if (posLess(p.from, m.from) || !mk.inclusiveLeft && posEq(p.from, m.from))
4190
newParts.push({from: p.from, to: m.from});
4191
if (posLess(m.to, p.to) || !mk.inclusiveRight && posEq(p.to, m.to))
4192
newParts.push({from: m.to, to: p.to});
4193
parts.splice.apply(parts, newParts);
4194
j += newParts.length - 1;
4195
}
4196
}
4197
return parts;
4198
}
4199
4200
function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
4201
function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
4202
4203
function compareCollapsedMarkers(a, b) {
4204
var lenDiff = a.lines.length - b.lines.length;
4205
if (lenDiff != 0) return lenDiff;
4206
var aPos = a.find(), bPos = b.find();
4207
var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
4208
if (fromCmp) return -fromCmp;
4209
var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
4210
if (toCmp) return toCmp;
4211
return b.id - a.id;
4212
}
4213
4214
function collapsedSpanAtSide(line, start) {
4215
var sps = sawCollapsedSpans && line.markedSpans, found;
4216
if (sps) for (var sp, i = 0; i < sps.length; ++i) {
4217
sp = sps[i];
4218
if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
4219
(!found || compareCollapsedMarkers(found, sp.marker) < 0))
4220
found = sp.marker;
4221
}
4222
return found;
4223
}
4224
function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
4225
function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
4226
4227
function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
4228
var line = getLine(doc, lineNo);
4229
var sps = sawCollapsedSpans && line.markedSpans;
4230
if (sps) for (var i = 0; i < sps.length; ++i) {
4231
var sp = sps[i];
4232
if (!sp.marker.collapsed) continue;
4233
var found = sp.marker.find(true);
4234
var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
4235
var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
4236
if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
4237
if (fromCmp <= 0 && (cmp(found.to, from) || extraRight(sp.marker) - extraLeft(marker)) > 0 ||
4238
fromCmp >= 0 && (cmp(found.from, to) || extraLeft(sp.marker) - extraRight(marker)) < 0)
4239
return true;
4240
}
4241
}
4242
4243
function visualLine(doc, line) {
4244
var merged;
4245
while (merged = collapsedSpanAtStart(line))
4246
line = getLine(doc, merged.find().from.line);
4247
return line;
4248
}
4249
4250
function lineIsHidden(doc, line) {
4251
var sps = sawCollapsedSpans && line.markedSpans;
4252
if (sps) for (var sp, i = 0; i < sps.length; ++i) {
4253
sp = sps[i];
4254
if (!sp.marker.collapsed) continue;
4255
if (sp.from == null) return true;
4256
if (sp.marker.replacedWith) continue;
4257
if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
4258
return true;
4259
}
4260
}
4261
function lineIsHiddenInner(doc, line, span) {
4262
if (span.to == null) {
4263
var end = span.marker.find().to, endLine = getLine(doc, end.line);
4264
return lineIsHiddenInner(doc, endLine, getMarkedSpanFor(endLine.markedSpans, span.marker));
4265
}
4266
if (span.marker.inclusiveRight && span.to == line.text.length)
4267
return true;
4268
for (var sp, i = 0; i < line.markedSpans.length; ++i) {
4269
sp = line.markedSpans[i];
4270
if (sp.marker.collapsed && !sp.marker.replacedWith && sp.from == span.to &&
4271
(sp.to == null || sp.to != span.from) &&
4272
(sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
4273
lineIsHiddenInner(doc, line, sp)) return true;
4274
}
4275
}
4276
4277
function detachMarkedSpans(line) {
4278
var spans = line.markedSpans;
4279
if (!spans) return;
4280
for (var i = 0; i < spans.length; ++i)
4281
spans[i].marker.detachLine(line);
4282
line.markedSpans = null;
4283
}
4284
4285
function attachMarkedSpans(line, spans) {
4286
if (!spans) return;
4287
for (var i = 0; i < spans.length; ++i)
4288
spans[i].marker.attachLine(line);
4289
line.markedSpans = spans;
4290
}
4291
4292
// LINE WIDGETS
4293
4294
var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {
4295
if (options) for (var opt in options) if (options.hasOwnProperty(opt))
4296
this[opt] = options[opt];
4297
this.cm = cm;
4298
this.node = node;
4299
};
4300
eventMixin(LineWidget);
4301
function widgetOperation(f) {
4302
return function() {
4303
var withOp = !this.cm.curOp;
4304
if (withOp) startOperation(this.cm);
4305
try {var result = f.apply(this, arguments);}
4306
finally {if (withOp) endOperation(this.cm);}
4307
return result;
4308
};
4309
}
4310
LineWidget.prototype.clear = widgetOperation(function() {
4311
var ws = this.line.widgets, no = lineNo(this.line);
4312
if (no == null || !ws) return;
4313
for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
4314
if (!ws.length) this.line.widgets = null;
4315
var aboveVisible = heightAtLine(this.cm, this.line) < this.cm.doc.scrollTop;
4316
updateLineHeight(this.line, Math.max(0, this.line.height - widgetHeight(this)));
4317
if (aboveVisible) addToScrollPos(this.cm, 0, -this.height);
4318
regChange(this.cm, no, no + 1);
4319
});
4320
LineWidget.prototype.changed = widgetOperation(function() {
4321
var oldH = this.height;
4322
this.height = null;
4323
var diff = widgetHeight(this) - oldH;
4324
if (!diff) return;
4325
updateLineHeight(this.line, this.line.height + diff);
4326
var no = lineNo(this.line);
4327
regChange(this.cm, no, no + 1);
4328
});
4329
4330
function widgetHeight(widget) {
4331
if (widget.height != null) return widget.height;
4332
if (!widget.node.parentNode || widget.node.parentNode.nodeType != 1)
4333
removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative"));
4334
return widget.height = widget.node.offsetHeight;
4335
}
4336
4337
function addLineWidget(cm, handle, node, options) {
4338
var widget = new LineWidget(cm, node, options);
4339
if (widget.noHScroll) cm.display.alignWidgets = true;
4340
changeLine(cm, handle, function(line) {
4341
var widgets = line.widgets || (line.widgets = []);
4342
if (widget.insertAt == null) widgets.push(widget);
4343
else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
4344
widget.line = line;
4345
if (!lineIsHidden(cm.doc, line) || widget.showIfHidden) {
4346
var aboveVisible = heightAtLine(cm, line) < cm.doc.scrollTop;
4347
updateLineHeight(line, line.height + widgetHeight(widget));
4348
if (aboveVisible) addToScrollPos(cm, 0, widget.height);
4349
}
4350
return true;
4351
});
4352
return widget;
4353
}
4354
4355
// LINE DATA STRUCTURE
4356
4357
// Line objects. These hold state related to a line, including
4358
// highlighting info (the styles array).
4359
var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
4360
this.text = text;
4361
attachMarkedSpans(this, markedSpans);
4362
this.height = estimateHeight ? estimateHeight(this) : 1;
4363
};
4364
eventMixin(Line);
4365
Line.prototype.lineNo = function() { return lineNo(this); };
4366
4367
function updateLine(line, text, markedSpans, estimateHeight) {
4368
line.text = text;
4369
if (line.stateAfter) line.stateAfter = null;
4370
if (line.styles) line.styles = null;
4371
if (line.order != null) line.order = null;
4372
detachMarkedSpans(line);
4373
attachMarkedSpans(line, markedSpans);
4374
var estHeight = estimateHeight ? estimateHeight(line) : 1;
4375
if (estHeight != line.height) updateLineHeight(line, estHeight);
4376
}
4377
4378
function cleanUpLine(line) {
4379
line.parent = null;
4380
detachMarkedSpans(line);
4381
}
4382
4383
// Run the given mode's parser over a line, update the styles
4384
// array, which contains alternating fragments of text and CSS
4385
// classes.
4386
function runMode(cm, text, mode, state, f, forceToEnd) {
4387
var flattenSpans = mode.flattenSpans;
4388
if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
4389
var curStart = 0, curStyle = null;
4390
var stream = new StringStream(text, cm.options.tabSize), style;
4391
if (text == "" && mode.blankLine) mode.blankLine(state);
4392
while (!stream.eol()) {
4393
if (stream.pos > cm.options.maxHighlightLength) {
4394
flattenSpans = false;
4395
if (forceToEnd) processLine(cm, text, state, stream.pos);
4396
stream.pos = text.length;
4397
style = null;
4398
} else {
4399
style = mode.token(stream, state);
4400
}
4401
if (cm.options.addModeClass) {
4402
var mName = CodeMirror.innerMode(mode, state).mode.name;
4403
if (mName) style = "m-" + (style ? mName + " " + style : mName);
4404
}
4405
if (!flattenSpans || curStyle != style) {
4406
if (curStart < stream.start) f(stream.start, curStyle);
4407
curStart = stream.start; curStyle = style;
4408
}
4409
stream.start = stream.pos;
4410
}
4411
while (curStart < stream.pos) {
4412
// Webkit seems to refuse to render text nodes longer than 57444 characters
4413
var pos = Math.min(stream.pos, curStart + 50000);
4414
f(pos, curStyle);
4415
curStart = pos;
4416
}
4417
}
4418
4419
function highlightLine(cm, line, state, forceToEnd) {
4420
// A styles array always starts with a number identifying the
4421
// mode/overlays that it is based on (for easy invalidation).
4422
var st = [cm.state.modeGen];
4423
// Compute the base array of styles
4424
runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
4425
st.push(end, style);
4426
}, forceToEnd);
4427
4428
// Run overlays, adjust style array.
4429
for (var o = 0; o < cm.state.overlays.length; ++o) {
4430
var overlay = cm.state.overlays[o], i = 1, at = 0;
4431
runMode(cm, line.text, overlay.mode, true, function(end, style) {
4432
var start = i;
4433
// Ensure there's a token end at the current position, and that i points at it
4434
while (at < end) {
4435
var i_end = st[i];
4436
if (i_end > end)
4437
st.splice(i, 1, end, st[i+1], i_end);
4438
i += 2;
4439
at = Math.min(end, i_end);
4440
}
4441
if (!style) return;
4442
if (overlay.opaque) {
4443
st.splice(start, i - start, end, style);
4444
i = start + 2;
4445
} else {
4446
for (; start < i; start += 2) {
4447
var cur = st[start+1];
4448
st[start+1] = cur ? cur + " " + style : style;
4449
}
4450
}
4451
});
4452
}
4453
4454
return st;
4455
}
4456
4457
function getLineStyles(cm, line) {
4458
if (!line.styles || line.styles[0] != cm.state.modeGen)
4459
line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
4460
return line.styles;
4461
}
4462
4463
// Lightweight form of highlight -- proceed over this line and
4464
// update state, but don't save a style array.
4465
function processLine(cm, text, state, startAt) {
4466
var mode = cm.doc.mode;
4467
var stream = new StringStream(text, cm.options.tabSize);
4468
stream.start = stream.pos = startAt || 0;
4469
if (text == "" && mode.blankLine) mode.blankLine(state);
4470
while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
4471
mode.token(stream, state);
4472
stream.start = stream.pos;
4473
}
4474
}
4475
4476
var styleToClassCache = {}, styleToClassCacheWithMode = {};
4477
function interpretTokenStyle(style, builder) {
4478
if (!style) return null;
4479
for (;;) {
4480
var lineClass = style.match(/(?:^|\s)line-(background-)?(\S+)/);
4481
if (!lineClass) break;
4482
style = style.slice(0, lineClass.index) + style.slice(lineClass.index + lineClass[0].length);
4483
var prop = lineClass[1] ? "bgClass" : "textClass";
4484
if (builder[prop] == null)
4485
builder[prop] = lineClass[2];
4486
else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(builder[prop]))
4487
builder[prop] += " " + lineClass[2];
4488
}
4489
var cache = builder.cm.options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
4490
return cache[style] ||
4491
(cache[style] = "cm-" + style.replace(/ +/g, " cm-"));
4492
}
4493
4494
function buildLineContent(cm, realLine, measure, copyWidgets) {
4495
var merged, line = realLine, empty = true;
4496
while (merged = collapsedSpanAtStart(line))
4497
line = getLine(cm.doc, merged.find().from.line);
4498
4499
var builder = {pre: elt("pre"), col: 0, pos: 0,
4500
measure: null, measuredSomething: false, cm: cm,
4501
copyWidgets: copyWidgets};
4502
4503
do {
4504
if (line.text) empty = false;
4505
builder.measure = line == realLine && measure;
4506
builder.pos = 0;
4507
builder.addToken = builder.measure ? buildTokenMeasure : buildToken;
4508
if ((old_ie || webkit) && cm.getOption("lineWrapping"))
4509
builder.addToken = buildTokenSplitSpaces(builder.addToken);
4510
var next = insertLineContent(line, builder, getLineStyles(cm, line));
4511
if (measure && line == realLine && !builder.measuredSomething) {
4512
measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure));
4513
builder.measuredSomething = true;
4514
}
4515
if (next) line = getLine(cm.doc, next.to.line);
4516
} while (next);
4517
4518
if (measure && !builder.measuredSomething && !measure[0])
4519
measure[0] = builder.pre.appendChild(empty ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure));
4520
if (!builder.pre.firstChild && !lineIsHidden(cm.doc, realLine))
4521
builder.pre.appendChild(document.createTextNode("\u00a0"));
4522
4523
var order;
4524
// Work around problem with the reported dimensions of single-char
4525
// direction spans on IE (issue #1129). See also the comment in
4526
// cursorCoords.
4527
if (measure && ie && (order = getOrder(line))) {
4528
var l = order.length - 1;
4529
if (order[l].from == order[l].to) --l;
4530
var last = order[l], prev = order[l - 1];
4531
if (last.from + 1 == last.to && prev && last.level < prev.level) {
4532
var span = measure[builder.pos - 1];
4533
if (span) span.parentNode.insertBefore(span.measureRight = zeroWidthElement(cm.display.measure),
4534
span.nextSibling);
4535
}
4536
}
4537
4538
var textClass = builder.textClass ? builder.textClass + " " + (realLine.textClass || "") : realLine.textClass;
4539
if (textClass) builder.pre.className = textClass;
4540
4541
signal(cm, "renderLine", cm, realLine, builder.pre);
4542
return builder;
4543
}
4544
4545
function defaultSpecialCharPlaceholder(ch) {
4546
var token = elt("span", "\u2022", "cm-invalidchar");
4547
token.title = "\\u" + ch.charCodeAt(0).toString(16);
4548
return token;
4549
}
4550
4551
function buildToken(builder, text, style, startStyle, endStyle, title) {
4552
if (!text) return;
4553
var special = builder.cm.options.specialChars;
4554
if (!special.test(text)) {
4555
builder.col += text.length;
4556
var content = document.createTextNode(text);
4557
} else {
4558
var content = document.createDocumentFragment(), pos = 0;
4559
while (true) {
4560
special.lastIndex = pos;
4561
var m = special.exec(text);
4562
var skipped = m ? m.index - pos : text.length - pos;
4563
if (skipped) {
4564
content.appendChild(document.createTextNode(text.slice(pos, pos + skipped)));
4565
builder.col += skipped;
4566
}
4567
if (!m) break;
4568
pos += skipped + 1;
4569
if (m[0] == "\t") {
4570
var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
4571
content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
4572
builder.col += tabWidth;
4573
} else {
4574
var token = builder.cm.options.specialCharPlaceholder(m[0]);
4575
content.appendChild(token);
4576
builder.col += 1;
4577
}
4578
}
4579
}
4580
if (style || startStyle || endStyle || builder.measure) {
4581
var fullStyle = style || "";
4582
if (startStyle) fullStyle += startStyle;
4583
if (endStyle) fullStyle += endStyle;
4584
var token = elt("span", [content], fullStyle);
4585
if (title) token.title = title;
4586
return builder.pre.appendChild(token);
4587
}
4588
builder.pre.appendChild(content);
4589
}
4590
4591
function buildTokenMeasure(builder, text, style, startStyle, endStyle) {
4592
var wrapping = builder.cm.options.lineWrapping;
4593
for (var i = 0; i < text.length; ++i) {
4594
var start = i == 0, to = i + 1;
4595
while (to < text.length && isExtendingChar(text.charAt(to))) ++to;
4596
var ch = text.slice(i, to);
4597
i = to - 1;
4598
if (i && wrapping && spanAffectsWrapping(text, i))
4599
builder.pre.appendChild(elt("wbr"));
4600
var old = builder.measure[builder.pos];
4601
var span = builder.measure[builder.pos] =
4602
buildToken(builder, ch, style,
4603
start && startStyle, i == text.length - 1 && endStyle);
4604
if (old) span.leftSide = old.leftSide || old;
4605
// In IE single-space nodes wrap differently than spaces
4606
// embedded in larger text nodes, except when set to
4607
// white-space: normal (issue #1268).
4608
if (old_ie && wrapping && ch == " " && i && !/\s/.test(text.charAt(i - 1)) &&
4609
i < text.length - 1 && !/\s/.test(text.charAt(i + 1)))
4610
span.style.whiteSpace = "normal";
4611
builder.pos += ch.length;
4612
}
4613
if (text.length) builder.measuredSomething = true;
4614
}
4615
4616
function buildTokenSplitSpaces(inner) {
4617
function split(old) {
4618
var out = " ";
4619
for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
4620
out += " ";
4621
return out;
4622
}
4623
return function(builder, text, style, startStyle, endStyle, title) {
4624
return inner(builder, text.replace(/ {3,}/g, split), style, startStyle, endStyle, title);
4625
};
4626
}
4627
4628
function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
4629
var widget = !ignoreWidget && marker.replacedWith;
4630
if (widget) {
4631
if (builder.copyWidgets) widget = widget.cloneNode(true);
4632
builder.pre.appendChild(widget);
4633
if (builder.measure) {
4634
if (size) {
4635
builder.measure[builder.pos] = widget;
4636
} else {
4637
var elt = zeroWidthElement(builder.cm.display.measure);
4638
if (marker.type == "bookmark" && !marker.insertLeft)
4639
builder.measure[builder.pos] = builder.pre.appendChild(elt);
4640
else if (builder.measure[builder.pos])
4641
return;
4642
else
4643
builder.measure[builder.pos] = builder.pre.insertBefore(elt, widget);
4644
}
4645
builder.measuredSomething = true;
4646
}
4647
}
4648
builder.pos += size;
4649
}
4650
4651
// Outputs a number of spans to make up a line, taking highlighting
4652
// and marked text into account.
4653
function insertLineContent(line, builder, styles) {
4654
var spans = line.markedSpans, allText = line.text, at = 0;
4655
if (!spans) {
4656
for (var i = 1; i < styles.length; i+=2)
4657
builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder));
4658
return;
4659
}
4660
4661
var len = allText.length, pos = 0, i = 1, text = "", style;
4662
var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
4663
for (;;) {
4664
if (nextChange == pos) { // Update current marker set
4665
spanStyle = spanEndStyle = spanStartStyle = title = "";
4666
collapsed = null; nextChange = Infinity;
4667
var foundBookmarks = [];
4668
for (var j = 0; j < spans.length; ++j) {
4669
var sp = spans[j], m = sp.marker;
4670
if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
4671
if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
4672
if (m.className) spanStyle += " " + m.className;
4673
if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
4674
if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
4675
if (m.title && !title) title = m.title;
4676
if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
4677
collapsed = sp;
4678
} else if (sp.from > pos && nextChange > sp.from) {
4679
nextChange = sp.from;
4680
}
4681
if (m.type == "bookmark" && sp.from == pos && m.replacedWith) foundBookmarks.push(m);
4682
}
4683
if (collapsed && (collapsed.from || 0) == pos) {
4684
buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos,
4685
collapsed.marker, collapsed.from == null);
4686
if (collapsed.to == null) return collapsed.marker.find();
4687
}
4688
if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
4689
buildCollapsedSpan(builder, 0, foundBookmarks[j]);
4690
}
4691
if (pos >= len) break;
4692
4693
var upto = Math.min(len, nextChange);
4694
while (true) {
4695
if (text) {
4696
var end = pos + text.length;
4697
if (!collapsed) {
4698
var tokenText = end > upto ? text.slice(0, upto - pos) : text;
4699
builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
4700
spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title);
4701
}
4702
if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
4703
pos = end;
4704
spanStartStyle = "";
4705
}
4706
text = allText.slice(at, at = styles[i++]);
4707
style = interpretTokenStyle(styles[i++], builder);
4708
}
4709
}
4710
}
4711
4712
// DOCUMENT DATA STRUCTURE
4713
4714
function updateDoc(doc, change, markedSpans, selAfter, estimateHeight) {
4715
function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
4716
function update(line, text, spans) {
4717
updateLine(line, text, spans, estimateHeight);
4718
signalLater(line, "change", line, change);
4719
}
4720
4721
var from = change.from, to = change.to, text = change.text;
4722
var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
4723
var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
4724
4725
// First adjust the line structure
4726
if (from.ch == 0 && to.ch == 0 && lastText == "" &&
4727
(!doc.cm || doc.cm.options.wholeLineUpdateBefore)) {
4728
// This is a whole-line replace. Treated specially to make
4729
// sure line objects move the way they are supposed to.
4730
for (var i = 0, e = text.length - 1, added = []; i < e; ++i)
4731
added.push(new Line(text[i], spansFor(i), estimateHeight));
4732
update(lastLine, lastLine.text, lastSpans);
4733
if (nlines) doc.remove(from.line, nlines);
4734
if (added.length) doc.insert(from.line, added);
4735
} else if (firstLine == lastLine) {
4736
if (text.length == 1) {
4737
update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
4738
} else {
4739
for (var added = [], i = 1, e = text.length - 1; i < e; ++i)
4740
added.push(new Line(text[i], spansFor(i), estimateHeight));
4741
added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
4742
update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4743
doc.insert(from.line + 1, added);
4744
}
4745
} else if (text.length == 1) {
4746
update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
4747
doc.remove(from.line + 1, nlines);
4748
} else {
4749
update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4750
update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
4751
for (var i = 1, e = text.length - 1, added = []; i < e; ++i)
4752
added.push(new Line(text[i], spansFor(i), estimateHeight));
4753
if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
4754
doc.insert(from.line + 1, added);
4755
}
4756
4757
signalLater(doc, "change", doc, change);
4758
setSelection(doc, selAfter.anchor, selAfter.head, null, true);
4759
}
4760
4761
function LeafChunk(lines) {
4762
this.lines = lines;
4763
this.parent = null;
4764
for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
4765
lines[i].parent = this;
4766
height += lines[i].height;
4767
}
4768
this.height = height;
4769
}
4770
4771
LeafChunk.prototype = {
4772
chunkSize: function() { return this.lines.length; },
4773
removeInner: function(at, n) {
4774
for (var i = at, e = at + n; i < e; ++i) {
4775
var line = this.lines[i];
4776
this.height -= line.height;
4777
cleanUpLine(line);
4778
signalLater(line, "delete");
4779
}
4780
this.lines.splice(at, n);
4781
},
4782
collapse: function(lines) {
4783
lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
4784
},
4785
insertInner: function(at, lines, height) {
4786
this.height += height;
4787
this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
4788
for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
4789
},
4790
iterN: function(at, n, op) {
4791
for (var e = at + n; at < e; ++at)
4792
if (op(this.lines[at])) return true;
4793
}
4794
};
4795
4796
function BranchChunk(children) {
4797
this.children = children;
4798
var size = 0, height = 0;
4799
for (var i = 0, e = children.length; i < e; ++i) {
4800
var ch = children[i];
4801
size += ch.chunkSize(); height += ch.height;
4802
ch.parent = this;
4803
}
4804
this.size = size;
4805
this.height = height;
4806
this.parent = null;
4807
}
4808
4809
BranchChunk.prototype = {
4810
chunkSize: function() { return this.size; },
4811
removeInner: function(at, n) {
4812
this.size -= n;
4813
for (var i = 0; i < this.children.length; ++i) {
4814
var child = this.children[i], sz = child.chunkSize();
4815
if (at < sz) {
4816
var rm = Math.min(n, sz - at), oldHeight = child.height;
4817
child.removeInner(at, rm);
4818
this.height -= oldHeight - child.height;
4819
if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
4820
if ((n -= rm) == 0) break;
4821
at = 0;
4822
} else at -= sz;
4823
}
4824
if (this.size - n < 25) {
4825
var lines = [];
4826
this.collapse(lines);
4827
this.children = [new LeafChunk(lines)];
4828
this.children[0].parent = this;
4829
}
4830
},
4831
collapse: function(lines) {
4832
for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
4833
},
4834
insertInner: function(at, lines, height) {
4835
this.size += lines.length;
4836
this.height += height;
4837
for (var i = 0, e = this.children.length; i < e; ++i) {
4838
var child = this.children[i], sz = child.chunkSize();
4839
if (at <= sz) {
4840
child.insertInner(at, lines, height);
4841
if (child.lines && child.lines.length > 50) {
4842
while (child.lines.length > 50) {
4843
var spilled = child.lines.splice(child.lines.length - 25, 25);
4844
var newleaf = new LeafChunk(spilled);
4845
child.height -= newleaf.height;
4846
this.children.splice(i + 1, 0, newleaf);
4847
newleaf.parent = this;
4848
}
4849
this.maybeSpill();
4850
}
4851
break;
4852
}
4853
at -= sz;
4854
}
4855
},
4856
maybeSpill: function() {
4857
if (this.children.length <= 10) return;
4858
var me = this;
4859
do {
4860
var spilled = me.children.splice(me.children.length - 5, 5);
4861
var sibling = new BranchChunk(spilled);
4862
if (!me.parent) { // Become the parent node
4863
var copy = new BranchChunk(me.children);
4864
copy.parent = me;
4865
me.children = [copy, sibling];
4866
me = copy;
4867
} else {
4868
me.size -= sibling.size;
4869
me.height -= sibling.height;
4870
var myIndex = indexOf(me.parent.children, me);
4871
me.parent.children.splice(myIndex + 1, 0, sibling);
4872
}
4873
sibling.parent = me.parent;
4874
} while (me.children.length > 10);
4875
me.parent.maybeSpill();
4876
},
4877
iterN: function(at, n, op) {
4878
for (var i = 0, e = this.children.length; i < e; ++i) {
4879
var child = this.children[i], sz = child.chunkSize();
4880
if (at < sz) {
4881
var used = Math.min(n, sz - at);
4882
if (child.iterN(at, used, op)) return true;
4883
if ((n -= used) == 0) break;
4884
at = 0;
4885
} else at -= sz;
4886
}
4887
}
4888
};
4889
4890
var nextDocId = 0;
4891
var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
4892
if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
4893
if (firstLine == null) firstLine = 0;
4894
4895
BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
4896
this.first = firstLine;
4897
this.scrollTop = this.scrollLeft = 0;
4898
this.cantEdit = false;
4899
this.history = makeHistory();
4900
this.cleanGeneration = 1;
4901
this.frontier = firstLine;
4902
var start = Pos(firstLine, 0);
4903
this.sel = {from: start, to: start, head: start, anchor: start, shift: false, extend: false, goalColumn: null};
4904
this.id = ++nextDocId;
4905
this.modeOption = mode;
4906
4907
if (typeof text == "string") text = splitLines(text);
4908
updateDoc(this, {from: start, to: start, text: text}, null, {head: start, anchor: start});
4909
};
4910
4911
Doc.prototype = createObj(BranchChunk.prototype, {
4912
constructor: Doc,
4913
iter: function(from, to, op) {
4914
if (op) this.iterN(from - this.first, to - from, op);
4915
else this.iterN(this.first, this.first + this.size, from);
4916
},
4917
4918
insert: function(at, lines) {
4919
var height = 0;
4920
for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
4921
this.insertInner(at - this.first, lines, height);
4922
},
4923
remove: function(at, n) { this.removeInner(at - this.first, n); },
4924
4925
getValue: function(lineSep) {
4926
var lines = getLines(this, this.first, this.first + this.size);
4927
if (lineSep === false) return lines;
4928
return lines.join(lineSep || "\n");
4929
},
4930
setValue: function(code) {
4931
var top = Pos(this.first, 0), last = this.first + this.size - 1;
4932
makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
4933
text: splitLines(code), origin: "setValue"},
4934
{head: top, anchor: top}, true);
4935
},
4936
replaceRange: function(code, from, to, origin) {
4937
from = clipPos(this, from);
4938
to = to ? clipPos(this, to) : from;
4939
replaceRange(this, code, from, to, origin);
4940
},
4941
getRange: function(from, to, lineSep) {
4942
var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
4943
if (lineSep === false) return lines;
4944
return lines.join(lineSep || "\n");
4945
},
4946
4947
getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
4948
setLine: function(line, text) {
4949
if (isLine(this, line))
4950
replaceRange(this, text, Pos(line, 0), clipPos(this, Pos(line)));
4951
},
4952
removeLine: function(line) {
4953
if (line) replaceRange(this, "", clipPos(this, Pos(line - 1)), clipPos(this, Pos(line)));
4954
else replaceRange(this, "", Pos(0, 0), clipPos(this, Pos(1, 0)));
4955
},
4956
4957
getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
4958
getLineNumber: function(line) {return lineNo(line);},
4959
4960
getLineHandleVisualStart: function(line) {
4961
if (typeof line == "number") line = getLine(this, line);
4962
return visualLine(this, line);
4963
},
4964
4965
lineCount: function() {return this.size;},
4966
firstLine: function() {return this.first;},
4967
lastLine: function() {return this.first + this.size - 1;},
4968
4969
clipPos: function(pos) {return clipPos(this, pos);},
4970
4971
getCursor: function(start) {
4972
var sel = this.sel, pos;
4973
if (start == null || start == "head") pos = sel.head;
4974
else if (start == "anchor") pos = sel.anchor;
4975
else if (start == "end" || start === false) pos = sel.to;
4976
else pos = sel.from;
4977
return copyPos(pos);
4978
},
4979
somethingSelected: function() {return !posEq(this.sel.head, this.sel.anchor);},
4980
4981
setCursor: docOperation(function(line, ch, extend) {
4982
var pos = clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line);
4983
if (extend) extendSelection(this, pos);
4984
else setSelection(this, pos, pos);
4985
}),
4986
setSelection: docOperation(function(anchor, head, bias) {
4987
setSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), bias);
4988
}),
4989
extendSelection: docOperation(function(from, to, bias) {
4990
extendSelection(this, clipPos(this, from), to && clipPos(this, to), bias);
4991
}),
4992
4993
getSelection: function(lineSep) {return this.getRange(this.sel.from, this.sel.to, lineSep);},
4994
replaceSelection: function(code, collapse, origin) {
4995
makeChange(this, {from: this.sel.from, to: this.sel.to, text: splitLines(code), origin: origin}, collapse || "around");
4996
},
4997
undo: docOperation(function() {makeChangeFromHistory(this, "undo");}),
4998
redo: docOperation(function() {makeChangeFromHistory(this, "redo");}),
4999
5000
setExtending: function(val) {this.sel.extend = val;},
5001
5002
historySize: function() {
5003
var hist = this.history;
5004
return {undo: hist.done.length, redo: hist.undone.length};
5005
},
5006
clearHistory: function() {this.history = makeHistory(this.history.maxGeneration);},
5007
5008
markClean: function() {
5009
this.cleanGeneration = this.changeGeneration(true);
5010
},
5011
changeGeneration: function(forceSplit) {
5012
if (forceSplit)
5013
this.history.lastOp = this.history.lastOrigin = null;
5014
return this.history.generation;
5015
},
5016
isClean: function (gen) {
5017
return this.history.generation == (gen || this.cleanGeneration);
5018
},
5019
5020
getHistory: function() {
5021
return {done: copyHistoryArray(this.history.done),
5022
undone: copyHistoryArray(this.history.undone)};
5023
},
5024
setHistory: function(histData) {
5025
var hist = this.history = makeHistory(this.history.maxGeneration);
5026
hist.done = histData.done.slice(0);
5027
hist.undone = histData.undone.slice(0);
5028
},
5029
5030
markText: function(from, to, options) {
5031
return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
5032
},
5033
setBookmark: function(pos, options) {
5034
var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
5035
insertLeft: options && options.insertLeft,
5036
clearWhenEmpty: false};
5037
pos = clipPos(this, pos);
5038
return markText(this, pos, pos, realOpts, "bookmark");
5039
},
5040
findMarksAt: function(pos) {
5041
pos = clipPos(this, pos);
5042
var markers = [], spans = getLine(this, pos.line).markedSpans;
5043
if (spans) for (var i = 0; i < spans.length; ++i) {
5044
var span = spans[i];
5045
if ((span.from == null || span.from <= pos.ch) &&
5046
(span.to == null || span.to >= pos.ch))
5047
markers.push(span.marker.parent || span.marker);
5048
}
5049
return markers;
5050
},
5051
getAllMarks: function() {
5052
var markers = [];
5053
this.iter(function(line) {
5054
var sps = line.markedSpans;
5055
if (sps) for (var i = 0; i < sps.length; ++i)
5056
if (sps[i].from != null) markers.push(sps[i].marker);
5057
});
5058
return markers;
5059
},
5060
5061
posFromIndex: function(off) {
5062
var ch, lineNo = this.first;
5063
this.iter(function(line) {
5064
var sz = line.text.length + 1;
5065
if (sz > off) { ch = off; return true; }
5066
off -= sz;
5067
++lineNo;
5068
});
5069
return clipPos(this, Pos(lineNo, ch));
5070
},
5071
indexFromPos: function (coords) {
5072
coords = clipPos(this, coords);
5073
var index = coords.ch;
5074
if (coords.line < this.first || coords.ch < 0) return 0;
5075
this.iter(this.first, coords.line, function (line) {
5076
index += line.text.length + 1;
5077
});
5078
return index;
5079
},
5080
5081
copy: function(copyHistory) {
5082
var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
5083
doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
5084
doc.sel = {from: this.sel.from, to: this.sel.to, head: this.sel.head, anchor: this.sel.anchor,
5085
shift: this.sel.shift, extend: false, goalColumn: this.sel.goalColumn};
5086
if (copyHistory) {
5087
doc.history.undoDepth = this.history.undoDepth;
5088
doc.setHistory(this.getHistory());
5089
}
5090
return doc;
5091
},
5092
5093
linkedDoc: function(options) {
5094
if (!options) options = {};
5095
var from = this.first, to = this.first + this.size;
5096
if (options.from != null && options.from > from) from = options.from;
5097
if (options.to != null && options.to < to) to = options.to;
5098
var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
5099
if (options.sharedHist) copy.history = this.history;
5100
(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
5101
copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
5102
return copy;
5103
},
5104
unlinkDoc: function(other) {
5105
if (other instanceof CodeMirror) other = other.doc;
5106
if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
5107
var link = this.linked[i];
5108
if (link.doc != other) continue;
5109
this.linked.splice(i, 1);
5110
other.unlinkDoc(this);
5111
break;
5112
}
5113
// If the histories were shared, split them again
5114
if (other.history == this.history) {
5115
var splitIds = [other.id];
5116
linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
5117
other.history = makeHistory();
5118
other.history.done = copyHistoryArray(this.history.done, splitIds);
5119
other.history.undone = copyHistoryArray(this.history.undone, splitIds);
5120
}
5121
},
5122
iterLinkedDocs: function(f) {linkedDocs(this, f);},
5123
5124
getMode: function() {return this.mode;},
5125
getEditor: function() {return this.cm;}
5126
});
5127
5128
Doc.prototype.eachLine = Doc.prototype.iter;
5129
5130
// The Doc methods that should be available on CodeMirror instances
5131
var dontDelegate = "iter insert remove copy getEditor".split(" ");
5132
for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
5133
CodeMirror.prototype[prop] = (function(method) {
5134
return function() {return method.apply(this.doc, arguments);};
5135
})(Doc.prototype[prop]);
5136
5137
eventMixin(Doc);
5138
5139
function linkedDocs(doc, f, sharedHistOnly) {
5140
function propagate(doc, skip, sharedHist) {
5141
if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
5142
var rel = doc.linked[i];
5143
if (rel.doc == skip) continue;
5144
var shared = sharedHist && rel.sharedHist;
5145
if (sharedHistOnly && !shared) continue;
5146
f(rel.doc, shared);
5147
propagate(rel.doc, doc, shared);
5148
}
5149
}
5150
propagate(doc, null, true);
5151
}
5152
5153
function attachDoc(cm, doc) {
5154
if (doc.cm) throw new Error("This document is already in use.");
5155
cm.doc = doc;
5156
doc.cm = cm;
5157
estimateLineHeights(cm);
5158
loadMode(cm);
5159
if (!cm.options.lineWrapping) computeMaxLength(cm);
5160
cm.options.mode = doc.modeOption;
5161
regChange(cm);
5162
}
5163
5164
// LINE UTILITIES
5165
5166
function getLine(chunk, n) {
5167
n -= chunk.first;
5168
while (!chunk.lines) {
5169
for (var i = 0;; ++i) {
5170
var child = chunk.children[i], sz = child.chunkSize();
5171
if (n < sz) { chunk = child; break; }
5172
n -= sz;
5173
}
5174
}
5175
return chunk.lines[n];
5176
}
5177
5178
function getBetween(doc, start, end) {
5179
var out = [], n = start.line;
5180
doc.iter(start.line, end.line + 1, function(line) {
5181
var text = line.text;
5182
if (n == end.line) text = text.slice(0, end.ch);
5183
if (n == start.line) text = text.slice(start.ch);
5184
out.push(text);
5185
++n;
5186
});
5187
return out;
5188
}
5189
function getLines(doc, from, to) {
5190
var out = [];
5191
doc.iter(from, to, function(line) { out.push(line.text); });
5192
return out;
5193
}
5194
5195
function updateLineHeight(line, height) {
5196
var diff = height - line.height;
5197
for (var n = line; n; n = n.parent) n.height += diff;
5198
}
5199
5200
function lineNo(line) {
5201
if (line.parent == null) return null;
5202
var cur = line.parent, no = indexOf(cur.lines, line);
5203
for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
5204
for (var i = 0;; ++i) {
5205
if (chunk.children[i] == cur) break;
5206
no += chunk.children[i].chunkSize();
5207
}
5208
}
5209
return no + cur.first;
5210
}
5211
5212
function lineAtHeight(chunk, h) {
5213
var n = chunk.first;
5214
outer: do {
5215
for (var i = 0, e = chunk.children.length; i < e; ++i) {
5216
var child = chunk.children[i], ch = child.height;
5217
if (h < ch) { chunk = child; continue outer; }
5218
h -= ch;
5219
n += child.chunkSize();
5220
}
5221
return n;
5222
} while (!chunk.lines);
5223
for (var i = 0, e = chunk.lines.length; i < e; ++i) {
5224
var line = chunk.lines[i], lh = line.height;
5225
if (h < lh) break;
5226
h -= lh;
5227
}
5228
return n + i;
5229
}
5230
5231
function heightAtLine(cm, lineObj) {
5232
lineObj = visualLine(cm.doc, lineObj);
5233
5234
var h = 0, chunk = lineObj.parent;
5235
for (var i = 0; i < chunk.lines.length; ++i) {
5236
var line = chunk.lines[i];
5237
if (line == lineObj) break;
5238
else h += line.height;
5239
}
5240
for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
5241
for (var i = 0; i < p.children.length; ++i) {
5242
var cur = p.children[i];
5243
if (cur == chunk) break;
5244
else h += cur.height;
5245
}
5246
}
5247
return h;
5248
}
5249
5250
function getOrder(line) {
5251
var order = line.order;
5252
if (order == null) order = line.order = bidiOrdering(line.text);
5253
return order;
5254
}
5255
5256
// HISTORY
5257
5258
function makeHistory(startGen) {
5259
return {
5260
// Arrays of history events. Doing something adds an event to
5261
// done and clears undo. Undoing moves events from done to
5262
// undone, redoing moves them in the other direction.
5263
done: [], undone: [], undoDepth: Infinity,
5264
// Used to track when changes can be merged into a single undo
5265
// event
5266
lastTime: 0, lastOp: null, lastOrigin: null,
5267
// Used by the isClean() method
5268
generation: startGen || 1, maxGeneration: startGen || 1
5269
};
5270
}
5271
5272
function attachLocalSpans(doc, change, from, to) {
5273
var existing = change["spans_" + doc.id], n = 0;
5274
doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
5275
if (line.markedSpans)
5276
(existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
5277
++n;
5278
});
5279
}
5280
5281
function historyChangeFromChange(doc, change) {
5282
var from = { line: change.from.line, ch: change.from.ch };
5283
var histChange = {from: from, to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
5284
attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
5285
linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
5286
return histChange;
5287
}
5288
5289
function addToHistory(doc, change, selAfter, opId) {
5290
var hist = doc.history;
5291
hist.undone.length = 0;
5292
var time = +new Date, cur = lst(hist.done);
5293
5294
if (cur &&
5295
(hist.lastOp == opId ||
5296
hist.lastOrigin == change.origin && change.origin &&
5297
((change.origin.charAt(0) == "+" && doc.cm && hist.lastTime > time - doc.cm.options.historyEventDelay) ||
5298
change.origin.charAt(0) == "*"))) {
5299
// Merge this change into the last event
5300
var last = lst(cur.changes);
5301
if (posEq(change.from, change.to) && posEq(change.from, last.to)) {
5302
// Optimized case for simple insertion -- don't want to add
5303
// new changesets for every character typed
5304
last.to = changeEnd(change);
5305
} else {
5306
// Add new sub-event
5307
cur.changes.push(historyChangeFromChange(doc, change));
5308
}
5309
cur.anchorAfter = selAfter.anchor; cur.headAfter = selAfter.head;
5310
} else {
5311
// Can not be merged, start a new event.
5312
cur = {changes: [historyChangeFromChange(doc, change)],
5313
generation: hist.generation,
5314
anchorBefore: doc.sel.anchor, headBefore: doc.sel.head,
5315
anchorAfter: selAfter.anchor, headAfter: selAfter.head};
5316
hist.done.push(cur);
5317
while (hist.done.length > hist.undoDepth)
5318
hist.done.shift();
5319
}
5320
hist.generation = ++hist.maxGeneration;
5321
hist.lastTime = time;
5322
hist.lastOp = opId;
5323
hist.lastOrigin = change.origin;
5324
}
5325
5326
function removeClearedSpans(spans) {
5327
if (!spans) return null;
5328
for (var i = 0, out; i < spans.length; ++i) {
5329
if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
5330
else if (out) out.push(spans[i]);
5331
}
5332
return !out ? spans : out.length ? out : null;
5333
}
5334
5335
function getOldSpans(doc, change) {
5336
var found = change["spans_" + doc.id];
5337
if (!found) return null;
5338
for (var i = 0, nw = []; i < change.text.length; ++i)
5339
nw.push(removeClearedSpans(found[i]));
5340
return nw;
5341
}
5342
5343
// Used both to provide a JSON-safe object in .getHistory, and, when
5344
// detaching a document, to split the history in two
5345
function copyHistoryArray(events, newGroup) {
5346
for (var i = 0, copy = []; i < events.length; ++i) {
5347
var event = events[i], changes = event.changes, newChanges = [];
5348
copy.push({changes: newChanges, anchorBefore: event.anchorBefore, headBefore: event.headBefore,
5349
anchorAfter: event.anchorAfter, headAfter: event.headAfter});
5350
for (var j = 0; j < changes.length; ++j) {
5351
var change = changes[j], m;
5352
newChanges.push({from: change.from, to: change.to, text: change.text});
5353
if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
5354
if (indexOf(newGroup, Number(m[1])) > -1) {
5355
lst(newChanges)[prop] = change[prop];
5356
delete change[prop];
5357
}
5358
}
5359
}
5360
}
5361
return copy;
5362
}
5363
5364
// Rebasing/resetting history to deal with externally-sourced changes
5365
5366
function rebaseHistSel(pos, from, to, diff) {
5367
if (to < pos.line) {
5368
pos.line += diff;
5369
} else if (from < pos.line) {
5370
pos.line = from;
5371
pos.ch = 0;
5372
}
5373
}
5374
5375
// Tries to rebase an array of history events given a change in the
5376
// document. If the change touches the same lines as the event, the
5377
// event, and everything 'behind' it, is discarded. If the change is
5378
// before the event, the event's positions are updated. Uses a
5379
// copy-on-write scheme for the positions, to avoid having to
5380
// reallocate them all on every rebase, but also avoid problems with
5381
// shared position objects being unsafely updated.
5382
function rebaseHistArray(array, from, to, diff) {
5383
for (var i = 0; i < array.length; ++i) {
5384
var sub = array[i], ok = true;
5385
for (var j = 0; j < sub.changes.length; ++j) {
5386
var cur = sub.changes[j];
5387
if (!sub.copied) { cur.from = copyPos(cur.from); cur.to = copyPos(cur.to); }
5388
if (to < cur.from.line) {
5389
cur.from.line += diff;
5390
cur.to.line += diff;
5391
} else if (from <= cur.to.line) {
5392
ok = false;
5393
break;
5394
}
5395
}
5396
if (!sub.copied) {
5397
sub.anchorBefore = copyPos(sub.anchorBefore); sub.headBefore = copyPos(sub.headBefore);
5398
sub.anchorAfter = copyPos(sub.anchorAfter); sub.readAfter = copyPos(sub.headAfter);
5399
sub.copied = true;
5400
}
5401
if (!ok) {
5402
array.splice(0, i + 1);
5403
i = 0;
5404
} else {
5405
rebaseHistSel(sub.anchorBefore); rebaseHistSel(sub.headBefore);
5406
rebaseHistSel(sub.anchorAfter); rebaseHistSel(sub.headAfter);
5407
}
5408
}
5409
}
5410
5411
function rebaseHist(hist, change) {
5412
var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
5413
rebaseHistArray(hist.done, from, to, diff);
5414
rebaseHistArray(hist.undone, from, to, diff);
5415
}
5416
5417
// EVENT OPERATORS
5418
5419
function stopMethod() {e_stop(this);}
5420
// Ensure an event has a stop method.
5421
function addStop(event) {
5422
if (!event.stop) event.stop = stopMethod;
5423
return event;
5424
}
5425
5426
function e_preventDefault(e) {
5427
if (e.preventDefault) e.preventDefault();
5428
else e.returnValue = false;
5429
}
5430
function e_stopPropagation(e) {
5431
if (e.stopPropagation) e.stopPropagation();
5432
else e.cancelBubble = true;
5433
}
5434
function e_defaultPrevented(e) {
5435
return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
5436
}
5437
function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
5438
CodeMirror.e_stop = e_stop;
5439
CodeMirror.e_preventDefault = e_preventDefault;
5440
CodeMirror.e_stopPropagation = e_stopPropagation;
5441
5442
function e_target(e) {return e.target || e.srcElement;}
5443
function e_button(e) {
5444
var b = e.which;
5445
if (b == null) {
5446
if (e.button & 1) b = 1;
5447
else if (e.button & 2) b = 3;
5448
else if (e.button & 4) b = 2;
5449
}
5450
if (mac && e.ctrlKey && b == 1) b = 3;
5451
return b;
5452
}
5453
5454
// EVENT HANDLING
5455
5456
function on(emitter, type, f) {
5457
if (emitter.addEventListener)
5458
emitter.addEventListener(type, f, false);
5459
else if (emitter.attachEvent)
5460
emitter.attachEvent("on" + type, f);
5461
else {
5462
var map = emitter._handlers || (emitter._handlers = {});
5463
var arr = map[type] || (map[type] = []);
5464
arr.push(f);
5465
}
5466
}
5467
5468
function off(emitter, type, f) {
5469
if (emitter.removeEventListener)
5470
emitter.removeEventListener(type, f, false);
5471
else if (emitter.detachEvent)
5472
emitter.detachEvent("on" + type, f);
5473
else {
5474
var arr = emitter._handlers && emitter._handlers[type];
5475
if (!arr) return;
5476
for (var i = 0; i < arr.length; ++i)
5477
if (arr[i] == f) { arr.splice(i, 1); break; }
5478
}
5479
}
5480
5481
function signal(emitter, type /*, values...*/) {
5482
var arr = emitter._handlers && emitter._handlers[type];
5483
if (!arr) return;
5484
var args = Array.prototype.slice.call(arguments, 2);
5485
for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
5486
}
5487
5488
var delayedCallbacks, delayedCallbackDepth = 0;
5489
function signalLater(emitter, type /*, values...*/) {
5490
var arr = emitter._handlers && emitter._handlers[type];
5491
if (!arr) return;
5492
var args = Array.prototype.slice.call(arguments, 2);
5493
if (!delayedCallbacks) {
5494
++delayedCallbackDepth;
5495
delayedCallbacks = [];
5496
setTimeout(fireDelayed, 0);
5497
}
5498
function bnd(f) {return function(){f.apply(null, args);};};
5499
for (var i = 0; i < arr.length; ++i)
5500
delayedCallbacks.push(bnd(arr[i]));
5501
}
5502
5503
function signalDOMEvent(cm, e, override) {
5504
signal(cm, override || e.type, cm, e);
5505
return e_defaultPrevented(e) || e.codemirrorIgnore;
5506
}
5507
5508
function fireDelayed() {
5509
--delayedCallbackDepth;
5510
var delayed = delayedCallbacks;
5511
delayedCallbacks = null;
5512
for (var i = 0; i < delayed.length; ++i) delayed[i]();
5513
}
5514
5515
function hasHandler(emitter, type) {
5516
var arr = emitter._handlers && emitter._handlers[type];
5517
return arr && arr.length > 0;
5518
}
5519
5520
CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal;
5521
5522
function eventMixin(ctor) {
5523
ctor.prototype.on = function(type, f) {on(this, type, f);};
5524
ctor.prototype.off = function(type, f) {off(this, type, f);};
5525
}
5526
5527
// MISC UTILITIES
5528
5529
// Number of pixels added to scroller and sizer to hide scrollbar
5530
var scrollerCutOff = 30;
5531
5532
// Returned or thrown by various protocols to signal 'I'm not
5533
// handling this'.
5534
var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
5535
5536
function Delayed() {this.id = null;}
5537
Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
5538
5539
// Counts the column offset in a string, taking tabs into account.
5540
// Used mostly to find indentation.
5541
function countColumn(string, end, tabSize, startIndex, startValue) {
5542
if (end == null) {
5543
end = string.search(/[^\s\u00a0]/);
5544
if (end == -1) end = string.length;
5545
}
5546
for (var i = startIndex || 0, n = startValue || 0; i < end; ++i) {
5547
if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
5548
else ++n;
5549
}
5550
return n;
5551
}
5552
CodeMirror.countColumn = countColumn;
5553
5554
var spaceStrs = [""];
5555
function spaceStr(n) {
5556
while (spaceStrs.length <= n)
5557
spaceStrs.push(lst(spaceStrs) + " ");
5558
return spaceStrs[n];
5559
}
5560
5561
function lst(arr) { return arr[arr.length-1]; }
5562
5563
function selectInput(node) {
5564
if (ios) { // Mobile Safari apparently has a bug where select() is broken.
5565
node.selectionStart = 0;
5566
node.selectionEnd = node.value.length;
5567
} else {
5568
// Suppress mysterious IE10 errors
5569
try { node.select(); }
5570
catch(_e) {}
5571
}
5572
}
5573
5574
function indexOf(collection, elt) {
5575
if (collection.indexOf) return collection.indexOf(elt);
5576
for (var i = 0, e = collection.length; i < e; ++i)
5577
if (collection[i] == elt) return i;
5578
return -1;
5579
}
5580
5581
function createObj(base, props) {
5582
function Obj() {}
5583
Obj.prototype = base;
5584
var inst = new Obj();
5585
if (props) copyObj(props, inst);
5586
return inst;
5587
}
5588
5589
function copyObj(obj, target) {
5590
if (!target) target = {};
5591
for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
5592
return target;
5593
}
5594
5595
function emptyArray(size) {
5596
for (var a = [], i = 0; i < size; ++i) a.push(undefined);
5597
return a;
5598
}
5599
5600
function bind(f) {
5601
var args = Array.prototype.slice.call(arguments, 1);
5602
return function(){return f.apply(null, args);};
5603
}
5604
5605
var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
5606
function isWordChar(ch) {
5607
return /\w/.test(ch) || ch > "\x80" &&
5608
(ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
5609
}
5610
5611
function isEmpty(obj) {
5612
for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
5613
return true;
5614
}
5615
5616
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]/;
5617
function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
5618
5619
// DOM UTILITIES
5620
5621
function elt(tag, content, className, style) {
5622
var e = document.createElement(tag);
5623
if (className) e.className = className;
5624
if (style) e.style.cssText = style;
5625
if (typeof content == "string") setTextContent(e, content);
5626
else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
5627
return e;
5628
}
5629
5630
function removeChildren(e) {
5631
for (var count = e.childNodes.length; count > 0; --count)
5632
e.removeChild(e.firstChild);
5633
return e;
5634
}
5635
5636
function removeChildrenAndAdd(parent, e) {
5637
return removeChildren(parent).appendChild(e);
5638
}
5639
5640
function setTextContent(e, str) {
5641
if (ie_lt9) {
5642
e.innerHTML = "";
5643
e.appendChild(document.createTextNode(str));
5644
} else e.textContent = str;
5645
}
5646
5647
function getRect(node) {
5648
return node.getBoundingClientRect();
5649
}
5650
CodeMirror.replaceGetRect = function(f) { getRect = f; };
5651
5652
// FEATURE DETECTION
5653
5654
// Detect drag-and-drop
5655
var dragAndDrop = function() {
5656
// There is *some* kind of drag-and-drop support in IE6-8, but I
5657
// couldn't get it to work yet.
5658
if (ie_lt9) return false;
5659
var div = elt('div');
5660
return "draggable" in div || "dragDrop" in div;
5661
}();
5662
5663
// For a reason I have yet to figure out, some browsers disallow
5664
// word wrapping between certain characters *only* if a new inline
5665
// element is started between them. This makes it hard to reliably
5666
// measure the position of things, since that requires inserting an
5667
// extra span. This terribly fragile set of tests matches the
5668
// character combinations that suffer from this phenomenon on the
5669
// various browsers.
5670
function spanAffectsWrapping() { return false; }
5671
if (gecko) // Only for "$'"
5672
spanAffectsWrapping = function(str, i) {
5673
return str.charCodeAt(i - 1) == 36 && str.charCodeAt(i) == 39;
5674
};
5675
else if (safari && !/Version\/([6-9]|\d\d)\b/.test(navigator.userAgent))
5676
spanAffectsWrapping = function(str, i) {
5677
return /\-[^ \-?]|\?[^ !\'\"\),.\-\/:;\?\]\}]/.test(str.slice(i - 1, i + 1));
5678
};
5679
else if (webkit && /Chrome\/(?:29|[3-9]\d|\d\d\d)\./.test(navigator.userAgent))
5680
spanAffectsWrapping = function(str, i) {
5681
var code = str.charCodeAt(i - 1);
5682
return code >= 8208 && code <= 8212;
5683
};
5684
else if (webkit)
5685
spanAffectsWrapping = function(str, i) {
5686
if (i > 1 && str.charCodeAt(i - 1) == 45) {
5687
if (/\w/.test(str.charAt(i - 2)) && /[^\-?\.]/.test(str.charAt(i))) return true;
5688
if (i > 2 && /[\d\.,]/.test(str.charAt(i - 2)) && /[\d\.,]/.test(str.charAt(i))) return false;
5689
}
5690
return /[~!#%&*)=+}\]\\|\"\.>,:;][({[<]|-[^\-?\.\u2010-\u201f\u2026]|\?[\w~`@#$%\^&*(_=+{[|><]|\u2026[\w~`@#$%\^&*(_=+{[><]/.test(str.slice(i - 1, i + 1));
5691
};
5692
5693
var knownScrollbarWidth;
5694
function scrollbarWidth(measure) {
5695
if (knownScrollbarWidth != null) return knownScrollbarWidth;
5696
var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll");
5697
removeChildrenAndAdd(measure, test);
5698
if (test.offsetWidth)
5699
knownScrollbarWidth = test.offsetHeight - test.clientHeight;
5700
return knownScrollbarWidth || 0;
5701
}
5702
5703
var zwspSupported;
5704
function zeroWidthElement(measure) {
5705
if (zwspSupported == null) {
5706
var test = elt("span", "\u200b");
5707
removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
5708
if (measure.firstChild.offsetHeight != 0)
5709
zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_lt8;
5710
}
5711
if (zwspSupported) return elt("span", "\u200b");
5712
else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
5713
}
5714
5715
// See if "".split is the broken IE version, if so, provide an
5716
// alternative way to split lines.
5717
var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
5718
var pos = 0, result = [], l = string.length;
5719
while (pos <= l) {
5720
var nl = string.indexOf("\n", pos);
5721
if (nl == -1) nl = string.length;
5722
var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
5723
var rt = line.indexOf("\r");
5724
if (rt != -1) {
5725
result.push(line.slice(0, rt));
5726
pos += rt + 1;
5727
} else {
5728
result.push(line);
5729
pos = nl + 1;
5730
}
5731
}
5732
return result;
5733
} : function(string){return string.split(/\r\n?|\n/);};
5734
CodeMirror.splitLines = splitLines;
5735
5736
var hasSelection = window.getSelection ? function(te) {
5737
try { return te.selectionStart != te.selectionEnd; }
5738
catch(e) { return false; }
5739
} : function(te) {
5740
try {var range = te.ownerDocument.selection.createRange();}
5741
catch(e) {}
5742
if (!range || range.parentElement() != te) return false;
5743
return range.compareEndPoints("StartToEnd", range) != 0;
5744
};
5745
5746
var hasCopyEvent = (function() {
5747
var e = elt("div");
5748
if ("oncopy" in e) return true;
5749
e.setAttribute("oncopy", "return;");
5750
return typeof e.oncopy == 'function';
5751
})();
5752
5753
// KEY NAMING
5754
5755
var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
5756
19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
5757
36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
5758
46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete",
5759
173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
5760
221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
5761
63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"};
5762
CodeMirror.keyNames = keyNames;
5763
(function() {
5764
// Number keys
5765
for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
5766
// Alphabetic keys
5767
for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
5768
// Function keys
5769
for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
5770
})();
5771
5772
// BIDI HELPERS
5773
5774
function iterateBidiSections(order, from, to, f) {
5775
if (!order) return f(from, to, "ltr");
5776
var found = false;
5777
for (var i = 0; i < order.length; ++i) {
5778
var part = order[i];
5779
if (part.from < to && part.to > from || from == to && part.to == from) {
5780
f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
5781
found = true;
5782
}
5783
}
5784
if (!found) f(from, to, "ltr");
5785
}
5786
5787
function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
5788
function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
5789
5790
function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
5791
function lineRight(line) {
5792
var order = getOrder(line);
5793
if (!order) return line.text.length;
5794
return bidiRight(lst(order));
5795
}
5796
5797
function lineStart(cm, lineN) {
5798
var line = getLine(cm.doc, lineN);
5799
var visual = visualLine(cm.doc, line);
5800
if (visual != line) lineN = lineNo(visual);
5801
var order = getOrder(visual);
5802
var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
5803
return Pos(lineN, ch);
5804
}
5805
function lineEnd(cm, lineN) {
5806
var merged, line;
5807
while (merged = collapsedSpanAtEnd(line = getLine(cm.doc, lineN)))
5808
lineN = merged.find().to.line;
5809
var order = getOrder(line);
5810
var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
5811
return Pos(lineN, ch);
5812
}
5813
5814
function compareBidiLevel(order, a, b) {
5815
var linedir = order[0].level;
5816
if (a == linedir) return true;
5817
if (b == linedir) return false;
5818
return a < b;
5819
}
5820
var bidiOther;
5821
function getBidiPartAt(order, pos) {
5822
bidiOther = null;
5823
for (var i = 0, found; i < order.length; ++i) {
5824
var cur = order[i];
5825
if (cur.from < pos && cur.to > pos) return i;
5826
if ((cur.from == pos || cur.to == pos)) {
5827
if (found == null) {
5828
found = i;
5829
} else if (compareBidiLevel(order, cur.level, order[found].level)) {
5830
if (cur.from != cur.to) bidiOther = found;
5831
return i;
5832
} else {
5833
if (cur.from != cur.to) bidiOther = i;
5834
return found;
5835
}
5836
}
5837
}
5838
return found;
5839
}
5840
5841
function moveInLine(line, pos, dir, byUnit) {
5842
if (!byUnit) return pos + dir;
5843
do pos += dir;
5844
while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
5845
return pos;
5846
}
5847
5848
// This is somewhat involved. It is needed in order to move
5849
// 'visually' through bi-directional text -- i.e., pressing left
5850
// should make the cursor go left, even when in RTL text. The
5851
// tricky part is the 'jumps', where RTL and LTR text touch each
5852
// other. This often requires the cursor offset to move more than
5853
// one unit, in order to visually move one unit.
5854
function moveVisually(line, start, dir, byUnit) {
5855
var bidi = getOrder(line);
5856
if (!bidi) return moveLogically(line, start, dir, byUnit);
5857
var pos = getBidiPartAt(bidi, start), part = bidi[pos];
5858
var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
5859
5860
for (;;) {
5861
if (target > part.from && target < part.to) return target;
5862
if (target == part.from || target == part.to) {
5863
if (getBidiPartAt(bidi, target) == pos) return target;
5864
part = bidi[pos += dir];
5865
return (dir > 0) == part.level % 2 ? part.to : part.from;
5866
} else {
5867
part = bidi[pos += dir];
5868
if (!part) return null;
5869
if ((dir > 0) == part.level % 2)
5870
target = moveInLine(line, part.to, -1, byUnit);
5871
else
5872
target = moveInLine(line, part.from, 1, byUnit);
5873
}
5874
}
5875
}
5876
5877
function moveLogically(line, start, dir, byUnit) {
5878
var target = start + dir;
5879
if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
5880
return target < 0 || target > line.text.length ? null : target;
5881
}
5882
5883
// Bidirectional ordering algorithm
5884
// See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
5885
// that this (partially) implements.
5886
5887
// One-char codes used for character types:
5888
// L (L): Left-to-Right
5889
// R (R): Right-to-Left
5890
// r (AL): Right-to-Left Arabic
5891
// 1 (EN): European Number
5892
// + (ES): European Number Separator
5893
// % (ET): European Number Terminator
5894
// n (AN): Arabic Number
5895
// , (CS): Common Number Separator
5896
// m (NSM): Non-Spacing Mark
5897
// b (BN): Boundary Neutral
5898
// s (B): Paragraph Separator
5899
// t (S): Segment Separator
5900
// w (WS): Whitespace
5901
// N (ON): Other Neutrals
5902
5903
// Returns null if characters are ordered as they appear
5904
// (left-to-right), or an array of sections ({from, to, level}
5905
// objects) in the order in which they occur visually.
5906
var bidiOrdering = (function() {
5907
// Character types for codepoints 0 to 0xff
5908
var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL";
5909
// Character types for codepoints 0x600 to 0x6ff
5910
var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr";
5911
function charType(code) {
5912
if (code <= 0xff) return lowTypes.charAt(code);
5913
else if (0x590 <= code && code <= 0x5f4) return "R";
5914
else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600);
5915
else if (0x700 <= code && code <= 0x8ac) return "r";
5916
else return "L";
5917
}
5918
5919
var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
5920
var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
5921
// Browsers seem to always treat the boundaries of block elements as being L.
5922
var outerType = "L";
5923
5924
return function(str) {
5925
if (!bidiRE.test(str)) return false;
5926
var len = str.length, types = [];
5927
for (var i = 0, type; i < len; ++i)
5928
types.push(type = charType(str.charCodeAt(i)));
5929
5930
// W1. Examine each non-spacing mark (NSM) in the level run, and
5931
// change the type of the NSM to the type of the previous
5932
// character. If the NSM is at the start of the level run, it will
5933
// get the type of sor.
5934
for (var i = 0, prev = outerType; i < len; ++i) {
5935
var type = types[i];
5936
if (type == "m") types[i] = prev;
5937
else prev = type;
5938
}
5939
5940
// W2. Search backwards from each instance of a European number
5941
// until the first strong type (R, L, AL, or sor) is found. If an
5942
// AL is found, change the type of the European number to Arabic
5943
// number.
5944
// W3. Change all ALs to R.
5945
for (var i = 0, cur = outerType; i < len; ++i) {
5946
var type = types[i];
5947
if (type == "1" && cur == "r") types[i] = "n";
5948
else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
5949
}
5950
5951
// W4. A single European separator between two European numbers
5952
// changes to a European number. A single common separator between
5953
// two numbers of the same type changes to that type.
5954
for (var i = 1, prev = types[0]; i < len - 1; ++i) {
5955
var type = types[i];
5956
if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
5957
else if (type == "," && prev == types[i+1] &&
5958
(prev == "1" || prev == "n")) types[i] = prev;
5959
prev = type;
5960
}
5961
5962
// W5. A sequence of European terminators adjacent to European
5963
// numbers changes to all European numbers.
5964
// W6. Otherwise, separators and terminators change to Other
5965
// Neutral.
5966
for (var i = 0; i < len; ++i) {
5967
var type = types[i];
5968
if (type == ",") types[i] = "N";
5969
else if (type == "%") {
5970
for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
5971
var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
5972
for (var j = i; j < end; ++j) types[j] = replace;
5973
i = end - 1;
5974
}
5975
}
5976
5977
// W7. Search backwards from each instance of a European number
5978
// until the first strong type (R, L, or sor) is found. If an L is
5979
// found, then change the type of the European number to L.
5980
for (var i = 0, cur = outerType; i < len; ++i) {
5981
var type = types[i];
5982
if (cur == "L" && type == "1") types[i] = "L";
5983
else if (isStrong.test(type)) cur = type;
5984
}
5985
5986
// N1. A sequence of neutrals takes the direction of the
5987
// surrounding strong text if the text on both sides has the same
5988
// direction. European and Arabic numbers act as if they were R in
5989
// terms of their influence on neutrals. Start-of-level-run (sor)
5990
// and end-of-level-run (eor) are used at level run boundaries.
5991
// N2. Any remaining neutrals take the embedding direction.
5992
for (var i = 0; i < len; ++i) {
5993
if (isNeutral.test(types[i])) {
5994
for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
5995
var before = (i ? types[i-1] : outerType) == "L";
5996
var after = (end < len ? types[end] : outerType) == "L";
5997
var replace = before || after ? "L" : "R";
5998
for (var j = i; j < end; ++j) types[j] = replace;
5999
i = end - 1;
6000
}
6001
}
6002
6003
// Here we depart from the documented algorithm, in order to avoid
6004
// building up an actual levels array. Since there are only three
6005
// levels (0, 1, 2) in an implementation that doesn't take
6006
// explicit embedding into account, we can build up the order on
6007
// the fly, without following the level-based algorithm.
6008
var order = [], m;
6009
for (var i = 0; i < len;) {
6010
if (countsAsLeft.test(types[i])) {
6011
var start = i;
6012
for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
6013
order.push({from: start, to: i, level: 0});
6014
} else {
6015
var pos = i, at = order.length;
6016
for (++i; i < len && types[i] != "L"; ++i) {}
6017
for (var j = pos; j < i;) {
6018
if (countsAsNum.test(types[j])) {
6019
if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1});
6020
var nstart = j;
6021
for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
6022
order.splice(at, 0, {from: nstart, to: j, level: 2});
6023
pos = j;
6024
} else ++j;
6025
}
6026
if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1});
6027
}
6028
}
6029
if (order[0].level == 1 && (m = str.match(/^\s+/))) {
6030
order[0].from = m[0].length;
6031
order.unshift({from: 0, to: m[0].length, level: 0});
6032
}
6033
if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
6034
lst(order).to -= m[0].length;
6035
order.push({from: len - m[0].length, to: len, level: 0});
6036
}
6037
if (order[0].level != lst(order).level)
6038
order.push({from: len, to: len, level: order[0].level});
6039
6040
return order;
6041
};
6042
})();
6043
6044
// THE END
6045
6046
CodeMirror.version = "3.21.0";
6047
6048
return CodeMirror;
6049
})();
6050
6051