Debian Codegraph @

share/www/js/editor.js

raw
1 /* The Editor object manages the content of the editable frame. It
2 * catches events, colours nodes, and indents lines. This file also
3 * holds some functions for transforming arbitrary DOM structures into
4 * plain sequences of <span> and <br> elements
5 */
6
7 var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent);
8 var webkit = /AppleWebKit/.test(navigator.userAgent);
9 var safari = /Apple Computer, Inc/.test(navigator.vendor);
10 var gecko = navigator.userAgent.match(/gecko\/(\d{8})/i);
11 if (gecko) gecko = Number(gecko[1]);
12 var mac = /Mac/.test(navigator.platform);
13
14 // TODO this is related to the backspace-at-end-of-line bug. Remove
15 // this if Opera gets their act together, make the version check more
16 // broad if they don't.
17 var brokenOpera = window.opera && /Version\/10.[56]/.test(navigator.userAgent);
18 // TODO remove this once WebKit 533 becomes less common.
19 var slowWebkit = /AppleWebKit\/533/.test(navigator.userAgent);
20
21 // Make sure a string does not contain two consecutive 'collapseable'
22 // whitespace characters.
23 function makeWhiteSpace(n) {
24 var buffer = [], nb = true;
25 for (; n > 0; n--) {
26 buffer.push((nb || n == 1) ? nbsp : " ");
27 nb ^= true;
28 }
29 return buffer.join("");
30 }
31
32 // Create a set of white-space characters that will not be collapsed
33 // by the browser, but will not break text-wrapping either.
34 function fixSpaces(string) {
35 if (string.charAt(0) == " ") string = nbsp + string.slice(1);
36 return string.replace(/\t/g, function() {return makeWhiteSpace(indentUnit);})
37 .replace(/[ \u00a0]{2,}/g, function(s) {return makeWhiteSpace(s.length);});
38 }
39
40 function cleanText(text) {
41 return text.replace(/\u00a0/g, " ").replace(/\u200b/g, "");
42 }
43
44 // Create a SPAN node with the expected properties for document part
45 // spans.
46 function makePartSpan(value) {
47 var text = value;
48 if (value.nodeType == 3) text = value.nodeValue;
49 else value = document.createTextNode(text);
50
51 var span = document.createElement("SPAN");
52 span.isPart = true;
53 span.appendChild(value);
54 span.currentText = text;
55 return span;
56 }
57
58 function alwaysZero() {return 0;}
59
60 // On webkit, when the last BR of the document does not have text
61 // behind it, the cursor can not be put on the line after it. This
62 // makes pressing enter at the end of the document occasionally do
63 // nothing (or at least seem to do nothing). To work around it, this
64 // function makes sure the document ends with a span containing a
65 // zero-width space character. The traverseDOM iterator filters such
66 // character out again, so that the parsers won't see them. This
67 // function is called from a few strategic places to make sure the
68 // zwsp is restored after the highlighting process eats it.
69 var webkitLastLineHack = webkit ?
70 function(container) {
71 var last = container.lastChild;
72 if (!last || !last.hackBR) {
73 var br = document.createElement("BR");
74 br.hackBR = true;
75 container.appendChild(br);
76 }
77 } : function() {};
78
79 var Editor = (function(){
80 // The HTML elements whose content should be suffixed by a newline
81 // when converting them to flat text.
82 var newlineElements = {"P": true, "DIV": true, "LI": true};
83
84 function asEditorLines(string) {
85 var tab = makeWhiteSpace(indentUnit);
86 return map(string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n").split("\n"), fixSpaces);
87 }
88
89 // Helper function for traverseDOM. Flattens an arbitrary DOM node
90 // into an array of textnodes and <br> tags.
91 function simplifyDOM(root, atEnd) {
92 var result = [];
93 var leaving = true;
94
95 function simplifyNode(node, top) {
96 if (node.nodeType == 3) {
97 var text = node.nodeValue = fixSpaces(node.nodeValue.replace(/[\r\u200b]/g, "").replace(/\n/g, " "));
98 if (text.length) leaving = false;
99 result.push(node);
100 }
101 else if (isBR(node) && node.childNodes.length == 0) {
102 leaving = true;
103 result.push(node);
104 }
105 else {
106 for (var n = node.firstChild; n; n = n.nextSibling) simplifyNode(n);
107 if (!leaving && newlineElements.hasOwnProperty(node.nodeName.toUpperCase())) {
108 leaving = true;
109 if (!atEnd || !top)
110 result.push(document.createElement("BR"));
111 }
112 }
113 }
114
115 simplifyNode(root, true);
116 return result;
117 }
118
119 // Creates a MochiKit-style iterator that goes over a series of DOM
120 // nodes. The values it yields are strings, the textual content of
121 // the nodes. It makes sure that all nodes up to and including the
122 // one whose text is being yielded have been 'normalized' to be just
123 // <span> and <br> elements.
124 function traverseDOM(start){
125 var nodeQueue = [];
126
127 // Create a function that can be used to insert nodes after the
128 // one given as argument.
129 function pointAt(node){
130 var parent = node.parentNode;
131 var next = node.nextSibling;
132 return function(newnode) {
133 parent.insertBefore(newnode, next);
134 };
135 }
136 var point = null;
137
138 // This an Opera-specific hack -- always insert an empty span
139 // between two BRs, because Opera's cursor code gets terribly
140 // confused when the cursor is between two BRs.
141 var afterBR = true;
142
143 // Insert a normalized node at the current point. If it is a text
144 // node, wrap it in a <span>, and give that span a currentText
145 // property -- this is used to cache the nodeValue, because
146 // directly accessing nodeValue is horribly slow on some browsers.
147 // The dirty property is used by the highlighter to determine
148 // which parts of the document have to be re-highlighted.
149 function insertPart(part){
150 var text = "\n";
151 if (part.nodeType == 3) {
152 select.snapshotChanged();
153 part = makePartSpan(part);
154 text = part.currentText;
155 afterBR = false;
156 }
157 else {
158 if (afterBR && window.opera)
159 point(makePartSpan(""));
160 afterBR = true;
161 }
162 part.dirty = true;
163 nodeQueue.push(part);
164 point(part);
165 return text;
166 }
167
168 // Extract the text and newlines from a DOM node, insert them into
169 // the document, and return the textual content. Used to replace
170 // non-normalized nodes.
171 function writeNode(node, end) {
172 var simplified = simplifyDOM(node, end);
173 for (var i = 0; i < simplified.length; i++)
174 simplified[i] = insertPart(simplified[i]);
175 return simplified.join("");
176 }
177
178 // Check whether a node is a normalized <span> element.
179 function partNode(node){
180 if (node.isPart && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
181 node.currentText = node.firstChild.nodeValue;
182 return !/[\n\t\r]/.test(node.currentText);
183 }
184 return false;
185 }
186
187 // Advance to next node, return string for current node.
188 function next() {
189 if (!start) throw StopIteration;
190 var node = start;
191 start = node.nextSibling;
192
193 if (partNode(node)){
194 nodeQueue.push(node);
195 afterBR = false;
196 return node.currentText;
197 }
198 else if (isBR(node)) {
199 if (afterBR && window.opera)
200 node.parentNode.insertBefore(makePartSpan(""), node);
201 nodeQueue.push(node);
202 afterBR = true;
203 return "\n";
204 }
205 else {
206 var end = !node.nextSibling;
207 point = pointAt(node);
208 removeElement(node);
209 return writeNode(node, end);
210 }
211 }
212
213 // MochiKit iterators are objects with a next function that
214 // returns the next value or throws StopIteration when there are
215 // no more values.
216 return {next: next, nodes: nodeQueue};
217 }
218
219 // Determine the text size of a processed node.
220 function nodeSize(node) {
221 return isBR(node) ? 1 : node.currentText.length;
222 }
223
224 // Search backwards through the top-level nodes until the next BR or
225 // the start of the frame.
226 function startOfLine(node) {
227 while (node && !isBR(node)) node = node.previousSibling;
228 return node;
229 }
230 function endOfLine(node, container) {
231 if (!node) node = container.firstChild;
232 else if (isBR(node)) node = node.nextSibling;
233
234 while (node && !isBR(node)) node = node.nextSibling;
235 return node;
236 }
237
238 function time() {return new Date().getTime();}
239
240 // Client interface for searching the content of the editor. Create
241 // these by calling CodeMirror.getSearchCursor. To use, call
242 // findNext on the resulting object -- this returns a boolean
243 // indicating whether anything was found, and can be called again to
244 // skip to the next find. Use the select and replace methods to
245 // actually do something with the found locations.
246 function SearchCursor(editor, string, from, caseFold) {
247 this.editor = editor;
248 this.history = editor.history;
249 this.history.commit();
250 this.valid = !!string;
251 this.atOccurrence = false;
252 if (caseFold == undefined) caseFold = string == string.toLowerCase();
253
254 function getText(node){
255 var line = cleanText(editor.history.textAfter(node));
256 return (caseFold ? line.toLowerCase() : line);
257 }
258
259 var topPos = {node: null, offset: 0};
260 if (from && typeof from == "object" && typeof from.character == "number") {
261 editor.checkLine(from.line);
262 var pos = {node: from.line, offset: from.character};
263 this.pos = {from: pos, to: pos};
264 }
265 else if (from) {
266 this.pos = {from: select.cursorPos(editor.container, true) || topPos,
267 to: select.cursorPos(editor.container, false) || topPos};
268 }
269 else {
270 this.pos = {from: topPos, to: topPos};
271 }
272
273 if (caseFold) string = string.toLowerCase();
274 // Create a matcher function based on the kind of string we have.
275 var target = string.split("\n");
276 this.matches = (target.length == 1) ?
277 // For one-line strings, searching can be done simply by calling
278 // indexOf or lastIndexOf on the current line.
279 function(reverse, node, offset) {
280 var line = getText(node), len = string.length, match;
281 if (reverse ? (offset >= len && (match = line.lastIndexOf(string, offset - len)) != -1)
282 : (match = line.indexOf(string, offset)) != -1)
283 return {from: {node: node, offset: match},
284 to: {node: node, offset: match + len}};
285 } :
286 // Multi-line strings require internal iteration over lines, and
287 // some clunky checks to make sure the first match ends at the
288 // end of the line and the last match starts at the start.
289 function(reverse, node, offset) {
290 var idx = (reverse ? target.length - 1 : 0), match = target[idx], line = getText(node);
291 var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
292 if (reverse ? offsetA >= offset || offsetA != match.length
293 : offsetA <= offset || offsetA != line.length - match.length)
294 return;
295
296 var pos = node;
297 while (true) {
298 if (reverse && !pos) return;
299 pos = (reverse ? this.history.nodeBefore(pos) : this.history.nodeAfter(pos) );
300 if (!reverse && !pos) return;
301
302 line = getText(pos);
303 match = target[reverse ? --idx : ++idx];
304
305 if (idx > 0 && idx < target.length - 1) {
306 if (line != match) return;
307 else continue;
308 }
309 var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
310 if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
311 return;
312 return {from: {node: reverse ? pos : node, offset: reverse ? offsetB : offsetA},
313 to: {node: reverse ? node : pos, offset: reverse ? offsetA : offsetB}};
314 }
315 };
316 }
317
318 SearchCursor.prototype = {
319 findNext: function() {return this.find(false);},
320 findPrevious: function() {return this.find(true);},
321
322 find: function(reverse) {
323 if (!this.valid) return false;
324
325 var self = this, pos = reverse ? this.pos.from : this.pos.to,
326 node = pos.node, offset = pos.offset;
327 // Reset the cursor if the current line is no longer in the DOM tree.
328 if (node && !node.parentNode) {
329 node = null; offset = 0;
330 }
331 function savePosAndFail() {
332 var pos = {node: node, offset: offset};
333 self.pos = {from: pos, to: pos};
334 self.atOccurrence = false;
335 return false;
336 }
337
338 while (true) {
339 if (this.pos = this.matches(reverse, node, offset)) {
340 this.atOccurrence = true;
341 return true;
342 }
343
344 if (reverse) {
345 if (!node) return savePosAndFail();
346 node = this.history.nodeBefore(node);
347 offset = this.history.textAfter(node).length;
348 }
349 else {
350 var next = this.history.nodeAfter(node);
351 if (!next) {
352 offset = this.history.textAfter(node).length;
353 return savePosAndFail();
354 }
355 node = next;
356 offset = 0;
357 }
358 }
359 },
360
361 select: function() {
362 if (this.atOccurrence) {
363 select.setCursorPos(this.editor.container, this.pos.from, this.pos.to);
364 select.scrollToCursor(this.editor.container);
365 }
366 },
367
368 replace: function(string) {
369 if (this.atOccurrence) {
370 var end = this.editor.replaceRange(this.pos.from, this.pos.to, string);
371 this.pos.to = end;
372 this.atOccurrence = false;
373 }
374 },
375
376 position: function() {
377 if (this.atOccurrence)
378 return {line: this.pos.from.node, character: this.pos.from.offset};
379 }
380 };
381
382 // The Editor object is the main inside-the-iframe interface.
383 function Editor(options) {
384 this.options = options;
385 window.indentUnit = options.indentUnit;
386 this.parent = parent;
387 var container = this.container = document.body;
388 this.history = new UndoHistory(container, options.undoDepth, options.undoDelay, this);
389 var self = this;
390
391 if (!Editor.Parser)
392 throw "No parser loaded.";
393 if (options.parserConfig && Editor.Parser.configure)
394 Editor.Parser.configure(options.parserConfig);
395
396 if (!options.readOnly && !internetExplorer)
397 select.setCursorPos(container, {node: null, offset: 0});
398
399 this.dirty = [];
400 this.importCode(options.content || "");
401 this.history.onChange = options.onChange;
402
403 if (!options.readOnly) {
404 if (options.continuousScanning !== false) {
405 this.scanner = this.documentScanner(options.passTime);
406 this.delayScanning();
407 }
408
409 function setEditable() {
410 // Use contentEditable instead of designMode on IE, since designMode frames
411 // can not run any scripts. It would be nice if we could use contentEditable
412 // everywhere, but it is significantly flakier than designMode on every
413 // single non-IE browser.
414 if (document.body.contentEditable != undefined && internetExplorer)
415 document.body.contentEditable = "true";
416 else
417 document.designMode = "on";
418
419 // Work around issue where you have to click on the actual
420 // body of the document to focus it in IE, making focusing
421 // hard when the document is small.
422 if (internetExplorer && options.height != "dynamic")
423 document.body.style.minHeight = (frameElement.clientHeight - 2 * document.body.offsetTop - 5) + "px";
424
425 document.documentElement.style.borderWidth = "0";
426 if (!options.textWrapping)
427 container.style.whiteSpace = "nowrap";
428 }
429
430 // If setting the frame editable fails, try again when the user
431 // focus it (happens when the frame is not visible on
432 // initialisation, in Firefox).
433 try {
434 setEditable();
435 }
436 catch(e) {
437 var focusEvent = addEventHandler(document, "focus", function() {
438 focusEvent();
439 setEditable();
440 }, true);
441 }
442
443 addEventHandler(document, "keydown", method(this, "keyDown"));
444 addEventHandler(document, "keypress", method(this, "keyPress"));
445 addEventHandler(document, "keyup", method(this, "keyUp"));
446
447 function cursorActivity() {self.cursorActivity(false);}
448 addEventHandler(internetExplorer ? document.body : window, "mouseup", cursorActivity);
449 addEventHandler(document.body, "cut", cursorActivity);
450
451 // workaround for a gecko bug [?] where going forward and then
452 // back again breaks designmode (no more cursor)
453 if (gecko)
454 addEventHandler(window, "pagehide", function(){self.unloaded = true;});
455
456 addEventHandler(document.body, "paste", function(event) {
457 cursorActivity();
458 var text = null;
459 try {
460 var clipboardData = event.clipboardData || window.clipboardData;
461 if (clipboardData) text = clipboardData.getData('Text');
462 }
463 catch(e) {}
464 if (text !== null) {
465 event.stop();
466 self.replaceSelection(text);
467 select.scrollToCursor(self.container);
468 }
469 });
470
471 if (this.options.autoMatchParens)
472 addEventHandler(document.body, "click", method(this, "scheduleParenHighlight"));
473 }
474 else if (!options.textWrapping) {
475 container.style.whiteSpace = "nowrap";
476 }
477 }
478
479 function isSafeKey(code) {
480 return (code >= 16 && code <= 18) || // shift, control, alt
481 (code >= 33 && code <= 40); // arrows, home, end
482 }
483
484 Editor.prototype = {
485 // Import a piece of code into the editor.
486 importCode: function(code) {
487 this.history.push(null, null, asEditorLines(code));
488 this.history.reset();
489 },
490
491 // Extract the code from the editor.
492 getCode: function() {
493 if (!this.container.firstChild)
494 return "";
495
496 var accum = [];
497 select.markSelection();
498 forEach(traverseDOM(this.container.firstChild), method(accum, "push"));
499 select.selectMarked();
500 // On webkit, don't count last (empty) line if the webkitLastLineHack BR is present
501 if (webkit && this.container.lastChild.hackBR)
502 accum.pop();
503 webkitLastLineHack(this.container);
504 return cleanText(accum.join(""));
505 },
506
507 checkLine: function(node) {
508 if (node === false || !(node == null || node.parentNode == this.container))
509 throw parent.CodeMirror.InvalidLineHandle;
510 },
511
512 cursorPosition: function(start) {
513 if (start == null) start = true;
514 var pos = select.cursorPos(this.container, start);
515 if (pos) return {line: pos.node, character: pos.offset};
516 else return {line: null, character: 0};
517 },
518
519 firstLine: function() {
520 return null;
521 },
522
523 lastLine: function() {
524 if (this.container.lastChild) return startOfLine(this.container.lastChild);
525 else return null;
526 },
527
528 nextLine: function(line) {
529 this.checkLine(line);
530 var end = endOfLine(line, this.container);
531 return end || false;
532 },
533
534 prevLine: function(line) {
535 this.checkLine(line);
536 if (line == null) return false;
537 return startOfLine(line.previousSibling);
538 },
539
540 visibleLineCount: function() {
541 var line = this.container.firstChild;
542 while (line && isBR(line)) line = line.nextSibling; // BR heights are unreliable
543 if (!line) return false;
544 var innerHeight = (window.innerHeight
545 || document.documentElement.clientHeight
546 || document.body.clientHeight);
547 return Math.floor(innerHeight / line.offsetHeight);
548 },
549
550 selectLines: function(startLine, startOffset, endLine, endOffset) {
551 this.checkLine(startLine);
552 var start = {node: startLine, offset: startOffset}, end = null;
553 if (endOffset !== undefined) {
554 this.checkLine(endLine);
555 end = {node: endLine, offset: endOffset};
556 }
557 select.setCursorPos(this.container, start, end);
558 select.scrollToCursor(this.container);
559 },
560
561 lineContent: function(line) {
562 var accum = [];
563 for (line = line ? line.nextSibling : this.container.firstChild;
564 line && !isBR(line); line = line.nextSibling)
565 accum.push(nodeText(line));
566 return cleanText(accum.join(""));
567 },
568
569 setLineContent: function(line, content) {
570 this.history.commit();
571 this.replaceRange({node: line, offset: 0},
572 {node: line, offset: this.history.textAfter(line).length},
573 content);
574 this.addDirtyNode(line);
575 this.scheduleHighlight();
576 },
577
578 removeLine: function(line) {
579 var node = line ? line.nextSibling : this.container.firstChild;
580 while (node) {
581 var next = node.nextSibling;
582 removeElement(node);
583 if (isBR(node)) break;
584 node = next;
585 }
586 this.addDirtyNode(line);
587 this.scheduleHighlight();
588 },
589
590 insertIntoLine: function(line, position, content) {
591 var before = null;
592 if (position == "end") {
593 before = endOfLine(line, this.container);
594 }
595 else {
596 for (var cur = line ? line.nextSibling : this.container.firstChild; cur; cur = cur.nextSibling) {
597 if (position == 0) {
598 before = cur;
599 break;
600 }
601 var text = nodeText(cur);
602 if (text.length > position) {
603 before = cur.nextSibling;
604 content = text.slice(0, position) + content + text.slice(position);
605 removeElement(cur);
606 break;
607 }
608 position -= text.length;
609 }
610 }
611
612 var lines = asEditorLines(content);
613 for (var i = 0; i < lines.length; i++) {
614 if (i > 0) this.container.insertBefore(document.createElement("BR"), before);
615 this.container.insertBefore(makePartSpan(lines[i]), before);
616 }
617 this.addDirtyNode(line);
618 this.scheduleHighlight();
619 },
620
621 // Retrieve the selected text.
622 selectedText: function() {
623 var h = this.history;
624 h.commit();
625
626 var start = select.cursorPos(this.container, true),
627 end = select.cursorPos(this.container, false);
628 if (!start || !end) return "";
629
630 if (start.node == end.node)
631 return h.textAfter(start.node).slice(start.offset, end.offset);
632
633 var text = [h.textAfter(start.node).slice(start.offset)];
634 for (var pos = h.nodeAfter(start.node); pos != end.node; pos = h.nodeAfter(pos))
635 text.push(h.textAfter(pos));
636 text.push(h.textAfter(end.node).slice(0, end.offset));
637 return cleanText(text.join("\n"));
638 },
639
640 // Replace the selection with another piece of text.
641 replaceSelection: function(text) {
642 this.history.commit();
643
644 var start = select.cursorPos(this.container, true),
645 end = select.cursorPos(this.container, false);
646 if (!start || !end) return;
647
648 end = this.replaceRange(start, end, text);
649 select.setCursorPos(this.container, end);
650 webkitLastLineHack(this.container);
651 },
652
653 cursorCoords: function(start) {
654 var sel = select.cursorPos(this.container, start);
655 if (!sel) return null;
656 var off = sel.offset, node = sel.node, self = this;
657 function measureFromNode(node, xOffset) {
658 var y = -(document.body.scrollTop || document.documentElement.scrollTop || 0),
659 x = -(document.body.scrollLeft || document.documentElement.scrollLeft || 0) + xOffset;
660 forEach([node, window.frameElement], function(n) {
661 while (n) {x += n.offsetLeft; y += n.offsetTop;n = n.offsetParent;}
662 });
663 return {x: x, y: y, yBot: y + node.offsetHeight};
664 }
665 function withTempNode(text, f) {
666 var node = document.createElement("SPAN");
667 node.appendChild(document.createTextNode(text));
668 try {return f(node);}
669 finally {if (node.parentNode) node.parentNode.removeChild(node);}
670 }
671
672 while (off) {
673 node = node ? node.nextSibling : this.container.firstChild;
674 var txt = nodeText(node);
675 if (off < txt.length)
676 return withTempNode(txt.substr(0, off), function(tmp) {
677 tmp.style.position = "absolute"; tmp.style.visibility = "hidden";
678 tmp.className = node.className;
679 self.container.appendChild(tmp);
680 return measureFromNode(node, tmp.offsetWidth);
681 });
682 off -= txt.length;
683 }
684 if (node && isSpan(node))
685 return measureFromNode(node, node.offsetWidth);
686 else if (node && node.nextSibling && isSpan(node.nextSibling))
687 return measureFromNode(node.nextSibling, 0);
688 else
689 return withTempNode("\u200b", function(tmp) {
690 if (node) node.parentNode.insertBefore(tmp, node.nextSibling);
691 else self.container.insertBefore(tmp, self.container.firstChild);
692 return measureFromNode(tmp, 0);
693 });
694 },
695
696 reroutePasteEvent: function() {
697 if (this.capturingPaste || window.opera || (gecko && gecko >= 20101026)) return;
698 this.capturingPaste = true;
699 var te = window.frameElement.CodeMirror.textareaHack;
700 parent.focus();
701 te.value = "";
702 te.focus();
703
704 var self = this;
705 this.parent.setTimeout(function() {
706 self.capturingPaste = false;
707 window.focus();
708 if (self.selectionSnapshot) // IE hack
709 window.select.setBookmark(self.container, self.selectionSnapshot);
710 var text = te.value;
711 if (text) {
712 self.replaceSelection(text);
713 select.scrollToCursor(self.container);
714 }
715 }, 10);
716 },
717
718 replaceRange: function(from, to, text) {
719 var lines = asEditorLines(text);
720 lines[0] = this.history.textAfter(from.node).slice(0, from.offset) + lines[0];
721 var lastLine = lines[lines.length - 1];
722 lines[lines.length - 1] = lastLine + this.history.textAfter(to.node).slice(to.offset);
723 var end = this.history.nodeAfter(to.node);
724 this.history.push(from.node, end, lines);
725 return {node: this.history.nodeBefore(end),
726 offset: lastLine.length};
727 },
728
729 getSearchCursor: function(string, fromCursor, caseFold) {
730 return new SearchCursor(this, string, fromCursor, caseFold);
731 },
732
733 // Re-indent the whole buffer
734 reindent: function() {
735 if (this.container.firstChild)
736 this.indentRegion(null, this.container.lastChild);
737 },
738
739 reindentSelection: function(direction) {
740 if (!select.somethingSelected()) {
741 this.indentAtCursor(direction);
742 }
743 else {
744 var start = select.selectionTopNode(this.container, true),
745 end = select.selectionTopNode(this.container, false);
746 if (start === false || end === false) return;
747 this.indentRegion(start, end, direction);
748 }
749 },
750
751 grabKeys: function(eventHandler, filter) {
752 this.frozen = eventHandler;
753 this.keyFilter = filter;
754 },
755 ungrabKeys: function() {
756 this.frozen = "leave";
757 },
758
759 setParser: function(name, parserConfig) {
760 Editor.Parser = window[name];
761 parserConfig = parserConfig || this.options.parserConfig;
762 if (parserConfig && Editor.Parser.configure)
763 Editor.Parser.configure(parserConfig);
764
765 if (this.container.firstChild) {
766 forEach(this.container.childNodes, function(n) {
767 if (n.nodeType != 3) n.dirty = true;
768 });
769 this.addDirtyNode(this.firstChild);
770 this.scheduleHighlight();
771 }
772 },
773
774 // Intercept enter and tab, and assign their new functions.
775 keyDown: function(event) {
776 if (this.frozen == "leave") {this.frozen = null; this.keyFilter = null;}
777 if (this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode, event))) {
778 event.stop();
779 this.frozen(event);
780 return;
781 }
782
783 var code = event.keyCode;
784 // Don't scan when the user is typing.
785 this.delayScanning();
786 // Schedule a paren-highlight event, if configured.
787 if (this.options.autoMatchParens)
788 this.scheduleParenHighlight();
789
790 // The various checks for !altKey are there because AltGr sets both
791 // ctrlKey and altKey to true, and should not be recognised as
792 // Control.
793 if (code == 13) { // enter
794 if (event.ctrlKey && !event.altKey) {
795 this.reparseBuffer();
796 }
797 else {
798 select.insertNewlineAtCursor();
799 var mode = this.options.enterMode;
800 if (mode != "flat") this.indentAtCursor(mode == "keep" ? "keep" : undefined);
801 select.scrollToCursor(this.container);
802 }
803 event.stop();
804 }
805 else if (code == 9 && this.options.tabMode != "default" && !event.ctrlKey) { // tab
806 this.handleTab(!event.shiftKey);
807 event.stop();
808 }
809 else if (code == 32 && event.shiftKey && this.options.tabMode == "default") { // space
810 this.handleTab(true);
811 event.stop();
812 }
813 else if (code == 36 && !event.shiftKey && !event.ctrlKey) { // home
814 if (this.home()) event.stop();
815 }
816 else if (code == 35 && !event.shiftKey && !event.ctrlKey) { // end
817 if (this.end()) event.stop();
818 }
819 // Only in Firefox is the default behavior for PgUp/PgDn correct.
820 else if (code == 33 && !event.shiftKey && !event.ctrlKey && !gecko) { // PgUp
821 if (this.pageUp()) event.stop();
822 }
823 else if (code == 34 && !event.shiftKey && !event.ctrlKey && !gecko) { // PgDn
824 if (this.pageDown()) event.stop();
825 }
826 else if ((code == 219 || code == 221) && event.ctrlKey && !event.altKey) { // [, ]
827 this.highlightParens(event.shiftKey, true);
828 event.stop();
829 }
830 else if (event.metaKey && !event.shiftKey && (code == 37 || code == 39)) { // Meta-left/right
831 var cursor = select.selectionTopNode(this.container);
832 if (cursor === false || !this.container.firstChild) return;
833
834 if (code == 37) select.focusAfterNode(startOfLine(cursor), this.container);
835 else {
836 var end = endOfLine(cursor, this.container);
837 select.focusAfterNode(end ? end.previousSibling : this.container.lastChild, this.container);
838 }
839 event.stop();
840 }
841 else if ((event.ctrlKey || event.metaKey) && !event.altKey) {
842 if ((event.shiftKey && code == 90) || code == 89) { // shift-Z, Y
843 select.scrollToNode(this.history.redo());
844 event.stop();
845 }
846 else if (code == 90 || (safari && code == 8)) { // Z, backspace
847 select.scrollToNode(this.history.undo());
848 event.stop();
849 }
850 else if (code == 83 && this.options.saveFunction) { // S
851 this.options.saveFunction();
852 event.stop();
853 }
854 else if (code == 86 && !mac) { // V
855 this.reroutePasteEvent();
856 }
857 }
858 },
859
860 // Check for characters that should re-indent the current line,
861 // and prevent Opera from handling enter and tab anyway.
862 keyPress: function(event) {
863 var electric = this.options.electricChars && Editor.Parser.electricChars, self = this;
864 // Hack for Opera, and Firefox on OS X, in which stopping a
865 // keydown event does not prevent the associated keypress event
866 // from happening, so we have to cancel enter and tab again
867 // here.
868 if ((this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode || event.code, event))) ||
869 event.code == 13 || (event.code == 9 && this.options.tabMode != "default") ||
870 (event.code == 32 && event.shiftKey && this.options.tabMode == "default"))
871 event.stop();
872 else if (mac && (event.ctrlKey || event.metaKey) && event.character == "v") {
873 this.reroutePasteEvent();
874 }
875 else if (electric && electric.indexOf(event.character) != -1)
876 this.parent.setTimeout(function(){self.indentAtCursor(null);}, 0);
877 // Work around a bug where pressing backspace at the end of a
878 // line, or delete at the start, often causes the cursor to jump
879 // to the start of the line in Opera 10.60.
880 else if (brokenOpera) {
881 if (event.code == 8) { // backspace
882 var sel = select.selectionTopNode(this.container), self = this,
883 next = sel ? sel.nextSibling : this.container.firstChild;
884 if (sel !== false && next && isBR(next))
885 this.parent.setTimeout(function(){
886 if (select.selectionTopNode(self.container) == next)
887 select.focusAfterNode(next.previousSibling, self.container);
888 }, 20);
889 }
890 else if (event.code == 46) { // delete
891 var sel = select.selectionTopNode(this.container), self = this;
892 if (sel && isBR(sel)) {
893 this.parent.setTimeout(function(){
894 if (select.selectionTopNode(self.container) != sel)
895 select.focusAfterNode(sel, self.container);
896 }, 20);
897 }
898 }
899 }
900 // In 533.* WebKit versions, when the document is big, typing
901 // something at the end of a line causes the browser to do some
902 // kind of stupid heavy operation, creating delays of several
903 // seconds before the typed characters appear. This very crude
904 // hack inserts a temporary zero-width space after the cursor to
905 // make it not be at the end of the line.
906 else if (slowWebkit) {
907 var sel = select.selectionTopNode(this.container),
908 next = sel ? sel.nextSibling : this.container.firstChild;
909 // Doesn't work on empty lines, for some reason those always
910 // trigger the delay.
911 if (sel && next && isBR(next) && !isBR(sel)) {
912 var cheat = document.createTextNode("\u200b");
913 this.container.insertBefore(cheat, next);
914 this.parent.setTimeout(function() {
915 if (cheat.nodeValue == "\u200b") removeElement(cheat);
916 else cheat.nodeValue = cheat.nodeValue.replace("\u200b", "");
917 }, 20);
918 }
919 }
920
921 // Magic incantation that works abound a webkit bug when you
922 // can't type on a blank line following a line that's wider than
923 // the window.
924 if (webkit && !this.options.textWrapping)
925 setTimeout(function () {
926 var node = select.selectionTopNode(self.container, true);
927 if (node && node.nodeType == 3 && node.previousSibling && isBR(node.previousSibling)
928 && node.nextSibling && isBR(node.nextSibling))
929 node.parentNode.replaceChild(document.createElement("BR"), node.previousSibling);
930 }, 50);
931 },
932
933 // Mark the node at the cursor dirty when a non-safe key is
934 // released.
935 keyUp: function(event) {
936 this.cursorActivity(isSafeKey(event.keyCode));
937 },
938
939 // Indent the line following a given <br>, or null for the first
940 // line. If given a <br> element, this must have been highlighted
941 // so that it has an indentation method. Returns the whitespace
942 // element that has been modified or created (if any).
943 indentLineAfter: function(start, direction) {
944 function whiteSpaceAfter(node) {
945 var ws = node ? node.nextSibling : self.container.firstChild;
946 if (!ws || !hasClass(ws, "whitespace")) return null;
947 return ws;
948 }
949
950 // whiteSpace is the whitespace span at the start of the line,
951 // or null if there is no such node.
952 var self = this, whiteSpace = whiteSpaceAfter(start);
953 var newIndent = 0, curIndent = whiteSpace ? whiteSpace.currentText.length : 0;
954
955 var firstText = whiteSpace ? whiteSpace.nextSibling : (start ? start.nextSibling : this.container.firstChild);
956 if (direction == "keep") {
957 if (start) {
958 var prevWS = whiteSpaceAfter(startOfLine(start.previousSibling))
959 if (prevWS) newIndent = prevWS.currentText.length;
960 }
961 }
962 else {
963 // Sometimes the start of the line can influence the correct
964 // indentation, so we retrieve it.
965 var nextChars = (start && firstText && firstText.currentText) ? firstText.currentText : "";
966
967 // Ask the lexical context for the correct indentation, and
968 // compute how much this differs from the current indentation.
969 if (direction != null && this.options.tabMode == "shift")
970 newIndent = direction ? curIndent + indentUnit : Math.max(0, curIndent - indentUnit)
971 else if (start)
972 newIndent = start.indentation(nextChars, curIndent, direction);
973 else if (Editor.Parser.firstIndentation)
974 newIndent = Editor.Parser.firstIndentation(nextChars, curIndent, direction);
975 }
976
977 var indentDiff = newIndent - curIndent;
978
979 // If there is too much, this is just a matter of shrinking a span.
980 if (indentDiff < 0) {
981 if (newIndent == 0) {
982 if (firstText) select.snapshotMove(whiteSpace.firstChild, firstText.firstChild || firstText, 0);
983 removeElement(whiteSpace);
984 whiteSpace = null;
985 }
986 else {
987 select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true);
988 whiteSpace.currentText = makeWhiteSpace(newIndent);
989 whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
990 }
991 }
992 // Not enough...
993 else if (indentDiff > 0) {
994 // If there is whitespace, we grow it.
995 if (whiteSpace) {
996 whiteSpace.currentText = makeWhiteSpace(newIndent);
997 whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
998 select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true);
999 }
1000 // Otherwise, we have to add a new whitespace node.
1001 else {
1002 whiteSpace = makePartSpan(makeWhiteSpace(newIndent));
1003 whiteSpace.className = "whitespace";
1004 if (start) insertAfter(whiteSpace, start);
1005 else this.container.insertBefore(whiteSpace, this.container.firstChild);
1006 select.snapshotMove(firstText && (firstText.firstChild || firstText),
1007 whiteSpace.firstChild, newIndent, false, true);
1008 }
1009 }
1010 // Make sure cursor ends up after the whitespace
1011 else if (whiteSpace) {
1012 select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, newIndent, false);
1013 }
1014 if (indentDiff != 0) this.addDirtyNode(start);
1015 },
1016
1017 // Re-highlight the selected part of the document.
1018 highlightAtCursor: function() {
1019 var pos = select.selectionTopNode(this.container, true);
1020 var to = select.selectionTopNode(this.container, false);
1021 if (pos === false || to === false) return false;
1022
1023 select.markSelection();
1024 if (this.highlight(pos, endOfLine(to, this.container), true, 20) === false)
1025 return false;
1026 select.selectMarked();
1027 return true;
1028 },
1029
1030 // When tab is pressed with text selected, the whole selection is
1031 // re-indented, when nothing is selected, the line with the cursor
1032 // is re-indented.
1033 handleTab: function(direction) {
1034 if (this.options.tabMode == "spaces")
1035 select.insertTabAtCursor();
1036 else
1037 this.reindentSelection(direction);
1038 },
1039
1040 // Custom home behaviour that doesn't land the cursor in front of
1041 // leading whitespace unless pressed twice.
1042 home: function() {
1043 var cur = select.selectionTopNode(this.container, true), start = cur;
1044 if (cur === false || !(!cur || cur.isPart || isBR(cur)) || !this.container.firstChild)
1045 return false;
1046
1047 while (cur && !isBR(cur)) cur = cur.previousSibling;
1048 var next = cur ? cur.nextSibling : this.container.firstChild;
1049 if (next && next != start && next.isPart && hasClass(next, "whitespace"))
1050 select.focusAfterNode(next, this.container);
1051 else
1052 select.focusAfterNode(cur, this.container);
1053
1054 select.scrollToCursor(this.container);
1055 return true;
1056 },
1057
1058 // Some browsers (Opera) don't manage to handle the end key
1059 // properly in the face of vertical scrolling.
1060 end: function() {
1061 var cur = select.selectionTopNode(this.container, true);
1062 if (cur === false) return false;
1063 cur = endOfLine(cur, this.container);
1064 if (!cur) return false;
1065 select.focusAfterNode(cur.previousSibling, this.container);
1066 select.scrollToCursor(this.container);
1067 return true;
1068 },
1069
1070 pageUp: function() {
1071 var line = this.cursorPosition().line, scrollAmount = this.visibleLineCount();
1072 if (line === false || scrollAmount === false) return false;
1073 // Try to keep one line on the screen.
1074 scrollAmount -= 2;
1075 for (var i = 0; i < scrollAmount; i++) {
1076 line = this.prevLine(line);
1077 if (line === false) break;
1078 }
1079 if (i == 0) return false; // Already at first line
1080 select.setCursorPos(this.container, {node: line, offset: 0});
1081 select.scrollToCursor(this.container);
1082 return true;
1083 },
1084
1085 pageDown: function() {
1086 var line = this.cursorPosition().line, scrollAmount = this.visibleLineCount();
1087 if (line === false || scrollAmount === false) return false;
1088 // Try to move to the last line of the current page.
1089 scrollAmount -= 2;
1090 for (var i = 0; i < scrollAmount; i++) {
1091 var nextLine = this.nextLine(line);
1092 if (nextLine === false) break;
1093 line = nextLine;
1094 }
1095 if (i == 0) return false; // Already at last line
1096 select.setCursorPos(this.container, {node: line, offset: 0});
1097 select.scrollToCursor(this.container);
1098 return true;
1099 },
1100
1101 // Delay (or initiate) the next paren highlight event.
1102 scheduleParenHighlight: function() {
1103 if (this.parenEvent) this.parent.clearTimeout(this.parenEvent);
1104 var self = this;
1105 this.parenEvent = this.parent.setTimeout(function(){self.highlightParens();}, 300);
1106 },
1107
1108 // Take the token before the cursor. If it contains a character in
1109 // '()[]{}', search for the matching paren/brace/bracket, and
1110 // highlight them in green for a moment, or red if no proper match
1111 // was found.
1112 highlightParens: function(jump, fromKey) {
1113 var self = this;
1114 // give the relevant nodes a colour.
1115 function highlight(node, ok) {
1116 if (!node) return;
1117 if (self.options.markParen) {
1118 self.options.markParen(node, ok);
1119 }
1120 else {
1121 node.style.fontWeight = "bold";
1122 node.style.color = ok ? "#8F8" : "#F88";
1123 }
1124 }
1125 function unhighlight(node) {
1126 if (!node) return;
1127 if (self.options.unmarkParen) {
1128 self.options.unmarkParen(node);
1129 }
1130 else {
1131 node.style.fontWeight = "";
1132 node.style.color = "";
1133 }
1134 }
1135 if (!fromKey && self.highlighted) {
1136 unhighlight(self.highlighted[0]);
1137 unhighlight(self.highlighted[1]);
1138 }
1139
1140 if (!window || !window.parent || !window.select) return;
1141 // Clear the event property.
1142 if (this.parenEvent) this.parent.clearTimeout(this.parenEvent);
1143 this.parenEvent = null;
1144
1145 // Extract a 'paren' from a piece of text.
1146 function paren(node) {
1147 if (node.currentText) {
1148 var match = node.currentText.match(/^[\s\u00a0]*([\(\)\[\]{}])[\s\u00a0]*$/);
1149 return match && match[1];
1150 }
1151 }
1152 // Determine the direction a paren is facing.
1153 function forward(ch) {
1154 return /[\(\[\{]/.test(ch);
1155 }
1156
1157 var ch, cursor = select.selectionTopNode(this.container, true);
1158 if (!cursor || !this.highlightAtCursor()) return;
1159 cursor = select.selectionTopNode(this.container, true);
1160 if (!(cursor && ((ch = paren(cursor)) || (cursor = cursor.nextSibling) && (ch = paren(cursor)))))
1161 return;
1162 // We only look for tokens with the same className.
1163 var className = cursor.className, dir = forward(ch), match = matching[ch];
1164
1165 // Since parts of the document might not have been properly
1166 // highlighted, and it is hard to know in advance which part we
1167 // have to scan, we just try, and when we find dirty nodes we
1168 // abort, parse them, and re-try.
1169 function tryFindMatch() {
1170 var stack = [], ch, ok = true;
1171 for (var runner = cursor; runner; runner = dir ? runner.nextSibling : runner.previousSibling) {
1172 if (runner.className == className && isSpan(runner) && (ch = paren(runner))) {
1173 if (forward(ch) == dir)
1174 stack.push(ch);
1175 else if (!stack.length)
1176 ok = false;
1177 else if (stack.pop() != matching[ch])
1178 ok = false;
1179 if (!stack.length) break;
1180 }
1181 else if (runner.dirty || !isSpan(runner) && !isBR(runner)) {
1182 return {node: runner, status: "dirty"};
1183 }
1184 }
1185 return {node: runner, status: runner && ok};
1186 }
1187
1188 while (true) {
1189 var found = tryFindMatch();
1190 if (found.status == "dirty") {
1191 this.highlight(found.node, endOfLine(found.node));
1192 // Needed because in some corner cases a highlight does not
1193 // reach a node.
1194 found.node.dirty = false;
1195 continue;
1196 }
1197 else {
1198 highlight(cursor, found.status);
1199 highlight(found.node, found.status);
1200 if (fromKey)
1201 self.parent.setTimeout(function() {unhighlight(cursor); unhighlight(found.node);}, 500);
1202 else
1203 self.highlighted = [cursor, found.node];
1204 if (jump && found.node)
1205 select.focusAfterNode(found.node.previousSibling, this.container);
1206 break;
1207 }
1208 }
1209 },
1210
1211 // Adjust the amount of whitespace at the start of the line that
1212 // the cursor is on so that it is indented properly.
1213 indentAtCursor: function(direction) {
1214 if (!this.container.firstChild) return;
1215 // The line has to have up-to-date lexical information, so we
1216 // highlight it first.
1217 if (!this.highlightAtCursor()) return;
1218 var cursor = select.selectionTopNode(this.container, false);
1219 // If we couldn't determine the place of the cursor,
1220 // there's nothing to indent.
1221 if (cursor === false)
1222 return;
1223 select.markSelection();
1224 this.indentLineAfter(startOfLine(cursor), direction);
1225 select.selectMarked();
1226 },
1227
1228 // Indent all lines whose start falls inside of the current
1229 // selection.
1230 indentRegion: function(start, end, direction) {
1231 var current = (start = startOfLine(start)), before = start && startOfLine(start.previousSibling);
1232 if (!isBR(end)) end = endOfLine(end, this.container);
1233 this.addDirtyNode(start);
1234
1235 do {
1236 var next = endOfLine(current, this.container);
1237 if (current) this.highlight(before, next, true);
1238 this.indentLineAfter(current, direction);
1239 before = current;
1240 current = next;
1241 } while (current != end);
1242 select.setCursorPos(this.container, {node: start, offset: 0}, {node: end, offset: 0});
1243 },
1244
1245 // Find the node that the cursor is in, mark it as dirty, and make
1246 // sure a highlight pass is scheduled.
1247 cursorActivity: function(safe) {
1248 // pagehide event hack above
1249 if (this.unloaded) {
1250 window.document.designMode = "off";
1251 window.document.designMode = "on";
1252 this.unloaded = false;
1253 }
1254
1255 if (internetExplorer) {
1256 this.container.createTextRange().execCommand("unlink");
1257 clearTimeout(this.saveSelectionSnapshot);
1258 var self = this;
1259 this.saveSelectionSnapshot = setTimeout(function() {
1260 var snapshot = select.getBookmark(self.container);
1261 if (snapshot) self.selectionSnapshot = snapshot;
1262 }, 200);
1263 }
1264
1265 var activity = this.options.cursorActivity;
1266 if (!safe || activity) {
1267 var cursor = select.selectionTopNode(this.container, false);
1268 if (cursor === false || !this.container.firstChild) return;
1269 cursor = cursor || this.container.firstChild;
1270 if (activity) activity(cursor);
1271 if (!safe) {
1272 this.scheduleHighlight();
1273 this.addDirtyNode(cursor);
1274 }
1275 }
1276 },
1277
1278 reparseBuffer: function() {
1279 forEach(this.container.childNodes, function(node) {node.dirty = true;});
1280 if (this.container.firstChild)
1281 this.addDirtyNode(this.container.firstChild);
1282 },
1283
1284 // Add a node to the set of dirty nodes, if it isn't already in
1285 // there.
1286 addDirtyNode: function(node) {
1287 node = node || this.container.firstChild;
1288 if (!node) return;
1289
1290 for (var i = 0; i < this.dirty.length; i++)
1291 if (this.dirty[i] == node) return;
1292
1293 if (node.nodeType != 3)
1294 node.dirty = true;
1295 this.dirty.push(node);
1296 },
1297
1298 allClean: function() {
1299 return !this.dirty.length;
1300 },
1301
1302 // Cause a highlight pass to happen in options.passDelay
1303 // milliseconds. Clear the existing timeout, if one exists. This
1304 // way, the passes do not happen while the user is typing, and
1305 // should as unobtrusive as possible.
1306 scheduleHighlight: function() {
1307 // Timeouts are routed through the parent window, because on
1308 // some browsers designMode windows do not fire timeouts.
1309 var self = this;
1310 this.parent.clearTimeout(this.highlightTimeout);
1311 this.highlightTimeout = this.parent.setTimeout(function(){self.highlightDirty();}, this.options.passDelay);
1312 },
1313
1314 // Fetch one dirty node, and remove it from the dirty set.
1315 getDirtyNode: function() {
1316 while (this.dirty.length > 0) {
1317 var found = this.dirty.pop();
1318 // IE8 sometimes throws an unexplainable 'invalid argument'
1319 // exception for found.parentNode
1320 try {
1321 // If the node has been coloured in the meantime, or is no
1322 // longer in the document, it should not be returned.
1323 while (found && found.parentNode != this.container)
1324 found = found.parentNode;
1325 if (found && (found.dirty || found.nodeType == 3))
1326 return found;
1327 } catch (e) {}
1328 }
1329 return null;
1330 },
1331
1332 // Pick dirty nodes, and highlight them, until options.passTime
1333 // milliseconds have gone by. The highlight method will continue
1334 // to next lines as long as it finds dirty nodes. It returns
1335 // information about the place where it stopped. If there are
1336 // dirty nodes left after this function has spent all its lines,
1337 // it shedules another highlight to finish the job.
1338 highlightDirty: function(force) {
1339 // Prevent FF from raising an error when it is firing timeouts
1340 // on a page that's no longer loaded.
1341 if (!window || !window.parent || !window.select) return false;
1342
1343 if (!this.options.readOnly) select.markSelection();
1344 var start, endTime = force ? null : time() + this.options.passTime;
1345 while ((time() < endTime || force) && (start = this.getDirtyNode())) {
1346 var result = this.highlight(start, endTime);
1347 if (result && result.node && result.dirty)
1348 this.addDirtyNode(result.node.nextSibling);
1349 }
1350 if (!this.options.readOnly) select.selectMarked();
1351 if (start) this.scheduleHighlight();
1352 return this.dirty.length == 0;
1353 },
1354
1355 // Creates a function that, when called through a timeout, will
1356 // continuously re-parse the document.
1357 documentScanner: function(passTime) {
1358 var self = this, pos = null;
1359 return function() {
1360 // FF timeout weirdness workaround.
1361 if (!window || !window.parent || !window.select) return;
1362 // If the current node is no longer in the document... oh
1363 // well, we start over.
1364 if (pos && pos.parentNode != self.container)
1365 pos = null;
1366 select.markSelection();
1367 var result = self.highlight(pos, time() + passTime, true);
1368 select.selectMarked();
1369 var newPos = result ? (result.node && result.node.nextSibling) : null;
1370 pos = (pos == newPos) ? null : newPos;
1371 self.delayScanning();
1372 };
1373 },
1374
1375 // Starts the continuous scanning process for this document after
1376 // a given interval.
1377 delayScanning: function() {
1378 if (this.scanner) {
1379 this.parent.clearTimeout(this.documentScan);
1380 this.documentScan = this.parent.setTimeout(this.scanner, this.options.continuousScanning);
1381 }
1382 },
1383
1384 // The function that does the actual highlighting/colouring (with
1385 // help from the parser and the DOM normalizer). Its interface is
1386 // rather overcomplicated, because it is used in different
1387 // situations: ensuring that a certain line is highlighted, or
1388 // highlighting up to X milliseconds starting from a certain
1389 // point. The 'from' argument gives the node at which it should
1390 // start. If this is null, it will start at the beginning of the
1391 // document. When a timestamp is given with the 'target' argument,
1392 // it will stop highlighting at that time. If this argument holds
1393 // a DOM node, it will highlight until it reaches that node. If at
1394 // any time it comes across two 'clean' lines (no dirty nodes), it
1395 // will stop, except when 'cleanLines' is true. maxBacktrack is
1396 // the maximum number of lines to backtrack to find an existing
1397 // parser instance. This is used to give up in situations where a
1398 // highlight would take too long and freeze the browser interface.
1399 highlight: function(from, target, cleanLines, maxBacktrack){
1400 var container = this.container, self = this, active = this.options.activeTokens;
1401 var endTime = (typeof target == "number" ? target : null);
1402
1403 if (!container.firstChild)
1404 return false;
1405 // Backtrack to the first node before from that has a partial
1406 // parse stored.
1407 while (from && (!from.parserFromHere || from.dirty)) {
1408 if (maxBacktrack != null && isBR(from) && (--maxBacktrack) < 0)
1409 return false;
1410 from = from.previousSibling;
1411 }
1412 // If we are at the end of the document, do nothing.
1413 if (from && !from.nextSibling)
1414 return false;
1415
1416 // Check whether a part (<span> node) and the corresponding token
1417 // match.
1418 function correctPart(token, part){
1419 return !part.reduced && part.currentText == token.value && part.className == token.style;
1420 }
1421 // Shorten the text associated with a part by chopping off
1422 // characters from the front. Note that only the currentText
1423 // property gets changed. For efficiency reasons, we leave the
1424 // nodeValue alone -- we set the reduced flag to indicate that
1425 // this part must be replaced.
1426 function shortenPart(part, minus){
1427 part.currentText = part.currentText.substring(minus);
1428 part.reduced = true;
1429 }
1430 // Create a part corresponding to a given token.
1431 function tokenPart(token){
1432 var part = makePartSpan(token.value);
1433 part.className = token.style;
1434 return part;
1435 }
1436
1437 function maybeTouch(node) {
1438 if (node) {
1439 var old = node.oldNextSibling;
1440 if (lineDirty || old === undefined || node.nextSibling != old)
1441 self.history.touch(node);
1442 node.oldNextSibling = node.nextSibling;
1443 }
1444 else {
1445 var old = self.container.oldFirstChild;
1446 if (lineDirty || old === undefined || self.container.firstChild != old)
1447 self.history.touch(null);
1448 self.container.oldFirstChild = self.container.firstChild;
1449 }
1450 }
1451
1452 // Get the token stream. If from is null, we start with a new
1453 // parser from the start of the frame, otherwise a partial parse
1454 // is resumed.
1455 var traversal = traverseDOM(from ? from.nextSibling : container.firstChild),
1456 stream = stringStream(traversal),
1457 parsed = from ? from.parserFromHere(stream) : Editor.Parser.make(stream);
1458
1459 function surroundedByBRs(node) {
1460 return (node.previousSibling == null || isBR(node.previousSibling)) &&
1461 (node.nextSibling == null || isBR(node.nextSibling));
1462 }
1463
1464 // parts is an interface to make it possible to 'delay' fetching
1465 // the next DOM node until we are completely done with the one
1466 // before it. This is necessary because often the next node is
1467 // not yet available when we want to proceed past the current
1468 // one.
1469 var parts = {
1470 current: null,
1471 // Fetch current node.
1472 get: function(){
1473 if (!this.current)
1474 this.current = traversal.nodes.shift();
1475 return this.current;
1476 },
1477 // Advance to the next part (do not fetch it yet).
1478 next: function(){
1479 this.current = null;
1480 },
1481 // Remove the current part from the DOM tree, and move to the
1482 // next.
1483 remove: function(){
1484 container.removeChild(this.get());
1485 this.current = null;
1486 },
1487 // Advance to the next part that is not empty, discarding empty
1488 // parts.
1489 getNonEmpty: function(){
1490 var part = this.get();
1491 // Allow empty nodes when they are alone on a line, needed
1492 // for the FF cursor bug workaround (see select.js,
1493 // insertNewlineAtCursor).
1494 while (part && isSpan(part) && part.currentText == "") {
1495 // Leave empty nodes that are alone on a line alone in
1496 // Opera, since that browsers doesn't deal well with
1497 // having 2 BRs in a row.
1498 if (window.opera && surroundedByBRs(part)) {
1499 this.next();
1500 part = this.get();
1501 }
1502 else {
1503 var old = part;
1504 this.remove();
1505 part = this.get();
1506 // Adjust selection information, if any. See select.js for details.
1507 select.snapshotMove(old.firstChild, part && (part.firstChild || part), 0);
1508 }
1509 }
1510
1511 return part;
1512 }
1513 };
1514
1515 var lineDirty = false, prevLineDirty = true, lineNodes = 0;
1516
1517 // This forEach loops over the tokens from the parsed stream, and
1518 // at the same time uses the parts object to proceed through the
1519 // corresponding DOM nodes.
1520 forEach(parsed, function(token){
1521 var part = parts.getNonEmpty();
1522
1523 if (token.value == "\n"){
1524 // The idea of the two streams actually staying synchronized
1525 // is such a long shot that we explicitly check.
1526 if (!isBR(part))
1527 throw "Parser out of sync. Expected BR.";
1528
1529 if (part.dirty || !part.indentation) lineDirty = true;
1530 maybeTouch(from);
1531 from = part;
1532
1533 // Every <br> gets a copy of the parser state and a lexical
1534 // context assigned to it. The first is used to be able to
1535 // later resume parsing from this point, the second is used
1536 // for indentation.
1537 part.parserFromHere = parsed.copy();
1538 part.indentation = token.indentation || alwaysZero;
1539 part.dirty = false;
1540
1541 // If the target argument wasn't an integer, go at least
1542 // until that node.
1543 if (endTime == null && part == target) throw StopIteration;
1544
1545 // A clean line with more than one node means we are done.
1546 // Throwing a StopIteration is the way to break out of a
1547 // MochiKit forEach loop.
1548 if ((endTime != null && time() >= endTime) || (!lineDirty && !prevLineDirty && lineNodes > 1 && !cleanLines))
1549 throw StopIteration;
1550 prevLineDirty = lineDirty; lineDirty = false; lineNodes = 0;
1551 parts.next();
1552 }
1553 else {
1554 if (!isSpan(part))
1555 throw "Parser out of sync. Expected SPAN.";
1556 if (part.dirty)
1557 lineDirty = true;
1558 lineNodes++;
1559
1560 // If the part matches the token, we can leave it alone.
1561 if (correctPart(token, part)){
1562 part.dirty = false;
1563 parts.next();
1564 }
1565 // Otherwise, we have to fix it.
1566 else {
1567 lineDirty = true;
1568 // Insert the correct part.
1569 var newPart = tokenPart(token);
1570 container.insertBefore(newPart, part);
1571 if (active) active(newPart, token, self);
1572 var tokensize = token.value.length;
1573 var offset = 0;
1574 // Eat up parts until the text for this token has been
1575 // removed, adjusting the stored selection info (see
1576 // select.js) in the process.
1577 while (tokensize > 0) {
1578 part = parts.get();
1579 var partsize = part.currentText.length;
1580 select.snapshotReplaceNode(part.firstChild, newPart.firstChild, tokensize, offset);
1581 if (partsize > tokensize){
1582 shortenPart(part, tokensize);
1583 tokensize = 0;
1584 }
1585 else {
1586 tokensize -= partsize;
1587 offset += partsize;
1588 parts.remove();
1589 }
1590 }
1591 }
1592 }
1593 });
1594 maybeTouch(from);
1595 webkitLastLineHack(this.container);
1596
1597 // The function returns some status information that is used by
1598 // hightlightDirty to determine whether and where it has to
1599 // continue.
1600 return {node: parts.getNonEmpty(),
1601 dirty: lineDirty};
1602 }
1603 };
1604
1605 return Editor;
1606 })();
1607
1608 addEventHandler(window, "load", function() {
1609 var CodeMirror = window.frameElement.CodeMirror;
1610 var e = CodeMirror.editor = new Editor(CodeMirror.options);
1611 this.parent.setTimeout(method(CodeMirror, "init"), 0);
1612 });