Merge branch 'master' into view-refactor
[redakcja.git] / project / static / js / lib / codemirror / editor.js
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 // Make sure a string does not contain two consecutive 'collapseable'
8 // whitespace characters.
9 function makeWhiteSpace(n) {
10   var buffer = [], nb = true;
11   for (; n > 0; n--) {
12     buffer.push((nb || n == 1) ? nbsp : " ");
13     nb = !nb;
14   }
15   return buffer.join("");
16 }
17
18 // Create a set of white-space characters that will not be collapsed
19 // by the browser, but will not break text-wrapping either.
20 function fixSpaces(string) {
21   if (string.charAt(0) == " ") string = nbsp + string.slice(1);
22   return string.replace(/\t/g, function(){return makeWhiteSpace(indentUnit);})
23     .replace(/[ \u00a0]{2,}/g, function(s) {return makeWhiteSpace(s.length);});
24 }
25
26 function cleanText(text) {
27   return text.replace(/\u00a0/g, " ").replace(/\u200b/g, "");
28 }
29
30 // Create a SPAN node with the expected properties for document part
31 // spans.
32 function makePartSpan(value, doc) {
33   var text = value;
34   if (value.nodeType == 3) text = value.nodeValue;
35   else value = doc.createTextNode(text);
36
37   var span = doc.createElement("SPAN");
38   span.isPart = true;
39   span.appendChild(value);
40   span.currentText = text;
41   return span;
42 }
43
44 // On webkit, when the last BR of the document does not have text
45 // behind it, the cursor can not be put on the line after it. This
46 // makes pressing enter at the end of the document occasionally do
47 // nothing (or at least seem to do nothing). To work around it, this
48 // function makes sure the document ends with a span containing a
49 // zero-width space character. The traverseDOM iterator filters such
50 // character out again, so that the parsers won't see them. This
51 // function is called from a few strategic places to make sure the
52 // zwsp is restored after the highlighting process eats it.
53 var webkitLastLineHack = webkit ?
54   function(container) {
55     var last = container.lastChild;
56     if (!last || !last.isPart || last.textContent != "\u200b")
57       container.appendChild(makePartSpan("\u200b", container.ownerDocument));
58   } : function() {};
59
60 var Editor = (function(){
61   // The HTML elements whose content should be suffixed by a newline
62   // when converting them to flat text.
63   var newlineElements = {"P": true, "DIV": true, "LI": true};
64
65   function asEditorLines(string) {
66     var tab = makeWhiteSpace(indentUnit);
67     return map(string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n").split("\n"), fixSpaces);
68   }
69
70   // Helper function for traverseDOM. Flattens an arbitrary DOM node
71   // into an array of textnodes and <br> tags.
72   function simplifyDOM(root, atEnd) {
73     var doc = root.ownerDocument;
74     var result = [];
75     var leaving = true;
76
77     function simplifyNode(node, top) {
78       if (node.nodeType == 3) {
79         var text = node.nodeValue = fixSpaces(node.nodeValue.replace(/[\r\u200b]/g, "").replace(/\n/g, " "));
80         if (text.length) leaving = false;
81         result.push(node);
82       }
83       else if (node.nodeName == "BR" && node.childNodes.length == 0) {
84         leaving = true;
85         result.push(node);
86       }
87       else {
88         forEach(node.childNodes, simplifyNode);
89         if (!leaving && newlineElements.hasOwnProperty(node.nodeName)) {
90           leaving = true;
91           if (!atEnd || !top)
92             result.push(doc.createElement("BR"));
93         }
94       }
95     }
96
97     simplifyNode(root, true);
98     return result;
99   }
100
101   // Creates a MochiKit-style iterator that goes over a series of DOM
102   // nodes. The values it yields are strings, the textual content of
103   // the nodes. It makes sure that all nodes up to and including the
104   // one whose text is being yielded have been 'normalized' to be just
105   // <span> and <br> elements.
106   // See the story.html file for some short remarks about the use of
107   // continuation-passing style in this iterator.
108   function traverseDOM(start){
109     function yield(value, c){cc = c; return value;}
110     function push(fun, arg, c){return function(){return fun(arg, c);};}
111     function stop(){cc = stop; throw StopIteration;};
112     var cc = push(scanNode, start, stop);
113     var owner = start.ownerDocument;
114     var nodeQueue = [];
115
116     // Create a function that can be used to insert nodes after the
117     // one given as argument.
118     function pointAt(node){
119       var parent = node.parentNode;
120       var next = node.nextSibling;
121       return function(newnode) {
122         parent.insertBefore(newnode, next);
123       };
124     }
125     var point = null;
126
127     // Insert a normalized node at the current point. If it is a text
128     // node, wrap it in a <span>, and give that span a currentText
129     // property -- this is used to cache the nodeValue, because
130     // directly accessing nodeValue is horribly slow on some browsers.
131     // The dirty property is used by the highlighter to determine
132     // which parts of the document have to be re-highlighted.
133     function insertPart(part){
134       var text = "\n";
135       if (part.nodeType == 3) {
136         select.snapshotChanged();
137         part = makePartSpan(part, owner);
138         text = part.currentText;
139       }
140       part.dirty = true;
141       nodeQueue.push(part);
142       point(part);
143       return text;
144     }
145
146     // Extract the text and newlines from a DOM node, insert them into
147     // the document, and yield the textual content. Used to replace
148     // non-normalized nodes.
149     function writeNode(node, c, end) {
150       var toYield = [];
151       forEach(simplifyDOM(node, end), function(part) {
152         toYield.push(insertPart(part));
153       });
154       return yield(toYield.join(""), c);
155     }
156
157     // Check whether a node is a normalized <span> element.
158     function partNode(node){
159       if (node.isPart && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
160         node.currentText = node.firstChild.nodeValue;
161         return !/[\n\t\r]/.test(node.currentText);
162       }
163       return false;
164     }
165
166     // Handle a node. Add its successor to the continuation if there
167     // is one, find out whether the node is normalized. If it is,
168     // yield its content, otherwise, normalize it (writeNode will take
169     // care of yielding).
170     function scanNode(node, c){
171       if (node.nextSibling)
172         c = push(scanNode, node.nextSibling, c);
173
174       if (partNode(node)){
175         nodeQueue.push(node);
176         return yield(node.currentText, c);
177       }
178       else if (node.nodeName == "BR") {
179         nodeQueue.push(node);
180         return yield("\n", c);
181       }
182       else {
183         var end = !node.nextSibling;
184         point = pointAt(node);
185         removeElement(node);
186         return writeNode(node, c, end);
187       }
188     }
189
190     // MochiKit iterators are objects with a next function that
191     // returns the next value or throws StopIteration when there are
192     // no more values.
193     return {next: function(){return cc();}, nodes: nodeQueue};
194   }
195
196   // Determine the text size of a processed node.
197   function nodeSize(node) {
198     if (node.nodeName == "BR")
199       return 1;
200     else
201       return node.currentText.length;
202   }
203
204   // Search backwards through the top-level nodes until the next BR or
205   // the start of the frame.
206   function startOfLine(node) {
207     while (node && node.nodeName != "BR") node = node.previousSibling;
208     return node;
209   }
210   function endOfLine(node, container) {
211     if (!node) node = container.firstChild;
212     else if (node.nodeName == "BR") node = node.nextSibling;
213
214     while (node && node.nodeName != "BR") node = node.nextSibling;
215     return node;
216   }
217
218   function time() {return new Date().getTime();}
219
220   // Replace all DOM nodes in the current selection with new ones.
221   // Needed to prevent issues in IE where the old DOM nodes can be
222   // pasted back into the document, still holding their old undo
223   // information.
224   function scrubPasted(container, start, start2) {
225     var end = select.selectionTopNode(container, true),
226         doc = container.ownerDocument;
227     if (start != null && start.parentNode != container) start = start2;
228     if (start === false) start = null;
229     if (start == end || !end || !container.firstChild) return;
230
231     var clear = traverseDOM(start ? start.nextSibling : container.firstChild);
232     while (end.parentNode == container) try{clear.next();}catch(e){break;}
233     forEach(clear.nodes, function(node) {
234       var newNode = node.nodeName == "BR" ? doc.createElement("BR") : makePartSpan(node.currentText, doc);
235       container.replaceChild(newNode, node);
236     });
237   }
238
239   // Client interface for searching the content of the editor. Create
240   // these by calling CodeMirror.getSearchCursor. To use, call
241   // findNext on the resulting object -- this returns a boolean
242   // indicating whether anything was found, and can be called again to
243   // skip to the next find. Use the select and replace methods to
244   // actually do something with the found locations.
245   function SearchCursor(editor, string, fromCursor) {
246     this.editor = editor;
247     this.history = editor.history;
248     this.history.commit();
249
250     // Are we currently at an occurrence of the search string?
251     this.atOccurrence = false;
252     // The object stores a set of nodes coming after its current
253     // position, so that when the current point is taken out of the
254     // DOM tree, we can still try to continue.
255     this.fallbackSize = 15;
256     var cursor;
257     // Start from the cursor when specified and a cursor can be found.
258     if (fromCursor && (cursor = select.cursorPos(this.editor.container))) {
259       this.line = cursor.node;
260       this.offset = cursor.offset;
261     }
262     else {
263       this.line = null;
264       this.offset = 0;
265     }
266     this.valid = !!string;
267
268     // Create a matcher function based on the kind of string we have.
269     var target = string.split("\n"), self = this;
270     this.matches = (target.length == 1) ?
271       // For one-line strings, searching can be done simply by calling
272       // indexOf on the current line.
273       function() {
274         var match = cleanText(self.history.textAfter(self.line).slice(self.offset)).indexOf(string);
275         if (match > -1)
276           return {from: {node: self.line, offset: self.offset + match},
277                   to: {node: self.line, offset: self.offset + match + string.length}};
278       } :
279       // Multi-line strings require internal iteration over lines, and
280       // some clunky checks to make sure the first match ends at the
281       // end of the line and the last match starts at the start.
282       function() {
283         var firstLine = cleanText(self.history.textAfter(self.line).slice(self.offset));
284         var match = firstLine.lastIndexOf(target[0]);
285         if (match == -1 || match != firstLine.length - target[0].length)
286           return false;
287         var startOffset = self.offset + match;
288
289         var line = self.history.nodeAfter(self.line);
290         for (var i = 1; i < target.length - 1; i++) {
291           if (cleanText(self.history.textAfter(line)) != target[i])
292             return false;
293           line = self.history.nodeAfter(line);
294         }
295
296         if (cleanText(self.history.textAfter(line)).indexOf(target[target.length - 1]) != 0)
297           return false;
298
299         return {from: {node: self.line, offset: startOffset},
300                 to: {node: line, offset: target[target.length - 1].length}};
301       };
302   }
303
304   SearchCursor.prototype = {
305     findNext: function() {
306       if (!this.valid) return false;
307       this.atOccurrence = false;
308       var self = this;
309
310       // Go back to the start of the document if the current line is
311       // no longer in the DOM tree.
312       if (this.line && !this.line.parentNode) {
313         this.line = null;
314         this.offset = 0;
315       }
316
317       // Set the cursor's position one character after the given
318       // position.
319       function saveAfter(pos) {
320         if (self.history.textAfter(pos.node).length > pos.offset) {
321           self.line = pos.node;
322           self.offset = pos.offset + 1;
323         }
324         else {
325           self.line = self.history.nodeAfter(pos.node);
326           self.offset = 0;
327         }
328       }
329
330       while (true) {
331         var match = this.matches();
332         // Found the search string.
333         if (match) {
334           this.atOccurrence = match;
335           saveAfter(match.from);
336           return true;
337         }
338         this.line = this.history.nodeAfter(this.line);
339         this.offset = 0;
340         // End of document.
341         if (!this.line) {
342           this.valid = false;
343           return false;
344         }
345       }
346     },
347
348     select: function() {
349       if (this.atOccurrence) {
350         select.setCursorPos(this.editor.container, this.atOccurrence.from, this.atOccurrence.to);
351         select.scrollToCursor(this.editor.container);
352       }
353     },
354
355     replace: function(string) {
356       if (this.atOccurrence) {
357         var end = this.editor.replaceRange(this.atOccurrence.from, this.atOccurrence.to, string);
358         this.line = end.node;
359         this.offset = end.offset;
360         this.atOccurrence = false;
361       }
362     }
363   };
364
365   // The Editor object is the main inside-the-iframe interface.
366   function Editor(options) {
367     this.options = options;
368     window.indentUnit = options.indentUnit;
369     this.parent = parent;
370     this.doc = document;
371     var container = this.container = this.doc.body;
372     this.win = window;
373     this.history = new History(container, options.undoDepth, options.undoDelay,
374                                this, options.onChange);
375     var self = this;
376
377     if (!Editor.Parser)
378       throw "No parser loaded.";
379     if (options.parserConfig && Editor.Parser.configure)
380       Editor.Parser.configure(options.parserConfig);
381
382     if (!options.readOnly)
383       select.setCursorPos(container, {node: null, offset: 0});
384
385     this.dirty = [];
386     if (options.content)
387       this.importCode(options.content);
388     else // FF acts weird when the editable document is completely empty
389       container.appendChild(this.doc.createElement("BR"));
390
391     if (!options.readOnly) {
392       if (options.continuousScanning !== false) {
393         this.scanner = this.documentScanner(options.passTime);
394         this.delayScanning();
395       }
396
397       function setEditable() {
398         // In IE, designMode frames can not run any scripts, so we use
399         // contentEditable instead.
400         if (document.body.contentEditable != undefined && internetExplorer)
401           document.body.contentEditable = "true";
402         else
403           document.designMode = "on";
404
405         document.documentElement.style.borderWidth = "0";
406         if (!options.textWrapping)
407           container.style.whiteSpace = "nowrap";
408       }
409
410       // If setting the frame editable fails, try again when the user
411       // focus it (happens when the frame is not visible on
412       // initialisation, in Firefox).
413       try {
414         setEditable();
415       }
416       catch(e) {
417         var focusEvent = addEventHandler(document, "focus", function() {
418           focusEvent();
419           setEditable();
420         }, true);
421       }
422
423       addEventHandler(document, "keydown", method(this, "keyDown"));
424       addEventHandler(document, "keypress", method(this, "keyPress"));
425       addEventHandler(document, "keyup", method(this, "keyUp"));
426
427       function cursorActivity() {self.cursorActivity(false);}
428       addEventHandler(document.body, "mouseup", cursorActivity);
429       addEventHandler(document.body, "paste", function(event) {
430         cursorActivity();
431         if (internetExplorer) {
432           var text = null;
433           try {text = window.clipboardData.getData("Text");}catch(e){}
434           if (text != null) {
435             self.replaceSelection(text);
436             event.stop();
437           }
438           else {
439             var start = select.selectionTopNode(self.container, true),
440                 start2 = start && start.previousSibling;
441             setTimeout(function(){scrubPasted(self.container, start, start2);}, 0);
442           }
443         }
444       });
445       addEventHandler(document.body, "cut", cursorActivity);
446
447       if (this.options.autoMatchParens)
448         addEventHandler(document.body, "click", method(this, "scheduleParenBlink"));
449     }
450     else if (!options.textWrapping) {
451       container.style.whiteSpace = "nowrap";
452     }
453   }
454
455   function isSafeKey(code) {
456     return (code >= 16 && code <= 18) || // shift, control, alt
457            (code >= 33 && code <= 40); // arrows, home, end
458   }
459
460   Editor.prototype = {
461     // Import a piece of code into the editor.
462     importCode: function(code) {
463       this.history.push(null, null, asEditorLines(code));
464       this.history.reset();
465     },
466
467     // Extract the code from the editor.
468     getCode: function() {
469       if (!this.container.firstChild)
470         return "";
471
472       var accum = [];
473       select.markSelection(this.win);
474       forEach(traverseDOM(this.container.firstChild), method(accum, "push"));
475       webkitLastLineHack(this.container);
476       select.selectMarked();
477       return cleanText(accum.join(""));
478     },
479
480     checkLine: function(node) {
481       if (node === false || !(node == null || node.parentNode == this.container))
482         throw parent.CodeMirror.InvalidLineHandle;
483     },
484
485     cursorPosition: function(start) {
486       if (start == null) start = true;
487       var pos = select.cursorPos(this.container, start);
488       if (pos) return {line: pos.node, character: pos.offset};
489       else return {line: null, character: 0};
490     },
491
492     firstLine: function() {
493       return null;
494     },
495
496     lastLine: function() {
497       if (this.container.lastChild) return startOfLine(this.container.lastChild);
498       else return null;
499     },
500
501     nextLine: function(line) {
502       this.checkLine(line);
503       var end = endOfLine(line, this.container);
504       return end || false;
505     },
506
507     prevLine: function(line) {
508       this.checkLine(line);
509       if (line == null) return false;
510       return startOfLine(line.previousSibling);
511     },
512
513     selectLines: function(startLine, startOffset, endLine, endOffset) {
514       this.checkLine(startLine);
515       var start = {node: startLine, offset: startOffset}, end = null;
516       if (endOffset !== undefined) {
517         this.checkLine(endLine);
518         end = {node: endLine, offset: endOffset};
519       }
520       select.setCursorPos(this.container, start, end);
521       select.scrollToCursor(this.container);
522     },
523
524     lineContent: function(line) {
525       this.checkLine(line);
526       var accum = [];
527       for (line = line ? line.nextSibling : this.container.firstChild;
528            line && line.nodeName != "BR"; line = line.nextSibling)
529         accum.push(nodeText(line));
530       return cleanText(accum.join(""));
531     },
532
533     setLineContent: function(line, content) {
534       this.history.commit();
535       this.replaceRange({node: line, offset: 0},
536                         {node: line, offset: this.history.textAfter(line).length},
537                         content);
538       this.addDirtyNode(line);
539       this.scheduleHighlight();
540     },
541
542     insertIntoLine: function(line, position, content) {
543       var before = null;
544       if (position == "end") {
545         before = endOfLine(line, this.container);
546       }
547       else {
548         for (var cur = line ? line.nextSibling : this.container.firstChild; cur; cur = cur.nextSibling) {
549           if (position == 0) {
550             before = cur;
551             break;
552           }
553           var text = (cur.innerText || cur.textContent || cur.nodeValue || "");
554           if (text.length > position) {
555             before = cur.nextSibling;
556             content = text.slice(0, position) + content + text.slice(position);
557             removeElement(cur);
558             break;
559           }
560           position -= text.length;
561         }
562       }
563
564       var lines = asEditorLines(content), doc = this.container.ownerDocument;
565       for (var i = 0; i < lines.length; i++) {
566         if (i > 0) this.container.insertBefore(doc.createElement("BR"), before);
567         this.container.insertBefore(makePartSpan(lines[i], doc), before);
568       }
569       this.addDirtyNode(line);
570       this.scheduleHighlight();
571     },
572
573     // Retrieve the selected text.
574     selectedText: function() {
575       var h = this.history;
576       h.commit();
577
578       var start = select.cursorPos(this.container, true),
579           end = select.cursorPos(this.container, false);
580       if (!start || !end) return "";
581
582       if (start.node == end.node)
583         return h.textAfter(start.node).slice(start.offset, end.offset);
584
585       var text = [h.textAfter(start.node).slice(start.offset)];
586       for (var pos = h.nodeAfter(start.node); pos != end.node; pos = h.nodeAfter(pos))
587         text.push(h.textAfter(pos));
588       text.push(h.textAfter(end.node).slice(0, end.offset));
589       return cleanText(text.join("\n"));
590     },
591
592     // Replace the selection with another piece of text.
593     replaceSelection: function(text) {
594       this.history.commit();
595       var start = select.cursorPos(this.container, true),
596           end = select.cursorPos(this.container, false);
597       if (!start || !end) return;
598
599       end = this.replaceRange(start, end, text);
600       select.setCursorPos(this.container, start, end);
601     },
602
603     replaceRange: function(from, to, text) {
604       var lines = asEditorLines(text);
605       lines[0] = this.history.textAfter(from.node).slice(0, from.offset) + lines[0];
606       var lastLine = lines[lines.length - 1];
607       lines[lines.length - 1] = lastLine + this.history.textAfter(to.node).slice(to.offset);
608       var end = this.history.nodeAfter(to.node);
609       this.history.push(from.node, end, lines);
610       return {node: this.history.nodeBefore(end),
611               offset: lastLine.length};
612     },
613
614     getSearchCursor: function(string, fromCursor) {
615       return new SearchCursor(this, string, fromCursor);
616     },
617
618     // Re-indent the whole buffer
619     reindent: function() {
620       if (this.container.firstChild)
621         this.indentRegion(null, this.container.lastChild);
622     },
623
624     reindentSelection: function(direction) {
625       if (!select.somethingSelected(this.win)) {
626         this.indentAtCursor(direction);
627       }
628       else {
629         var start = select.selectionTopNode(this.container, true),
630             end = select.selectionTopNode(this.container, false);
631         if (start === false || end === false) return;
632         this.indentRegion(start, end, direction);
633       }
634     },
635
636     grabKeys: function(eventHandler, filter) {
637       this.frozen = eventHandler;
638       this.keyFilter = filter;
639     },
640     ungrabKeys: function() {
641       this.frozen = "leave";
642       this.keyFilter = null;
643     },
644
645     setParser: function(name) {
646       Editor.Parser = window[name];
647       if (this.container.firstChild) {
648         forEach(this.container.childNodes, function(n) {
649           if (n.nodeType != 3) n.dirty = true;
650         });
651         this.addDirtyNode(this.firstChild);
652         this.scheduleHighlight();
653       }
654     },
655
656     // Intercept enter and tab, and assign their new functions.
657     keyDown: function(event) {
658       if (this.frozen == "leave") this.frozen = null;
659       if (this.frozen && (!this.keyFilter || this.keyFilter(event))) {
660         event.stop();
661         this.frozen(event);
662         return;
663       }
664
665       var code = event.keyCode;
666       // Don't scan when the user is typing.
667       this.delayScanning();
668       // Schedule a paren-highlight event, if configured.
669       if (this.options.autoMatchParens)
670         this.scheduleParenBlink();
671
672       // The variouschecks for !altKey are there because AltGr sets both
673       // ctrlKey and altKey to true, and should not be recognised as
674       // Control.
675       if (code == 13) { // enter
676         if (event.ctrlKey && !event.altKey) {
677           this.reparseBuffer();
678         }
679         else {
680           select.insertNewlineAtCursor(this.win);
681           this.indentAtCursor();
682           select.scrollToCursor(this.container);
683         }
684         event.stop();
685       }
686       else if (code == 9 && this.options.tabMode != "default") { // tab
687         this.handleTab(!event.ctrlKey && !event.shiftKey);
688         event.stop();
689       }
690       else if (code == 32 && event.shiftKey && this.options.tabMode == "default") { // space
691         this.handleTab(true);
692         event.stop();
693       }
694       else if (code == 36 && !event.shiftKey && !event.ctrlKey) { // home
695         if (this.home())
696           event.stop();
697       }
698       else if ((code == 219 || code == 221) && event.ctrlKey && !event.altKey) { // [, ]
699         this.blinkParens(event.shiftKey);
700         event.stop();
701       }
702       else if (event.metaKey && !event.shiftKey && (code == 37 || code == 39)) { // Meta-left/right
703         var cursor = select.selectionTopNode(this.container);
704         if (cursor === false || !this.container.firstChild) return;
705
706         if (code == 37) select.focusAfterNode(startOfLine(cursor), this.container);
707         else {
708           var end = endOfLine(cursor, this.container);
709           select.focusAfterNode(end ? end.previousSibling : this.container.lastChild, this.container);
710         }
711         event.stop();
712       }
713       else if ((event.ctrlKey || event.metaKey) && !event.altKey) {
714         if ((event.shiftKey && code == 90) || code == 89) { // shift-Z, Y
715           select.scrollToNode(this.history.redo());
716           event.stop();
717         }
718         else if (code == 90 || (safari && code == 8)) { // Z, backspace
719           select.scrollToNode(this.history.undo());
720           event.stop();
721         }
722         else if (code == 83 && this.options.saveFunction) { // S
723           this.options.saveFunction();
724           event.stop();
725         }
726       }
727     },
728
729     // Check for characters that should re-indent the current line,
730     // and prevent Opera from handling enter and tab anyway.
731     keyPress: function(event) {
732       var electric = Editor.Parser.electricChars, self = this;
733       // Hack for Opera, and Firefox on OS X, in which stopping a
734       // keydown event does not prevent the associated keypress event
735       // from happening, so we have to cancel enter and tab again
736       // here.
737       if ((this.frozen && (!this.keyFilter || this.keyFilter(event))) ||
738           event.code == 13 || (event.code == 9 && this.options.tabMode != "default") ||
739           (event.keyCode == 32 && event.shiftKey && this.options.tabMode == "default"))
740         event.stop();
741       else if (electric && electric.indexOf(event.character) != -1)
742         this.parent.setTimeout(function(){self.indentAtCursor(null);}, 0);
743     },
744
745     // Mark the node at the cursor dirty when a non-safe key is
746     // released.
747     keyUp: function(event) {
748       this.cursorActivity(isSafeKey(event.keyCode));
749     },
750
751     // Indent the line following a given <br>, or null for the first
752     // line. If given a <br> element, this must have been highlighted
753     // so that it has an indentation method. Returns the whitespace
754     // element that has been modified or created (if any).
755     indentLineAfter: function(start, direction) {
756       // whiteSpace is the whitespace span at the start of the line,
757       // or null if there is no such node.
758       var whiteSpace = start ? start.nextSibling : this.container.firstChild;
759       if (whiteSpace && !hasClass(whiteSpace, "whitespace"))
760         whiteSpace = null;
761
762       // Sometimes the start of the line can influence the correct
763       // indentation, so we retrieve it.
764       var firstText = whiteSpace ? whiteSpace.nextSibling : (start ? start.nextSibling : this.container.firstChild);
765       var nextChars = (start && firstText && firstText.currentText) ? firstText.currentText : "";
766
767       // Ask the lexical context for the correct indentation, and
768       // compute how much this differs from the current indentation.
769       var newIndent = 0, curIndent = whiteSpace ? whiteSpace.currentText.length : 0;
770       if (direction != null && this.options.tabMode == "shift")
771         newIndent = direction ? curIndent + indentUnit : Math.max(0, curIndent - indentUnit)
772       else if (start)
773         newIndent = start.indentation(nextChars, curIndent, direction);
774       else if (Editor.Parser.firstIndentation)
775         newIndent = Editor.Parser.firstIndentation(nextChars, curIndent, direction);
776       var indentDiff = newIndent - curIndent;
777
778       // If there is too much, this is just a matter of shrinking a span.
779       if (indentDiff < 0) {
780         if (newIndent == 0) {
781           if (firstText) select.snapshotMove(whiteSpace.firstChild, firstText.firstChild, 0);
782           removeElement(whiteSpace);
783           whiteSpace = null;
784         }
785         else {
786           select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true);
787           whiteSpace.currentText = makeWhiteSpace(newIndent);
788           whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
789         }
790       }
791       // Not enough...
792       else if (indentDiff > 0) {
793         // If there is whitespace, we grow it.
794         if (whiteSpace) {
795           whiteSpace.currentText = makeWhiteSpace(newIndent);
796           whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
797         }
798         // Otherwise, we have to add a new whitespace node.
799         else {
800           whiteSpace = makePartSpan(makeWhiteSpace(newIndent), this.doc);
801           whiteSpace.className = "whitespace";
802           if (start) insertAfter(whiteSpace, start);
803           else this.container.insertBefore(whiteSpace, this.container.firstChild);
804         }
805         if (firstText) select.snapshotMove(firstText.firstChild, whiteSpace.firstChild, curIndent, false, true);
806       }
807       if (indentDiff != 0) this.addDirtyNode(start);
808       return whiteSpace;
809     },
810
811     // Re-highlight the selected part of the document.
812     highlightAtCursor: function() {
813       var pos = select.selectionTopNode(this.container, true);
814       var to = select.selectionTopNode(this.container, false);
815       if (pos === false || to === false) return;
816
817       select.markSelection(this.win);
818       if (this.highlight(pos, endOfLine(to, this.container), true, 20) === false)
819         return false;
820       select.selectMarked();
821       return true;
822     },
823
824     // When tab is pressed with text selected, the whole selection is
825     // re-indented, when nothing is selected, the line with the cursor
826     // is re-indented.
827     handleTab: function(direction) {
828       if (this.options.tabMode == "spaces")
829         select.insertTabAtCursor(this.win);
830       else
831         this.reindentSelection(direction);
832     },
833
834     home: function() {
835       var cur = select.selectionTopNode(this.container, true), start = cur;
836       if (cur === false || !(!cur || cur.isPart || cur.nodeName == "BR") || !this.container.firstChild)
837         return false;
838
839       while (cur && cur.nodeName != "BR") cur = cur.previousSibling;
840       var next = cur ? cur.nextSibling : this.container.firstChild;
841       if (next && next != start && next.isPart && hasClass(next, "whitespace"))
842         select.focusAfterNode(next, this.container);
843       else
844         select.focusAfterNode(cur, this.container);
845
846       select.scrollToCursor(this.container);
847       return true;
848     },
849
850     // Delay (or initiate) the next paren blink event.
851     scheduleParenBlink: function() {
852       if (this.parenEvent) this.parent.clearTimeout(this.parenEvent);
853       var self = this;
854       this.parenEvent = this.parent.setTimeout(function(){self.blinkParens();}, 300);
855     },
856
857     // Take the token before the cursor. If it contains a character in
858     // '()[]{}', search for the matching paren/brace/bracket, and
859     // highlight them in green for a moment, or red if no proper match
860     // was found.
861     blinkParens: function(jump) {
862       if (!window.select) return;
863       // Clear the event property.
864       if (this.parenEvent) this.parent.clearTimeout(this.parenEvent);
865       this.parenEvent = null;
866
867       // Extract a 'paren' from a piece of text.
868       function paren(node) {
869         if (node.currentText) {
870           var match = node.currentText.match(/^[\s\u00a0]*([\(\)\[\]{}])[\s\u00a0]*$/);
871           return match && match[1];
872         }
873       }
874       // Determine the direction a paren is facing.
875       function forward(ch) {
876         return /[\(\[\{]/.test(ch);
877       }
878
879       var ch, self = this, cursor = select.selectionTopNode(this.container, true);
880       if (!cursor || !this.highlightAtCursor()) return;
881       cursor = select.selectionTopNode(this.container, true);
882       if (!(cursor && ((ch = paren(cursor)) || (cursor = cursor.nextSibling) && (ch = paren(cursor)))))
883         return;
884       // We only look for tokens with the same className.
885       var className = cursor.className, dir = forward(ch), match = matching[ch];
886
887       // Since parts of the document might not have been properly
888       // highlighted, and it is hard to know in advance which part we
889       // have to scan, we just try, and when we find dirty nodes we
890       // abort, parse them, and re-try.
891       function tryFindMatch() {
892         var stack = [], ch, ok = true;;
893         for (var runner = cursor; runner; runner = dir ? runner.nextSibling : runner.previousSibling) {
894           if (runner.className == className && runner.nodeName == "SPAN" && (ch = paren(runner))) {
895             if (forward(ch) == dir)
896               stack.push(ch);
897             else if (!stack.length)
898               ok = false;
899             else if (stack.pop() != matching[ch])
900               ok = false;
901             if (!stack.length) break;
902           }
903           else if (runner.dirty || runner.nodeName != "SPAN" && runner.nodeName != "BR") {
904             return {node: runner, status: "dirty"};
905           }
906         }
907         return {node: runner, status: runner && ok};
908       }
909       // Temporarily give the relevant nodes a colour.
910       function blink(node, ok) {
911         node.style.fontWeight = "bold";
912         node.style.color = ok ? "#8F8" : "#F88";
913         self.parent.setTimeout(function() {node.style.fontWeight = ""; node.style.color = "";}, 500);
914       }
915
916       while (true) {
917         var found = tryFindMatch();
918         if (found.status == "dirty") {
919           this.highlight(found.node, endOfLine(found.node));
920           // Needed because in some corner cases a highlight does not
921           // reach a node.
922           found.node.dirty = false;
923           continue;
924         }
925         else {
926           blink(cursor, found.status);
927           if (found.node) {
928             blink(found.node, found.status);
929             if (jump) select.focusAfterNode(found.node.previousSibling, this.container);
930           }
931           break;
932         }
933       }
934     },
935
936     // Adjust the amount of whitespace at the start of the line that
937     // the cursor is on so that it is indented properly.
938     indentAtCursor: function(direction) {
939       if (!this.container.firstChild) return;
940       // The line has to have up-to-date lexical information, so we
941       // highlight it first.
942       if (!this.highlightAtCursor()) return;
943       var cursor = select.selectionTopNode(this.container, false);
944       // If we couldn't determine the place of the cursor,
945       // there's nothing to indent.
946       if (cursor === false)
947         return;
948       var lineStart = startOfLine(cursor);
949       var whiteSpace = this.indentLineAfter(lineStart, direction);
950       if (cursor == lineStart && whiteSpace)
951           cursor = whiteSpace;
952       // This means the indentation has probably messed up the cursor.
953       if (cursor == whiteSpace)
954         select.focusAfterNode(cursor, this.container);
955     },
956
957     // Indent all lines whose start falls inside of the current
958     // selection.
959     indentRegion: function(start, end, direction) {
960       var current = (start = startOfLine(start)), before = start && startOfLine(start.previousSibling);
961       if (end.nodeName != "BR") end = endOfLine(end, this.container);
962
963       do {
964         var next = endOfLine(current, this.container);
965         if (current) this.highlight(before, next, true);
966         this.indentLineAfter(current, direction);
967         before = current;
968         current = next;
969       } while (current != end);
970       select.setCursorPos(this.container, {node: start, offset: 0}, {node: end, offset: 0});
971     },
972
973     // Find the node that the cursor is in, mark it as dirty, and make
974     // sure a highlight pass is scheduled.
975     cursorActivity: function(safe) {
976       if (internetExplorer) {
977         this.container.createTextRange().execCommand("unlink");
978         this.selectionSnapshot = select.selectionCoords(this.win);
979       }
980
981       var activity = this.options.cursorActivity;
982       if (!safe || activity) {
983         var cursor = select.selectionTopNode(this.container, false);
984         if (cursor === false || !this.container.firstChild) return;
985         cursor = cursor || this.container.firstChild;
986         if (activity) activity(cursor);
987         if (!safe) {
988           this.scheduleHighlight();
989           this.addDirtyNode(cursor);
990         }
991       }
992     },
993
994     reparseBuffer: function() {
995       forEach(this.container.childNodes, function(node) {node.dirty = true;});
996       if (this.container.firstChild)
997         this.addDirtyNode(this.container.firstChild);
998     },
999
1000     // Add a node to the set of dirty nodes, if it isn't already in
1001     // there.
1002     addDirtyNode: function(node) {
1003       node = node || this.container.firstChild;
1004       if (!node) return;
1005
1006       for (var i = 0; i < this.dirty.length; i++)
1007         if (this.dirty[i] == node) return;
1008
1009       if (node.nodeType != 3)
1010         node.dirty = true;
1011       this.dirty.push(node);
1012     },
1013
1014     // Cause a highlight pass to happen in options.passDelay
1015     // milliseconds. Clear the existing timeout, if one exists. This
1016     // way, the passes do not happen while the user is typing, and
1017     // should as unobtrusive as possible.
1018     scheduleHighlight: function() {
1019       // Timeouts are routed through the parent window, because on
1020       // some browsers designMode windows do not fire timeouts.
1021       var self = this;
1022       this.parent.clearTimeout(this.highlightTimeout);
1023       this.highlightTimeout = this.parent.setTimeout(function(){self.highlightDirty();}, this.options.passDelay);
1024     },
1025
1026     // Fetch one dirty node, and remove it from the dirty set.
1027     getDirtyNode: function() {
1028       while (this.dirty.length > 0) {
1029         var found = this.dirty.pop();
1030         // IE8 sometimes throws an unexplainable 'invalid argument'
1031         // exception for found.parentNode
1032         try {
1033           // If the node has been coloured in the meantime, or is no
1034           // longer in the document, it should not be returned.
1035           while (found && found.parentNode != this.container)
1036             found = found.parentNode
1037           if (found && (found.dirty || found.nodeType == 3))
1038             return found;
1039         } catch (e) {}
1040       }
1041       return null;
1042     },
1043
1044     // Pick dirty nodes, and highlight them, until options.passTime
1045     // milliseconds have gone by. The highlight method will continue
1046     // to next lines as long as it finds dirty nodes. It returns
1047     // information about the place where it stopped. If there are
1048     // dirty nodes left after this function has spent all its lines,
1049     // it shedules another highlight to finish the job.
1050     highlightDirty: function(force) {
1051       // Prevent FF from raising an error when it is firing timeouts
1052       // on a page that's no longer loaded.
1053       if (!window.select) return;
1054
1055       if (!this.options.readOnly) select.markSelection(this.win);
1056       var start, endTime = force ? null : time() + this.options.passTime;
1057       while (time() < endTime && (start = this.getDirtyNode())) {
1058         var result = this.highlight(start, endTime);
1059         if (result && result.node && result.dirty)
1060           this.addDirtyNode(result.node);
1061       }
1062       if (!this.options.readOnly) select.selectMarked();
1063       if (start) this.scheduleHighlight();
1064       return this.dirty.length == 0;
1065     },
1066
1067     // Creates a function that, when called through a timeout, will
1068     // continuously re-parse the document.
1069     documentScanner: function(passTime) {
1070       var self = this, pos = null;
1071       return function() {
1072         // FF timeout weirdness workaround.
1073         if (!window.select) return;
1074         // If the current node is no longer in the document... oh
1075         // well, we start over.
1076         if (pos && pos.parentNode != self.container)
1077           pos = null;
1078         select.markSelection(self.win);
1079         var result = self.highlight(pos, time() + passTime, true);
1080         select.selectMarked();
1081         var newPos = result ? (result.node && result.node.nextSibling) : null;
1082         pos = (pos == newPos) ? null : newPos;
1083         self.delayScanning();
1084       };
1085     },
1086
1087     // Starts the continuous scanning process for this document after
1088     // a given interval.
1089     delayScanning: function() {
1090       if (this.scanner) {
1091         this.parent.clearTimeout(this.documentScan);
1092         this.documentScan = this.parent.setTimeout(this.scanner, this.options.continuousScanning);
1093       }
1094     },
1095
1096     // The function that does the actual highlighting/colouring (with
1097     // help from the parser and the DOM normalizer). Its interface is
1098     // rather overcomplicated, because it is used in different
1099     // situations: ensuring that a certain line is highlighted, or
1100     // highlighting up to X milliseconds starting from a certain
1101     // point. The 'from' argument gives the node at which it should
1102     // start. If this is null, it will start at the beginning of the
1103     // document. When a timestamp is given with the 'target' argument,
1104     // it will stop highlighting at that time. If this argument holds
1105     // a DOM node, it will highlight until it reaches that node. If at
1106     // any time it comes across two 'clean' lines (no dirty nodes), it
1107     // will stop, except when 'cleanLines' is true. maxBacktrack is
1108     // the maximum number of lines to backtrack to find an existing
1109     // parser instance. This is used to give up in situations where a
1110     // highlight would take too long and freeze the browser interface.
1111     highlight: function(from, target, cleanLines, maxBacktrack){
1112       var container = this.container, self = this, active = this.options.activeTokens;
1113       var endTime = (typeof target == "number" ? target : null);
1114
1115       if (!container.firstChild)
1116         return;
1117       // Backtrack to the first node before from that has a partial
1118       // parse stored.
1119       while (from && (!from.parserFromHere || from.dirty)) {
1120         if (maxBacktrack != null && from.nodeName == "BR" && (--maxBacktrack) < 0)
1121           return false;
1122         from = from.previousSibling;
1123       }
1124       // If we are at the end of the document, do nothing.
1125       if (from && !from.nextSibling)
1126         return;
1127
1128       // Check whether a part (<span> node) and the corresponding token
1129       // match.
1130       function correctPart(token, part){
1131         return !part.reduced && part.currentText == token.value && part.className == token.style;
1132       }
1133       // Shorten the text associated with a part by chopping off
1134       // characters from the front. Note that only the currentText
1135       // property gets changed. For efficiency reasons, we leave the
1136       // nodeValue alone -- we set the reduced flag to indicate that
1137       // this part must be replaced.
1138       function shortenPart(part, minus){
1139         part.currentText = part.currentText.substring(minus);
1140         part.reduced = true;
1141       }
1142       // Create a part corresponding to a given token.
1143       function tokenPart(token){
1144         var part = makePartSpan(token.value, self.doc);     
1145         part.className = token.style;
1146         return part;
1147       }
1148
1149       function maybeTouch(node) {
1150         if (node) {
1151           if (lineDirty || node.nextSibling != node.oldNextSibling)
1152             self.history.touch(node);
1153           node.oldNextSibling = node.nextSibling;
1154         }
1155         else {
1156           if (lineDirty || self.container.firstChild != self.container.oldFirstChild)
1157             self.history.touch(node);
1158           self.container.oldFirstChild = self.container.firstChild;
1159         }
1160       }
1161
1162       // Get the token stream. If from is null, we start with a new
1163       // parser from the start of the frame, otherwise a partial parse
1164       // is resumed.
1165       var traversal = traverseDOM(from ? from.nextSibling : container.firstChild),
1166           stream = stringStream(traversal),
1167           parsed = from ? from.parserFromHere(stream) : Editor.Parser.make(stream);
1168
1169       // parts is an interface to make it possible to 'delay' fetching
1170       // the next DOM node until we are completely done with the one
1171       // before it. This is necessary because often the next node is
1172       // not yet available when we want to proceed past the current
1173       // one.
1174       var parts = {
1175         current: null,
1176         // Fetch current node.
1177         get: function(){
1178           if (!this.current)
1179             this.current = traversal.nodes.shift();
1180           return this.current;
1181         },
1182         // Advance to the next part (do not fetch it yet).
1183         next: function(){
1184           this.current = null;
1185         },
1186         // Remove the current part from the DOM tree, and move to the
1187         // next.
1188         remove: function(){
1189           container.removeChild(this.get());
1190           this.current = null;
1191         },
1192         // Advance to the next part that is not empty, discarding empty
1193         // parts.
1194         getNonEmpty: function(){
1195           var part = this.get();
1196           // Allow empty nodes when they are alone on a line, needed
1197           // for the FF cursor bug workaround (see select.js,
1198           // insertNewlineAtCursor).
1199           while (part && part.nodeName == "SPAN" && part.currentText == "") {
1200             var old = part;
1201             this.remove();
1202             part = this.get();
1203             // Adjust selection information, if any. See select.js for details.
1204             select.snapshotMove(old.firstChild, part && (part.firstChild || part), 0);
1205           }
1206           return part;
1207         }
1208       };
1209
1210       var lineDirty = false, prevLineDirty = true, lineNodes = 0;
1211
1212       // This forEach loops over the tokens from the parsed stream, and
1213       // at the same time uses the parts object to proceed through the
1214       // corresponding DOM nodes.
1215       forEach(parsed, function(token){
1216         var part = parts.getNonEmpty();
1217
1218         if (token.value == "\n"){
1219           // The idea of the two streams actually staying synchronized
1220           // is such a long shot that we explicitly check.
1221           if (part.nodeName != "BR")
1222             throw "Parser out of sync. Expected BR.";
1223
1224           if (part.dirty || !part.indentation) lineDirty = true;
1225           maybeTouch(from);
1226           from = part;
1227
1228           // Every <br> gets a copy of the parser state and a lexical
1229           // context assigned to it. The first is used to be able to
1230           // later resume parsing from this point, the second is used
1231           // for indentation.
1232           part.parserFromHere = parsed.copy();
1233           part.indentation = token.indentation;
1234           part.dirty = false;
1235
1236           // If the target argument wasn't an integer, go at least
1237           // until that node.
1238           if (endTime == null && part == target) throw StopIteration;
1239
1240           // A clean line with more than one node means we are done.
1241           // Throwing a StopIteration is the way to break out of a
1242           // MochiKit forEach loop.
1243           if ((endTime != null && time() >= endTime) || (!lineDirty && !prevLineDirty && lineNodes > 1 && !cleanLines))
1244             throw StopIteration;
1245           prevLineDirty = lineDirty; lineDirty = false; lineNodes = 0;
1246           parts.next();
1247         }
1248         else {
1249           if (part.nodeName != "SPAN")
1250             throw "Parser out of sync. Expected SPAN.";
1251           if (part.dirty)
1252             lineDirty = true;
1253           lineNodes++;
1254
1255           // If the part matches the token, we can leave it alone.
1256           if (correctPart(token, part)){
1257             part.dirty = false;
1258             parts.next();
1259           }
1260           // Otherwise, we have to fix it.
1261           else {
1262             lineDirty = true;
1263             // Insert the correct part.
1264             var newPart = tokenPart(token);
1265             container.insertBefore(newPart, part);
1266             if (active) active(newPart, token, self);
1267             var tokensize = token.value.length;
1268             var offset = 0;
1269             // Eat up parts until the text for this token has been
1270             // removed, adjusting the stored selection info (see
1271             // select.js) in the process.
1272             while (tokensize > 0) {
1273               part = parts.get();
1274               var partsize = part.currentText.length;
1275               select.snapshotReplaceNode(part.firstChild, newPart.firstChild, tokensize, offset);
1276               if (partsize > tokensize){
1277                 shortenPart(part, tokensize);
1278                 tokensize = 0;
1279               }
1280               else {
1281                 tokensize -= partsize;
1282                 offset += partsize;
1283                 parts.remove();
1284               }
1285             }
1286           }
1287         }
1288       });
1289       maybeTouch(from);
1290       webkitLastLineHack(this.container);
1291
1292       // The function returns some status information that is used by
1293       // hightlightDirty to determine whether and where it has to
1294       // continue.
1295       return {node: parts.getNonEmpty(),
1296               dirty: lineDirty};
1297     }
1298   };
1299
1300   return Editor;
1301 })();
1302
1303 addEventHandler(window, "load", function() {
1304   var CodeMirror = window.frameElement.CodeMirror;
1305   CodeMirror.editor = new Editor(CodeMirror.options);
1306   this.parent.setTimeout(method(CodeMirror, "init"), 0);
1307 });