##// END OF EJS Templates
updated codemirror to 2.34
marcink -
r2861:f034e6a1 beta
parent child Browse files
Show More
@@ -9,8 +9,7
9 9 }
10 10
11 11 .CodeMirror-scroll {
12 overflow-x: auto;
13 overflow-y: hidden;
12 overflow: auto;
14 13 height: 300px;
15 14 /* This is needed to prevent an IE[67] bug where the scrolled content
16 15 is visible outside of the scrolling box. */
@@ -20,13 +19,11
20 19
21 20 /* Vertical scrollbar */
22 21 .CodeMirror-scrollbar {
23 float: right;
22 position: absolute;
23 right: 0; top: 0;
24 24 overflow-x: hidden;
25 25 overflow-y: scroll;
26
27 /* This corrects for the 1px gap introduced to the left of the scrollbar
28 by the rule for .CodeMirror-scrollbar-inner. */
29 margin-left: -1px;
26 z-index: 5;
30 27 }
31 28 .CodeMirror-scrollbar-inner {
32 29 /* This needs to have a nonzero width in order for the scrollbar to appear
@@ -62,16 +59,13
62 59 text-align: right;
63 60 padding: .4em .2em .4em .4em;
64 61 white-space: pre !important;
62 cursor: default;
65 63 }
66 64 .CodeMirror-lines {
67 65 padding: .4em;
68 66 white-space: pre;
69 67 cursor: text;
70 68 }
71 .CodeMirror-lines * {
72 /* Necessary for throw-scrolling to decelerate properly on Safari. */
73 pointer-events: none;
74 }
75 69
76 70 .CodeMirror pre {
77 71 -moz-border-radius: 0;
@@ -151,7 +145,7 div.CodeMirror-selected { background: #d
151 145 .cm-s-default span.cm-error {color: #f00;}
152 146 .cm-s-default span.cm-qualifier {color: #555;}
153 147 .cm-s-default span.cm-builtin {color: #30a;}
154 .cm-s-default span.cm-bracket {color: #cc7;}
148 .cm-s-default span.cm-bracket {color: #997;}
155 149 .cm-s-default span.cm-tag {color: #170;}
156 150 .cm-s-default span.cm-attribute {color: #00c;}
157 151 .cm-s-default span.cm-header {color: blue;}
@@ -164,5 +158,16 span.cm-em {font-style: italic;}
164 158 span.cm-emstrong {font-style: italic; font-weight: bold;}
165 159 span.cm-link {text-decoration: underline;}
166 160
161 span.cm-invalidchar {color: #f00;}
162
167 163 div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
168 164 div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
165
166 @media print {
167
168 /* Hide the cursor when printing */
169 .CodeMirror pre.CodeMirror-cursor {
170 visibility: hidden;
171 }
172
173 }
This diff has been collapsed as it changes many lines, (1598 lines changed) Show them Hide them
@@ -3,7 +3,8
3 3 // some utilities are defined.
4 4
5 5 // CodeMirror is the only global var we claim
6 var CodeMirror = (function() {
6 window.CodeMirror = (function() {
7 "use strict";
7 8 // This is the function that produces an editor instance. Its
8 9 // closure is used to store the editor state.
9 10 function CodeMirror(place, givenOptions) {
@@ -13,38 +14,33 var CodeMirror = (function() {
13 14 if (defaults.hasOwnProperty(opt))
14 15 options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt];
15 16
17 var input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em");
18 input.setAttribute("wrap", "off"); input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off");
19 // Wraps and hides input textarea
20 var inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
21 // The empty scrollbar content, used solely for managing the scrollbar thumb.
22 var scrollbarInner = elt("div", null, "CodeMirror-scrollbar-inner");
23 // The vertical scrollbar. Horizontal scrolling is handled by the scroller itself.
24 var scrollbar = elt("div", [scrollbarInner], "CodeMirror-scrollbar");
25 // DIVs containing the selection and the actual code
26 var lineDiv = elt("div"), selectionDiv = elt("div", null, null, "position: relative; z-index: -1");
27 // Blinky cursor, and element used to ensure cursor fits at the end of a line
28 var cursor = elt("pre", "\u00a0", "CodeMirror-cursor"), widthForcer = elt("pre", "\u00a0", "CodeMirror-cursor", "visibility: hidden");
29 // Used to measure text size
30 var measure = elt("div", null, null, "position: absolute; width: 100%; height: 0px; overflow: hidden; visibility: hidden;");
31 var lineSpace = elt("div", [measure, cursor, widthForcer, selectionDiv, lineDiv], null, "position: relative; z-index: 0");
32 var gutterText = elt("div", null, "CodeMirror-gutter-text"), gutter = elt("div", [gutterText], "CodeMirror-gutter");
33 // Moved around its parent to cover visible view
34 var mover = elt("div", [gutter, elt("div", [lineSpace], "CodeMirror-lines")], null, "position: relative");
35 // Set to the height of the text, causes scrolling
36 var sizer = elt("div", [mover], null, "position: relative");
37 // Provides scrolling
38 var scroller = elt("div", [sizer], "CodeMirror-scroll");
39 scroller.setAttribute("tabIndex", "-1");
16 40 // The element in which the editor lives.
17 var wrapper = document.createElement("div");
18 wrapper.className = "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : "");
19 // This mess creates the base DOM structure for the editor.
20 wrapper.innerHTML =
21 '<div style="overflow: hidden; position: relative; width: 3px; height: 0px;">' + // Wraps and hides input textarea
22 '<textarea style="position: absolute; padding: 0; width: 1px; height: 1em" wrap="off" ' +
23 'autocorrect="off" autocapitalize="off"></textarea></div>' +
24 '<div class="CodeMirror-scrollbar">' + // The vertical scrollbar. Horizontal scrolling is handled by the scroller itself.
25 '<div class="CodeMirror-scrollbar-inner">' + // The empty scrollbar content, used solely for managing the scrollbar thumb.
26 '</div></div>' + // This must be before the scroll area because it's float-right.
27 '<div class="CodeMirror-scroll" tabindex="-1">' +
28 '<div style="position: relative">' + // Set to the height of the text, causes scrolling
29 '<div style="position: relative">' + // Moved around its parent to cover visible view
30 '<div class="CodeMirror-gutter"><div class="CodeMirror-gutter-text"></div></div>' +
31 // Provides positioning relative to (visible) text origin
32 '<div class="CodeMirror-lines"><div style="position: relative; z-index: 0">' +
33 // Used to measure text size
34 '<div style="position: absolute; width: 100%; height: 0; overflow: hidden; visibility: hidden;"></div>' +
35 '<pre class="CodeMirror-cursor">&#160;</pre>' + // Absolutely positioned blinky cursor
36 '<pre class="CodeMirror-cursor" style="visibility: hidden">&#160;</pre>' + // Used to force a width
37 '<div style="position: relative; z-index: -1"></div><div></div>' + // DIVs containing the selection and the actual code
38 '</div></div></div></div></div>';
41 var wrapper = elt("div", [inputDiv, scrollbar, scroller], "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : ""));
39 42 if (place.appendChild) place.appendChild(wrapper); else place(wrapper);
40 // I've never seen more elegant code in my life.
41 var inputDiv = wrapper.firstChild, input = inputDiv.firstChild,
42 scroller = wrapper.lastChild, code = scroller.firstChild,
43 mover = code.firstChild, gutter = mover.firstChild, gutterText = gutter.firstChild,
44 lineSpace = gutter.nextSibling.firstChild, measure = lineSpace.firstChild,
45 cursor = measure.nextSibling, widthForcer = cursor.nextSibling,
46 selectionDiv = widthForcer.nextSibling, lineDiv = selectionDiv.nextSibling,
47 scrollbar = inputDiv.nextSibling, scrollbarInner = scrollbar.firstChild;
43
48 44 themeChanged(); keyMapChanged();
49 45 // Needed to hide big blue blinking cursor on Mobile Safari
50 46 if (ios) input.style.width = "0px";
@@ -56,33 +52,21 var CodeMirror = (function() {
56 52 // Needed to handle Tab key in KHTML
57 53 if (khtml) inputDiv.style.height = "1px", inputDiv.style.position = "absolute";
58 54
59 // Check for OS X >= 10.7. If so, we need to force a width on the scrollbar, and
60 // make it overlap the content. (But we only do this if the scrollbar doesn't already
61 // have a natural width. If the mouse is plugged in or the user sets the system pref
62 // to always show scrollbars, the scrollbar shouldn't overlap.)
63 if (mac_geLion) {
64 scrollbar.className += (overlapScrollbars() ? " cm-sb-overlap" : " cm-sb-nonoverlap");
65 } else if (ie_lt8) {
55 // Check for OS X >= 10.7. This has transparent scrollbars, so the
56 // overlaying of one scrollbar with another won't work. This is a
57 // temporary hack to simply turn off the overlay scrollbar. See
58 // issue #727.
59 if (mac_geLion) { scrollbar.style.zIndex = -2; scrollbar.style.visibility = "hidden"; }
66 60 // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
67 scrollbar.className += " cm-sb-ie7";
68 }
69
70 // Check for problem with IE innerHTML not working when we have a
71 // P (or similar) parent node.
72 try { stringWidth("x"); }
73 catch (e) {
74 if (e.message.match(/runtime/i))
75 e = new Error("A CodeMirror inside a P-style element does not work in Internet Explorer. (innerHTML bug)");
76 throw e;
77 }
61 else if (ie_lt8) scrollbar.style.minWidth = "18px";
78 62
79 63 // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval.
80 64 var poll = new Delayed(), highlight = new Delayed(), blinker;
81 65
82 66 // mode holds a mode API object. doc is the tree of Line objects,
83 // work an array of lines that should be parsed, and history the
84 // undo history (instance of History constructor).
85 var mode, doc = new BranchChunk([new LeafChunk([new Line("")])]), work, focused;
67 // frontier is the point up to which the content has been parsed,
68 // and history the undo history (instance of History constructor).
69 var mode, doc = new BranchChunk([new LeafChunk([new Line("")])]), frontier = 0, focused;
86 70 loadMode();
87 71 // The selection. These are always maintained to point at valid
88 72 // positions. Inverted is used to remember that the user is
@@ -90,11 +74,11 var CodeMirror = (function() {
90 74 var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false};
91 75 // Selection-related flags. shiftSelecting obviously tracks
92 76 // whether the user is holding shift.
93 var shiftSelecting, lastClick, lastDoubleClick, lastScrollTop = 0, lastScrollLeft = 0, draggingText,
77 var shiftSelecting, lastClick, lastDoubleClick, lastScrollTop = 0, draggingText,
94 78 overwrite = false, suppressEdits = false;
95 79 // Variables used by startOperation/endOperation to track what
96 80 // happened during the operation.
97 var updateInput, userSelChange, changes, textChanged, selectionChanged, leaveInputAlone,
81 var updateInput, userSelChange, changes, textChanged, selectionChanged,
98 82 gutterDirty, callbacks;
99 83 // Current visible range (may be bigger than the view window).
100 84 var displayOffset = 0, showingFrom = 0, showingTo = 0, lastSizeC = 0;
@@ -103,8 +87,9 var CodeMirror = (function() {
103 87 var bracketHighlighted;
104 88 // Tracks the maximum line length so that the horizontal scrollbar
105 89 // can be kept static when scrolling.
106 var maxLine = "", updateMaxLine = false, maxLineChanged = true;
107 var tabCache = {};
90 var maxLine = getLine(0), updateMaxLine = false, maxLineChanged = true;
91 var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll
92 var goalColumn = null;
108 93
109 94 // Initialize the content.
110 95 operation(function(){setValue(options.value || ""); updateInput = false;})();
@@ -118,12 +103,13 var CodeMirror = (function() {
118 103 // which point we can't mess with it anymore. Context menu is
119 104 // handled in onMouseDown for Gecko.
120 105 if (!gecko) connect(scroller, "contextmenu", onContextMenu);
121 connect(scroller, "scroll", onScroll);
122 connect(scrollbar, "scroll", onScroll);
123 connect(scrollbar, "mousedown", function() {setTimeout(focusInput, 0);});
124 connect(scroller, "mousewheel", onMouseWheel);
125 connect(scroller, "DOMMouseScroll", onMouseWheel);
126 connect(window, "resize", function() {updateDisplay(true);});
106 connect(scroller, "scroll", onScrollMain);
107 connect(scrollbar, "scroll", onScrollBar);
108 connect(scrollbar, "mousedown", function() {if (focused) setTimeout(focusInput, 0);});
109 var resizeHandler = connect(window, "resize", function() {
110 if (wrapper.parentNode) updateDisplay(true);
111 else resizeHandler();
112 }, true);
127 113 connect(input, "keyup", operation(onKeyUp));
128 114 connect(input, "input", fastPoll);
129 115 connect(input, "keydown", operation(onKeyDown));
@@ -131,12 +117,12 var CodeMirror = (function() {
131 117 connect(input, "focus", onFocus);
132 118 connect(input, "blur", onBlur);
133 119
134 if (options.dragDrop) {
135 connect(scroller, "dragstart", onDragStart);
136 120 function drag_(e) {
137 121 if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return;
138 122 e_stop(e);
139 123 }
124 if (options.dragDrop) {
125 connect(scroller, "dragstart", onDragStart);
140 126 connect(scroller, "dragenter", drag_);
141 127 connect(scroller, "dragover", drag_);
142 128 connect(scroller, "drop", operation(onDrop));
@@ -148,7 +134,7 var CodeMirror = (function() {
148 134 }));
149 135
150 136 // Needed to handle Tab key in KHTML
151 if (khtml) connect(code, "mouseup", function() {
137 if (khtml) connect(sizer, "mouseup", function() {
152 138 if (document.activeElement == input) input.blur();
153 139 focusInput();
154 140 });
@@ -181,12 +167,14 var CodeMirror = (function() {
181 167 else if (option == "lineWrapping" && oldVal != value) operation(wrappingChanged)();
182 168 else if (option == "tabSize") updateDisplay(true);
183 169 else if (option == "keyMap") keyMapChanged();
184 if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" || option == "theme") {
170 if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" ||
171 option == "theme" || option == "lineNumberFormatter") {
185 172 gutterChanged();
186 173 updateDisplay(true);
187 174 }
188 175 },
189 176 getOption: function(option) {return options[option];},
177 getMode: function() {return mode;},
190 178 undo: operation(undo),
191 179 redo: operation(redo),
192 180 indentLine: operation(function(n, dir) {
@@ -199,10 +187,29 var CodeMirror = (function() {
199 187 indentSelection: operation(indentSelected),
200 188 historySize: function() {return {undo: history.done.length, redo: history.undone.length};},
201 189 clearHistory: function() {history = new History();},
190 setHistory: function(histData) {
191 history = new History();
192 history.done = histData.done;
193 history.undone = histData.undone;
194 },
195 getHistory: function() {
196 function cp(arr) {
197 for (var i = 0, nw = [], nwelt; i < arr.length; ++i) {
198 nw.push(nwelt = []);
199 for (var j = 0, elt = arr[i]; j < elt.length; ++j) {
200 var old = [], cur = elt[j];
201 nwelt.push({start: cur.start, added: cur.added, old: old});
202 for (var k = 0; k < cur.old.length; ++k) old.push(hlText(cur.old[k]));
203 }
204 }
205 return nw;
206 }
207 return {done: cp(history.done), undone: cp(history.undone)};
208 },
202 209 matchBrackets: operation(function(){matchBrackets(true);}),
203 210 getTokenAt: operation(function(pos) {
204 211 pos = clipPos(pos);
205 return getLine(pos.line).getTokenAt(mode, getStateBefore(pos.line), pos.ch);
212 return getLine(pos.line).getTokenAt(mode, getStateBefore(pos.line), options.tabSize, pos.ch);
206 213 }),
207 214 getStateAfter: function(line) {
208 215 line = clipLine(line == null ? doc.size - 1: line);
@@ -239,15 +246,16 var CodeMirror = (function() {
239 246 return line;
240 247 },
241 248 lineInfo: lineInfo,
249 getViewport: function() { return {from: showingFrom, to: showingTo};},
242 250 addWidget: function(pos, node, scroll, vert, horiz) {
243 251 pos = localCoords(clipPos(pos));
244 252 var top = pos.yBot, left = pos.x;
245 253 node.style.position = "absolute";
246 code.appendChild(node);
254 sizer.appendChild(node);
247 255 if (vert == "over") top = pos.y;
248 256 else if (vert == "near") {
249 257 var vspace = Math.max(scroller.offsetHeight, doc.height * textHeight()),
250 hspace = Math.max(code.clientWidth, lineSpace.clientWidth) - paddingLeft();
258 hspace = Math.max(sizer.clientWidth, lineSpace.clientWidth) - paddingLeft();
251 259 if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight)
252 260 top = pos.y - node.offsetHeight;
253 261 if (left + node.offsetWidth > hspace)
@@ -256,11 +264,11 var CodeMirror = (function() {
256 264 node.style.top = (top + paddingTop()) + "px";
257 265 node.style.left = node.style.right = "";
258 266 if (horiz == "right") {
259 left = code.clientWidth - node.offsetWidth;
267 left = sizer.clientWidth - node.offsetWidth;
260 268 node.style.right = "0px";
261 269 } else {
262 270 if (horiz == "left") left = 0;
263 else if (horiz == "middle") left = (code.clientWidth - node.offsetWidth) / 2;
271 else if (horiz == "middle") left = (sizer.clientWidth - node.offsetWidth) / 2;
264 272 node.style.left = (left + paddingLeft()) + "px";
265 273 }
266 274 if (scroll)
@@ -290,7 +298,7 var CodeMirror = (function() {
290 298 if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0}));
291 299 }),
292 300 replaceRange: operation(replaceRange),
293 getRange: function(from, to) {return getRange(clipPos(from), clipPos(to));},
301 getRange: function(from, to, lineSep) {return getRange(clipPos(from), clipPos(to), lineSep);},
294 302
295 303 triggerOnKeyDown: operation(onKeyDown),
296 304 execCommand: function(cmd) {return commands[cmd](instance);},
@@ -328,18 +336,27 var CodeMirror = (function() {
328 336 },
329 337 scrollTo: function(x, y) {
330 338 if (x != null) scroller.scrollLeft = x;
331 if (y != null) scrollbar.scrollTop = y;
339 if (y != null) scrollbar.scrollTop = scroller.scrollTop = y;
332 340 updateDisplay([]);
333 341 },
334 342 getScrollInfo: function() {
335 343 return {x: scroller.scrollLeft, y: scrollbar.scrollTop,
336 344 height: scrollbar.scrollHeight, width: scroller.scrollWidth};
337 345 },
346 setSize: function(width, height) {
347 function interpret(val) {
348 val = String(val);
349 return /^\d+$/.test(val) ? val + "px" : val;
350 }
351 if (width != null) wrapper.style.width = interpret(width);
352 if (height != null) scroller.style.height = interpret(height);
353 instance.refresh();
354 },
338 355
339 356 operation: function(f){return operation(f)();},
340 357 compoundChange: function(f){return compoundChange(f);},
341 358 refresh: function(){
342 updateDisplay(true);
359 updateDisplay(true, null, lastScrollTop);
343 360 if (scrollbar.scrollHeight > lastScrollTop)
344 361 scrollbar.scrollTop = lastScrollTop;
345 362 },
@@ -356,33 +373,48 var CodeMirror = (function() {
356 373 for (var n = line; n; n = n.parent) n.height += diff;
357 374 }
358 375
376 function lineContent(line, wrapAt) {
377 if (!line.styles)
378 line.highlight(mode, line.stateAfter = getStateBefore(lineNo(line)), options.tabSize);
379 return line.getContent(options.tabSize, wrapAt, options.lineWrapping);
380 }
381
359 382 function setValue(code) {
360 383 var top = {line: 0, ch: 0};
361 384 updateLines(top, {line: doc.size - 1, ch: getLine(doc.size-1).text.length},
362 385 splitLines(code), top, top);
363 386 updateInput = true;
364 387 }
365 function getValue() {
388 function getValue(lineSep) {
366 389 var text = [];
367 390 doc.iter(0, doc.size, function(line) { text.push(line.text); });
368 return text.join("\n");
391 return text.join(lineSep || "\n");
369 392 }
370 393
371 function onScroll(e) {
372 if (lastScrollTop != scrollbar.scrollTop || lastScrollLeft != scroller.scrollLeft) {
373 lastScrollTop = scrollbar.scrollTop;
374 lastScrollLeft = scroller.scrollLeft;
394 function onScrollBar(e) {
395 if (scrollbar.scrollTop != lastScrollTop) {
396 lastScrollTop = scroller.scrollTop = scrollbar.scrollTop;
375 397 updateDisplay([]);
376 if (options.fixedGutter) gutter.style.left = scroller.scrollLeft + "px";
398 }
399 }
400
401 function onScrollMain(e) {
402 if (options.fixedGutter && gutter.style.left != scroller.scrollLeft + "px")
403 gutter.style.left = scroller.scrollLeft + "px";
404 if (scroller.scrollTop != lastScrollTop) {
405 lastScrollTop = scroller.scrollTop;
406 if (scrollbar.scrollTop != lastScrollTop)
407 scrollbar.scrollTop = lastScrollTop;
408 updateDisplay([]);
409 }
377 410 if (options.onScroll) options.onScroll(instance);
378 411 }
379 }
380 412
381 413 function onMouseDown(e) {
382 414 setShift(e_prop(e, "shiftKey"));
383 415 // Check whether this is a click in a widget
384 416 for (var n = e_target(e); n != wrapper; n = n.parentNode)
385 if (n.parentNode == code && n != mover) return;
417 if (n.parentNode == sizer && n != mover) return;
386 418
387 419 // See if this is a click in the gutter
388 420 for (var n = e_target(e); n != wrapper; n = n.parentNode)
@@ -396,7 +428,7 var CodeMirror = (function() {
396 428
397 429 switch (e_button(e)) {
398 430 case 3:
399 if (gecko && !mac) onContextMenu(e);
431 if (gecko) onContextMenu(e);
400 432 return;
401 433 case 2:
402 434 if (start) setCursor(start.line, start.ch, true);
@@ -411,22 +443,20 var CodeMirror = (function() {
411 443
412 444 if (!focused) onFocus();
413 445
414 var now = +new Date;
446 var now = +new Date, type = "single";
415 447 if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
448 type = "triple";
416 449 e_preventDefault(e);
417 450 setTimeout(focusInput, 20);
418 return selectLine(start.line);
451 selectLine(start.line);
419 452 } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
453 type = "double";
420 454 lastDoubleClick = {time: now, pos: start};
421 455 e_preventDefault(e);
422 return selectWordAt(start);
456 var word = findWordAt(start);
457 setSelectionUser(word.from, word.to);
423 458 } else { lastClick = {time: now, pos: start}; }
424 459
425 var last = start, going;
426 if (options.dragDrop && dragAndDrop && !options.readOnly && !posEq(sel.from, sel.to) &&
427 !posLess(start, sel.from) && !posLess(sel.to, start)) {
428 // Let the drag handler handle this.
429 if (webkit) scroller.draggable = true;
430 460 function dragEnd(e2) {
431 461 if (webkit) scroller.draggable = false;
432 462 draggingText = false;
@@ -437,6 +467,11 var CodeMirror = (function() {
437 467 focusInput();
438 468 }
439 469 }
470 var last = start, going;
471 if (options.dragDrop && dragAndDrop && !options.readOnly && !posEq(sel.from, sel.to) &&
472 !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") {
473 // Let the drag handler handle this.
474 if (webkit) scroller.draggable = true;
440 475 var up = connect(document, "mouseup", operation(dragEnd), true);
441 476 var drop = connect(scroller, "drop", operation(dragEnd), true);
442 477 draggingText = true;
@@ -445,14 +480,29 var CodeMirror = (function() {
445 480 return;
446 481 }
447 482 e_preventDefault(e);
448 setCursor(start.line, start.ch, true);
483 if (type == "single") setCursor(start.line, start.ch, true);
484
485 var startstart = sel.from, startend = sel.to;
486
487 function doSelect(cur) {
488 if (type == "single") {
489 setSelectionUser(start, cur);
490 } else if (type == "double") {
491 var word = findWordAt(cur);
492 if (posLess(cur, startstart)) setSelectionUser(word.from, startend);
493 else setSelectionUser(startstart, word.to);
494 } else if (type == "triple") {
495 if (posLess(cur, startstart)) setSelectionUser(startend, clipPos({line: cur.line, ch: 0}));
496 else setSelectionUser(startstart, clipPos({line: cur.line + 1, ch: 0}));
497 }
498 }
449 499
450 500 function extend(e) {
451 501 var cur = posFromMouse(e, true);
452 502 if (cur && !posEq(cur, last)) {
453 503 if (!focused) onFocus();
454 504 last = cur;
455 setSelectionUser(start, cur);
505 doSelect(cur);
456 506 updateInput = false;
457 507 var visible = visibleLines();
458 508 if (cur.line >= visible.to || cur.line < visible.from)
@@ -463,7 +513,7 var CodeMirror = (function() {
463 513 function done(e) {
464 514 clearTimeout(going);
465 515 var cur = posFromMouse(e);
466 if (cur) setSelectionUser(start, cur);
516 if (cur) doSelect(cur);
467 517 e_preventDefault(e);
468 518 focusInput();
469 519 updateInput = true;
@@ -480,19 +530,16 var CodeMirror = (function() {
480 530 function onDoubleClick(e) {
481 531 for (var n = e_target(e); n != wrapper; n = n.parentNode)
482 532 if (n.parentNode == gutterText) return e_preventDefault(e);
483 var start = posFromMouse(e);
484 if (!start) return;
485 lastDoubleClick = {time: +new Date, pos: start};
486 533 e_preventDefault(e);
487 selectWordAt(start);
488 534 }
489 535 function onDrop(e) {
490 536 if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return;
491 e.preventDefault();
537 e_preventDefault(e);
492 538 var pos = posFromMouse(e, true), files = e.dataTransfer.files;
493 539 if (!pos || options.readOnly) return;
494 540 if (files && files.length && window.FileReader && window.File) {
495 function loadFile(file, i) {
541 var n = files.length, text = Array(n), read = 0;
542 var loadFile = function(file, i) {
496 543 var reader = new FileReader;
497 544 reader.onload = function() {
498 545 text[i] = reader.result;
@@ -505,8 +552,7 var CodeMirror = (function() {
505 552 }
506 553 };
507 554 reader.readAsText(file);
508 }
509 var n = files.length, text = Array(n), read = 0;
555 };
510 556 for (var i = 0; i < n; ++i) loadFile(files[i], i);
511 557 } else {
512 558 // Don't do a replace if the drop happened inside of the selected text.
@@ -531,11 +577,8 var CodeMirror = (function() {
531 577 e.dataTransfer.setData("Text", txt);
532 578
533 579 // Use dummy image instead of default browsers image.
534 if (gecko || chrome || opera) {
535 var img = document.createElement('img');
536 img.scr = 'data:image/gif;base64,R0lGODdhAgACAIAAAAAAAP///ywAAAAAAgACAAACAoRRADs='; //1x1 image
537 e.dataTransfer.setDragImage(img, 0, 0);
538 }
580 if (e.dataTransfer.setDragImage)
581 e.dataTransfer.setDragImage(elt('img'), 0, 0);
539 582 }
540 583
541 584 function doHandleBinding(bound, dropShift) {
@@ -557,6 +600,7 var CodeMirror = (function() {
557 600 }
558 601 return true;
559 602 }
603 var maybeTransition;
560 604 function handleKeyBinding(e) {
561 605 // Handle auto keymap transitions
562 606 var startMap = getKeyMap(options.keyMap), next = startMap.auto;
@@ -568,10 +612,11 var CodeMirror = (function() {
568 612 }, 50);
569 613
570 614 var name = keyNames[e_prop(e, "keyCode")], handled = false;
615 var flipCtrlCmd = opera && mac;
571 616 if (name == null || e.altGraphKey) return false;
572 617 if (e_prop(e, "altKey")) name = "Alt-" + name;
573 if (e_prop(e, "ctrlKey")) name = "Ctrl-" + name;
574 if (e_prop(e, "metaKey")) name = "Cmd-" + name;
618 if (e_prop(e, flipCtrlCmd ? "metaKey" : "ctrlKey")) name = "Ctrl-" + name;
619 if (e_prop(e, flipCtrlCmd ? "ctrlKey" : "metaKey")) name = "Cmd-" + name;
575 620
576 621 var stopped = false;
577 622 function stop() { stopped = true; }
@@ -603,7 +648,7 var CodeMirror = (function() {
603 648 return handled;
604 649 }
605 650
606 var lastStoppedKey = null, maybeTransition;
651 var lastStoppedKey = null;
607 652 function onKeyDown(e) {
608 653 if (!focused) onFocus();
609 654 if (ie && e.keyCode == 27) { e.returnValue = false; }
@@ -647,7 +692,6 var CodeMirror = (function() {
647 692 focused = true;
648 693 if (scroller.className.search(/\bCodeMirror-focused\b/) == -1)
649 694 scroller.className += " CodeMirror-focused";
650 if (!leaveInputAlone) resetInput(true);
651 695 }
652 696 slowPoll();
653 697 restartBlink();
@@ -666,53 +710,20 var CodeMirror = (function() {
666 710 setTimeout(function() {if (!focused) shiftSelecting = null;}, 150);
667 711 }
668 712
669 function chopDelta(delta) {
670 // Make sure we always scroll a little bit for any nonzero delta.
671 if (delta > 0.0 && delta < 1.0) return 1;
672 else if (delta > -1.0 && delta < 0.0) return -1;
673 else return Math.round(delta);
674 }
675
676 function onMouseWheel(e) {
677 var deltaX = 0, deltaY = 0;
678 if (e.type == "DOMMouseScroll") { // Firefox
679 var delta = -e.detail * 8.0;
680 if (e.axis == e.HORIZONTAL_AXIS) deltaX = delta;
681 else if (e.axis == e.VERTICAL_AXIS) deltaY = delta;
682 } else if (e.wheelDeltaX !== undefined && e.wheelDeltaY !== undefined) { // WebKit
683 deltaX = e.wheelDeltaX / 3.0;
684 deltaY = e.wheelDeltaY / 3.0;
685 } else if (e.wheelDelta !== undefined) { // IE or Opera
686 deltaY = e.wheelDelta / 3.0;
687 }
688
689 var scrolled = false;
690 deltaX = chopDelta(deltaX);
691 deltaY = chopDelta(deltaY);
692 if ((deltaX > 0 && scroller.scrollLeft > 0) ||
693 (deltaX < 0 && scroller.scrollLeft + scroller.clientWidth < scroller.scrollWidth)) {
694 scroller.scrollLeft -= deltaX;
695 scrolled = true;
696 }
697 if ((deltaY > 0 && scrollbar.scrollTop > 0) ||
698 (deltaY < 0 && scrollbar.scrollTop + scrollbar.clientHeight < scrollbar.scrollHeight)) {
699 scrollbar.scrollTop -= deltaY;
700 scrolled = true;
701 }
702 if (scrolled) e_stop(e);
703 }
704
705 713 // Replace the range from from to to by the strings in newText.
706 714 // Afterwards, set the selection to selFrom, selTo.
707 715 function updateLines(from, to, newText, selFrom, selTo) {
708 716 if (suppressEdits) return;
717 var old = [];
718 doc.iter(from.line, to.line + 1, function(line) {
719 old.push(newHL(line.text, line.markedSpans));
720 });
709 721 if (history) {
710 var old = [];
711 doc.iter(from.line, to.line + 1, function(line) { old.push(line.text); });
712 722 history.addChange(from.line, newText.length, old);
713 723 while (history.done.length > options.undoDepth) history.done.shift();
714 724 }
715 updateLinesNoUndo(from, to, newText, selFrom, selTo);
725 var lines = updateMarkedSpans(hlSpans(old[0]), hlSpans(lst(old)), from.ch, to.ch, newText);
726 updateLinesNoUndo(from, to, lines, selFrom, selTo);
716 727 }
717 728 function unredoHelper(from, to) {
718 729 if (!from.length) return;
@@ -720,11 +731,12 var CodeMirror = (function() {
720 731 for (var i = set.length - 1; i >= 0; i -= 1) {
721 732 var change = set[i];
722 733 var replaced = [], end = change.start + change.added;
723 doc.iter(change.start, end, function(line) { replaced.push(line.text); });
734 doc.iter(change.start, end, function(line) { replaced.push(newHL(line.text, line.markedSpans)); });
724 735 out.push({start: change.start, added: change.old.length, old: replaced});
725 736 var pos = {line: change.start + change.old.length - 1,
726 ch: editEnd(replaced[replaced.length-1], change.old[change.old.length-1])};
727 updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: getLine(end-1).text.length}, change.old, pos, pos);
737 ch: editEnd(hlText(lst(replaced)), hlText(lst(change.old)))};
738 updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: getLine(end-1).text.length},
739 change.old, pos, pos);
728 740 }
729 741 updateInput = true;
730 742 to.push(out);
@@ -732,95 +744,86 var CodeMirror = (function() {
732 744 function undo() {unredoHelper(history.done, history.undone);}
733 745 function redo() {unredoHelper(history.undone, history.done);}
734 746
735 function updateLinesNoUndo(from, to, newText, selFrom, selTo) {
747 function updateLinesNoUndo(from, to, lines, selFrom, selTo) {
736 748 if (suppressEdits) return;
737 var recomputeMaxLength = false, maxLineLength = maxLine.length;
749 var recomputeMaxLength = false, maxLineLength = maxLine.text.length;
738 750 if (!options.lineWrapping)
739 751 doc.iter(from.line, to.line + 1, function(line) {
740 752 if (!line.hidden && line.text.length == maxLineLength) {recomputeMaxLength = true; return true;}
741 753 });
742 if (from.line != to.line || newText.length > 1) gutterDirty = true;
754 if (from.line != to.line || lines.length > 1) gutterDirty = true;
743 755
744 756 var nlines = to.line - from.line, firstLine = getLine(from.line), lastLine = getLine(to.line);
745 // First adjust the line structure, taking some care to leave highlighting intact.
746 if (from.ch == 0 && to.ch == 0 && newText[newText.length - 1] == "") {
757 var lastHL = lst(lines);
758
759 // First adjust the line structure
760 if (from.ch == 0 && to.ch == 0 && hlText(lastHL) == "") {
747 761 // This is a whole-line replace. Treated specially to make
748 762 // sure line objects move the way they are supposed to.
749 763 var added = [], prevLine = null;
750 if (from.line) {
751 prevLine = getLine(from.line - 1);
752 prevLine.fixMarkEnds(lastLine);
753 } else lastLine.fixMarkStarts();
754 for (var i = 0, e = newText.length - 1; i < e; ++i)
755 added.push(Line.inheritMarks(newText[i], prevLine));
764 for (var i = 0, e = lines.length - 1; i < e; ++i)
765 added.push(new Line(hlText(lines[i]), hlSpans(lines[i])));
766 lastLine.update(lastLine.text, hlSpans(lastHL));
756 767 if (nlines) doc.remove(from.line, nlines, callbacks);
757 768 if (added.length) doc.insert(from.line, added);
758 769 } else if (firstLine == lastLine) {
759 if (newText.length == 1)
760 firstLine.replace(from.ch, to.ch, newText[0]);
761 else {
762 lastLine = firstLine.split(to.ch, newText[newText.length-1]);
763 firstLine.replace(from.ch, null, newText[0]);
764 firstLine.fixMarkEnds(lastLine);
765 var added = [];
766 for (var i = 1, e = newText.length - 1; i < e; ++i)
767 added.push(Line.inheritMarks(newText[i], firstLine));
768 added.push(lastLine);
770 if (lines.length == 1) {
771 firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]) + firstLine.text.slice(to.ch), hlSpans(lines[0]));
772 } else {
773 for (var added = [], i = 1, e = lines.length - 1; i < e; ++i)
774 added.push(new Line(hlText(lines[i]), hlSpans(lines[i])));
775 added.push(new Line(hlText(lastHL) + firstLine.text.slice(to.ch), hlSpans(lastHL)));
776 firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0]));
769 777 doc.insert(from.line + 1, added);
770 778 }
771 } else if (newText.length == 1) {
772 firstLine.replace(from.ch, null, newText[0]);
773 lastLine.replace(null, to.ch, "");
774 firstLine.append(lastLine);
779 } else if (lines.length == 1) {
780 firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]) + lastLine.text.slice(to.ch), hlSpans(lines[0]));
775 781 doc.remove(from.line + 1, nlines, callbacks);
776 782 } else {
777 783 var added = [];
778 firstLine.replace(from.ch, null, newText[0]);
779 lastLine.replace(null, to.ch, newText[newText.length-1]);
780 firstLine.fixMarkEnds(lastLine);
781 for (var i = 1, e = newText.length - 1; i < e; ++i)
782 added.push(Line.inheritMarks(newText[i], firstLine));
784 firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0]));
785 lastLine.update(hlText(lastHL) + lastLine.text.slice(to.ch), hlSpans(lastHL));
786 for (var i = 1, e = lines.length - 1; i < e; ++i)
787 added.push(new Line(hlText(lines[i]), hlSpans(lines[i])));
783 788 if (nlines > 1) doc.remove(from.line + 1, nlines - 1, callbacks);
784 789 doc.insert(from.line + 1, added);
785 790 }
786 791 if (options.lineWrapping) {
787 792 var perLine = Math.max(5, scroller.clientWidth / charWidth() - 3);
788 doc.iter(from.line, from.line + newText.length, function(line) {
793 doc.iter(from.line, from.line + lines.length, function(line) {
789 794 if (line.hidden) return;
790 795 var guess = Math.ceil(line.text.length / perLine) || 1;
791 796 if (guess != line.height) updateLineHeight(line, guess);
792 797 });
793 798 } else {
794 doc.iter(from.line, from.line + newText.length, function(line) {
799 doc.iter(from.line, from.line + lines.length, function(line) {
795 800 var l = line.text;
796 801 if (!line.hidden && l.length > maxLineLength) {
797 maxLine = l; maxLineLength = l.length; maxLineChanged = true;
802 maxLine = line; maxLineLength = l.length; maxLineChanged = true;
798 803 recomputeMaxLength = false;
799 804 }
800 805 });
801 806 if (recomputeMaxLength) updateMaxLine = true;
802 807 }
803 808
804 // Add these lines to the work array, so that they will be
805 // highlighted. Adjust work lines if lines were added/removed.
806 var newWork = [], lendiff = newText.length - nlines - 1;
807 for (var i = 0, l = work.length; i < l; ++i) {
808 var task = work[i];
809 if (task < from.line) newWork.push(task);
810 else if (task > to.line) newWork.push(task + lendiff);
811 }
812 var hlEnd = from.line + Math.min(newText.length, 500);
813 highlightLines(from.line, hlEnd);
814 newWork.push(hlEnd);
815 work = newWork;
816 startWorker(100);
809 // Adjust frontier, schedule worker
810 frontier = Math.min(frontier, from.line);
811 startWorker(400);
812
813 var lendiff = lines.length - nlines - 1;
817 814 // Remember that these lines changed, for updating the display
818 815 changes.push({from: from.line, to: to.line + 1, diff: lendiff});
819 var changeObj = {from: from, to: to, text: newText};
816 if (options.onChange) {
817 // Normalize lines to contain only strings, since that's what
818 // the change event handler expects
819 for (var i = 0; i < lines.length; ++i)
820 if (typeof lines[i] != "string") lines[i] = lines[i].text;
821 var changeObj = {from: from, to: to, text: lines};
820 822 if (textChanged) {
821 823 for (var cur = textChanged; cur.next; cur = cur.next) {}
822 824 cur.next = changeObj;
823 825 } else textChanged = changeObj;
826 }
824 827
825 828 // Update the selection
826 829 function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;}
@@ -828,42 +831,45 var CodeMirror = (function() {
828 831 updateLine(sel.from.line), updateLine(sel.to.line));
829 832 }
830 833
831 function updateVerticalScroll(scrollTop) {
832 var th = textHeight(), virtualHeight = Math.floor(doc.height * th + 2 * paddingTop()), scrollbarHeight = scroller.clientHeight;
833 scrollbar.style.height = scrollbarHeight + "px";
834 if (scroller.clientHeight)
835 scrollbarInner.style.height = virtualHeight + "px";
836 // Position the mover div to align with the current virtual scroll position
837 if (scrollTop != null) scrollbar.scrollTop = scrollTop;
838 mover.style.top = (displayOffset * th - scrollbar.scrollTop) + "px";
839 scrollbar.style.display = (virtualHeight > scrollbarHeight) ? "block" : "none";
834 function needsScrollbar() {
835 var realHeight = doc.height * textHeight() + 2 * paddingTop();
836 return realHeight * .99 > scroller.offsetHeight ? realHeight : false;
840 837 }
841 838
842 // On Mac OS X Lion and up, detect whether the mouse is plugged in by measuring
843 // the width of a div with a scrollbar in it. If the width is <= 1, then
844 // the mouse isn't plugged in and scrollbars should overlap the content.
845 function overlapScrollbars() {
846 var tmpSb = document.createElement('div'),
847 tmpSbInner = document.createElement('div');
848 tmpSb.className = "CodeMirror-scrollbar";
849 tmpSb.style.cssText = "position: absolute; left: -9999px; height: 100px;";
850 tmpSbInner.className = "CodeMirror-scrollbar-inner";
851 tmpSbInner.style.height = "200px";
852 tmpSb.appendChild(tmpSbInner);
853
854 document.body.appendChild(tmpSb);
855 var result = (tmpSb.offsetWidth <= 1);
856 document.body.removeChild(tmpSb);
857 return result;
839 function updateVerticalScroll(scrollTop) {
840 var scrollHeight = needsScrollbar();
841 scrollbar.style.display = scrollHeight ? "block" : "none";
842 if (scrollHeight) {
843 scrollbarInner.style.height = sizer.style.minHeight = scrollHeight + "px";
844 scrollbar.style.height = scroller.clientHeight + "px";
845 if (scrollTop != null) {
846 scrollbar.scrollTop = scroller.scrollTop = scrollTop;
847 // 'Nudge' the scrollbar to work around a Webkit bug where,
848 // in some situations, we'd end up with a scrollbar that
849 // reported its scrollTop (and looked) as expected, but
850 // *behaved* as if it was still in a previous state (i.e.
851 // couldn't scroll up, even though it appeared to be at the
852 // bottom).
853 if (webkit) setTimeout(function() {
854 if (scrollbar.scrollTop != scrollTop) return;
855 scrollbar.scrollTop = scrollTop + (scrollTop ? -1 : 1);
856 scrollbar.scrollTop = scrollTop;
857 }, 0);
858 }
859 } else {
860 sizer.style.minHeight = "";
861 }
862 // Position the mover div to align with the current virtual scroll position
863 mover.style.top = displayOffset * textHeight() + "px";
858 864 }
859 865
860 866 function computeMaxLength() {
861 var maxLineLength = 0;
862 maxLine = ""; maxLineChanged = true;
863 doc.iter(0, doc.size, function(line) {
867 maxLine = getLine(0); maxLineChanged = true;
868 var maxLineLength = maxLine.text.length;
869 doc.iter(1, doc.size, function(line) {
864 870 var l = line.text;
865 871 if (!line.hidden && l.length > maxLineLength) {
866 maxLineLength = l.length; maxLine = l;
872 maxLineLength = l.length; maxLine = line;
867 873 }
868 874 });
869 875 updateMaxLine = false;
@@ -879,7 +885,7 var CodeMirror = (function() {
879 885 var line = pos.line + code.length - (to.line - from.line) - 1;
880 886 var ch = pos.ch;
881 887 if (pos.line == to.line)
882 ch += code[code.length-1].length - (to.ch - (to.line == from.line ? from.ch : 0));
888 ch += lst(code).length - (to.ch - (to.line == from.line ? from.ch : 0));
883 889 return {line: line, ch: ch};
884 890 }
885 891 var end;
@@ -897,42 +903,37 var CodeMirror = (function() {
897 903 });
898 904 }
899 905 function replaceRange1(code, from, to, computeSel) {
900 var endch = code.length == 1 ? code[0].length + from.ch : code[code.length-1].length;
906 var endch = code.length == 1 ? code[0].length + from.ch : lst(code).length;
901 907 var newSel = computeSel({line: from.line + code.length - 1, ch: endch});
902 908 updateLines(from, to, code, newSel.from, newSel.to);
903 909 }
904 910
905 function getRange(from, to) {
911 function getRange(from, to, lineSep) {
906 912 var l1 = from.line, l2 = to.line;
907 913 if (l1 == l2) return getLine(l1).text.slice(from.ch, to.ch);
908 914 var code = [getLine(l1).text.slice(from.ch)];
909 915 doc.iter(l1 + 1, l2, function(line) { code.push(line.text); });
910 916 code.push(getLine(l2).text.slice(0, to.ch));
911 return code.join("\n");
912 }
913 function getSelection() {
914 return getRange(sel.from, sel.to);
917 return code.join(lineSep || "\n");
918 }
919 function getSelection(lineSep) {
920 return getRange(sel.from, sel.to, lineSep);
915 921 }
916 922
917 var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll
918 923 function slowPoll() {
919 924 if (pollingFast) return;
920 925 poll.set(options.pollInterval, function() {
921 startOperation();
922 926 readInput();
923 927 if (focused) slowPoll();
924 endOperation();
925 928 });
926 929 }
927 930 function fastPoll() {
928 931 var missed = false;
929 932 pollingFast = true;
930 933 function p() {
931 startOperation();
932 934 var changed = readInput();
933 935 if (!changed && !missed) {missed = true; poll.set(60, p);}
934 936 else {pollingFast = false; slowPoll();}
935 endOperation();
936 937 }
937 938 poll.set(20, p);
938 939 }
@@ -944,9 +945,10 var CodeMirror = (function() {
944 945 // supported or compatible enough yet to rely on.)
945 946 var prevInput = "";
946 947 function readInput() {
947 if (leaveInputAlone || !focused || hasSelection(input) || options.readOnly) return false;
948 if (!focused || hasSelection(input) || options.readOnly) return false;
948 949 var text = input.value;
949 950 if (text == prevInput) return false;
951 if (!nestedOperation) startOperation();
950 952 shiftSelecting = null;
951 953 var same = 0, l = Math.min(prevInput.length, text.length);
952 954 while (same < l && prevInput[same] == text[same]) ++same;
@@ -957,13 +959,14 var CodeMirror = (function() {
957 959 replaceSelection(text.slice(same), "end");
958 960 if (text.length > 1000) { input.value = prevInput = ""; }
959 961 else prevInput = text;
962 if (!nestedOperation) endOperation();
960 963 return true;
961 964 }
962 965 function resetInput(user) {
963 966 if (!posEq(sel.from, sel.to)) {
964 967 prevInput = "";
965 968 input.value = getSelection();
966 selectInput(input);
969 if (focused) selectInput(input);
967 970 } else if (user) prevInput = input.value = "";
968 971 }
969 972
@@ -971,17 +974,23 var CodeMirror = (function() {
971 974 if (options.readOnly != "nocursor") input.focus();
972 975 }
973 976
974 function scrollEditorIntoView() {
975 if (!cursor.getBoundingClientRect) return;
976 var rect = cursor.getBoundingClientRect();
977 // IE returns bogus coordinates when the instance sits inside of an iframe and the cursor is hidden
978 if (ie && rect.top == rect.bottom) return;
979 var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
980 if (rect.top < 0 || rect.bottom > winH) scrollCursorIntoView();
981 }
982 977 function scrollCursorIntoView() {
983 978 var coords = calculateCursorCoords();
984 return scrollIntoView(coords.x, coords.y, coords.x, coords.yBot);
979 scrollIntoView(coords.x, coords.y, coords.x, coords.yBot);
980 if (!focused) return;
981 var box = sizer.getBoundingClientRect(), doScroll = null;
982 if (coords.y + box.top < 0) doScroll = true;
983 else if (coords.y + box.top + textHeight() > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
984 if (doScroll != null) {
985 var hidden = cursor.style.display == "none";
986 if (hidden) {
987 cursor.style.display = "";
988 cursor.style.left = coords.x + "px";
989 cursor.style.top = (coords.y - displayOffset) + "px";
990 }
991 cursor.scrollIntoView(doScroll);
992 if (hidden) cursor.style.display = "none";
993 }
985 994 }
986 995 function calculateCursorCoords() {
987 996 var cursor = localCoords(sel.inverted ? sel.from : sel.to);
@@ -989,18 +998,18 var CodeMirror = (function() {
989 998 return {x: x, y: cursor.y, yBot: cursor.yBot};
990 999 }
991 1000 function scrollIntoView(x1, y1, x2, y2) {
992 var scrollPos = calculateScrollPos(x1, y1, x2, y2), scrolled = false;
993 if (scrollPos.scrollLeft != null) {scroller.scrollLeft = scrollPos.scrollLeft; scrolled = true;}
994 if (scrollPos.scrollTop != null) {scrollbar.scrollTop = scrollPos.scrollTop; scrolled = true;}
995 if (scrolled && options.onScroll) options.onScroll(instance);
1001 var scrollPos = calculateScrollPos(x1, y1, x2, y2);
1002 if (scrollPos.scrollLeft != null) {scroller.scrollLeft = scrollPos.scrollLeft;}
1003 if (scrollPos.scrollTop != null) {scrollbar.scrollTop = scroller.scrollTop = scrollPos.scrollTop;}
996 1004 }
997 1005 function calculateScrollPos(x1, y1, x2, y2) {
998 1006 var pl = paddingLeft(), pt = paddingTop();
999 1007 y1 += pt; y2 += pt; x1 += pl; x2 += pl;
1000 1008 var screen = scroller.clientHeight, screentop = scrollbar.scrollTop, result = {};
1001 var atTop = y1 < paddingTop() + 10;
1009 var docBottom = needsScrollbar() || Infinity;
1010 var atTop = y1 < pt + 10, atBottom = y2 + pt > docBottom - 10;
1002 1011 if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1);
1003 else if (y2 > screentop + screen) result.scrollTop = y2 - screen;
1012 else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2) - screen;
1004 1013
1005 1014 var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft;
1006 1015 var gutterw = options.fixedGutter ? gutter.clientWidth : 0;
@@ -1070,8 +1079,13 var CodeMirror = (function() {
1070 1079 // This is just a bogus formula that detects when the editor is
1071 1080 // resized or the font size changes.
1072 1081 if (different) lastSizeC = scroller.clientHeight + th;
1082 if (from != showingFrom || to != showingTo && options.onViewportChange)
1083 setTimeout(function(){
1084 if (options.onViewportChange) options.onViewportChange(instance, from, to);
1085 });
1073 1086 showingFrom = from; showingTo = to;
1074 1087 displayOffset = heightAtLine(doc, from);
1088 startWorker(100);
1075 1089
1076 1090 // Since this is all rather error prone, it is honoured with the
1077 1091 // only assertion in the whole file.
@@ -1082,6 +1096,10 var CodeMirror = (function() {
1082 1096 function checkHeights() {
1083 1097 var curNode = lineDiv.firstChild, heightChanged = false;
1084 1098 doc.iter(showingFrom, showingTo, function(line) {
1099 // Work around bizarro IE7 bug where, sometimes, our curNode
1100 // is magically replaced with a new node in the DOM, leaving
1101 // us with a reference to an orphan (nextSibling-less) node.
1102 if (!curNode) return;
1085 1103 if (!line.hidden) {
1086 1104 var height = Math.round(curNode.offsetHeight / th) || 1;
1087 1105 if (line.height != height) {
@@ -1094,23 +1112,15 var CodeMirror = (function() {
1094 1112 return heightChanged;
1095 1113 }
1096 1114
1097 if (options.lineWrapping) {
1098 // Guess whether we're going to need the scrollbar, so that we don't end up changing the linewrapping
1099 // after the scrollbar appears (during updateVerticalScroll()). Only do this if the scrollbar is
1100 // appearing (if it's disappearing, we don't have to worry about the scroll position, and there are
1101 // issues on IE7 if we turn it off too early).
1102 var virtualHeight = Math.floor(doc.height * th + 2 * paddingTop()), scrollbarHeight = scroller.clientHeight;
1103 if (virtualHeight > scrollbarHeight) scrollbar.style.display = "block";
1104 checkHeights();
1105 }
1115 if (options.lineWrapping) checkHeights();
1106 1116
1107 1117 gutter.style.display = gutterDisplay;
1108 1118 if (different || gutterDirty) {
1109 1119 // If the gutter grew in size, re-check heights. If those changed, re-draw gutter.
1110 1120 updateGutter() && options.lineWrapping && checkHeights() && updateGutter();
1111 1121 }
1122 updateVerticalScroll(scrollTop);
1112 1123 updateSelection();
1113 updateVerticalScroll(scrollTop);
1114 1124 if (!suppressCallback && options.onUpdate) options.onUpdate(instance);
1115 1125 return true;
1116 1126 }
@@ -1139,14 +1149,14 var CodeMirror = (function() {
1139 1149 }
1140 1150
1141 1151 function patchDisplay(from, to, intact) {
1142 // The first pass removes the DOM nodes that aren't intact.
1143 if (!intact.length) lineDiv.innerHTML = "";
1144 else {
1145 1152 function killNode(node) {
1146 1153 var tmp = node.nextSibling;
1147 1154 node.parentNode.removeChild(node);
1148 1155 return tmp;
1149 1156 }
1157 // The first pass removes the DOM nodes that aren't intact.
1158 if (!intact.length) removeChildren(lineDiv);
1159 else {
1150 1160 var domPos = 0, curNode = lineDiv.firstChild, n;
1151 1161 for (var i = 0; i < intact.length; ++i) {
1152 1162 var cur = intact[i];
@@ -1157,21 +1167,20 var CodeMirror = (function() {
1157 1167 }
1158 1168 // This pass fills in the lines that actually changed.
1159 1169 var nextIntact = intact.shift(), curNode = lineDiv.firstChild, j = from;
1160 var scratch = document.createElement("div");
1161 1170 doc.iter(from, to, function(line) {
1162 1171 if (nextIntact && nextIntact.to == j) nextIntact = intact.shift();
1163 1172 if (!nextIntact || nextIntact.from > j) {
1164 if (line.hidden) var html = scratch.innerHTML = "<pre></pre>";
1173 if (line.hidden) var lineElement = elt("pre");
1165 1174 else {
1166 var html = '<pre' + (line.className ? ' class="' + line.className + '"' : '') + '>'
1167 + line.getHTML(makeTab) + '</pre>';
1175 var lineElement = lineContent(line);
1176 if (line.className) lineElement.className = line.className;
1168 1177 // Kludge to make sure the styled element lies behind the selection (by z-index)
1169 if (line.bgClassName)
1170 html = '<div style="position: relative"><pre class="' + line.bgClassName +
1171 '" style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: -2">&#160;</pre>' + html + "</div>";
1172 }
1173 scratch.innerHTML = html;
1174 lineDiv.insertBefore(scratch.firstChild, curNode);
1178 if (line.bgClassName) {
1179 var pre = elt("pre", "\u00a0", line.bgClassName, "position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: -2");
1180 lineElement = elt("div", [pre, lineElement], null, "position: relative");
1181 }
1182 }
1183 lineDiv.insertBefore(lineElement, curNode);
1175 1184 } else {
1176 1185 curNode = curNode.nextSibling;
1177 1186 }
@@ -1183,26 +1192,29 var CodeMirror = (function() {
1183 1192 if (!options.gutter && !options.lineNumbers) return;
1184 1193 var hText = mover.offsetHeight, hEditor = scroller.clientHeight;
1185 1194 gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px";
1186 var html = [], i = showingFrom, normalNode;
1195 var fragment = document.createDocumentFragment(), i = showingFrom, normalNode;
1187 1196 doc.iter(showingFrom, Math.max(showingTo, showingFrom + 1), function(line) {
1188 1197 if (line.hidden) {
1189 html.push("<pre></pre>");
1198 fragment.appendChild(elt("pre"));
1190 1199 } else {
1191 1200 var marker = line.gutterMarker;
1192 var text = options.lineNumbers ? i + options.firstLineNumber : null;
1201 var text = options.lineNumbers ? options.lineNumberFormatter(i + options.firstLineNumber) : null;
1193 1202 if (marker && marker.text)
1194 1203 text = marker.text.replace("%N%", text != null ? text : "");
1195 1204 else if (text == null)
1196 1205 text = "\u00a0";
1197 html.push((marker && marker.style ? '<pre class="' + marker.style + '">' : "<pre>"), text);
1198 for (var j = 1; j < line.height; ++j) html.push("<br/>&#160;");
1199 html.push("</pre>");
1206 var markerElement = fragment.appendChild(elt("pre", null, marker && marker.style));
1207 markerElement.innerHTML = text;
1208 for (var j = 1; j < line.height; ++j) {
1209 markerElement.appendChild(elt("br"));
1210 markerElement.appendChild(document.createTextNode("\u00a0"));
1211 }
1200 1212 if (!marker) normalNode = i;
1201 1213 }
1202 1214 ++i;
1203 1215 });
1204 1216 gutter.style.display = "none";
1205 gutterText.innerHTML = html.join("");
1217 removeChildrenAndAdd(gutterText, fragment);
1206 1218 // Make sure scrolling doesn't cause number gutter size to pop
1207 1219 if (normalNode != null && options.lineNumbers) {
1208 1220 var node = gutterText.childNodes[normalNode - showingFrom];
@@ -1230,15 +1242,15 var CodeMirror = (function() {
1230 1242 cursor.style.display = "";
1231 1243 selectionDiv.style.display = "none";
1232 1244 } else {
1233 var sameLine = fromPos.y == toPos.y, html = "";
1245 var sameLine = fromPos.y == toPos.y, fragment = document.createDocumentFragment();
1234 1246 var clientWidth = lineSpace.clientWidth || lineSpace.offsetWidth;
1235 1247 var clientHeight = lineSpace.clientHeight || lineSpace.offsetHeight;
1236 function add(left, top, right, height) {
1248 var add = function(left, top, right, height) {
1237 1249 var rstyle = quirksMode ? "width: " + (!right ? clientWidth : clientWidth - right - left) + "px"
1238 1250 : "right: " + right + "px";
1239 html += '<div class="CodeMirror-selected" style="position: absolute; left: ' + left +
1240 'px; top: ' + top + 'px; ' + rstyle + '; height: ' + height + 'px"></div>';
1241 }
1251 fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
1252 "px; top: " + top + "px; " + rstyle + "; height: " + height + "px"));
1253 };
1242 1254 if (sel.from.ch && fromPos.y >= 0) {
1243 1255 var right = sameLine ? clientWidth - toPos.x : 0;
1244 1256 add(fromPos.x, fromPos.y, right, th);
@@ -1249,7 +1261,7 var CodeMirror = (function() {
1249 1261 add(0, middleStart, 0, middleHeight);
1250 1262 if ((!sameLine || !sel.from.ch) && toPos.y < clientHeight - .5 * th)
1251 1263 add(0, toPos.y, clientWidth - toPos.x, th);
1252 selectionDiv.innerHTML = html;
1264 removeChildrenAndAdd(selectionDiv, fragment);
1253 1265 cursor.style.display = "none";
1254 1266 selectionDiv.style.display = "";
1255 1267 }
@@ -1381,24 +1393,34 var CodeMirror = (function() {
1381 1393 else replaceRange("", sel.from, findPosH(dir, unit));
1382 1394 userSelChange = true;
1383 1395 }
1384 var goalColumn = null;
1385 1396 function moveV(dir, unit) {
1386 1397 var dist = 0, pos = localCoords(sel.inverted ? sel.from : sel.to, true);
1387 1398 if (goalColumn != null) pos.x = goalColumn;
1388 if (unit == "page") dist = Math.min(scroller.clientHeight, window.innerHeight || document.documentElement.clientHeight);
1389 else if (unit == "line") dist = textHeight();
1390 var target = coordsChar(pos.x, pos.y + dist * dir + 2);
1399 if (unit == "page") {
1400 var screen = Math.min(scroller.clientHeight, window.innerHeight || document.documentElement.clientHeight);
1401 var target = coordsChar(pos.x, pos.y + screen * dir);
1402 } else if (unit == "line") {
1403 var th = textHeight();
1404 var target = coordsChar(pos.x, pos.y + .5 * th + dir * th);
1405 }
1391 1406 if (unit == "page") scrollbar.scrollTop += localCoords(target, true).y - pos.y;
1392 1407 setCursor(target.line, target.ch, true);
1393 1408 goalColumn = pos.x;
1394 1409 }
1395 1410
1396 function selectWordAt(pos) {
1411 function findWordAt(pos) {
1397 1412 var line = getLine(pos.line).text;
1398 1413 var start = pos.ch, end = pos.ch;
1399 while (start > 0 && isWordChar(line.charAt(start - 1))) --start;
1400 while (end < line.length && isWordChar(line.charAt(end))) ++end;
1401 setSelectionUser({line: pos.line, ch: start}, {line: pos.line, ch: end});
1414 if (line) {
1415 if (pos.after === false || end == line.length) --start; else ++end;
1416 var startChar = line.charAt(start);
1417 var check = isWordChar(startChar) ? isWordChar :
1418 /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} :
1419 function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
1420 while (start > 0 && check(line.charAt(start - 1))) --start;
1421 while (end < line.length && check(line.charAt(end))) ++end;
1422 }
1423 return {from: {line: pos.line, ch: start}, to: {line: pos.line, ch: end}};
1402 1424 }
1403 1425 function selectLine(line) {
1404 1426 setSelectionUser({line: line, ch: 0}, clipPos({line: line + 1, ch: 0}));
@@ -1431,24 +1453,20 var CodeMirror = (function() {
1431 1453 indentation = Math.max(0, indentation);
1432 1454 var diff = indentation - curSpace;
1433 1455
1434 if (!diff) {
1435 if (sel.from.line != n && sel.to.line != n) return;
1436 var indentString = curSpaceString;
1437 } else {
1438 1456 var indentString = "", pos = 0;
1439 1457 if (options.indentWithTabs)
1440 1458 for (var i = Math.floor(indentation / options.tabSize); i; --i) {pos += options.tabSize; indentString += "\t";}
1441 while (pos < indentation) {++pos; indentString += " ";}
1442 }
1459 if (pos < indentation) indentString += spaceStr(indentation - pos);
1443 1460
1461 if (indentString != curSpaceString)
1444 1462 replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length});
1445 1463 }
1446 1464
1447 1465 function loadMode() {
1448 1466 mode = CodeMirror.getMode(options, options.mode);
1449 1467 doc.iter(0, doc.size, function(line) { line.stateAfter = null; });
1450 work = [0];
1451 startWorker();
1468 frontier = 0;
1469 startWorker(100);
1452 1470 }
1453 1471 function gutterChanged() {
1454 1472 var visible = options.gutter || options.lineNumbers;
@@ -1465,24 +1483,16 var CodeMirror = (function() {
1465 1483 var guess = Math.ceil(line.text.length / perLine) || 1;
1466 1484 if (guess != 1) updateLineHeight(line, guess);
1467 1485 });
1468 lineSpace.style.width = code.style.width = "";
1469 widthForcer.style.left = "";
1486 lineSpace.style.minWidth = widthForcer.style.left = "";
1470 1487 } else {
1471 1488 wrapper.className = wrapper.className.replace(" CodeMirror-wrap", "");
1472 maxLine = ""; maxLineChanged = true;
1489 computeMaxLength();
1473 1490 doc.iter(0, doc.size, function(line) {
1474 1491 if (line.height != 1 && !line.hidden) updateLineHeight(line, 1);
1475 if (line.text.length > maxLine.length) maxLine = line.text;
1476 1492 });
1477 1493 }
1478 1494 changes.push({from: 0, to: doc.size});
1479 1495 }
1480 function makeTab(col) {
1481 var w = options.tabSize - col % options.tabSize, cached = tabCache[w];
1482 if (cached) return cached;
1483 for (var str = '<span class="cm-tab">', i = 0; i < w; ++i) str += " ";
1484 return (tabCache[w] = {html: str + "</span>", width: w});
1485 }
1486 1496 function themeChanged() {
1487 1497 scroller.className = scroller.className.replace(/\s*cm-s-\S+/g, "") +
1488 1498 options.theme.replace(/(^|\s)\s*/g, " cm-s-");
@@ -1493,74 +1503,71 var CodeMirror = (function() {
1493 1503 (style ? " cm-keymap-" + style : "");
1494 1504 }
1495 1505
1496 function TextMarker() { this.set = []; }
1506 function TextMarker(type, style) { this.lines = []; this.type = type; if (style) this.style = style; }
1497 1507 TextMarker.prototype.clear = operation(function() {
1498 1508 var min = Infinity, max = -Infinity;
1499 for (var i = 0, e = this.set.length; i < e; ++i) {
1500 var line = this.set[i], mk = line.marked;
1501 if (!mk || !line.parent) continue;
1509 for (var i = 0; i < this.lines.length; ++i) {
1510 var line = this.lines[i];
1511 var span = getMarkedSpanFor(line.markedSpans, this, true);
1512 if (span.from != null || span.to != null) {
1502 1513 var lineN = lineNo(line);
1503 1514 min = Math.min(min, lineN); max = Math.max(max, lineN);
1504 for (var j = 0; j < mk.length; ++j)
1505 if (mk[j].marker == this) mk.splice(j--, 1);
1515 }
1506 1516 }
1507 1517 if (min != Infinity)
1508 1518 changes.push({from: min, to: max + 1});
1519 this.lines.length = 0;
1509 1520 });
1510 1521 TextMarker.prototype.find = function() {
1511 1522 var from, to;
1512 for (var i = 0, e = this.set.length; i < e; ++i) {
1513 var line = this.set[i], mk = line.marked;
1514 for (var j = 0; j < mk.length; ++j) {
1515 var mark = mk[j];
1516 if (mark.marker == this) {
1517 if (mark.from != null || mark.to != null) {
1523 for (var i = 0; i < this.lines.length; ++i) {
1524 var line = this.lines[i];
1525 var span = getMarkedSpanFor(line.markedSpans, this);
1526 if (span.from != null || span.to != null) {
1518 1527 var found = lineNo(line);
1519 if (found != null) {
1520 if (mark.from != null) from = {line: found, ch: mark.from};
1521 if (mark.to != null) to = {line: found, ch: mark.to};
1522 }
1523 }
1524 }
1525 }
1526 }
1527 return {from: from, to: to};
1528 if (span.from != null) from = {line: found, ch: span.from};
1529 if (span.to != null) to = {line: found, ch: span.to};
1530 }
1531 }
1532 if (this.type == "bookmark") return from;
1533 return from && {from: from, to: to};
1528 1534 };
1529 1535
1530 function markText(from, to, className) {
1536 function markText(from, to, className, options) {
1531 1537 from = clipPos(from); to = clipPos(to);
1532 var tm = new TextMarker();
1533 if (!posLess(from, to)) return tm;
1534 function add(line, from, to, className) {
1535 getLine(line).addMark(new MarkedText(from, to, className, tm));
1536 }
1537 if (from.line == to.line) add(from.line, from.ch, to.ch, className);
1538 else {
1539 add(from.line, from.ch, null, className);
1540 for (var i = from.line + 1, e = to.line; i < e; ++i)
1541 add(i, null, null, className);
1542 add(to.line, null, to.ch, className);
1543 }
1538 var marker = new TextMarker("range", className);
1539 if (options) for (var opt in options) if (options.hasOwnProperty(opt))
1540 marker[opt] = options[opt];
1541 var curLine = from.line;
1542 doc.iter(curLine, to.line + 1, function(line) {
1543 var span = {from: curLine == from.line ? from.ch : null,
1544 to: curLine == to.line ? to.ch : null,
1545 marker: marker};
1546 (line.markedSpans || (line.markedSpans = [])).push(span);
1547 marker.lines.push(line);
1548 ++curLine;
1549 });
1544 1550 changes.push({from: from.line, to: to.line + 1});
1545 return tm;
1551 return marker;
1546 1552 }
1547 1553
1548 1554 function setBookmark(pos) {
1549 1555 pos = clipPos(pos);
1550 var bm = new Bookmark(pos.ch);
1551 getLine(pos.line).addMark(bm);
1552 return bm;
1556 var marker = new TextMarker("bookmark"), line = getLine(pos.line);
1557 var span = {from: pos.ch, to: pos.ch, marker: marker};
1558 (line.markedSpans || (line.markedSpans = [])).push(span);
1559 marker.lines.push(line);
1560 return marker;
1553 1561 }
1554 1562
1555 1563 function findMarksAt(pos) {
1556 1564 pos = clipPos(pos);
1557 var markers = [], marked = getLine(pos.line).marked;
1558 if (!marked) return markers;
1559 for (var i = 0, e = marked.length; i < e; ++i) {
1560 var m = marked[i];
1561 if ((m.from == null || m.from <= pos.ch) &&
1562 (m.to == null || m.to >= pos.ch))
1563 markers.push(m.marker || m);
1565 var markers = [], spans = getLine(pos.line).markedSpans;
1566 if (spans) for (var i = 0; i < spans.length; ++i) {
1567 var span = spans[i];
1568 if ((span.from == null || span.from <= pos.ch) &&
1569 (span.to == null || span.to >= pos.ch))
1570 markers.push(span.marker);
1564 1571 }
1565 1572 return markers;
1566 1573 }
@@ -1600,11 +1607,10 var CodeMirror = (function() {
1600 1607 if (line.hidden != hidden) {
1601 1608 line.hidden = hidden;
1602 1609 if (!options.lineWrapping) {
1603 var l = line.text;
1604 if (hidden && l.length == maxLine.length) {
1610 if (hidden && line.text.length == maxLine.text.length) {
1605 1611 updateMaxLine = true;
1606 } else if (!hidden && l.length > maxLine.length) {
1607 maxLine = l; maxWidth = null; updateMaxLine = false;
1612 } else if (!hidden && line.text.length > maxLine.text.length) {
1613 maxLine = line; updateMaxLine = false;
1608 1614 }
1609 1615 }
1610 1616 updateLineHeight(line, hidden ? 0 : 1);
@@ -1636,53 +1642,18 var CodeMirror = (function() {
1636 1642 markerClass: marker && marker.style, lineClass: line.className, bgClass: line.bgClassName};
1637 1643 }
1638 1644
1639 function stringWidth(str) {
1640 measure.innerHTML = "<pre><span>x</span></pre>";
1641 measure.firstChild.firstChild.firstChild.nodeValue = str;
1642 return measure.firstChild.firstChild.offsetWidth || 10;
1643 }
1644 // These are used to go from pixel positions to character
1645 // positions, taking varying character widths into account.
1646 function charFromX(line, x) {
1647 if (x <= 0) return 0;
1648 var lineObj = getLine(line), text = lineObj.text;
1649 function getX(len) {
1650 return measureLine(lineObj, len).left;
1651 }
1652 var from = 0, fromX = 0, to = text.length, toX;
1653 // Guess a suitable upper bound for our search.
1654 var estimated = Math.min(to, Math.ceil(x / charWidth()));
1655 for (;;) {
1656 var estX = getX(estimated);
1657 if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
1658 else {toX = estX; to = estimated; break;}
1659 }
1660 if (x > toX) return to;
1661 // Try to guess a suitable lower bound as well.
1662 estimated = Math.floor(to * 0.8); estX = getX(estimated);
1663 if (estX < x) {from = estimated; fromX = estX;}
1664 // Do a binary search between these bounds.
1665 for (;;) {
1666 if (to - from <= 1) return (toX - x > x - fromX) ? from : to;
1667 var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
1668 if (middleX > x) {to = middle; toX = middleX;}
1669 else {from = middle; fromX = middleX;}
1670 }
1671 }
1672
1673 var tempId = "CodeMirror-temp-" + Math.floor(Math.random() * 0xffffff).toString(16);
1674 1645 function measureLine(line, ch) {
1675 1646 if (ch == 0) return {top: 0, left: 0};
1676 1647 var wbr = options.lineWrapping && ch < line.text.length &&
1677 1648 spanAffectsWrapping.test(line.text.slice(ch - 1, ch + 1));
1678 measure.innerHTML = "<pre>" + line.getHTML(makeTab, ch, tempId, wbr) + "</pre>";
1679 var elt = document.getElementById(tempId);
1680 var top = elt.offsetTop, left = elt.offsetLeft;
1649 var pre = lineContent(line, ch);
1650 removeChildrenAndAdd(measure, pre);
1651 var anchor = pre.anchor;
1652 var top = anchor.offsetTop, left = anchor.offsetLeft;
1681 1653 // Older IEs report zero offsets for spans directly after a wrap
1682 1654 if (ie && top == 0 && left == 0) {
1683 var backup = document.createElement("span");
1684 backup.innerHTML = "x";
1685 elt.parentNode.insertBefore(backup, elt.nextSibling);
1655 var backup = elt("span", "x");
1656 anchor.parentNode.insertBefore(backup, anchor.nextSibling);
1686 1657 top = backup.offsetTop;
1687 1658 }
1688 1659 return {top: top, left: left};
@@ -1699,17 +1670,19 var CodeMirror = (function() {
1699 1670 }
1700 1671 // Coords must be lineSpace-local
1701 1672 function coordsChar(x, y) {
1702 if (y < 0) y = 0;
1703 1673 var th = textHeight(), cw = charWidth(), heightPos = displayOffset + Math.floor(y / th);
1674 if (heightPos < 0) return {line: 0, ch: 0};
1704 1675 var lineNo = lineAtHeight(doc, heightPos);
1705 1676 if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc.size - 1).text.length};
1706 1677 var lineObj = getLine(lineNo), text = lineObj.text;
1707 1678 var tw = options.lineWrapping, innerOff = tw ? heightPos - heightAtLine(doc, lineNo) : 0;
1708 1679 if (x <= 0 && innerOff == 0) return {line: lineNo, ch: 0};
1680 var wrongLine = false;
1709 1681 function getX(len) {
1710 1682 var sp = measureLine(lineObj, len);
1711 1683 if (tw) {
1712 1684 var off = Math.round(sp.top / th);
1685 wrongLine = off != innerOff;
1713 1686 return Math.max(0, sp.left + (off - innerOff) * scroller.clientWidth);
1714 1687 }
1715 1688 return sp.left;
@@ -1728,9 +1701,12 var CodeMirror = (function() {
1728 1701 if (estX < x) {from = estimated; fromX = estX;}
1729 1702 // Do a binary search between these bounds.
1730 1703 for (;;) {
1731 if (to - from <= 1) return {line: lineNo, ch: (toX - x > x - fromX) ? from : to};
1704 if (to - from <= 1) {
1705 var after = x - fromX < toX - x;
1706 return {line: lineNo, ch: after ? from : to, after: after};
1707 }
1732 1708 var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
1733 if (middleX > x) {to = middle; toX = middleX;}
1709 if (middleX > x) {to = middle; toX = middleX; if (wrongLine) toX += 1000; }
1734 1710 else {from = middle; fromX = middleX;}
1735 1711 }
1736 1712 }
@@ -1739,26 +1715,32 var CodeMirror = (function() {
1739 1715 return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot};
1740 1716 }
1741 1717
1742 var cachedHeight, cachedHeightFor, measureText;
1718 var cachedHeight, cachedHeightFor, measurePre;
1743 1719 function textHeight() {
1744 if (measureText == null) {
1745 measureText = "<pre>";
1746 for (var i = 0; i < 49; ++i) measureText += "x<br/>";
1747 measureText += "x</pre>";
1720 if (measurePre == null) {
1721 measurePre = elt("pre");
1722 for (var i = 0; i < 49; ++i) {
1723 measurePre.appendChild(document.createTextNode("x"));
1724 measurePre.appendChild(elt("br"));
1725 }
1726 measurePre.appendChild(document.createTextNode("x"));
1748 1727 }
1749 1728 var offsetHeight = lineDiv.clientHeight;
1750 1729 if (offsetHeight == cachedHeightFor) return cachedHeight;
1751 1730 cachedHeightFor = offsetHeight;
1752 measure.innerHTML = measureText;
1731 removeChildrenAndAdd(measure, measurePre.cloneNode(true));
1753 1732 cachedHeight = measure.firstChild.offsetHeight / 50 || 1;
1754 measure.innerHTML = "";
1733 removeChildren(measure);
1755 1734 return cachedHeight;
1756 1735 }
1757 1736 var cachedWidth, cachedWidthFor = 0;
1758 1737 function charWidth() {
1759 1738 if (scroller.clientWidth == cachedWidthFor) return cachedWidth;
1760 1739 cachedWidthFor = scroller.clientWidth;
1761 return (cachedWidth = stringWidth("x"));
1740 var anchor = elt("span", "x");
1741 var pre = elt("pre", [anchor]);
1742 removeChildrenAndAdd(measure, pre);
1743 return (cachedWidth = anchor.offsetWidth || 10);
1762 1744 }
1763 1745 function paddingTop() {return lineSpace.offsetTop;}
1764 1746 function paddingLeft() {return lineSpace.offsetLeft;}
@@ -1775,6 +1757,7 var CodeMirror = (function() {
1775 1757 var offL = eltOffset(lineSpace, true);
1776 1758 return coordsChar(x - offL.left, y - offL.top);
1777 1759 }
1760 var detectingSelectAll;
1778 1761 function onContextMenu(e) {
1779 1762 var pos = posFromMouse(e), scrollPos = scrollbar.scrollTop;
1780 1763 if (!pos || opera) return; // Opera is difficult.
@@ -1786,19 +1769,30 var CodeMirror = (function() {
1786 1769 input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
1787 1770 "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; " +
1788 1771 "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1789 leaveInputAlone = true;
1790 var val = input.value = getSelection();
1791 1772 focusInput();
1792 selectInput(input);
1773 resetInput(true);
1774 // Adds "Select all" to context menu in FF
1775 if (posEq(sel.from, sel.to)) input.value = prevInput = " ";
1776
1793 1777 function rehide() {
1794 var newVal = splitLines(input.value).join("\n");
1795 if (newVal != val && !options.readOnly) operation(replaceSelection)(newVal, "end");
1796 1778 inputDiv.style.position = "relative";
1797 1779 input.style.cssText = oldCSS;
1798 1780 if (ie_lt9) scrollbar.scrollTop = scrollPos;
1799 leaveInputAlone = false;
1800 resetInput(true);
1801 1781 slowPoll();
1782
1783 // Try to detect the user choosing select-all
1784 if (input.selectionStart != null) {
1785 clearTimeout(detectingSelectAll);
1786 var extval = input.value = " " + (posEq(sel.from, sel.to) ? "" : input.value), i = 0;
1787 prevInput = " ";
1788 input.selectionStart = 1; input.selectionEnd = extval.length;
1789 detectingSelectAll = setTimeout(function poll(){
1790 if (prevInput == " " && input.selectionStart == 0)
1791 operation(commands.selectAll)(instance);
1792 else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
1793 else resetInput();
1794 }, 200);
1795 }
1802 1796 }
1803 1797
1804 1798 if (gecko) {
@@ -1819,7 +1813,7 var CodeMirror = (function() {
1819 1813 cursor.style.visibility = "";
1820 1814 blinker = setInterval(function() {
1821 1815 cursor.style.visibility = (on = !on) ? "" : "hidden";
1822 }, 650);
1816 }, options.cursorBlinkRate);
1823 1817 }
1824 1818
1825 1819 var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
@@ -1882,70 +1876,39 var CodeMirror = (function() {
1882 1876 return minline;
1883 1877 }
1884 1878 function getStateBefore(n) {
1885 var start = findStartLine(n), state = start && getLine(start-1).stateAfter;
1879 var pos = findStartLine(n), state = pos && getLine(pos-1).stateAfter;
1886 1880 if (!state) state = startState(mode);
1887 1881 else state = copyState(mode, state);
1888 doc.iter(start, n, function(line) {
1889 line.highlight(mode, state, options.tabSize);
1890 line.stateAfter = copyState(mode, state);
1882 doc.iter(pos, n, function(line) {
1883 line.process(mode, state, options.tabSize);
1884 line.stateAfter = (pos == n - 1 || pos % 5 == 0) ? copyState(mode, state) : null;
1891 1885 });
1892 if (start < n) changes.push({from: start, to: n});
1893 if (n < doc.size && !getLine(n).stateAfter) work.push(n);
1894 1886 return state;
1895 1887 }
1896 function highlightLines(start, end) {
1897 var state = getStateBefore(start);
1898 doc.iter(start, end, function(line) {
1899 line.highlight(mode, state, options.tabSize);
1900 line.stateAfter = copyState(mode, state);
1901 });
1902 }
1903 1888 function highlightWorker() {
1904 var end = +new Date + options.workTime;
1905 var foundWork = work.length;
1906 while (work.length) {
1907 if (!getLine(showingFrom).stateAfter) var task = showingFrom;
1908 else var task = work.pop();
1909 if (task >= doc.size) continue;
1910 var start = findStartLine(task), state = start && getLine(start-1).stateAfter;
1911 if (state) state = copyState(mode, state);
1912 else state = startState(mode);
1913
1914 var unchanged = 0, compare = mode.compareStates, realChange = false,
1915 i = start, bail = false;
1916 doc.iter(i, doc.size, function(line) {
1917 var hadState = line.stateAfter;
1889 if (frontier >= showingTo) return;
1890 var end = +new Date + options.workTime, state = copyState(mode, getStateBefore(frontier));
1891 var startFrontier = frontier;
1892 doc.iter(frontier, showingTo, function(line) {
1893 if (frontier >= showingFrom) { // Visible
1894 line.highlight(mode, state, options.tabSize);
1895 line.stateAfter = copyState(mode, state);
1896 } else {
1897 line.process(mode, state, options.tabSize);
1898 line.stateAfter = frontier % 5 == 0 ? copyState(mode, state) : null;
1899 }
1900 ++frontier;
1918 1901 if (+new Date > end) {
1919 work.push(i);
1920 1902 startWorker(options.workDelay);
1921 if (realChange) changes.push({from: task, to: i + 1});
1922 return (bail = true);
1923 }
1924 var changed = line.highlight(mode, state, options.tabSize);
1925 if (changed) realChange = true;
1926 line.stateAfter = copyState(mode, state);
1927 var done = null;
1928 if (compare) {
1929 var same = hadState && compare(hadState, state);
1930 if (same != Pass) done = !!same;
1931 }
1932 if (done == null) {
1933 if (changed !== false || !hadState) unchanged = 0;
1934 else if (++unchanged > 3 && (!mode.indent || mode.indent(hadState, "") == mode.indent(state, "")))
1935 done = true;
1936 }
1937 if (done) return true;
1938 ++i;
1903 return true;
1904 }
1939 1905 });
1940 if (bail) return;
1941 if (realChange) changes.push({from: task, to: i + 1});
1942 }
1943 if (foundWork && options.onHighlightComplete)
1944 options.onHighlightComplete(instance);
1906 if (showingTo > startFrontier && frontier >= showingFrom)
1907 operation(function() {changes.push({from: startFrontier, to: frontier});})();
1945 1908 }
1946 1909 function startWorker(time) {
1947 if (!work.length) return;
1948 highlight.set(time, operation(highlightWorker));
1910 if (frontier < showingTo)
1911 highlight.set(time, highlightWorker);
1949 1912 }
1950 1913
1951 1914 // Operations are used to wrap changes in such a way that each
@@ -1959,7 +1922,11 var CodeMirror = (function() {
1959 1922 function endOperation() {
1960 1923 if (updateMaxLine) computeMaxLength();
1961 1924 if (maxLineChanged && !options.lineWrapping) {
1962 widthForcer.style.left = stringWidth(maxLine) + "px";
1925 var cursorWidth = widthForcer.offsetWidth, left = measureLine(maxLine, maxLine.text.length).left;
1926 if (!ie_lt8) {
1927 widthForcer.style.left = left + "px";
1928 lineSpace.style.minWidth = (left + cursorWidth) + "px";
1929 }
1963 1930 maxLineChanged = false;
1964 1931 }
1965 1932 var newScrollPos, updated;
@@ -1967,16 +1934,16 var CodeMirror = (function() {
1967 1934 var coords = calculateCursorCoords();
1968 1935 newScrollPos = calculateScrollPos(coords.x, coords.y, coords.x, coords.yBot);
1969 1936 }
1970 if (changes.length) updated = updateDisplay(changes, true, (newScrollPos ? newScrollPos.scrollTop : null));
1971 else {
1937 if (changes.length || newScrollPos && newScrollPos.scrollTop != null)
1938 updated = updateDisplay(changes, true, newScrollPos && newScrollPos.scrollTop);
1939 if (!updated) {
1972 1940 if (selectionChanged) updateSelection();
1973 1941 if (gutterDirty) updateGutter();
1974 1942 }
1975 1943 if (newScrollPos) scrollCursorIntoView();
1976 if (selectionChanged) {scrollEditorIntoView(); restartBlink();}
1944 if (selectionChanged) restartBlink();
1977 1945
1978 if (focused && !leaveInputAlone &&
1979 (updateInput === true || (updateInput !== false && selectionChanged)))
1946 if (focused && (updateInput === true || (updateInput !== false && selectionChanged)))
1980 1947 resetInput(userSelChange);
1981 1948
1982 1949 if (selectionChanged && options.matchBrackets)
@@ -2038,17 +2005,19 var CodeMirror = (function() {
2038 2005 dragDrop: true,
2039 2006 onChange: null,
2040 2007 onCursorActivity: null,
2008 onViewportChange: null,
2041 2009 onGutterClick: null,
2042 onHighlightComplete: null,
2043 2010 onUpdate: null,
2044 2011 onFocus: null, onBlur: null, onScroll: null,
2045 2012 matchBrackets: false,
2013 cursorBlinkRate: 530,
2046 2014 workTime: 100,
2047 2015 workDelay: 200,
2048 2016 pollInterval: 100,
2049 2017 undoDepth: 40,
2050 2018 tabindex: null,
2051 autofocus: null
2019 autofocus: null,
2020 lineNumberFormatter: function(integer) { return integer; }
2052 2021 };
2053 2022
2054 2023 var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
@@ -2080,7 +2049,13 var CodeMirror = (function() {
2080 2049 var spec = CodeMirror.resolveMode(spec);
2081 2050 var mfactory = modes[spec.name];
2082 2051 if (!mfactory) return CodeMirror.getMode(options, "text/plain");
2083 return mfactory(options, spec);
2052 var modeObj = mfactory(options, spec);
2053 if (modeExtensions.hasOwnProperty(spec.name)) {
2054 var exts = modeExtensions[spec.name];
2055 for (var prop in exts) if (exts.hasOwnProperty(prop)) modeObj[prop] = exts[prop];
2056 }
2057 modeObj.name = spec.name;
2058 return modeObj;
2084 2059 };
2085 2060 CodeMirror.listModes = function() {
2086 2061 var list = [];
@@ -2100,6 +2075,13 var CodeMirror = (function() {
2100 2075 extensions[name] = func;
2101 2076 };
2102 2077
2078 var modeExtensions = CodeMirror.modeExtensions = {};
2079 CodeMirror.extendMode = function(mode, properties) {
2080 var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
2081 for (var prop in properties) if (properties.hasOwnProperty(prop))
2082 exts[prop] = properties[prop];
2083 };
2084
2103 2085 var commands = CodeMirror.commands = {
2104 2086 selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});},
2105 2087 killLine: function(cm) {
@@ -2197,6 +2179,10 var CodeMirror = (function() {
2197 2179 function lookup(map) {
2198 2180 map = getKeyMap(map);
2199 2181 var found = map[name];
2182 if (found === false) {
2183 if (stop) stop();
2184 return true;
2185 }
2200 2186 if (found != null && handle(found)) return true;
2201 2187 if (map.nofallthrough) {
2202 2188 if (stop) stop();
@@ -2224,8 +2210,15 var CodeMirror = (function() {
2224 2210 options.value = textarea.value;
2225 2211 if (!options.tabindex && textarea.tabindex)
2226 2212 options.tabindex = textarea.tabindex;
2227 if (options.autofocus == null && textarea.getAttribute("autofocus") != null)
2228 options.autofocus = true;
2213 // Set autofocus to true if this textarea is focused, or if it has
2214 // autofocus and no other element is focused.
2215 if (options.autofocus == null) {
2216 var hasFocus = document.body;
2217 // doc.activeElement occasionally throws on IE
2218 try { hasFocus = document.activeElement; } catch(e) {}
2219 options.autofocus = hasFocus == textarea ||
2220 textarea.getAttribute("autofocus") != null && hasFocus == document.body;
2221 }
2229 2222
2230 2223 function save() {textarea.value = instance.getValue();}
2231 2224 if (textarea.form) {
@@ -2233,13 +2226,12 var CodeMirror = (function() {
2233 2226 var rmSubmit = connect(textarea.form, "submit", save, true);
2234 2227 if (typeof textarea.form.submit == "function") {
2235 2228 var realSubmit = textarea.form.submit;
2236 function wrappedSubmit() {
2229 textarea.form.submit = function wrappedSubmit() {
2237 2230 save();
2238 2231 textarea.form.submit = realSubmit;
2239 2232 textarea.form.submit();
2240 2233 textarea.form.submit = wrappedSubmit;
2241 }
2242 textarea.form.submit = wrappedSubmit;
2234 };
2243 2235 }
2244 2236 }
2245 2237
@@ -2262,6 +2254,18 var CodeMirror = (function() {
2262 2254 return instance;
2263 2255 };
2264 2256
2257 var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
2258 var ie = /MSIE \d/.test(navigator.userAgent);
2259 var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent);
2260 var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
2261 var quirksMode = ie && document.documentMode == 5;
2262 var webkit = /WebKit\//.test(navigator.userAgent);
2263 var chrome = /Chrome\//.test(navigator.userAgent);
2264 var opera = /Opera\//.test(navigator.userAgent);
2265 var safari = /Apple Computer/.test(navigator.vendor);
2266 var khtml = /KHTML\//.test(navigator.userAgent);
2267 var mac_geLion = /Mac OS X 10\D([7-9]|\d\d)\D/.test(navigator.userAgent);
2268
2265 2269 // Utility functions for working with state. Exported because modes
2266 2270 // sometimes need to do this.
2267 2271 function copyState(mode, state) {
@@ -2280,6 +2284,14 var CodeMirror = (function() {
2280 2284 return mode.startState ? mode.startState(a1, a2) : true;
2281 2285 }
2282 2286 CodeMirror.startState = startState;
2287 CodeMirror.innerMode = function(mode, state) {
2288 while (mode.innerMode) {
2289 var info = mode.innerMode(state);
2290 state = info.state;
2291 mode = info.mode;
2292 }
2293 return info || {mode: mode, state: state};
2294 };
2283 2295
2284 2296 // The character stream used by a mode's parser.
2285 2297 function StringStream(string, tabSize) {
@@ -2290,7 +2302,7 var CodeMirror = (function() {
2290 2302 StringStream.prototype = {
2291 2303 eol: function() {return this.pos >= this.string.length;},
2292 2304 sol: function() {return this.pos == 0;},
2293 peek: function() {return this.string.charAt(this.pos);},
2305 peek: function() {return this.string.charAt(this.pos) || undefined;},
2294 2306 next: function() {
2295 2307 if (this.pos < this.string.length)
2296 2308 return this.string.charAt(this.pos++);
@@ -2321,13 +2333,14 var CodeMirror = (function() {
2321 2333 indentation: function() {return countColumn(this.string, null, this.tabSize);},
2322 2334 match: function(pattern, consume, caseInsensitive) {
2323 2335 if (typeof pattern == "string") {
2324 function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
2336 var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
2325 2337 if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
2326 2338 if (consume !== false) this.pos += pattern.length;
2327 2339 return true;
2328 2340 }
2329 2341 } else {
2330 2342 var match = this.string.slice(this.pos).match(pattern);
2343 if (match && match.index > 0) return null;
2331 2344 if (match && consume !== false) this.pos += match[0].length;
2332 2345 return match;
2333 2346 }
@@ -2336,201 +2349,162 var CodeMirror = (function() {
2336 2349 };
2337 2350 CodeMirror.StringStream = StringStream;
2338 2351
2339 function MarkedText(from, to, className, marker) {
2340 this.from = from; this.to = to; this.style = className; this.marker = marker;
2341 }
2342 MarkedText.prototype = {
2343 attach: function(line) { this.marker.set.push(line); },
2344 detach: function(line) {
2345 var ix = indexOf(this.marker.set, line);
2346 if (ix > -1) this.marker.set.splice(ix, 1);
2347 },
2348 split: function(pos, lenBefore) {
2349 if (this.to <= pos && this.to != null) return null;
2350 var from = this.from < pos || this.from == null ? null : this.from - pos + lenBefore;
2351 var to = this.to == null ? null : this.to - pos + lenBefore;
2352 return new MarkedText(from, to, this.style, this.marker);
2353 },
2354 dup: function() { return new MarkedText(null, null, this.style, this.marker); },
2355 clipTo: function(fromOpen, from, toOpen, to, diff) {
2356 if (fromOpen && to > this.from && (to < this.to || this.to == null))
2357 this.from = null;
2358 else if (this.from != null && this.from >= from)
2359 this.from = Math.max(to, this.from) + diff;
2360 if (toOpen && (from < this.to || this.to == null) && (from > this.from || this.from == null))
2361 this.to = null;
2362 else if (this.to != null && this.to > from)
2363 this.to = to < this.to ? this.to + diff : from;
2364 },
2365 isDead: function() { return this.from != null && this.to != null && this.from >= this.to; },
2366 sameSet: function(x) { return this.marker == x.marker; }
2367 };
2352 function MarkedSpan(from, to, marker) {
2353 this.from = from; this.to = to; this.marker = marker;
2354 }
2355
2356 function getMarkedSpanFor(spans, marker, del) {
2357 if (spans) for (var i = 0; i < spans.length; ++i) {
2358 var span = spans[i];
2359 if (span.marker == marker) {
2360 if (del) spans.splice(i, 1);
2361 return span;
2362 }
2363 }
2364 }
2365
2366 function markedSpansBefore(old, startCh, endCh) {
2367 if (old) for (var i = 0, nw; i < old.length; ++i) {
2368 var span = old[i], marker = span.marker;
2369 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
2370 if (startsBefore || marker.type == "bookmark" && span.from == startCh && span.from != endCh) {
2371 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
2372 (nw || (nw = [])).push({from: span.from,
2373 to: endsAfter ? null : span.to,
2374 marker: marker});
2375 }
2376 }
2377 return nw;
2378 }
2379
2380 function markedSpansAfter(old, endCh) {
2381 if (old) for (var i = 0, nw; i < old.length; ++i) {
2382 var span = old[i], marker = span.marker;
2383 var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
2384 if (endsAfter || marker.type == "bookmark" && span.from == endCh) {
2385 var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
2386 (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh,
2387 to: span.to == null ? null : span.to - endCh,
2388 marker: marker});
2389 }
2390 }
2391 return nw;
2392 }
2393
2394 function updateMarkedSpans(oldFirst, oldLast, startCh, endCh, newText) {
2395 if (!oldFirst && !oldLast) return newText;
2396 // Get the spans that 'stick out' on both sides
2397 var first = markedSpansBefore(oldFirst, startCh);
2398 var last = markedSpansAfter(oldLast, endCh);
2368 2399
2369 function Bookmark(pos) {
2370 this.from = pos; this.to = pos; this.line = null;
2371 }
2372 Bookmark.prototype = {
2373 attach: function(line) { this.line = line; },
2374 detach: function(line) { if (this.line == line) this.line = null; },
2375 split: function(pos, lenBefore) {
2376 if (pos < this.from) {
2377 this.from = this.to = (this.from - pos) + lenBefore;
2378 return this;
2379 }
2380 },
2381 isDead: function() { return this.from > this.to; },
2382 clipTo: function(fromOpen, from, toOpen, to, diff) {
2383 if ((fromOpen || from < this.from) && (toOpen || to > this.to)) {
2384 this.from = 0; this.to = -1;
2385 } else if (this.from > from) {
2386 this.from = this.to = Math.max(to, this.from) + diff;
2387 }
2388 },
2389 sameSet: function(x) { return false; },
2390 find: function() {
2391 if (!this.line || !this.line.parent) return null;
2392 return {line: lineNo(this.line), ch: this.from};
2393 },
2394 clear: function() {
2395 if (this.line) {
2396 var found = indexOf(this.line.marked, this);
2397 if (found != -1) this.line.marked.splice(found, 1);
2398 this.line = null;
2399 }
2400 }
2401 };
2400 // Next, merge those two ends
2401 var sameLine = newText.length == 1, offset = lst(newText).length + (sameLine ? startCh : 0);
2402 if (first) {
2403 // Fix up .to properties of first
2404 for (var i = 0; i < first.length; ++i) {
2405 var span = first[i];
2406 if (span.to == null) {
2407 var found = getMarkedSpanFor(last, span.marker);
2408 if (!found) span.to = startCh;
2409 else if (sameLine) span.to = found.to == null ? null : found.to + offset;
2410 }
2411 }
2412 }
2413 if (last) {
2414 // Fix up .from in last (or move them into first in case of sameLine)
2415 for (var i = 0; i < last.length; ++i) {
2416 var span = last[i];
2417 if (span.to != null) span.to += offset;
2418 if (span.from == null) {
2419 var found = getMarkedSpanFor(first, span.marker);
2420 if (!found) {
2421 span.from = offset;
2422 if (sameLine) (first || (first = [])).push(span);
2423 }
2424 } else {
2425 span.from += offset;
2426 if (sameLine) (first || (first = [])).push(span);
2427 }
2428 }
2429 }
2430
2431 var newMarkers = [newHL(newText[0], first)];
2432 if (!sameLine) {
2433 // Fill gap with whole-line-spans
2434 var gap = newText.length - 2, gapMarkers;
2435 if (gap > 0 && first)
2436 for (var i = 0; i < first.length; ++i)
2437 if (first[i].to == null)
2438 (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker});
2439 for (var i = 0; i < gap; ++i)
2440 newMarkers.push(newHL(newText[i+1], gapMarkers));
2441 newMarkers.push(newHL(lst(newText), last));
2442 }
2443 return newMarkers;
2444 }
2445
2446 // hl stands for history-line, a data structure that can be either a
2447 // string (line without markers) or a {text, markedSpans} object.
2448 function hlText(val) { return typeof val == "string" ? val : val.text; }
2449 function hlSpans(val) { return typeof val == "string" ? null : val.markedSpans; }
2450 function newHL(text, spans) { return spans ? {text: text, markedSpans: spans} : text; }
2451
2452 function detachMarkedSpans(line) {
2453 var spans = line.markedSpans;
2454 if (!spans) return;
2455 for (var i = 0; i < spans.length; ++i) {
2456 var lines = spans[i].marker.lines;
2457 var ix = indexOf(lines, line);
2458 lines.splice(ix, 1);
2459 }
2460 line.markedSpans = null;
2461 }
2462
2463 function attachMarkedSpans(line, spans) {
2464 if (!spans) return;
2465 for (var i = 0; i < spans.length; ++i)
2466 var marker = spans[i].marker.lines.push(line);
2467 line.markedSpans = spans;
2468 }
2469
2470 // When measuring the position of the end of a line, different
2471 // browsers require different approaches. If an empty span is added,
2472 // many browsers report bogus offsets. Of those, some (Webkit,
2473 // recent IE) will accept a space without moving the whole span to
2474 // the next line when wrapping it, others work with a zero-width
2475 // space.
2476 var eolSpanContent = " ";
2477 if (gecko || (ie && !ie_lt8)) eolSpanContent = "\u200b";
2478 else if (opera) eolSpanContent = "";
2402 2479
2403 2480 // Line objects. These hold state related to a line, including
2404 2481 // highlighting info (the styles array).
2405 function Line(text, styles) {
2406 this.styles = styles || [text, null];
2482 function Line(text, markedSpans) {
2407 2483 this.text = text;
2408 2484 this.height = 1;
2409 this.marked = this.gutterMarker = this.className = this.bgClassName = this.handlers = null;
2410 this.stateAfter = this.parent = this.hidden = null;
2411 }
2412 Line.inheritMarks = function(text, orig) {
2413 var ln = new Line(text), mk = orig && orig.marked;
2414 if (mk) {
2415 for (var i = 0; i < mk.length; ++i) {
2416 if (mk[i].to == null && mk[i].style) {
2417 var newmk = ln.marked || (ln.marked = []), mark = mk[i];
2418 var nmark = mark.dup(); newmk.push(nmark); nmark.attach(ln);
2419 }
2420 }
2421 }
2422 return ln;
2485 attachMarkedSpans(this, markedSpans);
2423 2486 }
2424 2487 Line.prototype = {
2425 // Replace a piece of a line, keeping the styles around it intact.
2426 replace: function(from, to_, text) {
2427 var st = [], mk = this.marked, to = to_ == null ? this.text.length : to_;
2428 copyStyles(0, from, this.styles, st);
2429 if (text) st.push(text, null);
2430 copyStyles(to, this.text.length, this.styles, st);
2431 this.styles = st;
2432 this.text = this.text.slice(0, from) + text + this.text.slice(to);
2433 this.stateAfter = null;
2434 if (mk) {
2435 var diff = text.length - (to - from);
2436 for (var i = 0; i < mk.length; ++i) {
2437 var mark = mk[i];
2438 mark.clipTo(from == null, from || 0, to_ == null, to, diff);
2439 if (mark.isDead()) {mark.detach(this); mk.splice(i--, 1);}
2440 }
2441 }
2442 },
2443 // Split a part off a line, keeping styles and markers intact.
2444 split: function(pos, textBefore) {
2445 var st = [textBefore, null], mk = this.marked;
2446 copyStyles(pos, this.text.length, this.styles, st);
2447 var taken = new Line(textBefore + this.text.slice(pos), st);
2448 if (mk) {
2449 for (var i = 0; i < mk.length; ++i) {
2450 var mark = mk[i];
2451 var newmark = mark.split(pos, textBefore.length);
2452 if (newmark) {
2453 if (!taken.marked) taken.marked = [];
2454 taken.marked.push(newmark); newmark.attach(taken);
2455 if (newmark == mark) mk.splice(i--, 1);
2456 }
2457 }
2458 }
2459 return taken;
2460 },
2461 append: function(line) {
2462 var mylen = this.text.length, mk = line.marked, mymk = this.marked;
2463 this.text += line.text;
2464 copyStyles(0, line.text.length, line.styles, this.styles);
2465 if (mymk) {
2466 for (var i = 0; i < mymk.length; ++i)
2467 if (mymk[i].to == null) mymk[i].to = mylen;
2468 }
2469 if (mk && mk.length) {
2470 if (!mymk) this.marked = mymk = [];
2471 outer: for (var i = 0; i < mk.length; ++i) {
2472 var mark = mk[i];
2473 if (!mark.from) {
2474 for (var j = 0; j < mymk.length; ++j) {
2475 var mymark = mymk[j];
2476 if (mymark.to == mylen && mymark.sameSet(mark)) {
2477 mymark.to = mark.to == null ? null : mark.to + mylen;
2478 if (mymark.isDead()) {
2479 mymark.detach(this);
2480 mk.splice(i--, 1);
2481 }
2482 continue outer;
2483 }
2484 }
2485 }
2486 mymk.push(mark);
2487 mark.attach(this);
2488 mark.from += mylen;
2489 if (mark.to != null) mark.to += mylen;
2490 }
2491 }
2492 },
2493 fixMarkEnds: function(other) {
2494 var mk = this.marked, omk = other.marked;
2495 if (!mk) return;
2496 for (var i = 0; i < mk.length; ++i) {
2497 var mark = mk[i], close = mark.to == null;
2498 if (close && omk) {
2499 for (var j = 0; j < omk.length; ++j)
2500 if (omk[j].sameSet(mark)) {close = false; break;}
2501 }
2502 if (close) mark.to = this.text.length;
2503 }
2504 },
2505 fixMarkStarts: function() {
2506 var mk = this.marked;
2507 if (!mk) return;
2508 for (var i = 0; i < mk.length; ++i)
2509 if (mk[i].from == null) mk[i].from = 0;
2510 },
2511 addMark: function(mark) {
2512 mark.attach(this);
2513 if (this.marked == null) this.marked = [];
2514 this.marked.push(mark);
2515 this.marked.sort(function(a, b){return (a.from || 0) - (b.from || 0);});
2488 update: function(text, markedSpans) {
2489 this.text = text;
2490 this.stateAfter = this.styles = null;
2491 detachMarkedSpans(this);
2492 attachMarkedSpans(this, markedSpans);
2516 2493 },
2517 2494 // Run the given mode's parser over a line, update the styles
2518 2495 // array, which contains alternating fragments of text and CSS
2519 2496 // classes.
2520 2497 highlight: function(mode, state, tabSize) {
2521 var stream = new StringStream(this.text, tabSize), st = this.styles, pos = 0;
2522 var changed = false, curWord = st[0], prevWord;
2498 var stream = new StringStream(this.text, tabSize), st = this.styles || (this.styles = []);
2499 var pos = st.length = 0;
2523 2500 if (this.text == "" && mode.blankLine) mode.blankLine(state);
2524 2501 while (!stream.eol()) {
2525 var style = mode.token(stream, state);
2526 var substr = this.text.slice(stream.start, stream.pos);
2502 var style = mode.token(stream, state), substr = stream.current();
2527 2503 stream.start = stream.pos;
2528 if (pos && st[pos-1] == style)
2504 if (pos && st[pos-1] == style) {
2529 2505 st[pos-2] += substr;
2530 else if (substr) {
2531 if (!changed && (st[pos+1] != style || (pos && st[pos-2] != prevWord))) changed = true;
2506 } else if (substr) {
2532 2507 st[pos++] = substr; st[pos++] = style;
2533 prevWord = curWord; curWord = st[pos];
2534 2508 }
2535 2509 // Give up when line is ridiculously long
2536 2510 if (stream.pos > 5000) {
@@ -2538,17 +2512,19 var CodeMirror = (function() {
2538 2512 break;
2539 2513 }
2540 2514 }
2541 if (st.length != pos) {st.length = pos; changed = true;}
2542 if (pos && st[pos-2] != prevWord) changed = true;
2543 // Short lines with simple highlights return null, and are
2544 // counted as changed by the driver because they are likely to
2545 // highlight the same way in various contexts.
2546 return changed || (st.length < 5 && this.text.length < 10 ? null : false);
2515 },
2516 process: function(mode, state, tabSize) {
2517 var stream = new StringStream(this.text, tabSize);
2518 if (this.text == "" && mode.blankLine) mode.blankLine(state);
2519 while (!stream.eol() && stream.pos <= 5000) {
2520 mode.token(stream, state);
2521 stream.start = stream.pos;
2522 }
2547 2523 },
2548 2524 // Fetch the parser token for a given character. Useful for hacks
2549 2525 // that want to inspect the mode state (say, for completion).
2550 getTokenAt: function(mode, state, ch) {
2551 var txt = this.text, stream = new StringStream(txt);
2526 getTokenAt: function(mode, state, tabSize, ch) {
2527 var txt = this.text, stream = new StringStream(txt, tabSize);
2552 2528 while (stream.pos < ch && !stream.eol()) {
2553 2529 stream.start = stream.pos;
2554 2530 var style = mode.token(stream, state);
@@ -2562,98 +2538,108 var CodeMirror = (function() {
2562 2538 indentation: function(tabSize) {return countColumn(this.text, null, tabSize);},
2563 2539 // Produces an HTML fragment for the line, taking selection,
2564 2540 // marking, and highlighting into account.
2565 getHTML: function(makeTab, wrapAt, wrapId, wrapWBR) {
2566 var html = [], first = true, col = 0;
2567 function span_(text, style) {
2541 getContent: function(tabSize, wrapAt, compensateForWrapping) {
2542 var first = true, col = 0, specials = /[\t\u0000-\u0019\u200b\u2028\u2029\uFEFF]/g;
2543 var pre = elt("pre");
2544 function span_(html, text, style) {
2568 2545 if (!text) return;
2569 2546 // Work around a bug where, in some compat modes, IE ignores leading spaces
2570 2547 if (first && ie && text.charAt(0) == " ") text = "\u00a0" + text.slice(1);
2571 2548 first = false;
2572 if (text.indexOf("\t") == -1) {
2549 if (!specials.test(text)) {
2573 2550 col += text.length;
2574 var escaped = htmlEscape(text);
2551 var content = document.createTextNode(text);
2575 2552 } else {
2576 var escaped = "";
2577 for (var pos = 0;;) {
2578 var idx = text.indexOf("\t", pos);
2579 if (idx == -1) {
2580 escaped += htmlEscape(text.slice(pos));
2581 col += text.length - pos;
2582 break;
2553 var content = document.createDocumentFragment(), pos = 0;
2554 while (true) {
2555 specials.lastIndex = pos;
2556 var m = specials.exec(text);
2557 var skipped = m ? m.index - pos : text.length - pos;
2558 if (skipped) {
2559 content.appendChild(document.createTextNode(text.slice(pos, pos + skipped)));
2560 col += skipped;
2561 }
2562 if (!m) break;
2563 pos += skipped + 1;
2564 if (m[0] == "\t") {
2565 var tabWidth = tabSize - col % tabSize;
2566 content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
2567 col += tabWidth;
2583 2568 } else {
2584 col += idx - pos;
2585 var tab = makeTab(col);
2586 escaped += htmlEscape(text.slice(pos, idx)) + tab.html;
2587 col += tab.width;
2588 pos = idx + 1;
2589 }
2590 }
2591 }
2592 if (style) html.push('<span class="', style, '">', escaped, "</span>");
2593 else html.push(escaped);
2569 var token = elt("span", "\u2022", "cm-invalidchar");
2570 token.title = "\\u" + m[0].charCodeAt(0).toString(16);
2571 content.appendChild(token);
2572 col += 1;
2573 }
2574 }
2575 }
2576 if (style) html.appendChild(elt("span", [content], style));
2577 else html.appendChild(content);
2594 2578 }
2595 2579 var span = span_;
2596 2580 if (wrapAt != null) {
2597 var outPos = 0, open = "<span id=\"" + wrapId + "\">";
2598 span = function(text, style) {
2581 var outPos = 0, anchor = pre.anchor = elt("span");
2582 span = function(html, text, style) {
2599 2583 var l = text.length;
2600 2584 if (wrapAt >= outPos && wrapAt < outPos + l) {
2601 2585 if (wrapAt > outPos) {
2602 span_(text.slice(0, wrapAt - outPos), style);
2586 span_(html, text.slice(0, wrapAt - outPos), style);
2603 2587 // See comment at the definition of spanAffectsWrapping
2604 if (wrapWBR) html.push("<wbr>");
2605 }
2606 html.push(open);
2588 if (compensateForWrapping) html.appendChild(elt("wbr"));
2589 }
2590 html.appendChild(anchor);
2607 2591 var cut = wrapAt - outPos;
2608 span_(opera ? text.slice(cut, cut + 1) : text.slice(cut), style);
2609 html.push("</span>");
2610 if (opera) span_(text.slice(cut + 1), style);
2592 span_(anchor, opera ? text.slice(cut, cut + 1) : text.slice(cut), style);
2593 if (opera) span_(html, text.slice(cut + 1), style);
2611 2594 wrapAt--;
2612 2595 outPos += l;
2613 2596 } else {
2614 2597 outPos += l;
2615 span_(text, style);
2616 // Output empty wrapper when at end of line
2617 if (outPos == wrapAt && outPos == len) html.push(open + " </span>");
2598 span_(html, text, style);
2599 if (outPos == wrapAt && outPos == len) {
2600 setTextContent(anchor, eolSpanContent);
2601 html.appendChild(anchor);
2602 }
2618 2603 // Stop outputting HTML when gone sufficiently far beyond measure
2619 2604 else if (outPos > wrapAt + 10 && /\s/.test(text)) span = function(){};
2620 2605 }
2621 }
2606 };
2622 2607 }
2623 2608
2624 var st = this.styles, allText = this.text, marked = this.marked;
2609 var st = this.styles, allText = this.text, marked = this.markedSpans;
2625 2610 var len = allText.length;
2626 2611 function styleToClass(style) {
2627 2612 if (!style) return null;
2628 2613 return "cm-" + style.replace(/ +/g, " cm-");
2629 2614 }
2630
2631 2615 if (!allText && wrapAt == null) {
2632 span(" ");
2616 span(pre, " ");
2633 2617 } else if (!marked || !marked.length) {
2634 2618 for (var i = 0, ch = 0; ch < len; i+=2) {
2635 2619 var str = st[i], style = st[i+1], l = str.length;
2636 2620 if (ch + l > len) str = str.slice(0, len - ch);
2637 2621 ch += l;
2638 span(str, styleToClass(style));
2622 span(pre, str, styleToClass(style));
2639 2623 }
2640 2624 } else {
2625 marked.sort(function(a, b) { return a.from - b.from; });
2641 2626 var pos = 0, i = 0, text = "", style, sg = 0;
2642 2627 var nextChange = marked[0].from || 0, marks = [], markpos = 0;
2643 function advanceMarks() {
2628 var advanceMarks = function() {
2644 2629 var m;
2645 2630 while (markpos < marked.length &&
2646 2631 ((m = marked[markpos]).from == pos || m.from == null)) {
2647 if (m.style != null) marks.push(m);
2632 if (m.marker.type == "range") marks.push(m);
2648 2633 ++markpos;
2649 2634 }
2650 2635 nextChange = markpos < marked.length ? marked[markpos].from : Infinity;
2651 2636 for (var i = 0; i < marks.length; ++i) {
2652 var to = marks[i].to || Infinity;
2637 var to = marks[i].to;
2638 if (to == null) to = Infinity;
2653 2639 if (to == pos) marks.splice(i--, 1);
2654 2640 else nextChange = Math.min(to, nextChange);
2655 2641 }
2656 }
2642 };
2657 2643 var m = 0;
2658 2644 while (pos < len) {
2659 2645 if (nextChange == pos) advanceMarks();
@@ -2662,9 +2648,13 var CodeMirror = (function() {
2662 2648 if (text) {
2663 2649 var end = pos + text.length;
2664 2650 var appliedStyle = style;
2665 for (var j = 0; j < marks.length; ++j)
2666 appliedStyle = (appliedStyle ? appliedStyle + " " : "") + marks[j].style;
2667 span(end > upto ? text.slice(0, upto - pos) : text, appliedStyle);
2651 for (var j = 0; j < marks.length; ++j) {
2652 var mark = marks[j];
2653 appliedStyle = (appliedStyle ? appliedStyle + " " : "") + mark.marker.style;
2654 if (mark.marker.endStyle && mark.to === Math.min(end, upto)) appliedStyle += " " + mark.marker.endStyle;
2655 if (mark.marker.startStyle && mark.from === pos) appliedStyle += " " + mark.marker.startStyle;
2656 }
2657 span(pre, end > upto ? text.slice(0, upto - pos) : text, appliedStyle);
2668 2658 if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
2669 2659 pos = end;
2670 2660 }
@@ -2672,28 +2662,13 var CodeMirror = (function() {
2672 2662 }
2673 2663 }
2674 2664 }
2675 return html.join("");
2665 return pre;
2676 2666 },
2677 2667 cleanUp: function() {
2678 2668 this.parent = null;
2679 if (this.marked)
2680 for (var i = 0, e = this.marked.length; i < e; ++i) this.marked[i].detach(this);
2669 detachMarkedSpans(this);
2681 2670 }
2682 2671 };
2683 // Utility used by replace and split above
2684 function copyStyles(from, to, source, dest) {
2685 for (var i = 0, pos = 0, state = 0; pos < to; i+=2) {
2686 var part = source[i], end = pos + part.length;
2687 if (state == 0) {
2688 if (end > from) dest.push(part.slice(from - pos, Math.min(part.length, to - pos)), source[i+1]);
2689 if (end >= from) state = 1;
2690 } else if (state == 1) {
2691 if (end > to) dest.push(part.slice(0, to - pos), source[i+1]);
2692 else dest.push(part, source[i+1]);
2693 }
2694 pos = end;
2695 }
2696 }
2697 2672
2698 2673 // Data structure that holds the sequence of lines.
2699 2674 function LeafChunk(lines) {
@@ -2894,7 +2869,7 var CodeMirror = (function() {
2894 2869 History.prototype = {
2895 2870 addChange: function(start, added, old) {
2896 2871 this.undone.length = 0;
2897 var time = +new Date, cur = this.done[this.done.length - 1], last = cur && cur[cur.length - 1];
2872 var time = +new Date, cur = lst(this.done), last = cur && lst(cur);
2898 2873 var dtime = time - this.time;
2899 2874
2900 2875 if (this.compound && cur && !this.closed) {
@@ -2943,10 +2918,14 var CodeMirror = (function() {
2943 2918
2944 2919 function e_target(e) {return e.target || e.srcElement;}
2945 2920 function e_button(e) {
2946 if (e.which) return e.which;
2947 else if (e.button & 1) return 1;
2948 else if (e.button & 2) return 3;
2949 else if (e.button & 4) return 2;
2921 var b = e.which;
2922 if (b == null) {
2923 if (e.button & 1) b = 1;
2924 else if (e.button & 2) b = 3;
2925 else if (e.button & 4) b = 2;
2926 }
2927 if (mac && e.ctrlKey && b == 1) b = 3;
2928 return b;
2950 2929 }
2951 2930
2952 2931 // Allow 3rd-party code to override event properties by adding an override
@@ -2975,30 +2954,18 var CodeMirror = (function() {
2975 2954
2976 2955 var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
2977 2956
2978 var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
2979 var ie = /MSIE \d/.test(navigator.userAgent);
2980 var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent);
2981 var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
2982 var quirksMode = ie && document.documentMode == 5;
2983 var webkit = /WebKit\//.test(navigator.userAgent);
2984 var chrome = /Chrome\//.test(navigator.userAgent);
2985 var opera = /Opera\//.test(navigator.userAgent);
2986 var safari = /Apple Computer/.test(navigator.vendor);
2987 var khtml = /KHTML\//.test(navigator.userAgent);
2988 var mac_geLion = /Mac OS X 10\D([7-9]|\d\d)\D/.test(navigator.userAgent);
2989
2990 2957 // Detect drag-and-drop
2991 2958 var dragAndDrop = function() {
2992 2959 // There is *some* kind of drag-and-drop support in IE6-8, but I
2993 2960 // couldn't get it to work yet.
2994 2961 if (ie_lt9) return false;
2995 var div = document.createElement('div');
2962 var div = elt('div');
2996 2963 return "draggable" in div || "dragDrop" in div;
2997 2964 }();
2998 2965
2999 2966 // Feature-detect whether newlines in textareas are converted to \r\n
3000 2967 var lineSep = function () {
3001 var te = document.createElement("textarea");
2968 var te = elt("textarea");
3002 2969 te.value = "foo\nbar";
3003 2970 if (te.value.indexOf("\r") > -1) return "\r\n";
3004 2971 return "\n";
@@ -3030,31 +2997,7 var CodeMirror = (function() {
3030 2997 return n;
3031 2998 }
3032 2999
3033 function computedStyle(elt) {
3034 if (elt.currentStyle) return elt.currentStyle;
3035 return window.getComputedStyle(elt, null);
3036 }
3037
3038 // Find the position of an element by following the offsetParent chain.
3039 // If screen==true, it returns screen (rather than page) coordinates.
3040 3000 function eltOffset(node, screen) {
3041 var bod = node.ownerDocument.body;
3042 var x = 0, y = 0, skipBody = false;
3043 for (var n = node; n; n = n.offsetParent) {
3044 var ol = n.offsetLeft, ot = n.offsetTop;
3045 // Firefox reports weird inverted offsets when the body has a border.
3046 if (n == bod) { x += Math.abs(ol); y += Math.abs(ot); }
3047 else { x += ol, y += ot; }
3048 if (screen && computedStyle(n).position == "fixed")
3049 skipBody = true;
3050 }
3051 var e = screen && !skipBody ? null : bod;
3052 for (var n = node.parentNode; n != e; n = n.parentNode)
3053 if (n.scrollLeft != null) { x -= n.scrollLeft; y -= n.scrollTop;}
3054 return {left: x, top: y};
3055 }
3056 // Use the faster and saner getBoundingClientRect method when possible.
3057 if (document.documentElement.getBoundingClientRect != null) eltOffset = function(node, screen) {
3058 3001 // Take the parts of bounding client rect that we are interested in so we are able to edit if need be,
3059 3002 // since the returned value cannot be changed externally (they are kept in sync as the element moves within the page)
3060 3003 try { var box = node.getBoundingClientRect(); box = { top: box.top, left: box.left }; }
@@ -3070,12 +3013,21 var CodeMirror = (function() {
3070 3013 }
3071 3014 }
3072 3015 return box;
3073 };
3016 }
3074 3017
3075 // Get a node's text content.
3076 3018 function eltText(node) {
3077 3019 return node.textContent || node.innerText || node.nodeValue || "";
3078 3020 }
3021
3022 var spaceStrs = [""];
3023 function spaceStr(n) {
3024 while (spaceStrs.length <= n)
3025 spaceStrs.push(lst(spaceStrs) + " ");
3026 return spaceStrs[n];
3027 }
3028
3029 function lst(arr) { return arr[arr.length-1]; }
3030
3079 3031 function selectInput(node) {
3080 3032 if (ios) { // Mobile Safari apparently has a bug where select() is broken.
3081 3033 node.selectionStart = 0;
@@ -3088,27 +3040,27 var CodeMirror = (function() {
3088 3040 function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
3089 3041 function copyPos(x) {return {line: x.line, ch: x.ch};}
3090 3042
3091 var escapeElement = document.createElement("pre");
3092 function htmlEscape(str) {
3093 escapeElement.textContent = str;
3094 return escapeElement.innerHTML;
3095 }
3096 // Recent (late 2011) Opera betas insert bogus newlines at the start
3097 // of the textContent, so we strip those.
3098 if (htmlEscape("a") == "\na") {
3099 htmlEscape = function(str) {
3100 escapeElement.textContent = str;
3101 return escapeElement.innerHTML.slice(1);
3102 };
3103 // Some IEs don't preserve tabs through innerHTML
3104 } else if (htmlEscape("\t") != "\t") {
3105 htmlEscape = function(str) {
3106 escapeElement.innerHTML = "";
3107 escapeElement.appendChild(document.createTextNode(str));
3108 return escapeElement.innerHTML;
3109 };
3110 }
3111 CodeMirror.htmlEscape = htmlEscape;
3043 function elt(tag, content, className, style) {
3044 var e = document.createElement(tag);
3045 if (className) e.className = className;
3046 if (style) e.style.cssText = style;
3047 if (typeof content == "string") setTextContent(e, content);
3048 else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
3049 return e;
3050 }
3051 function removeChildren(e) {
3052 e.innerHTML = "";
3053 return e;
3054 }
3055 function removeChildrenAndAdd(parent, e) {
3056 removeChildren(parent).appendChild(e);
3057 }
3058 function setTextContent(e, str) {
3059 if (ie_lt9) {
3060 e.innerHTML = "";
3061 e.appendChild(document.createTextNode(str));
3062 } else e.textContent = str;
3063 }
3112 3064
3113 3065 // Used to position the cursor after an undo/redo by finding the
3114 3066 // last edited character.
@@ -3133,14 +3085,22 var CodeMirror = (function() {
3133 3085 // See if "".split is the broken IE version, if so, provide an
3134 3086 // alternative way to split lines.
3135 3087 var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
3136 var pos = 0, nl, result = [];
3137 while ((nl = string.indexOf("\n", pos)) > -1) {
3138 result.push(string.slice(pos, string.charAt(nl-1) == "\r" ? nl - 1 : nl));
3088 var pos = 0, result = [], l = string.length;
3089 while (pos <= l) {
3090 var nl = string.indexOf("\n", pos);
3091 if (nl == -1) nl = string.length;
3092 var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
3093 var rt = line.indexOf("\r");
3094 if (rt != -1) {
3095 result.push(line.slice(0, rt));
3096 pos += rt + 1;
3097 } else {
3098 result.push(line);
3139 3099 pos = nl + 1;
3140 3100 }
3141 result.push(string.slice(pos));
3101 }
3142 3102 return result;
3143 } : function(string){return string.split(/\r?\n/);};
3103 } : function(string){return string.split(/\r\n?|\n/);};
3144 3104 CodeMirror.splitLines = splitLines;
3145 3105
3146 3106 var hasSelection = window.getSelection ? function(te) {
@@ -3175,5 +3135,7 var CodeMirror = (function() {
3175 3135 for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
3176 3136 })();
3177 3137
3138 CodeMirror.version = "2.34";
3139
3178 3140 return CodeMirror;
3179 3141 })();
General Comments 0
You need to be logged in to leave comments. Login now