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