Web Inspector: home button behaviour is wrong in DTE
[WebKit-https.git] / Source / WebCore / inspector / front-end / DefaultTextEditor.js
1 /*
2  * Copyright (C) 2011 Google Inc. All rights reserved.
3  * Copyright (C) 2010 Apple Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  * copyright notice, this list of conditions and the following disclaimer
13  * in the documentation and/or other materials provided with the
14  * distribution.
15  *     * Neither the name of Google Inc. nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 /**
33  * @constructor
34  * @extends {WebInspector.View}
35  * @implements {WebInspector.TextEditor}
36  * @param {?string} url
37  * @param {WebInspector.TextEditorDelegate} delegate
38  */
39 WebInspector.DefaultTextEditor = function(url, delegate)
40 {
41     WebInspector.View.call(this);
42     this._delegate = delegate;
43     this._url = url;
44
45     this.registerRequiredCSS("textEditor.css");
46
47     this.element.className = "text-editor monospace";
48
49     // Prevent middle-click pasting in the editor unless it is explicitly enabled for certain component.
50     this.element.addEventListener("mouseup", preventDefaultOnMouseUp.bind(this), false);
51     function preventDefaultOnMouseUp(event)
52     {
53         if (event.button === 1)
54             event.consume(true);
55     }
56
57     this._textModel = new WebInspector.TextEditorModel();
58     this._textModel.addEventListener(WebInspector.TextEditorModel.Events.TextChanged, this._textChanged, this);
59
60     var syncScrollListener = this._syncScroll.bind(this);
61     var syncDecorationsForLineListener = this._syncDecorationsForLine.bind(this);
62     var syncLineHeightListener = this._syncLineHeight.bind(this);
63     this._mainPanel = new WebInspector.TextEditorMainPanel(this._delegate, this._textModel, url, syncScrollListener, syncDecorationsForLineListener);
64     this._gutterPanel = new WebInspector.TextEditorGutterPanel(this._textModel, syncDecorationsForLineListener, syncLineHeightListener);
65
66     this._mainPanel.element.addEventListener("scroll", this._handleScrollChanged.bind(this), false);
67
68     this._gutterPanel.element.addEventListener("mousedown", this._onMouseDown.bind(this), true);
69
70     // Explicitly enable middle-click pasting in the editor main panel.
71     this._mainPanel.element.addEventListener("mouseup", consumeMouseUp.bind(this), false);
72     function consumeMouseUp(event)
73     {
74         if (event.button === 1)
75             event.consume(false);
76     }
77
78     this.element.appendChild(this._mainPanel.element);
79     this.element.appendChild(this._gutterPanel.element);
80
81     // Forward mouse wheel events from the unscrollable gutter to the main panel.
82     function forwardWheelEvent(event)
83     {
84         var clone = document.createEvent("WheelEvent");
85         clone.initWebKitWheelEvent(event.wheelDeltaX, event.wheelDeltaY,
86                                    event.view,
87                                    event.screenX, event.screenY,
88                                    event.clientX, event.clientY,
89                                    event.ctrlKey, event.altKey, event.shiftKey, event.metaKey);
90         this._mainPanel.element.dispatchEvent(clone);
91     }
92     this._gutterPanel.element.addEventListener("mousewheel", forwardWheelEvent.bind(this), false);
93
94     this.element.addEventListener("keydown", this._handleKeyDown.bind(this), false);
95     this.element.addEventListener("contextmenu", this._contextMenu.bind(this), true);
96
97     this._wordMovementController = new WebInspector.DefaultTextEditor.WordMovementController(this, this._textModel);
98     this._registerShortcuts();
99 }
100
101 /**
102  * @constructor
103  * @param {WebInspector.TextRange} range
104  * @param {string} text
105  */
106 WebInspector.DefaultTextEditor.EditInfo = function(range, text)
107 {
108     this.range = range;
109     this.text = text;
110 }
111
112 WebInspector.DefaultTextEditor.prototype = {
113     /**
114      * @param {WebInspector.TextRange} range
115      * @return {string}
116      */
117     copyRange: function(range)
118     {
119         return this._textModel.copyRange(range);
120     },
121
122     /**
123      * @param {string} regex
124      * @param {string} cssClass
125      * @return {WebInspector.TextEditorMainPanel.HighlightDescriptor}
126      */
127     highlightRegex: function(regex, cssClass)
128     {
129         return this._mainPanel.highlightRegex(regex, cssClass);
130     },
131
132     /**
133      * @param {WebInspector.TextEditorMainPanel.HighlightDescriptor} highlightDescriptor
134      */
135     removeHighlight: function(highlightDescriptor)
136     {
137         this._mainPanel.removeHighlight(highlightDescriptor);
138     },
139
140     /**
141      * @param {WebInspector.TextRange} range
142      * @param {string} cssClass
143      */
144     highlightRange: function(range, cssClass)
145     {
146         return this._mainPanel.highlightRange(range, cssClass);
147     },
148
149     /**
150      * @param {string} mimeType
151      */
152     set mimeType(mimeType)
153     {
154         this._mainPanel.mimeType = mimeType;
155     },
156
157     /**
158      * @param {boolean} readOnly
159      */
160     setReadOnly: function(readOnly)
161     {
162         if (this._mainPanel.readOnly() === readOnly)
163             return;
164         this._mainPanel.setReadOnly(readOnly, this.isShowing());
165         WebInspector.markBeingEdited(this.element, !readOnly);
166     },
167
168     /**
169      * @return {boolean}
170      */
171     readOnly: function()
172     {
173         return this._mainPanel.readOnly();
174     },
175
176     /**
177      * @return {Element}
178      */
179     defaultFocusedElement: function()
180     {
181         return this._mainPanel.defaultFocusedElement();
182     },
183
184     /**
185      * @param {number} lineNumber
186      */
187     revealLine: function(lineNumber)
188     {
189         this._mainPanel.revealLine(lineNumber);
190     },
191
192     _onMouseDown: function(event)
193     {
194         var target = event.target.enclosingNodeOrSelfWithClass("webkit-line-number");
195         if (!target)
196             return;
197         this.dispatchEventToListeners(WebInspector.TextEditor.Events.GutterClick, { lineNumber: target.lineNumber, event: event });
198     },
199
200     /**
201      * @param {number} lineNumber
202      * @param {boolean} disabled
203      * @param {boolean} conditional
204      */
205     addBreakpoint: function(lineNumber, disabled, conditional)
206     {
207         this.beginUpdates();
208         this._gutterPanel.addDecoration(lineNumber, "webkit-breakpoint");
209         if (disabled)
210             this._gutterPanel.addDecoration(lineNumber, "webkit-breakpoint-disabled");
211         else
212             this._gutterPanel.removeDecoration(lineNumber, "webkit-breakpoint-disabled");
213         if (conditional)
214             this._gutterPanel.addDecoration(lineNumber, "webkit-breakpoint-conditional");
215         else
216             this._gutterPanel.removeDecoration(lineNumber, "webkit-breakpoint-conditional");
217         this.endUpdates();
218     },
219
220     /**
221      * @param {number} lineNumber
222      */
223     removeBreakpoint: function(lineNumber)
224     {
225         this.beginUpdates();
226         this._gutterPanel.removeDecoration(lineNumber, "webkit-breakpoint");
227         this._gutterPanel.removeDecoration(lineNumber, "webkit-breakpoint-disabled");
228         this._gutterPanel.removeDecoration(lineNumber, "webkit-breakpoint-conditional");
229         this.endUpdates();
230     },
231
232     /**
233      * @param {number} lineNumber
234      */
235     setExecutionLine: function(lineNumber)
236     {
237         this._executionLineNumber = lineNumber;
238         this._mainPanel.addDecoration(lineNumber, "webkit-execution-line");
239         this._gutterPanel.addDecoration(lineNumber, "webkit-execution-line");
240     },
241
242     clearExecutionLine: function()
243     {
244         if (typeof this._executionLineNumber === "number") {
245             this._mainPanel.removeDecoration(this._executionLineNumber, "webkit-execution-line");
246             this._gutterPanel.removeDecoration(this._executionLineNumber, "webkit-execution-line");
247         }
248         delete this._executionLineNumber;
249     },
250
251     /**
252      * @param {number} lineNumber
253      * @param {Element} element
254      */
255     addDecoration: function(lineNumber, element)
256     {
257         this._mainPanel.addDecoration(lineNumber, element);
258         this._gutterPanel.addDecoration(lineNumber, element);
259         this._syncDecorationsForLine(lineNumber);
260     },
261
262     /**
263      * @param {number} lineNumber
264      * @param {Element} element
265      */
266     removeDecoration: function(lineNumber, element)
267     {
268         this._mainPanel.removeDecoration(lineNumber, element);
269         this._gutterPanel.removeDecoration(lineNumber, element);
270         this._syncDecorationsForLine(lineNumber);
271     },
272
273     /**
274      * @param {WebInspector.TextRange} range
275      */
276     markAndRevealRange: function(range)
277     {
278         if (range)
279             this.setSelection(range);
280         this._mainPanel.markAndRevealRange(range);
281     },
282
283     /**
284      * @param {number} lineNumber
285      */
286     highlightLine: function(lineNumber)
287     {
288         if (typeof lineNumber !== "number" || lineNumber < 0)
289             return;
290
291         lineNumber = Math.min(lineNumber, this._textModel.linesCount - 1);
292         this._mainPanel.highlightLine(lineNumber);
293     },
294
295     clearLineHighlight: function()
296     {
297         this._mainPanel.clearLineHighlight();
298     },
299
300     /**
301      * @return {Array.<Element>}
302      */
303     elementsToRestoreScrollPositionsFor: function()
304     {
305         return [this._mainPanel.element];
306     },
307
308     /**
309      * @param {WebInspector.TextEditor} textEditor
310      */
311     inheritScrollPositions: function(textEditor)
312     {
313         this._mainPanel.element._scrollTop = textEditor._mainPanel.element.scrollTop;
314         this._mainPanel.element._scrollLeft = textEditor._mainPanel.element.scrollLeft;
315     },
316
317     beginUpdates: function()
318     {
319         this._mainPanel.beginUpdates();
320         this._gutterPanel.beginUpdates();
321     },
322
323     endUpdates: function()
324     {
325         this._mainPanel.endUpdates();
326         this._gutterPanel.endUpdates();
327         this._updatePanelOffsets();
328     },
329
330     onResize: function()
331     {
332         this._mainPanel.resize();
333         this._gutterPanel.resize();
334         this._updatePanelOffsets();
335     },
336
337     _textChanged: function(event)
338     {
339         this._mainPanel.textChanged(event.data.oldRange, event.data.newRange);
340         this._gutterPanel.textChanged(event.data.oldRange, event.data.newRange);
341         this._updatePanelOffsets();
342         if (event.data.editRange)
343             this._delegate.onTextChanged(event.data.oldRange, event.data.newRange);
344     },
345
346     /**
347      * @param {WebInspector.TextRange} range
348      * @param {string} text
349      * @return {WebInspector.TextRange}
350      */
351     editRange: function(range, text)
352     {
353         return this._textModel.editRange(range, text);
354     },
355
356     _updatePanelOffsets: function()
357     {
358         var lineNumbersWidth = this._gutterPanel.element.offsetWidth;
359         if (lineNumbersWidth)
360             this._mainPanel.element.style.setProperty("left", (lineNumbersWidth + 2) + "px");
361         else
362             this._mainPanel.element.style.removeProperty("left"); // Use default value set in CSS.
363     },
364
365     _syncScroll: function()
366     {
367         var mainElement = this._mainPanel.element;
368         var gutterElement = this._gutterPanel.element;
369         // Handle horizontal scroll bar at the bottom of the main panel.
370         this._gutterPanel.syncClientHeight(mainElement.clientHeight);
371         gutterElement.scrollTop = mainElement.scrollTop;
372     },
373
374     /**
375      * @param {number} lineNumber
376      */
377     _syncDecorationsForLine: function(lineNumber)
378     {
379         if (lineNumber >= this._textModel.linesCount)
380             return;
381
382         var mainChunk = this._mainPanel.chunkForLine(lineNumber);
383         if (mainChunk.linesCount === 1 && mainChunk.isDecorated()) {
384             var gutterChunk = this._gutterPanel.makeLineAChunk(lineNumber);
385             var height = mainChunk.height;
386             if (height)
387                 gutterChunk.element.style.setProperty("height", height + "px");
388             else
389                 gutterChunk.element.style.removeProperty("height");
390         } else {
391             var gutterChunk = this._gutterPanel.chunkForLine(lineNumber);
392             if (gutterChunk.linesCount === 1)
393                 gutterChunk.element.style.removeProperty("height");
394         }
395     },
396
397     /**
398      * @param {Element} gutterRow
399      */
400     _syncLineHeight: function(gutterRow)
401     {
402         if (this._lineHeightSynced)
403             return;
404         if (gutterRow && gutterRow.offsetHeight) {
405             // Force equal line heights for the child panels.
406             this.element.style.setProperty("line-height", gutterRow.offsetHeight + "px");
407             this._lineHeightSynced = true;
408         }
409     },
410
411     _registerShortcuts: function()
412     {
413         var keys = WebInspector.KeyboardShortcut.Keys;
414         var modifiers = WebInspector.KeyboardShortcut.Modifiers;
415
416         this._shortcuts = {};
417
418         this._shortcuts[WebInspector.KeyboardShortcut.SelectAll] = this._handleSelectAll.bind(this);
419         this._wordMovementController._registerShortcuts(this._shortcuts);
420     },
421
422     _handleSelectAll: function()
423     {
424         this.setSelection(this._textModel.range());
425         return true;
426     },
427
428     _handleKeyDown: function(e)
429     {
430         // If the event was not triggered from the entire editor, then
431         // ignore it. https://bugs.webkit.org/show_bug.cgi?id=102906
432         if (e.target.enclosingNodeOrSelfWithClass("webkit-line-decorations"))
433             return;
434
435         var shortcutKey = WebInspector.KeyboardShortcut.makeKeyFromEvent(e);
436
437         var handler = this._shortcuts[shortcutKey];
438         if (handler && handler()) {
439             e.consume(true);
440             return;
441         }
442         this._mainPanel.handleKeyDown(shortcutKey, e);
443     },
444
445     _contextMenu: function(event)
446     {
447         var anchor = event.target.enclosingNodeOrSelfWithNodeName("a");
448         if (anchor)
449             return;
450         var contextMenu = new WebInspector.ContextMenu(event);
451         var target = event.target.enclosingNodeOrSelfWithClass("webkit-line-number");
452         if (target)
453             this._delegate.populateLineGutterContextMenu(contextMenu, target.lineNumber);
454         else {
455             this._mainPanel.populateContextMenu(event.target, contextMenu);
456         }
457         contextMenu.show();
458     },
459
460     _handleScrollChanged: function(event)
461     {
462         var visibleFrom = this._mainPanel.scrollTop();
463         var firstVisibleLineNumber = this._mainPanel.lineNumberAtOffset(visibleFrom);
464         this._delegate.scrollChanged(firstVisibleLineNumber);
465     },
466
467     /**
468      * @param {number} lineNumber
469      */
470     scrollToLine: function(lineNumber)
471     {
472         this._mainPanel.scrollToLine(lineNumber);
473     },
474
475     /**
476      * @return {WebInspector.TextRange}
477      */
478     selection: function()
479     {
480         return this._mainPanel.selection();
481     },
482
483     /**
484      * @return {WebInspector.TextRange?}
485      */
486     lastSelection: function()
487     {
488         return this._mainPanel.lastSelection();
489     },
490
491     /**
492      * @param {WebInspector.TextRange} textRange
493      */
494     setSelection: function(textRange)
495     {
496         this._mainPanel.setSelection(textRange);
497     },
498
499     /**
500      * @param {string} text
501      */
502     setText: function(text)
503     {
504         this._textModel.setText(text);
505     },
506
507     /**
508      * @return {string}
509      */
510     text: function()
511     {
512         return this._textModel.text();
513     },
514
515     /**
516      * @return {WebInspector.TextRange}
517      */
518     range: function()
519     {
520         return this._textModel.range();
521     },
522
523     /**
524      * @param {number} lineNumber
525      * @return {string}
526      */
527     line: function(lineNumber)
528     {
529         return this._textModel.line(lineNumber);
530     },
531
532     /**
533      * @return {number}
534      */
535     get linesCount()
536     {
537         return this._textModel.linesCount;
538     },
539
540     /**
541      * @param {number} line
542      * @param {string} name
543      * @param {?Object} value
544      */
545     setAttribute: function(line, name, value)
546     {
547         this._textModel.setAttribute(line, name, value);
548     },
549
550     /**
551      * @param {number} line
552      * @param {string} name
553      * @return {?Object} value
554      */
555     getAttribute: function(line, name)
556     {
557         return this._textModel.getAttribute(line, name);
558     },
559
560     /**
561      * @param {number} line
562      * @param {string} name
563      */
564     removeAttribute: function(line, name)
565     {
566         this._textModel.removeAttribute(line, name);
567     },
568
569     wasShown: function()
570     {
571         if (!this.readOnly())
572             WebInspector.markBeingEdited(this.element, true);
573
574         this._mainPanel.wasShown();
575     },
576
577     willHide: function()
578     {
579         this._mainPanel.willHide();
580         this._gutterPanel.willHide();
581
582         if (!this.readOnly())
583             WebInspector.markBeingEdited(this.element, false);
584     },
585
586     /**
587      * @param {Element} element
588      * @param {Array.<Object>} resultRanges
589      * @param {string} styleClass
590      * @param {Array.<Object>=} changes
591      */
592     highlightRangesWithStyleClass: function(element, resultRanges, styleClass, changes)
593     {
594         this._mainPanel.beginDomUpdates();
595         WebInspector.highlightRangesWithStyleClass(element, resultRanges, styleClass, changes);
596         this._mainPanel.endDomUpdates();
597     },
598
599     /**
600      * @param {Element} element
601      * @param {Object} skipClasses
602      * @param {Object} skipTokens
603      * @return {Element}
604      */
605     highlightExpression: function(element, skipClasses, skipTokens)
606     {
607         // Collect tokens belonging to evaluated expression.
608         var tokens = [element];
609         var token = element.previousSibling;
610         while (token && (skipClasses[token.className] || skipTokens[token.textContent.trim()])) {
611             tokens.push(token);
612             token = token.previousSibling;
613         }
614         tokens.reverse();
615
616         // Wrap them with highlight element.
617         this._mainPanel.beginDomUpdates();
618         var parentElement = element.parentElement;
619         var nextElement = element.nextSibling;
620         var container = document.createElement("span");
621         for (var i = 0; i < tokens.length; ++i)
622             container.appendChild(tokens[i]);
623         parentElement.insertBefore(container, nextElement);
624         this._mainPanel.endDomUpdates();
625         return container;
626     },
627
628     /**
629      * @param {Element} highlightElement
630      */
631     hideHighlightedExpression: function(highlightElement)
632     {
633         this._mainPanel.beginDomUpdates();
634         var parentElement = highlightElement.parentElement;
635         if (parentElement) {
636             var child = highlightElement.firstChild;
637             while (child) {
638                 var nextSibling = child.nextSibling;
639                 parentElement.insertBefore(child, highlightElement);
640                 child = nextSibling;
641             }
642             parentElement.removeChild(highlightElement);
643         }
644         this._mainPanel.endDomUpdates();
645     },
646
647     /**
648      * @param {number} scrollTop
649      * @param {number} clientHeight
650      * @param {number} chunkSize
651      */
652     overrideViewportForTest: function(scrollTop, clientHeight, chunkSize)
653     {
654         this._mainPanel.overrideViewportForTest(scrollTop, clientHeight, chunkSize);
655     },
656
657     __proto__: WebInspector.View.prototype
658 }
659
660 /**
661  * @constructor
662  * @param {WebInspector.TextEditorModel} textModel
663  */
664 WebInspector.TextEditorChunkedPanel = function(textModel)
665 {
666     this._textModel = textModel;
667
668     this.element = document.createElement("div");
669     this.element.addEventListener("scroll", this._scroll.bind(this), false);
670
671     this._defaultChunkSize = 50;
672     this._paintCoalescingLevel = 0;
673     this._domUpdateCoalescingLevel = 0;
674 }
675
676 WebInspector.TextEditorChunkedPanel.prototype = {
677     /**
678      * @param {number} lineNumber
679      */
680     scrollToLine: function(lineNumber)
681     {
682         if (lineNumber >= this._textModel.linesCount)
683             return;
684
685         var chunk = this.makeLineAChunk(lineNumber);
686         this.element.scrollTop = chunk.offsetTop;
687     },
688
689     /**
690      * @param {number} lineNumber
691      */
692     revealLine: function(lineNumber)
693     {
694         if (lineNumber >= this._textModel.linesCount)
695             return;
696
697         var chunk = this.makeLineAChunk(lineNumber);
698         chunk.element.scrollIntoViewIfNeeded();
699     },
700
701     /**
702      * @param {number} lineNumber
703      * @param {string|Element} decoration
704      */
705     addDecoration: function(lineNumber, decoration)
706     {
707         if (lineNumber >= this._textModel.linesCount)
708             return;
709
710         var chunk = this.makeLineAChunk(lineNumber);
711         chunk.addDecoration(decoration);
712     },
713
714     /**
715      * @param {number} lineNumber
716      * @param {string|Element} decoration
717      */
718     removeDecoration: function(lineNumber, decoration)
719     {
720         if (lineNumber >= this._textModel.linesCount)
721             return;
722
723         var chunk = this.chunkForLine(lineNumber);
724         chunk.removeDecoration(decoration);
725     },
726
727     buildChunks: function()
728     {
729         this.beginDomUpdates();
730
731         this._container.removeChildren();
732
733         this._textChunks = [];
734         for (var i = 0; i < this._textModel.linesCount; i += this._defaultChunkSize) {
735             var chunk = this.createNewChunk(i, i + this._defaultChunkSize);
736             this._textChunks.push(chunk);
737             this._container.appendChild(chunk.element);
738         }
739
740         this.repaintAll();
741
742         this.endDomUpdates();
743     },
744
745     /**
746      * @param {number} lineNumber
747      * @return {Object}
748      */
749     makeLineAChunk: function(lineNumber)
750     {
751         var chunkNumber = this.chunkNumberForLine(lineNumber);
752         var oldChunk = this._textChunks[chunkNumber];
753
754         if (!oldChunk) {
755             console.error("No chunk for line number: " + lineNumber);
756             return null;
757         }
758
759         if (oldChunk.linesCount === 1)
760             return oldChunk;
761
762         return this.splitChunkOnALine(lineNumber, chunkNumber, true);
763     },
764
765     /**
766      * @param {number} lineNumber
767      * @param {number} chunkNumber
768      * @param {boolean=} createSuffixChunk
769      * @return {Object}
770      */
771     splitChunkOnALine: function(lineNumber, chunkNumber, createSuffixChunk)
772     {
773         this.beginDomUpdates();
774
775         var oldChunk = this._textChunks[chunkNumber];
776         var wasExpanded = oldChunk.expanded();
777         oldChunk.collapse();
778
779         var insertIndex = chunkNumber + 1;
780
781         // Prefix chunk.
782         if (lineNumber > oldChunk.startLine) {
783             var prefixChunk = this.createNewChunk(oldChunk.startLine, lineNumber);
784             this._textChunks.splice(insertIndex++, 0, prefixChunk);
785             this._container.insertBefore(prefixChunk.element, oldChunk.element);
786         }
787
788         // Line chunk.
789         var endLine = createSuffixChunk ? lineNumber + 1 : oldChunk.startLine + oldChunk.linesCount;
790         var lineChunk = this.createNewChunk(lineNumber, endLine);
791         this._textChunks.splice(insertIndex++, 0, lineChunk);
792         this._container.insertBefore(lineChunk.element, oldChunk.element);
793
794         // Suffix chunk.
795         if (oldChunk.startLine + oldChunk.linesCount > endLine) {
796             var suffixChunk = this.createNewChunk(endLine, oldChunk.startLine + oldChunk.linesCount);
797             this._textChunks.splice(insertIndex, 0, suffixChunk);
798             this._container.insertBefore(suffixChunk.element, oldChunk.element);
799         }
800
801         // Remove enclosing chunk.
802         this._textChunks.splice(chunkNumber, 1);
803         this._container.removeChild(oldChunk.element);
804
805         if (wasExpanded) {
806             if (prefixChunk)
807                 prefixChunk.expand();
808             lineChunk.expand();
809             if (suffixChunk)
810                 suffixChunk.expand();
811         }
812
813         this.endDomUpdates();
814
815         return lineChunk;
816     },
817
818     createNewChunk: function(startLine, endLine)
819     {
820         throw new Error("createNewChunk() should be implemented by descendants");
821     },
822
823     _scroll: function()
824     {
825         this._scheduleRepaintAll();
826         if (this._syncScrollListener)
827             this._syncScrollListener();
828     },
829
830     _scheduleRepaintAll: function()
831     {
832         if (this._repaintAllTimer)
833             clearTimeout(this._repaintAllTimer);
834         this._repaintAllTimer = setTimeout(this.repaintAll.bind(this), 50);
835     },
836
837     beginUpdates: function()
838     {
839         this._paintCoalescingLevel++;
840     },
841
842     endUpdates: function()
843     {
844         this._paintCoalescingLevel--;
845         if (!this._paintCoalescingLevel)
846             this.repaintAll();
847     },
848
849     beginDomUpdates: function()
850     {
851         this._domUpdateCoalescingLevel++;
852     },
853
854     endDomUpdates: function()
855     {
856         this._domUpdateCoalescingLevel--;
857     },
858
859     /**
860      * @param {number} lineNumber
861      * @return {number}
862      */
863     chunkNumberForLine: function(lineNumber)
864     {
865         function compareLineNumbers(value, chunk)
866         {
867             return value < chunk.startLine ? -1 : 1;
868         }
869         var insertBefore = insertionIndexForObjectInListSortedByFunction(lineNumber, this._textChunks, compareLineNumbers);
870         return insertBefore - 1;
871     },
872
873     /**
874      * @param {number} lineNumber
875      * @return {Object}
876      */
877     chunkForLine: function(lineNumber)
878     {
879         return this._textChunks[this.chunkNumberForLine(lineNumber)];
880     },
881
882     /**
883      * @param {number} visibleFrom
884      * @return {number}
885      */
886     _findFirstVisibleChunkNumber: function(visibleFrom)
887     {
888         function compareOffsetTops(value, chunk)
889         {
890             return value < chunk.offsetTop ? -1 : 1;
891         }
892         var insertBefore = insertionIndexForObjectInListSortedByFunction(visibleFrom, this._textChunks, compareOffsetTops);
893         return insertBefore - 1;
894     },
895
896     /**
897      * @param {number} visibleFrom
898      * @param {number} visibleTo
899      * @return {{start: number, end: number}}
900      */
901     findVisibleChunks: function(visibleFrom, visibleTo)
902     {
903         var span = (visibleTo - visibleFrom) * 0.5;
904         visibleFrom = Math.max(visibleFrom - span, 0);
905         visibleTo = visibleTo + span;
906
907         var from = this._findFirstVisibleChunkNumber(visibleFrom);
908         for (var to = from + 1; to < this._textChunks.length; ++to) {
909             if (this._textChunks[to].offsetTop >= visibleTo)
910                 break;
911         }
912         return { start: from, end: to };
913     },
914
915     /**
916      * @param {number} visibleFrom
917      * @return {number}
918      */
919     lineNumberAtOffset: function(visibleFrom)
920     {
921         var chunk = this._textChunks[this._findFirstVisibleChunkNumber(visibleFrom)];
922         if (!chunk.expanded())
923             return chunk.startLine;
924
925         var lineNumbers = [];
926         for (var i = 0; i < chunk.linesCount; ++i) {
927             lineNumbers.push(chunk.startLine + i);
928         }
929
930         function compareLineRowOffsetTops(value, lineNumber)
931         {
932             var lineRow = chunk.expandedLineRow(lineNumber);
933             return value < lineRow.offsetTop ? -1 : 1;
934         }
935         var insertBefore = insertionIndexForObjectInListSortedByFunction(visibleFrom, lineNumbers, compareLineRowOffsetTops);
936         return lineNumbers[insertBefore - 1];
937     },
938
939     repaintAll: function()
940     {
941         delete this._repaintAllTimer;
942
943         if (this._paintCoalescingLevel)
944             return;
945
946         var visibleFrom = this.scrollTop();
947         var visibleTo = visibleFrom + this.clientHeight();
948
949         if (visibleTo) {
950             var result = this.findVisibleChunks(visibleFrom, visibleTo);
951             this.expandChunks(result.start, result.end);
952         }
953     },
954
955     scrollTop: function()
956     {
957         return typeof this._scrollTopOverrideForTest === "number" ? this._scrollTopOverrideForTest : this.element.scrollTop;
958     },
959
960     clientHeight: function()
961     {
962         return typeof this._clientHeightOverrideForTest === "number" ? this._clientHeightOverrideForTest : this.element.clientHeight;
963     },
964
965     /**
966      * @param {number} fromIndex
967      * @param {number} toIndex
968      */
969     expandChunks: function(fromIndex, toIndex)
970     {
971         // First collapse chunks to collect the DOM elements into a cache to reuse them later.
972         for (var i = 0; i < fromIndex; ++i)
973             this._textChunks[i].collapse();
974         for (var i = toIndex; i < this._textChunks.length; ++i)
975             this._textChunks[i].collapse();
976         for (var i = fromIndex; i < toIndex; ++i)
977             this._textChunks[i].expand();
978     },
979
980     /**
981      * @param {Element} firstElement
982      * @param {Element=} lastElement
983      * @return {number}
984      */
985     totalHeight: function(firstElement, lastElement)
986     {
987         lastElement = (lastElement || firstElement).nextElementSibling;
988         if (lastElement)
989             return lastElement.offsetTop - firstElement.offsetTop;
990
991         var offsetParent = firstElement.offsetParent;
992         if (offsetParent && offsetParent.scrollHeight > offsetParent.clientHeight)
993             return offsetParent.scrollHeight - firstElement.offsetTop;
994
995         var total = 0;
996         while (firstElement && firstElement !== lastElement) {
997             total += firstElement.offsetHeight;
998             firstElement = firstElement.nextElementSibling;
999         }
1000         return total;
1001     },
1002
1003     resize: function()
1004     {
1005         this.repaintAll();
1006     }
1007 }
1008
1009 /**
1010  * @constructor
1011  * @extends {WebInspector.TextEditorChunkedPanel}
1012  * @param {WebInspector.TextEditorModel} textModel
1013  * @param {function(number)} syncDecorationsForLineListener
1014  * @param {function(Element)} syncLineHeightListener
1015  */
1016 WebInspector.TextEditorGutterPanel = function(textModel, syncDecorationsForLineListener, syncLineHeightListener)
1017 {
1018     WebInspector.TextEditorChunkedPanel.call(this, textModel);
1019
1020     this._syncDecorationsForLineListener = syncDecorationsForLineListener;
1021     this._syncLineHeightListener = syncLineHeightListener;
1022
1023     this.element.className = "text-editor-lines";
1024
1025     this._container = document.createElement("div");
1026     this._container.className = "inner-container";
1027     this.element.appendChild(this._container);
1028
1029     this._freeCachedElements();
1030     this.buildChunks();
1031     this._decorations = {};
1032 }
1033
1034 WebInspector.TextEditorGutterPanel.prototype = {
1035     _freeCachedElements: function()
1036     {
1037         this._cachedRows = [];
1038     },
1039
1040     willHide: function()
1041     {
1042         this._freeCachedElements();
1043     },
1044
1045     /**
1046      * @param {number} startLine
1047      * @param {number} endLine
1048      * @return {WebInspector.TextEditorGutterChunk}
1049      */
1050     createNewChunk: function(startLine, endLine)
1051     {
1052         return new WebInspector.TextEditorGutterChunk(this, startLine, endLine);
1053     },
1054
1055     /**
1056      * @param {WebInspector.TextRange} oldRange
1057      * @param {WebInspector.TextRange} newRange
1058      */
1059     textChanged: function(oldRange, newRange)
1060     {
1061         this.beginDomUpdates();
1062
1063         var linesDiff = newRange.linesCount - oldRange.linesCount;
1064         if (linesDiff) {
1065             // Remove old chunks (if needed).
1066             for (var chunkNumber = this._textChunks.length - 1; chunkNumber >= 0; --chunkNumber) {
1067                 var chunk = this._textChunks[chunkNumber];
1068                 if (chunk.startLine + chunk.linesCount <= this._textModel.linesCount)
1069                     break;
1070                 chunk.collapse();
1071                 this._container.removeChild(chunk.element);
1072             }
1073             this._textChunks.length = chunkNumber + 1;
1074
1075             // Add new chunks (if needed).
1076             var totalLines = 0;
1077             if (this._textChunks.length) {
1078                 var lastChunk = this._textChunks[this._textChunks.length - 1];
1079                 totalLines = lastChunk.startLine + lastChunk.linesCount;
1080             }
1081
1082             for (var i = totalLines; i < this._textModel.linesCount; i += this._defaultChunkSize) {
1083                 var chunk = this.createNewChunk(i, i + this._defaultChunkSize);
1084                 this._textChunks.push(chunk);
1085                 this._container.appendChild(chunk.element);
1086             }
1087
1088             // Shift decorations if necessary
1089             for (var lineNumber in this._decorations) {
1090                 lineNumber = parseInt(lineNumber, 10);
1091
1092                 // Do not move decorations before the start position.
1093                 if (lineNumber < oldRange.startLine)
1094                     continue;
1095                 // Decorations follow the first character of line.
1096                 if (lineNumber === oldRange.startLine && oldRange.startColumn)
1097                     continue;
1098
1099                 var lineDecorationsCopy = this._decorations[lineNumber].slice();
1100                 for (var i = 0; i < lineDecorationsCopy.length; ++i) {
1101                     var decoration = lineDecorationsCopy[i];
1102                     this.removeDecoration(lineNumber, decoration);
1103
1104                     // Do not restore the decorations before the end position.
1105                     if (lineNumber < oldRange.endLine)
1106                         continue;
1107
1108                     this.addDecoration(lineNumber + linesDiff, decoration);
1109                 }
1110             }
1111
1112             this.repaintAll();
1113         } else {
1114             // Decorations may have been removed, so we may have to sync those lines.
1115             var chunkNumber = this.chunkNumberForLine(newRange.startLine);
1116             var chunk = this._textChunks[chunkNumber];
1117             while (chunk && chunk.startLine <= newRange.endLine) {
1118                 if (chunk.linesCount === 1)
1119                     this._syncDecorationsForLineListener(chunk.startLine);
1120                 chunk = this._textChunks[++chunkNumber];
1121             }
1122         }
1123
1124         this.endDomUpdates();
1125     },
1126
1127     /**
1128      * @param {number} clientHeight
1129      */
1130     syncClientHeight: function(clientHeight)
1131     {
1132         if (this.element.offsetHeight > clientHeight)
1133             this._container.style.setProperty("padding-bottom", (this.element.offsetHeight - clientHeight) + "px");
1134         else
1135             this._container.style.removeProperty("padding-bottom");
1136     },
1137
1138     /**
1139      * @param {number} lineNumber
1140      * @param {string|Element} decoration
1141      */
1142     addDecoration: function(lineNumber, decoration)
1143     {
1144         WebInspector.TextEditorChunkedPanel.prototype.addDecoration.call(this, lineNumber, decoration);
1145         var decorations = this._decorations[lineNumber];
1146         if (!decorations) {
1147             decorations = [];
1148             this._decorations[lineNumber] = decorations;
1149         }
1150         decorations.push(decoration);
1151     },
1152
1153     /**
1154      * @param {number} lineNumber
1155      * @param {string|Element} decoration
1156      */
1157     removeDecoration: function(lineNumber, decoration)
1158     {
1159         WebInspector.TextEditorChunkedPanel.prototype.removeDecoration.call(this, lineNumber, decoration);
1160         var decorations = this._decorations[lineNumber];
1161         if (decorations) {
1162             decorations.remove(decoration);
1163             if (!decorations.length)
1164                 delete this._decorations[lineNumber];
1165         }
1166     },
1167
1168     __proto__: WebInspector.TextEditorChunkedPanel.prototype
1169 }
1170
1171 /**
1172  * @constructor
1173  * @param {WebInspector.TextEditorGutterPanel} chunkedPanel
1174  * @param {number} startLine
1175  * @param {number} endLine
1176  */
1177 WebInspector.TextEditorGutterChunk = function(chunkedPanel, startLine, endLine)
1178 {
1179     this._chunkedPanel = chunkedPanel;
1180     this._textModel = chunkedPanel._textModel;
1181
1182     this.startLine = startLine;
1183     endLine = Math.min(this._textModel.linesCount, endLine);
1184     this.linesCount = endLine - startLine;
1185
1186     this._expanded = false;
1187
1188     this.element = document.createElement("div");
1189     this.element.lineNumber = startLine;
1190     this.element.className = "webkit-line-number";
1191
1192     if (this.linesCount === 1) {
1193         // Single line chunks are typically created for decorations. Host line number in
1194         // the sub-element in order to allow flexible border / margin management.
1195         var innerSpan = document.createElement("span");
1196         innerSpan.className = "webkit-line-number-inner";
1197         innerSpan.textContent = startLine + 1;
1198         var outerSpan = document.createElement("div");
1199         outerSpan.className = "webkit-line-number-outer";
1200         outerSpan.appendChild(innerSpan);
1201         this.element.appendChild(outerSpan);
1202     } else {
1203         var lineNumbers = [];
1204         for (var i = startLine; i < endLine; ++i)
1205             lineNumbers.push(i + 1);
1206         this.element.textContent = lineNumbers.join("\n");
1207     }
1208 }
1209
1210 WebInspector.TextEditorGutterChunk.prototype = {
1211     /**
1212      * @param {string} decoration
1213      */
1214     addDecoration: function(decoration)
1215     {
1216         this._chunkedPanel.beginDomUpdates();
1217         if (typeof decoration === "string")
1218             this.element.addStyleClass(decoration);
1219         this._chunkedPanel.endDomUpdates();
1220     },
1221
1222     /**
1223      * @param {string} decoration
1224      */
1225     removeDecoration: function(decoration)
1226     {
1227         this._chunkedPanel.beginDomUpdates();
1228         if (typeof decoration === "string")
1229             this.element.removeStyleClass(decoration);
1230         this._chunkedPanel.endDomUpdates();
1231     },
1232
1233     /**
1234      * @return {boolean}
1235      */
1236     expanded: function()
1237     {
1238         return this._expanded;
1239     },
1240
1241     expand: function()
1242     {
1243         if (this.linesCount === 1)
1244             this._chunkedPanel._syncDecorationsForLineListener(this.startLine);
1245
1246         if (this._expanded)
1247             return;
1248
1249         this._expanded = true;
1250
1251         if (this.linesCount === 1)
1252             return;
1253
1254         this._chunkedPanel.beginDomUpdates();
1255
1256         this._expandedLineRows = [];
1257         var parentElement = this.element.parentElement;
1258         for (var i = this.startLine; i < this.startLine + this.linesCount; ++i) {
1259             var lineRow = this._createRow(i);
1260             parentElement.insertBefore(lineRow, this.element);
1261             this._expandedLineRows.push(lineRow);
1262         }
1263         parentElement.removeChild(this.element);
1264         this._chunkedPanel._syncLineHeightListener(this._expandedLineRows[0]);
1265
1266         this._chunkedPanel.endDomUpdates();
1267     },
1268
1269     collapse: function()
1270     {
1271         if (this.linesCount === 1)
1272             this._chunkedPanel._syncDecorationsForLineListener(this.startLine);
1273
1274         if (!this._expanded)
1275             return;
1276
1277         this._expanded = false;
1278
1279         if (this.linesCount === 1)
1280             return;
1281
1282         this._chunkedPanel.beginDomUpdates();
1283
1284         var elementInserted = false;
1285         for (var i = 0; i < this._expandedLineRows.length; ++i) {
1286             var lineRow = this._expandedLineRows[i];
1287             var parentElement = lineRow.parentElement;
1288             if (parentElement) {
1289                 if (!elementInserted) {
1290                     elementInserted = true;
1291                     parentElement.insertBefore(this.element, lineRow);
1292                 }
1293                 parentElement.removeChild(lineRow);
1294             }
1295             this._chunkedPanel._cachedRows.push(lineRow);
1296         }
1297         delete this._expandedLineRows;
1298
1299         this._chunkedPanel.endDomUpdates();
1300     },
1301
1302     /**
1303      * @return {number}
1304      */
1305     get height()
1306     {
1307         if (!this._expandedLineRows)
1308             return this._chunkedPanel.totalHeight(this.element);
1309         return this._chunkedPanel.totalHeight(this._expandedLineRows[0], this._expandedLineRows[this._expandedLineRows.length - 1]);
1310     },
1311
1312     /**
1313      * @return {number}
1314      */
1315     get offsetTop()
1316     {
1317         return (this._expandedLineRows && this._expandedLineRows.length) ? this._expandedLineRows[0].offsetTop : this.element.offsetTop;
1318     },
1319
1320     /**
1321      * @param {number} lineNumber
1322      * @return {Element}
1323      */
1324     _createRow: function(lineNumber)
1325     {
1326         var lineRow = this._chunkedPanel._cachedRows.pop() || document.createElement("div");
1327         lineRow.lineNumber = lineNumber;
1328         lineRow.className = "webkit-line-number";
1329         lineRow.textContent = lineNumber + 1;
1330         return lineRow;
1331     }
1332 }
1333
1334 /**
1335  * @constructor
1336  * @extends {WebInspector.TextEditorChunkedPanel}
1337  * @param {WebInspector.TextEditorDelegate} delegate
1338  * @param {WebInspector.TextEditorModel} textModel
1339  * @param {?string} url
1340  * @param {function()} syncScrollListener
1341  * @param {function(number)} syncDecorationsForLineListener
1342  */
1343 WebInspector.TextEditorMainPanel = function(delegate, textModel, url, syncScrollListener, syncDecorationsForLineListener)
1344 {
1345     WebInspector.TextEditorChunkedPanel.call(this, textModel);
1346
1347     this._delegate = delegate;
1348     this._syncScrollListener = syncScrollListener;
1349     this._syncDecorationsForLineListener = syncDecorationsForLineListener;
1350
1351     this._url = url;
1352     this._highlighter = new WebInspector.TextEditorHighlighter(textModel, this._highlightDataReady.bind(this));
1353     this._readOnly = true;
1354
1355     this.element.className = "text-editor-contents";
1356     this.element.tabIndex = 0;
1357
1358     this._container = document.createElement("div");
1359     this._container.className = "inner-container";
1360     this._container.tabIndex = 0;
1361     this.element.appendChild(this._container);
1362
1363     this.element.addEventListener("focus", this._handleElementFocus.bind(this), false);
1364     this.element.addEventListener("textInput", this._handleTextInput.bind(this), false);
1365     this.element.addEventListener("cut", this._handleCut.bind(this), false);
1366
1367     this._showWhitespace = WebInspector.settings.showWhitespaceInEditor.get();
1368     this._handleShowWhitespaceInEditorChange = this._handleShowWhitespaceInEditorChange.bind(this);
1369
1370     this._container.addEventListener("focus", this._handleFocused.bind(this), false);
1371
1372     this._highlightDescriptors = [];
1373
1374     this._tokenHighlighter = new WebInspector.TextEditorMainPanel.TokenHighlighter(this, textModel);
1375     this._braceMatcher = new WebInspector.TextEditorModel.BraceMatcher(textModel);
1376     this._braceHighlighter = new WebInspector.TextEditorMainPanel.BraceHighlightController(this, textModel, this._braceMatcher);
1377
1378     this._freeCachedElements();
1379     this.buildChunks();
1380     this._registerShortcuts();
1381 }
1382
1383 WebInspector.TextEditorMainPanel._ConsecutiveWhitespaceChars = {
1384     1: " ",
1385     2: "  ",
1386     4: "    ",
1387     8: "        ",
1388     16: "                "
1389 };
1390
1391 WebInspector.TextEditorMainPanel.prototype = {
1392     _registerShortcuts: function()
1393     {
1394         var keys = WebInspector.KeyboardShortcut.Keys;
1395         var modifiers = WebInspector.KeyboardShortcut.Modifiers;
1396
1397         this._shortcuts = {};
1398
1399         this._shortcuts[WebInspector.KeyboardShortcut.makeKey(keys.Enter.code, WebInspector.KeyboardShortcut.Modifiers.None)] = this._handleEnterKey.bind(this);
1400         this._shortcuts[WebInspector.KeyboardShortcut.makeKey("z", modifiers.CtrlOrMeta)] = this._handleUndoRedo.bind(this, false);
1401
1402         var handleRedo = this._handleUndoRedo.bind(this, true);
1403         this._shortcuts[WebInspector.KeyboardShortcut.makeKey("z", modifiers.Shift | modifiers.CtrlOrMeta)] = handleRedo;
1404         if (!WebInspector.isMac())
1405             this._shortcuts[WebInspector.KeyboardShortcut.makeKey("y", modifiers.CtrlOrMeta)] = handleRedo;
1406
1407         var handleTabKey = this._handleTabKeyPress.bind(this, false);
1408         var handleShiftTabKey = this._handleTabKeyPress.bind(this, true);
1409         this._shortcuts[WebInspector.KeyboardShortcut.makeKey(keys.Tab.code)] = handleTabKey;
1410         this._shortcuts[WebInspector.KeyboardShortcut.makeKey(keys.Tab.code, modifiers.Shift)] = handleShiftTabKey;
1411
1412         var homeKey = WebInspector.isMac() ? keys.Right : keys.Home;
1413         var homeModifier = WebInspector.isMac() ? modifiers.Meta : modifiers.None;
1414         this._shortcuts[WebInspector.KeyboardShortcut.makeKey(homeKey.code, homeModifier)] = this._handleHomeKey.bind(this, false);
1415         this._shortcuts[WebInspector.KeyboardShortcut.makeKey(homeKey.code, homeModifier | modifiers.Shift)] = this._handleHomeKey.bind(this, true);
1416     },
1417
1418     /**
1419      * @param {boolean} shift
1420      */
1421     _handleHomeKey: function(shift)
1422     {
1423         var selection = this.selection();
1424
1425         var line = this._textModel.line(selection.endLine);
1426         var firstNonBlankCharacter = 0;
1427         while (firstNonBlankCharacter < line.length) {
1428             var char = line.charAt(firstNonBlankCharacter);
1429             if (char === " " || char === "\t")
1430                 ++firstNonBlankCharacter;
1431             else
1432                 break;
1433         }
1434         if (firstNonBlankCharacter >= line.length || selection.endColumn === firstNonBlankCharacter)
1435             return false;
1436
1437         selection.endColumn = firstNonBlankCharacter;
1438         if (!shift)
1439             selection = selection.collapseToEnd();
1440         this._restoreSelection(selection);
1441         return true;
1442     },
1443
1444     _handleShowWhitespaceInEditorChange: function()
1445     {
1446         this._showWhitespace = WebInspector.settings.showWhitespaceInEditor.get();
1447         var visibleFrom = this.scrollTop();
1448         var visibleTo = visibleFrom + this.clientHeight();
1449
1450         if (!visibleTo)
1451             return;
1452
1453         var result = this.findVisibleChunks(visibleFrom, visibleTo);
1454         var startLine = this._textChunks[result.start].startLine;
1455         var endLine = this._textChunks[result.end - 1].startLine + this._textChunks[result.end - 1].linesCount;
1456         this._paintLines(startLine, endLine + 1);
1457     },
1458
1459     /**
1460      * @param {string} regex
1461      * @param {string} cssClass
1462      * @return {WebInspector.TextEditorMainPanel.HighlightDescriptor}
1463      */
1464     highlightRegex: function(regex, cssClass)
1465     {
1466         var highlightDescriptor = new WebInspector.TextEditorMainPanel.RegexHighlightDescriptor(new RegExp(regex, "g"), cssClass);
1467         this._highlightDescriptors.push(highlightDescriptor);
1468         this._repaintLineRowsAffectedByHighlightDescriptors([highlightDescriptor]);
1469         return highlightDescriptor;
1470     },
1471
1472     /**
1473      * @param {WebInspector.TextEditorMainPanel.HighlightDescriptor} highlightDescriptor
1474      */
1475     removeHighlight: function(highlightDescriptor)
1476     {
1477         this._highlightDescriptors.remove(highlightDescriptor);
1478         this._repaintLineRowsAffectedByHighlightDescriptors([highlightDescriptor]);
1479     },
1480
1481     /**
1482      * @param {WebInspector.TextRange} range
1483      * @param {string} cssClass
1484      */
1485     highlightRange: function(range, cssClass)
1486     {
1487         var highlightDescriptor = new WebInspector.TextEditorMainPanel.RangeHighlightDescriptor(range, cssClass);
1488         this._highlightDescriptors.push(highlightDescriptor);
1489         this._repaintLineRowsAffectedByHighlightDescriptors([highlightDescriptor]);
1490         return highlightDescriptor;
1491     },
1492
1493     /**
1494      * @param {Array.<WebInspector.TextEditorMainPanel.HighlightDescriptor>} highlightDescriptors
1495      */
1496     _repaintLineRowsAffectedByHighlightDescriptors: function(highlightDescriptors)
1497     {
1498         var visibleFrom = this.scrollTop();
1499         var visibleTo = visibleFrom + this.clientHeight();
1500
1501         var visibleChunks = this.findVisibleChunks(visibleFrom, visibleTo);
1502
1503         var affectedLineRows = [];
1504         for (var i = visibleChunks.start; i < visibleChunks.end; ++i) {
1505             var chunk = this._textChunks[i];
1506             if (!chunk.expanded())
1507                 continue;
1508             for (var lineNumber = chunk.startLine; lineNumber < chunk.startLine + chunk.linesCount; ++lineNumber) {
1509                 var lineRow = chunk.expandedLineRow(lineNumber);
1510                 var line = this._textModel.line(lineNumber);
1511                 for(var j = 0; j < highlightDescriptors.length; ++j) {
1512                     if (highlightDescriptors[j].affectsLine(lineNumber, line)) {
1513                         affectedLineRows.push(lineRow);
1514                         break;
1515                     }
1516                 }
1517             }
1518         }
1519         if (affectedLineRows.length === 0)
1520             return;
1521         var selection = this.selection();
1522         this._paintLineRows(affectedLineRows);
1523         this._restoreSelection(selection);
1524     },
1525
1526     resize: function()
1527     {
1528         WebInspector.TextEditorChunkedPanel.prototype.resize.call(this);
1529         this._repaintLineRowsAffectedByHighlightDescriptors(this._highlightDescriptors);
1530     },
1531
1532     wasShown: function()
1533     {
1534         WebInspector.settings.showWhitespaceInEditor.addChangeListener(this._handleShowWhitespaceInEditorChange);
1535
1536         this._boundSelectionChangeListener = this._handleSelectionChange.bind(this);
1537         document.addEventListener("selectionchange", this._boundSelectionChangeListener, false);
1538
1539         this._isShowing = true;
1540         this._attachMutationObserver();
1541     },
1542
1543     willHide: function()
1544     {
1545         WebInspector.settings.showWhitespaceInEditor.removeChangeListener(this._handleShowWhitespaceInEditorChange);
1546
1547         document.removeEventListener("selectionchange", this._boundSelectionChangeListener, false);
1548         delete this._boundSelectionChangeListener;
1549
1550         this._detachMutationObserver();
1551         this._isShowing = false;
1552         this._freeCachedElements();
1553     },
1554
1555     /**
1556      * @param {Element} eventTarget
1557      * @param {WebInspector.ContextMenu} contextMenu
1558      */
1559     populateContextMenu: function(eventTarget, contextMenu)
1560     {
1561         var target = this._enclosingLineRowOrSelf(eventTarget);
1562         this._delegate.populateTextAreaContextMenu(contextMenu, target && target.lineNumber);
1563     },
1564
1565     /**
1566      * @param {WebInspector.TextRange} textRange
1567      */
1568     setSelection: function(textRange)
1569     {
1570         this._lastSelection = textRange;
1571         if (this.element.isAncestor(document.activeElement))
1572             this._restoreSelection(textRange);
1573     },
1574
1575     _handleFocused: function()
1576     {
1577         if (this._lastSelection)
1578             this.setSelection(this._lastSelection);
1579     },
1580
1581     _attachMutationObserver: function()
1582     {
1583         if (!this._isShowing)
1584             return;
1585
1586         if (this._mutationObserver)
1587             this._mutationObserver.disconnect();
1588         this._mutationObserver = new NonLeakingMutationObserver(this._handleMutations.bind(this));
1589         this._mutationObserver.observe(this._container, { subtree: true, childList: true, characterData: true });
1590     },
1591
1592     _detachMutationObserver: function()
1593     {
1594         if (!this._isShowing)
1595             return;
1596
1597         if (this._mutationObserver) {
1598             this._mutationObserver.disconnect();
1599             delete this._mutationObserver;
1600         }
1601     },
1602
1603     /**
1604      * @param {string} mimeType
1605      */
1606     set mimeType(mimeType)
1607     {
1608         this._highlighter.mimeType = mimeType;
1609     },
1610
1611     /**
1612      * @param {boolean} readOnly
1613      * @param {boolean} requestFocus
1614      */
1615     setReadOnly: function(readOnly, requestFocus)
1616     {
1617         if (this._readOnly === readOnly)
1618             return;
1619
1620         this.beginDomUpdates();
1621         this._readOnly = readOnly;
1622         if (this._readOnly)
1623             this._container.removeStyleClass("text-editor-editable");
1624         else {
1625             this._container.addStyleClass("text-editor-editable");
1626             if (requestFocus)
1627                 this._updateSelectionOnStartEditing();
1628         }
1629         this.endDomUpdates();
1630     },
1631
1632     /**
1633      * @return {boolean}
1634      */
1635     readOnly: function()
1636     {
1637         return this._readOnly;
1638     },
1639
1640     _handleElementFocus: function()
1641     {
1642         if (!this._readOnly)
1643             this._container.focus();
1644     },
1645
1646     /**
1647      * @return {Element}
1648      */
1649     defaultFocusedElement: function()
1650     {
1651         if (this._readOnly)
1652             return this.element;
1653         return this._container;
1654     },
1655
1656     _updateSelectionOnStartEditing: function()
1657     {
1658         // focus() needs to go first for the case when the last selection was inside the editor and
1659         // the "Edit" button was clicked. In this case we bail at the check below, but the
1660         // editor does not receive the focus, thus "Esc" does not cancel editing until at least
1661         // one change has been made to the editor contents.
1662         this._container.focus();
1663         var selection = window.getSelection();
1664         if (selection.rangeCount) {
1665             var commonAncestorContainer = selection.getRangeAt(0).commonAncestorContainer;
1666             if (this._container.isSelfOrAncestor(commonAncestorContainer))
1667                 return;
1668         }
1669
1670         selection.removeAllRanges();
1671         var range = document.createRange();
1672         range.setStart(this._container, 0);
1673         range.setEnd(this._container, 0);
1674         selection.addRange(range);
1675     },
1676
1677     /**
1678      * @param {WebInspector.TextRange} range
1679      */
1680     markAndRevealRange: function(range)
1681     {
1682         if (this._rangeToMark) {
1683             var markedLine = this._rangeToMark.startLine;
1684             delete this._rangeToMark;
1685             // Remove the marked region immediately.
1686             this.beginDomUpdates();
1687             var chunk = this.chunkForLine(markedLine);
1688             var wasExpanded = chunk.expanded();
1689             chunk.collapse();
1690             chunk.updateCollapsedLineRow();
1691             if (wasExpanded)
1692                 chunk.expand();
1693             this.endDomUpdates();
1694         }
1695
1696         if (range) {
1697             this._rangeToMark = range;
1698             this.revealLine(range.startLine);
1699             var chunk = this.makeLineAChunk(range.startLine);
1700             this._paintLines(chunk.startLine, chunk.startLine + 1);
1701             if (this._markedRangeElement)
1702                 this._markedRangeElement.scrollIntoViewIfNeeded();
1703         }
1704         delete this._markedRangeElement;
1705     },
1706
1707     /**
1708      * @param {number} lineNumber
1709      */
1710     highlightLine: function(lineNumber)
1711     {
1712         this.clearLineHighlight();
1713         this._highlightedLine = lineNumber;
1714         this.revealLine(lineNumber);
1715
1716         if (!this._readOnly)
1717             this._restoreSelection(WebInspector.TextRange.createFromLocation(lineNumber, 0), false);
1718
1719         this.addDecoration(lineNumber, "webkit-highlighted-line");
1720     },
1721
1722     clearLineHighlight: function()
1723     {
1724         if (typeof this._highlightedLine === "number") {
1725             this.removeDecoration(this._highlightedLine, "webkit-highlighted-line");
1726             delete this._highlightedLine;
1727         }
1728     },
1729
1730     _freeCachedElements: function()
1731     {
1732         this._cachedSpans = [];
1733         this._cachedTextNodes = [];
1734         this._cachedRows = [];
1735     },
1736
1737     /**
1738      * @param {boolean} redo
1739      * @return {boolean}
1740      */
1741     _handleUndoRedo: function(redo)
1742     {
1743         if (this.readOnly())
1744             return false;
1745
1746         this.beginUpdates();
1747
1748         var range = redo ? this._textModel.redo() : this._textModel.undo();
1749
1750         this.endUpdates();
1751
1752         // Restore location post-repaint.
1753         if (range)
1754             this._restoreSelection(range, true);
1755
1756         return true;
1757     },
1758
1759     /**
1760      * @param {boolean} shiftKey
1761      * @return {boolean}
1762      */
1763     _handleTabKeyPress: function(shiftKey)
1764     {
1765         if (this.readOnly())
1766             return false;
1767
1768         var selection = this.selection();
1769         if (!selection)
1770             return false;
1771
1772         var range = selection.normalize();
1773
1774         this.beginUpdates();
1775
1776         var newRange;
1777         var rangeWasEmpty = range.isEmpty();
1778         if (shiftKey)
1779             newRange = this._textModel.unindentLines(range);
1780         else {
1781             if (rangeWasEmpty)
1782                 newRange = this._textModel.editRange(range, WebInspector.settings.textEditorIndent.get());
1783             else
1784                 newRange = this._textModel.indentLines(range);
1785         }
1786
1787         this.endUpdates();
1788         if (rangeWasEmpty)
1789             newRange.startColumn = newRange.endColumn;
1790         this._restoreSelection(newRange, true);
1791         return true;
1792     },
1793
1794     _handleEnterKey: function()
1795     {
1796         if (this.readOnly())
1797             return false;
1798
1799         var range = this.selection();
1800         if (!range)
1801             return false;
1802
1803         range = range.normalize();
1804
1805         if (range.endColumn === 0)
1806             return false;
1807
1808         var line = this._textModel.line(range.startLine);
1809         var linePrefix = line.substring(0, range.startColumn);
1810         var indentMatch = linePrefix.match(/^\s+/);
1811         var currentIndent = indentMatch ? indentMatch[0] : "";
1812
1813         var textEditorIndent = WebInspector.settings.textEditorIndent.get();
1814         var indent = WebInspector.TextEditorModel.endsWithBracketRegex.test(linePrefix) ? currentIndent + textEditorIndent : currentIndent;
1815
1816         if (!indent)
1817             return false;
1818
1819         this.beginDomUpdates();
1820
1821         var lineBreak = this._textModel.lineBreak;
1822         var newRange;
1823         if (range.isEmpty() && line.substr(range.endColumn - 1, 2) === '{}') {
1824             // {|}
1825             // becomes
1826             // {
1827             //     |
1828             // }
1829             newRange = this._textModel.editRange(range, lineBreak + indent + lineBreak + currentIndent);
1830             newRange.endLine--;
1831             newRange.endColumn += textEditorIndent.length;
1832         } else
1833             newRange = this._textModel.editRange(range, lineBreak + indent);
1834
1835         this.endDomUpdates();
1836         this._restoreSelection(newRange.collapseToEnd(), true);
1837
1838         return true;
1839     },
1840
1841     /**
1842      * @param {number} lineNumber
1843      * @param {number} chunkNumber
1844      * @param {boolean=} createSuffixChunk
1845      * @return {Object}
1846      */
1847     splitChunkOnALine: function(lineNumber, chunkNumber, createSuffixChunk)
1848     {
1849         var selection = this.selection();
1850         var chunk = WebInspector.TextEditorChunkedPanel.prototype.splitChunkOnALine.call(this, lineNumber, chunkNumber, createSuffixChunk);
1851         this._restoreSelection(selection);
1852         return chunk;
1853     },
1854
1855     beginDomUpdates: function()
1856     {
1857         if (!this._domUpdateCoalescingLevel)
1858             this._detachMutationObserver();
1859         WebInspector.TextEditorChunkedPanel.prototype.beginDomUpdates.call(this);
1860     },
1861
1862     endDomUpdates: function()
1863     {
1864         WebInspector.TextEditorChunkedPanel.prototype.endDomUpdates.call(this);
1865         if (!this._domUpdateCoalescingLevel)
1866             this._attachMutationObserver();
1867     },
1868
1869     buildChunks: function()
1870     {
1871         for (var i = 0; i < this._textModel.linesCount; ++i)
1872             this._textModel.removeAttribute(i, "highlight");
1873
1874         WebInspector.TextEditorChunkedPanel.prototype.buildChunks.call(this);
1875     },
1876
1877     /**
1878      * @param {number} startLine
1879      * @param {number} endLine
1880      * @return {WebInspector.TextEditorMainChunk}
1881      */
1882     createNewChunk: function(startLine, endLine)
1883     {
1884         return new WebInspector.TextEditorMainChunk(this, startLine, endLine);
1885     },
1886
1887     /**
1888      * @param {number} fromIndex
1889      * @param {number} toIndex
1890      */
1891     expandChunks: function(fromIndex, toIndex)
1892     {
1893         var lastChunk = this._textChunks[toIndex - 1];
1894         var lastVisibleLine = lastChunk.startLine + lastChunk.linesCount;
1895
1896         var selection = this.selection();
1897
1898         this._muteHighlightListener = true;
1899         this._highlighter.highlight(lastVisibleLine);
1900         delete this._muteHighlightListener;
1901
1902         WebInspector.TextEditorChunkedPanel.prototype.expandChunks.call(this, fromIndex, toIndex);
1903
1904         this._restoreSelection(selection);
1905     },
1906
1907     /**
1908      * @param {number} fromLine
1909      * @param {number} toLine
1910      */
1911     _highlightDataReady: function(fromLine, toLine)
1912     {
1913         if (this._muteHighlightListener)
1914             return;
1915         this._paintLines(fromLine, toLine, true /*restoreSelection*/);
1916     },
1917
1918     /**
1919      * @param {number} fromLine
1920      * @param {number} toLine
1921      * @param {boolean=} restoreSelection
1922      */
1923     _paintLines: function(fromLine, toLine, restoreSelection)
1924     {
1925         var lineRows = [];
1926         var chunk;
1927         for (var lineNumber = fromLine; lineNumber < toLine; ++lineNumber) {
1928             if (!chunk || lineNumber < chunk.startLine || lineNumber >= chunk.startLine + chunk.linesCount)
1929                 chunk = this.chunkForLine(lineNumber);
1930             var lineRow = chunk.expandedLineRow(lineNumber);
1931             if (!lineRow)
1932                 continue;
1933             lineRows.push(lineRow);
1934         }
1935         if (lineRows.length === 0)
1936             return;
1937
1938         var selection;
1939         if (restoreSelection)
1940             selection = this.selection();
1941
1942         this._paintLineRows(lineRows);
1943
1944         if (restoreSelection)
1945             this._restoreSelection(selection);
1946     },
1947
1948     /**
1949      * @param {Array.<Element>} lineRows
1950      */
1951     _paintLineRows: function(lineRows)
1952     {
1953         var highlight = {};
1954         this.beginDomUpdates();
1955         for(var i = 0; i < this._highlightDescriptors.length; ++i) {
1956             var highlightDescriptor = this._highlightDescriptors[i];
1957             this._measureHighlightDescriptor(highlight, lineRows, highlightDescriptor);
1958         }
1959
1960         for(var i = 0; i < lineRows.length; ++i)
1961             this._paintLine(lineRows[i], highlight[lineRows[i].lineNumber]);
1962
1963         this.endDomUpdates();
1964     },
1965
1966     /**
1967      * @param {Object.<number, Array.<WebInspector.TextEditorMainPanel.LineOverlayHighlight>>} highlight
1968      * @param {Array.<Element>} lineRows
1969      * @param {WebInspector.TextEditorMainPanel.HighlightDescriptor} highlightDescriptor
1970      */
1971     _measureHighlightDescriptor: function(highlight, lineRows, highlightDescriptor)
1972     {
1973         var rowsToMeasure = [];
1974         for(var i = 0; i < lineRows.length; ++i) {
1975             var lineRow = lineRows[i];
1976             var line = this._textModel.line(lineRow.lineNumber);
1977             var ranges = highlightDescriptor.rangesForLine(lineRow.lineNumber, line);
1978             if (ranges.length === 0)
1979                 continue;
1980
1981             this._renderRanges(lineRow, line, ranges);
1982             rowsToMeasure.push(lineRow);
1983         }
1984
1985         for(var i = 0; i < rowsToMeasure.length; ++i) {
1986             var lineRow = rowsToMeasure[i];
1987             var lineNumber = lineRow.lineNumber;
1988             var metrics = this._measureSpans(lineRow);
1989
1990             if (!highlight[lineNumber])
1991                 highlight[lineNumber] = [];
1992
1993             highlight[lineNumber].push(new WebInspector.TextEditorMainPanel.LineOverlayHighlight(metrics, highlightDescriptor.cssClass()));
1994         }
1995     },
1996
1997     /**
1998      * @param {Element} lineRow
1999      * @return {Array.<WebInspector.TextEditorMainPanel.ElementMetrics>}
2000      */
2001     _measureSpans: function(lineRow)
2002     {
2003         var spans = lineRow.getElementsByTagName("span");
2004         var metrics = [];
2005         for(var i = 0; i < spans.length; ++i)
2006             metrics.push(new WebInspector.TextEditorMainPanel.ElementMetrics(spans[i]));
2007         return metrics;
2008     },
2009
2010     /**
2011      * @param {Element} lineRow
2012      * @param {WebInspector.TextEditorMainPanel.LineOverlayHighlight} highlight
2013      */
2014     _appendOverlayHighlight: function(lineRow, highlight)
2015     {
2016         var metrics = highlight.metrics;
2017         var cssClass = highlight.cssClass;
2018         for(var i = 0; i < metrics.length; ++i) {
2019             var highlightSpan = document.createElement("span");
2020             highlightSpan._isOverlayHighlightElement = true;
2021             highlightSpan.addStyleClass(cssClass);
2022             highlightSpan.style.left = metrics[i].left + "px";
2023             highlightSpan.style.width = metrics[i].width + "px";
2024             highlightSpan.style.height = metrics[i].height + "px";
2025             highlightSpan.addStyleClass("text-editor-overlay-highlight");
2026             lineRow.insertBefore(highlightSpan, lineRow.decorationsElement);
2027         }
2028     },
2029
2030     /**
2031      * @param {Element} lineRow
2032      * @param {string} line
2033      * @param {Array.<{startColumn: number, endColumn: number, token: ?string}>} ranges
2034      * @param {boolean=} splitWhitespaceSequences
2035      */
2036     _renderRanges: function(lineRow, line, ranges, splitWhitespaceSequences)
2037     {
2038         var decorationsElement = lineRow.decorationsElement;
2039
2040         if (!decorationsElement)
2041             lineRow.removeChildren();
2042         else {
2043             while (true) {
2044                 var child = lineRow.firstChild;
2045                 if (!child || child === decorationsElement)
2046                     break;
2047                 lineRow.removeChild(child);
2048             }
2049         }
2050
2051         if (!line)
2052             lineRow.insertBefore(document.createElement("br"), decorationsElement);
2053
2054         var plainTextStart = 0;
2055         for(var i = 0; i < ranges.length; i++) {
2056             var rangeStart = ranges[i].startColumn;
2057             var rangeEnd = ranges[i].endColumn;
2058
2059             if (plainTextStart < rangeStart) {
2060                 this._insertTextNodeBefore(lineRow, decorationsElement, line.substring(plainTextStart, rangeStart));
2061             }
2062
2063             if (splitWhitespaceSequences && ranges[i].token === "whitespace")
2064                 this._renderWhitespaceCharsWithFixedSizeSpans(lineRow, decorationsElement, rangeEnd - rangeStart + 1);
2065             else
2066                 this._insertSpanBefore(lineRow, decorationsElement, line.substring(rangeStart, rangeEnd + 1), ranges[i].token ? "webkit-" + ranges[i].token : "");
2067             plainTextStart = rangeEnd + 1;
2068         }
2069         if (plainTextStart < line.length) {
2070             this._insertTextNodeBefore(lineRow, decorationsElement, line.substring(plainTextStart, line.length));
2071         }
2072     },
2073
2074     /**
2075      * @param {Element} lineRow
2076      * @param {Element} decorationsElement
2077      * @param {number} length
2078      */
2079     _renderWhitespaceCharsWithFixedSizeSpans: function(lineRow, decorationsElement, length)
2080     {
2081         for (var whitespaceLength = 16; whitespaceLength > 0; whitespaceLength >>= 1) {
2082             var cssClass = "webkit-whitespace webkit-whitespace-" + whitespaceLength;
2083             for (; length >= whitespaceLength; length -= whitespaceLength)
2084                 this._insertSpanBefore(lineRow, decorationsElement, WebInspector.TextEditorMainPanel._ConsecutiveWhitespaceChars[whitespaceLength], cssClass);
2085         }
2086     },
2087
2088     /**
2089      * @param {Element} lineRow
2090      * @param {Array.<WebInspector.TextEditorMainPanel.LineOverlayHighlight>} overlayHighlight
2091      */
2092     _paintLine: function(lineRow, overlayHighlight)
2093     {
2094         var lineNumber = lineRow.lineNumber;
2095
2096         this.beginDomUpdates();
2097         try {
2098             var syntaxHighlight = this._textModel.getAttribute(lineNumber, "highlight");
2099             if (!syntaxHighlight)
2100                 return;
2101
2102             var line = this._textModel.line(lineNumber);
2103             var ranges = syntaxHighlight.ranges;
2104             this._renderRanges(lineRow, line, ranges, this._showWhitespace);
2105
2106             if (overlayHighlight)
2107                 for(var i = 0; i < overlayHighlight.length; ++i)
2108                     this._appendOverlayHighlight(lineRow, overlayHighlight[i]);
2109         } finally {
2110             if (this._rangeToMark && this._rangeToMark.startLine === lineNumber)
2111                 this._markedRangeElement = WebInspector.highlightSearchResult(lineRow, this._rangeToMark.startColumn, this._rangeToMark.endColumn - this._rangeToMark.startColumn);
2112             this.endDomUpdates();
2113         }
2114     },
2115
2116     /**
2117      * @param {Element} lineRow
2118      */
2119     _releaseLinesHighlight: function(lineRow)
2120     {
2121         if (!lineRow)
2122             return;
2123         if ("spans" in lineRow) {
2124             var spans = lineRow.spans;
2125             for (var j = 0; j < spans.length; ++j)
2126                 this._cachedSpans.push(spans[j]);
2127             delete lineRow.spans;
2128         }
2129         if ("textNodes" in lineRow) {
2130             var textNodes = lineRow.textNodes;
2131             for (var j = 0; j < textNodes.length; ++j)
2132                 this._cachedTextNodes.push(textNodes[j]);
2133             delete lineRow.textNodes;
2134         }
2135         this._cachedRows.push(lineRow);
2136     },
2137
2138     /**
2139      * @param {?Node=} lastUndamagedLineRow
2140      * @return {WebInspector.TextRange}
2141      */
2142     selection: function(lastUndamagedLineRow)
2143     {
2144         var selection = window.getSelection();
2145         if (!selection.rangeCount)
2146             return null;
2147         // Selection may be outside of the editor.
2148         if (!this._container.isAncestor(selection.anchorNode) || !this._container.isAncestor(selection.focusNode))
2149             return null;
2150         // Selection may be inside one of decorations.
2151         if (selection.focusNode.enclosingNodeOrSelfWithClass("webkit-line-decorations", this._container))
2152             return null;
2153         var start = this._selectionToPosition(selection.anchorNode, selection.anchorOffset, lastUndamagedLineRow);
2154         var end = selection.isCollapsed ? start : this._selectionToPosition(selection.focusNode, selection.focusOffset, lastUndamagedLineRow);
2155         return new WebInspector.TextRange(start.line, start.column, end.line, end.column);
2156     },
2157
2158     lastSelection: function()
2159     {
2160         return this._lastSelection;
2161     },
2162
2163     /**
2164      * @param {boolean=} scrollIntoView
2165      */
2166     _restoreSelection: function(range, scrollIntoView)
2167     {
2168         if (!range)
2169             return;
2170
2171         var start = this._positionToSelection(range.startLine, range.startColumn);
2172         var end = range.isEmpty() ? start : this._positionToSelection(range.endLine, range.endColumn);
2173         window.getSelection().setBaseAndExtent(start.container, start.offset, end.container, end.offset);
2174
2175         if (scrollIntoView) {
2176             for (var node = end.container; node; node = node.parentElement) {
2177                 if (node.scrollIntoViewIfNeeded) {
2178                     node.scrollIntoViewIfNeeded();
2179                     break;
2180                 }
2181             }
2182         }
2183         this._lastSelection = range;
2184     },
2185
2186     /**
2187      * @param {Node} container
2188      * @param {number} offset
2189      * @param {?Node=} lastUndamagedLineRow
2190      * @return {{line: number, column: number}}
2191      */
2192     _selectionToPosition: function(container, offset, lastUndamagedLineRow)
2193     {
2194         if (container === this._container && offset === 0)
2195             return { line: 0, column: 0 };
2196         if (container === this._container && offset === 1)
2197             return { line: this._textModel.linesCount - 1, column: this._textModel.lineLength(this._textModel.linesCount - 1) };
2198
2199         // This method can be called on the damaged DOM (when DOM does not match model).
2200         // We need to start counting lines from the first undamaged line if it is given.
2201         var lineNumber;
2202         var column = 0;
2203         var node;
2204         var scopeNode;
2205         if (lastUndamagedLineRow === null) {
2206              // Last undamaged row is given, but is null - force traverse from the beginning
2207             node = this._container.firstChild;
2208             scopeNode = this._container;
2209             lineNumber = 0;
2210         } else {
2211             var lineRow = this._enclosingLineRowOrSelf(container);
2212             if (!lastUndamagedLineRow || (typeof lineRow.lineNumber === "number" && lineRow.lineNumber <= lastUndamagedLineRow.lineNumber)) {
2213                 // DOM is consistent (or we belong to the first damaged row)- lookup the row we belong to and start with it.
2214                 node = lineRow;
2215                 scopeNode = node;
2216                 lineNumber = node.lineNumber;
2217             } else {
2218                 // Start with the node following undamaged row. It corresponds to lineNumber + 1.
2219                 node = lastUndamagedLineRow.nextSibling;
2220                 scopeNode = this._container;
2221                 lineNumber = lastUndamagedLineRow.lineNumber + 1;
2222             }
2223         }
2224
2225         // Fast return the line start.
2226         if (container === node && offset === 0)
2227             return { line: lineNumber, column: 0 };
2228
2229         // Traverse text and increment lineNumber / column.
2230         for (; node && node !== container; node = node.traverseNextNode(scopeNode)) {
2231             if (node.nodeName.toLowerCase() === "br") {
2232                 lineNumber++;
2233                 column = 0;
2234             } else if (node.nodeType === Node.TEXT_NODE) {
2235                 var text = node.textContent;
2236                 for (var i = 0; i < text.length; ++i) {
2237                     if (text.charAt(i) === "\n") {
2238                         lineNumber++;
2239                         column = 0;
2240                     } else
2241                         column++;
2242                 }
2243             }
2244         }
2245
2246         // We reached our container node, traverse within itself until we reach given offset.
2247         if (node === container && offset) {
2248             var text = node.textContent;
2249             // In case offset == 1 and lineRow is a chunk div, we need to traverse it all.
2250             var textOffset = (node._chunk && offset === 1) ? text.length : offset;
2251             for (var i = 0; i < textOffset; ++i) {
2252                 if (text.charAt(i) === "\n") {
2253                     lineNumber++;
2254                     column = 0;
2255                 } else
2256                     column++;
2257             }
2258         }
2259         return { line: lineNumber, column: column };
2260     },
2261
2262     /**
2263      * @param {number} line
2264      * @param {number} column
2265      * @return {{container: Element, offset: number}}
2266      */
2267     _positionToSelection: function(line, column)
2268     {
2269         var chunk = this.chunkForLine(line);
2270         // One-lined collapsed chunks may still stay highlighted.
2271         var lineRow = chunk.linesCount === 1 ? chunk.element : chunk.expandedLineRow(line);
2272         if (lineRow)
2273             var rangeBoundary = lineRow.rangeBoundaryForOffset(column);
2274         else {
2275             var offset = column;
2276             for (var i = chunk.startLine; i < line && i < this._textModel.linesCount; ++i)
2277                 offset += this._textModel.lineLength(i) + 1; // \n
2278             lineRow = chunk.element;
2279             if (lineRow.firstChild)
2280                 var rangeBoundary = { container: lineRow.firstChild, offset: offset };
2281             else
2282                 var rangeBoundary = { container: lineRow, offset: 0 };
2283         }
2284         return rangeBoundary;
2285     },
2286
2287     /**
2288      * @param {Node} element
2289      * @return {?Node}
2290      */
2291     _enclosingLineRowOrSelf: function(element)
2292     {
2293         var lineRow = element.enclosingNodeOrSelfWithClass("webkit-line-content");
2294         if (lineRow)
2295             return lineRow;
2296
2297         for (lineRow = element; lineRow; lineRow = lineRow.parentElement) {
2298             if (lineRow.parentElement === this._container)
2299                 return lineRow;
2300         }
2301         return null;
2302     },
2303
2304     /**
2305      * @param {Element} element
2306      * @param {Element} oldChild
2307      * @param {string} content
2308      * @param {string} className
2309      */
2310     _insertSpanBefore: function(element, oldChild, content, className)
2311     {
2312         if (className === "html-resource-link" || className === "html-external-link") {
2313             element.insertBefore(this._createLink(content, className === "html-external-link"), oldChild);
2314             return;
2315         }
2316
2317         var span = this._cachedSpans.pop() || document.createElement("span");
2318         span.className = className;
2319         if (WebInspector.FALSE) // For paint debugging.
2320             span.addStyleClass("debug-fadeout");
2321         span.textContent = content;
2322         element.insertBefore(span, oldChild);
2323         if (!("spans" in element))
2324             element.spans = [];
2325         element.spans.push(span);
2326     },
2327
2328     /**
2329      * @param {Element} element
2330      * @param {Element} oldChild
2331      * @param {string} text
2332      */
2333     _insertTextNodeBefore: function(element, oldChild, text)
2334     {
2335         var textNode = this._cachedTextNodes.pop();
2336         if (textNode)
2337             textNode.nodeValue = text;
2338         else
2339             textNode = document.createTextNode(text);
2340         element.insertBefore(textNode, oldChild);
2341         if (!("textNodes" in element))
2342             element.textNodes = [];
2343         element.textNodes.push(textNode);
2344     },
2345
2346     /**
2347      * @param {string} content
2348      * @param {boolean} isExternal
2349      * @return {Element}
2350      */
2351     _createLink: function(content, isExternal)
2352     {
2353         var quote = content.charAt(0);
2354         if (content.length > 1 && (quote === "\"" || quote === "'"))
2355             content = content.substring(1, content.length - 1);
2356         else
2357             quote = null;
2358
2359         var span = document.createElement("span");
2360         span.className = "webkit-html-attribute-value";
2361         if (quote)
2362             span.appendChild(document.createTextNode(quote));
2363         span.appendChild(this._delegate.createLink(content, isExternal));
2364         if (quote)
2365             span.appendChild(document.createTextNode(quote));
2366         return span;
2367     },
2368
2369     /**
2370      * @param {Array.<WebKitMutation>} mutations
2371      */
2372     _handleMutations: function(mutations)
2373     {
2374         if (this._readOnly) {
2375             delete this._keyDownCode;
2376             return;
2377         }
2378
2379         // Annihilate noop BR addition + removal that takes place upon line removal.
2380         var filteredMutations = mutations.slice();
2381         var addedBRs = new Map();
2382         for (var i = 0; i < mutations.length; ++i) {
2383             var mutation = mutations[i];
2384             if (mutation.type !== "childList")
2385                 continue;
2386             if (mutation.addedNodes.length === 1 && mutation.addedNodes[0].nodeName === "BR")
2387                 addedBRs.put(mutation.addedNodes[0], mutation);
2388             else if (mutation.removedNodes.length === 1 && mutation.removedNodes[0].nodeName === "BR") {
2389                 var noopMutation = addedBRs.get(mutation.removedNodes[0]);
2390                 if (noopMutation) {
2391                     filteredMutations.remove(mutation);
2392                     filteredMutations.remove(noopMutation);
2393                 }
2394             }
2395         }
2396
2397         var dirtyLines;
2398         for (var i = 0; i < filteredMutations.length; ++i) {
2399             var mutation = filteredMutations[i];
2400             var changedNodes = [];
2401             if (mutation.type === "childList" && mutation.addedNodes.length)
2402                 changedNodes = Array.prototype.slice.call(mutation.addedNodes);
2403             else if (mutation.type === "childList" && mutation.removedNodes.length)
2404                 changedNodes = Array.prototype.slice.call(mutation.removedNodes);
2405             changedNodes.push(mutation.target);
2406
2407             for (var j = 0; j < changedNodes.length; ++j) {
2408                 var lines = this._collectDirtyLines(mutation, changedNodes[j]);
2409                 if (!lines)
2410                     continue;
2411                 if (!dirtyLines) {
2412                     dirtyLines = lines;
2413                     continue;
2414                 }
2415                 dirtyLines.start = Math.min(dirtyLines.start, lines.start);
2416                 dirtyLines.end = Math.max(dirtyLines.end, lines.end);
2417             }
2418         }
2419         if (dirtyLines) {
2420             delete this._rangeToMark;
2421             this._applyDomUpdates(dirtyLines);
2422         }
2423
2424         this._assertDOMMatchesTextModel();
2425
2426         delete this._keyDownCode;
2427     },
2428
2429     /**
2430      * @param {WebKitMutation} mutation
2431      * @param {Node} target
2432      * @return {?Object}
2433      */
2434     _collectDirtyLines: function(mutation, target)
2435     {
2436         var lineRow = this._enclosingLineRowOrSelf(target);
2437         if (!lineRow)
2438             return null;
2439
2440         if (lineRow.decorationsElement && lineRow.decorationsElement.isSelfOrAncestor(target)) {
2441             if (this._syncDecorationsForLineListener)
2442                 this._syncDecorationsForLineListener(lineRow.lineNumber);
2443             return null;
2444         }
2445
2446         if (typeof lineRow.lineNumber !== "number")
2447             return null;
2448
2449         var startLine = lineRow.lineNumber;
2450         var endLine = lineRow._chunk ? lineRow._chunk.endLine - 1 : lineRow.lineNumber;
2451         return { start: startLine, end: endLine };
2452     },
2453
2454     /**
2455      * @param {Object} dirtyLines
2456      */
2457     _applyDomUpdates: function(dirtyLines)
2458     {
2459         var lastUndamagedLineNumber = dirtyLines.start - 1; // Can be -1
2460         var firstUndamagedLineNumber = dirtyLines.end + 1; // Can be this._textModel.linesCount
2461
2462         var lastUndamagedLineChunk = lastUndamagedLineNumber >= 0 ? this._textChunks[this.chunkNumberForLine(lastUndamagedLineNumber)] : null;
2463         var firstUndamagedLineChunk = firstUndamagedLineNumber < this._textModel.linesCount ? this._textChunks[this.chunkNumberForLine(firstUndamagedLineNumber)] : null;
2464
2465         var collectLinesFromNode = lastUndamagedLineChunk ? lastUndamagedLineChunk.lineRowContainingLine(lastUndamagedLineNumber) : null;
2466         var collectLinesToNode = firstUndamagedLineChunk ? firstUndamagedLineChunk.lineRowContainingLine(firstUndamagedLineNumber) : null;
2467         var lines = this._collectLinesFromDOM(collectLinesFromNode, collectLinesToNode);
2468
2469         var startLine = dirtyLines.start;
2470         var endLine = dirtyLines.end;
2471
2472         var editInfo = this._guessEditRangeBasedOnSelection(startLine, endLine, lines);
2473         if (!editInfo) {
2474             if (WebInspector.debugDefaultTextEditor)
2475                 console.warn("Falling back to expensive edit");
2476             var range = new WebInspector.TextRange(startLine, 0, endLine, this._textModel.lineLength(endLine));
2477             if (!lines.length) {
2478                 // Entire damaged area has collapsed. Replace everything between start and end lines with nothing.
2479                 editInfo = new WebInspector.DefaultTextEditor.EditInfo(this._textModel.growRangeRight(range), "");
2480             } else
2481                 editInfo = new WebInspector.DefaultTextEditor.EditInfo(range, lines.join("\n"));
2482         }
2483
2484         var selection = this.selection(collectLinesFromNode);
2485
2486         // Unindent after block
2487         if (editInfo.text === "}" && editInfo.range.isEmpty() && selection.isEmpty() && !this._textModel.line(editInfo.range.endLine).trim()) {
2488             var offset = this._closingBlockOffset(editInfo.range);
2489             if (offset >= 0) {
2490                 editInfo.range.startColumn = offset;
2491                 selection.startColumn = offset + 1;
2492                 selection.endColumn = offset + 1;
2493             }
2494         }
2495
2496         this._textModel.editRange(editInfo.range, editInfo.text);
2497         this._restoreSelection(selection);
2498     },
2499
2500     /**
2501      * @param {number} startLine
2502      * @param {number} endLine
2503      * @param {Array.<string>} lines
2504      * @return {?WebInspector.DefaultTextEditor.EditInfo}
2505      */
2506     _guessEditRangeBasedOnSelection: function(startLine, endLine, lines)
2507     {
2508         // Analyze input data
2509         var textInputData = this._textInputData;
2510         delete this._textInputData;
2511         var isBackspace = this._keyDownCode === WebInspector.KeyboardShortcut.Keys.Backspace.code;
2512         var isDelete = this._keyDownCode === WebInspector.KeyboardShortcut.Keys.Delete.code;
2513
2514         if (!textInputData && (isDelete || isBackspace))
2515             textInputData = "";
2516
2517         // Return if there is no input data or selection
2518         if (typeof textInputData === "undefined" || !this._lastSelection)
2519             return null;
2520
2521         // Adjust selection based on the keyboard actions (grow for backspace, etc.).
2522         textInputData = textInputData || "";
2523         var range = this._lastSelection.normalize();
2524         if (isBackspace && range.isEmpty())
2525             range = this._textModel.growRangeLeft(range);
2526         else if (isDelete && range.isEmpty())
2527             range = this._textModel.growRangeRight(range);
2528
2529         // Test that selection intersects damaged lines
2530         if (startLine > range.endLine || endLine < range.startLine)
2531             return null;
2532
2533         var replacementLineCount = textInputData.split("\n").length - 1;
2534         var lineCountDelta = replacementLineCount - range.linesCount;
2535         if (startLine + lines.length - endLine - 1 !== lineCountDelta)
2536             return null;
2537
2538         // Clone text model of the size that fits both: selection before edit and the damaged lines after edit.
2539         var cloneFromLine = Math.min(range.startLine, startLine);
2540         var postLastLine = startLine + lines.length + lineCountDelta;
2541         var cloneToLine = Math.min(Math.max(postLastLine, range.endLine) + 1, this._textModel.linesCount);
2542         var domModel = this._textModel.slice(cloneFromLine, cloneToLine);
2543         domModel.editRange(range.shift(-cloneFromLine), textInputData);
2544
2545         // Then we'll test if this new model matches the DOM lines.
2546         for (var i = 0; i < lines.length; ++i) {
2547             if (domModel.line(i + startLine - cloneFromLine) !== lines[i])
2548                 return null;
2549         }
2550         return new WebInspector.DefaultTextEditor.EditInfo(range, textInputData);
2551     },
2552
2553     _assertDOMMatchesTextModel: function()
2554     {
2555         if (!WebInspector.debugDefaultTextEditor)
2556             return;
2557
2558         console.assert(this.element.innerText === this._textModel.text() + "\n", "DOM does not match model.");
2559         for (var lineRow = this._container.firstChild; lineRow; lineRow = lineRow.nextSibling) {
2560             var lineNumber = lineRow.lineNumber;
2561             if (typeof lineNumber !== "number") {
2562                 console.warn("No line number on line row");
2563                 continue;
2564             }
2565             if (lineRow._chunk) {
2566                 var chunk = lineRow._chunk;
2567                 console.assert(lineNumber === chunk.startLine);
2568                 var chunkText = this._textModel.copyRange(new WebInspector.TextRange(chunk.startLine, 0, chunk.endLine - 1, this._textModel.lineLength(chunk.endLine - 1)));
2569                 if (chunkText !== lineRow.textContent)
2570                     console.warn("Chunk is not matching: %d %O", lineNumber, lineRow);
2571             } else if (this._textModel.line(lineNumber) !== lineRow.textContent)
2572                 console.warn("Line is not matching: %d %O", lineNumber, lineRow);
2573         }
2574     },
2575
2576     /**
2577      * @param {WebInspector.TextRange} oldRange
2578      * @return {number}
2579      */
2580     _closingBlockOffset: function(oldRange)
2581     {
2582         var leftBrace = this._braceMatcher.findLeftCandidate(oldRange.startLine, oldRange.startColumn);
2583         if (!leftBrace || leftBrace.token !== "block-start")
2584             return -1;
2585         var lineContent = this._textModel.line(leftBrace.lineNumber);
2586         return lineContent.length - lineContent.trimLeft().length;
2587     },
2588
2589     /**
2590      * @param {WebInspector.TextRange} oldRange
2591      * @param {WebInspector.TextRange} newRange
2592      */
2593     textChanged: function(oldRange, newRange)
2594     {
2595         this.beginDomUpdates();
2596         this._removeDecorationsInRange(oldRange);
2597         this._updateChunksForRanges(oldRange, newRange);
2598         this._updateHighlightsForRange(newRange);
2599         this.endDomUpdates();
2600     },
2601
2602     /**
2603      * @param {WebInspector.TextRange} range
2604      */
2605     _removeDecorationsInRange: function(range)
2606     {
2607         for (var i = this.chunkNumberForLine(range.startLine); i < this._textChunks.length; ++i) {
2608             var chunk = this._textChunks[i];
2609             if (chunk.startLine > range.endLine)
2610                 break;
2611             chunk.removeAllDecorations();
2612         }
2613     },
2614
2615     /**
2616      * @param {WebInspector.TextRange} oldRange
2617      * @param {WebInspector.TextRange} newRange
2618      */
2619     _updateChunksForRanges: function(oldRange, newRange)
2620     {
2621         var firstDamagedChunkNumber = this.chunkNumberForLine(oldRange.startLine);
2622         var lastDamagedChunkNumber = firstDamagedChunkNumber;
2623         while (lastDamagedChunkNumber + 1 < this._textChunks.length) {
2624             if (this._textChunks[lastDamagedChunkNumber + 1].startLine > oldRange.endLine)
2625                 break;
2626             ++lastDamagedChunkNumber;
2627         }
2628
2629         var firstDamagedChunk = this._textChunks[firstDamagedChunkNumber];
2630         var lastDamagedChunk = this._textChunks[lastDamagedChunkNumber];
2631
2632         var linesDiff = newRange.linesCount - oldRange.linesCount;
2633
2634         // First, detect chunks that have not been modified and simply shift them.
2635         if (linesDiff) {
2636             for (var chunkNumber = lastDamagedChunkNumber + 1; chunkNumber < this._textChunks.length; ++chunkNumber)
2637                 this._textChunks[chunkNumber].startLine += linesDiff;
2638         }
2639
2640         // Remove damaged chunks from DOM and from textChunks model.
2641         var lastUndamagedChunk = firstDamagedChunkNumber > 0 ? this._textChunks[firstDamagedChunkNumber - 1] : null;
2642         var firstUndamagedChunk = lastDamagedChunkNumber + 1 < this._textChunks.length ? this._textChunks[lastDamagedChunkNumber + 1] : null;
2643
2644         var removeDOMFromNode = lastUndamagedChunk ? lastUndamagedChunk.lastElement().nextSibling : this._container.firstChild;
2645         var removeDOMToNode = firstUndamagedChunk ? firstUndamagedChunk.firstElement() : null;
2646
2647         // Fast case - patch single expanded chunk that did not grow / shrink during edit.
2648         if (!linesDiff && firstDamagedChunk === lastDamagedChunk && firstDamagedChunk._expandedLineRows) {
2649             var lastUndamagedLineRow = lastDamagedChunk.expandedLineRow(oldRange.startLine - 1);
2650             var firstUndamagedLineRow = firstDamagedChunk.expandedLineRow(oldRange.endLine + 1);
2651             var localRemoveDOMFromNode = lastUndamagedLineRow ? lastUndamagedLineRow.nextSibling : removeDOMFromNode;
2652             var localRemoveDOMToNode = firstUndamagedLineRow || removeDOMToNode;
2653             removeSubsequentNodes(localRemoveDOMFromNode, localRemoveDOMToNode);
2654             for (var i = newRange.startLine; i < newRange.endLine + 1; ++i) {
2655                 var row = firstDamagedChunk._createRow(i);
2656                 firstDamagedChunk._expandedLineRows[i - firstDamagedChunk.startLine] = row;
2657                 this._container.insertBefore(row, localRemoveDOMToNode);
2658             }
2659             firstDamagedChunk.updateCollapsedLineRow();
2660             this._assertDOMMatchesTextModel();
2661             return;
2662         }
2663
2664         removeSubsequentNodes(removeDOMFromNode, removeDOMToNode);
2665         this._textChunks.splice(firstDamagedChunkNumber, lastDamagedChunkNumber - firstDamagedChunkNumber + 1);
2666
2667         // Compute damaged chunks span
2668         var startLine = firstDamagedChunk.startLine;
2669         var endLine = lastDamagedChunk.endLine + linesDiff;
2670         var lineSpan = endLine - startLine;
2671
2672         // Re-create chunks for damaged area.
2673         var insertionIndex = firstDamagedChunkNumber;
2674         var chunkSize = Math.ceil(lineSpan / Math.ceil(lineSpan / this._defaultChunkSize));
2675
2676         for (var i = startLine; i < endLine; i += chunkSize) {
2677             var chunk = this.createNewChunk(i, Math.min(endLine, i + chunkSize));
2678             this._textChunks.splice(insertionIndex++, 0, chunk);
2679             this._container.insertBefore(chunk.element, removeDOMToNode);
2680         }
2681
2682         this._assertDOMMatchesTextModel();
2683     },
2684
2685     /**
2686      * @param {WebInspector.TextRange} range
2687      */
2688     _updateHighlightsForRange: function(range)
2689     {
2690         var visibleFrom = this.scrollTop();
2691         var visibleTo = visibleFrom + this.clientHeight();
2692
2693         var result = this.findVisibleChunks(visibleFrom, visibleTo);
2694         var chunk = this._textChunks[result.end - 1];
2695         var lastVisibleLine = chunk.startLine + chunk.linesCount;
2696
2697         lastVisibleLine = Math.max(lastVisibleLine, range.endLine + 1);
2698         lastVisibleLine = Math.min(lastVisibleLine, this._textModel.linesCount);
2699
2700         var updated = this._highlighter.updateHighlight(range.startLine, lastVisibleLine);
2701         if (!updated) {
2702             // Highlights for the chunks below are invalid, so just collapse them.
2703             for (var i = this.chunkNumberForLine(range.startLine); i < this._textChunks.length; ++i)
2704                 this._textChunks[i].collapse();
2705         }
2706
2707         this.repaintAll();
2708     },
2709
2710     /**
2711      * @param {Node} from
2712      * @param {Node} to
2713      * @return {Array.<string>}
2714      */
2715     _collectLinesFromDOM: function(from, to)
2716     {
2717         var textContents = [];
2718         var hasContent = false;
2719         for (var node = from ? from.nextSibling : this._container; node && node !== to; node = node.traverseNextNode(this._container)) {
2720             // Skip all children of the decoration container and overlay highlight spans.
2721             while (node && node !== to && (node._isDecorationsElement || node._isOverlayHighlightElement))
2722                 node = node.nextSibling;
2723             if (!node || node === to)
2724                 break;
2725
2726             hasContent = true;
2727             if (node.nodeName.toLowerCase() === "br")
2728                 textContents.push("\n");
2729             else if (node.nodeType === Node.TEXT_NODE)
2730                 textContents.push(node.textContent);
2731         }
2732         if (!hasContent)
2733             return [];
2734
2735         var textContent = textContents.join("");
2736         // The last \n (if any) does not "count" in a DIV.
2737         textContent = textContent.replace(/\n$/, "");
2738
2739         return textContent.split("\n");
2740     },
2741
2742     /**
2743      * @param {Event} event
2744      */
2745     _handleSelectionChange: function(event)
2746     {
2747         var textRange = this.selection();
2748         if (textRange)
2749             this._lastSelection = textRange;
2750
2751         this._tokenHighlighter.handleSelectionChange(textRange);
2752         this._braceHighlighter.handleSelectionChange(textRange);
2753         this._delegate.selectionChanged(textRange);
2754     },
2755
2756     /**
2757      * @param {Event} event
2758      */
2759     _handleTextInput: function(event)
2760     {
2761         this._textInputData = event.data;
2762     },
2763
2764     /**
2765      * @param {number} shortcutKey
2766      * @param {Event} event
2767      */
2768     handleKeyDown: function(shortcutKey, event)
2769     {
2770         var handler = this._shortcuts[shortcutKey];
2771         if (handler && handler()) {
2772             event.consume(true);
2773             return;
2774         }
2775
2776         this._keyDownCode = event.keyCode;
2777     },
2778
2779     /**
2780      * @param {Event} event
2781      */
2782     _handleCut: function(event)
2783     {
2784         this._keyDownCode = WebInspector.KeyboardShortcut.Keys.Delete.code;
2785     },
2786
2787     /**
2788      * @param {number} scrollTop
2789      * @param {number} clientHeight
2790      * @param {number} chunkSize
2791      */
2792     overrideViewportForTest: function(scrollTop, clientHeight, chunkSize)
2793     {
2794         this._scrollTopOverrideForTest = scrollTop;
2795         this._clientHeightOverrideForTest = clientHeight;
2796         this._defaultChunkSize = chunkSize;
2797     },
2798
2799     __proto__: WebInspector.TextEditorChunkedPanel.prototype
2800 }
2801
2802 /**
2803  * @interface
2804  */
2805 WebInspector.TextEditorMainPanel.HighlightDescriptor = function() { }
2806
2807 WebInspector.TextEditorMainPanel.HighlightDescriptor.prototype = {
2808     /**
2809      * @param {number} lineNumber
2810      * @param {string} line
2811      * @return {boolean}
2812      */
2813     affectsLine: function(lineNumber, line) { return false; },
2814
2815     /**
2816      * @param {number} lineNumber
2817      * @param {string} line
2818      * @return {Array.<{startColumn: number, endColumn: number}>}
2819      */
2820     rangesForLine: function(lineNumber, line) { return []; },
2821
2822     /**
2823      * @return {string}
2824      */
2825     cssClass: function() { return ""; },
2826 }
2827
2828 /**
2829  * @constructor
2830  * @implements {WebInspector.TextEditorMainPanel.HighlightDescriptor}
2831  */
2832 WebInspector.TextEditorMainPanel.RegexHighlightDescriptor = function(regex, cssClass)
2833 {
2834     this._cssClass = cssClass;
2835     this._regex = regex;
2836 }
2837
2838 WebInspector.TextEditorMainPanel.RegexHighlightDescriptor.prototype = {
2839     /**
2840      * @param {number} lineNumber
2841      * @param {string} line
2842      * @return {boolean}
2843      */
2844     affectsLine: function(lineNumber, line)
2845     {
2846         this._regex.lastIndex = 0;
2847         return this._regex.test(line);
2848     },
2849
2850     /**
2851      * @param {number} lineNumber
2852      * @param {string} line
2853      * @return {Array.<{startColumn: number, endColumn: number}>}
2854      */
2855     rangesForLine: function(lineNumber, line)
2856     {
2857         var ranges = [];
2858         var regexResult;
2859         this._regex.lastIndex = 0;
2860         while (regexResult = this._regex.exec(line)) {
2861             ranges.push({
2862                 startColumn: regexResult.index,
2863                 endColumn: regexResult.index + regexResult[0].length - 1
2864             });
2865         }
2866         return ranges;
2867     },
2868
2869     /**
2870      * @return {string}
2871      */
2872     cssClass: function()
2873     {
2874         return this._cssClass;
2875     }
2876 }
2877
2878 /**
2879  * @constructor
2880  * @implements {WebInspector.TextEditorMainPanel.HighlightDescriptor}
2881  * @param {WebInspector.TextRange} range
2882  * @param {string} cssClass
2883  */
2884 WebInspector.TextEditorMainPanel.RangeHighlightDescriptor = function(range, cssClass)
2885 {
2886     this._cssClass = cssClass;
2887     this._range = range;
2888 }
2889
2890 WebInspector.TextEditorMainPanel.RangeHighlightDescriptor.prototype = {
2891     /**
2892      * @param {number} lineNumber
2893      * @param {string} line
2894      * @return {boolean}
2895      */
2896     affectsLine: function(lineNumber, line)
2897     {
2898         return this._range.startLine <= lineNumber && lineNumber <= this._range.endLine && line.length > 0;
2899     },
2900
2901     /**
2902      * @param {number} lineNumber
2903      * @param {string} line
2904      * @return {Array.<{startColumn: number, endColumn: number}>}
2905      */
2906     rangesForLine: function(lineNumber, line)
2907     {
2908         if (!this.affectsLine(lineNumber, line))
2909             return [];
2910
2911         var startColumn = lineNumber === this._range.startLine ? this._range.startColumn : 0;
2912         var endColumn = lineNumber === this._range.endLine ? Math.min(this._range.endColumn, line.length) : line.length;
2913         return [{
2914             startColumn: startColumn,
2915             endColumn: endColumn
2916         }];
2917     },
2918
2919     /**
2920      * @return {string}
2921      */
2922     cssClass: function()
2923     {
2924         return this._cssClass;
2925     }
2926 }
2927
2928 /**
2929  * @constructor
2930  * @param {Element} element
2931  */
2932 WebInspector.TextEditorMainPanel.ElementMetrics = function(element)
2933 {
2934     this.width = element.offsetWidth;
2935     this.height = element.offsetHeight;
2936     this.left = element.offsetLeft;
2937 }
2938
2939 /**
2940  * @constructor
2941  * @param {Array.<WebInspector.TextEditorMainPanel.ElementMetrics>} metrics
2942  * @param {string} cssClass
2943  */
2944 WebInspector.TextEditorMainPanel.LineOverlayHighlight = function(metrics, cssClass)
2945 {
2946     this.metrics = metrics;
2947     this.cssClass = cssClass;
2948 }
2949
2950 /**
2951  * @constructor
2952  * @param {WebInspector.TextEditorChunkedPanel} chunkedPanel
2953  * @param {number} startLine
2954  * @param {number} endLine
2955  */
2956 WebInspector.TextEditorMainChunk = function(chunkedPanel, startLine, endLine)
2957 {
2958     this._chunkedPanel = chunkedPanel;
2959     this._textModel = chunkedPanel._textModel;
2960
2961     this.element = document.createElement("div");
2962     this.element.lineNumber = startLine;
2963     this.element.className = "webkit-line-content";
2964     this.element._chunk = this;
2965
2966     this._startLine = startLine;
2967     endLine = Math.min(this._textModel.linesCount, endLine);
2968     this.linesCount = endLine - startLine;
2969
2970     this._expanded = false;
2971
2972     this.updateCollapsedLineRow();
2973 }
2974
2975 WebInspector.TextEditorMainChunk.prototype = {
2976     /**
2977      * @param {Element|string} decoration
2978      */
2979     addDecoration: function(decoration)
2980     {
2981         this._chunkedPanel.beginDomUpdates();
2982         if (typeof decoration === "string")
2983             this.element.addStyleClass(decoration);
2984         else {
2985             if (!this.element.decorationsElement) {
2986                 this.element.decorationsElement = document.createElement("div");
2987                 this.element.decorationsElement.className = "webkit-line-decorations";
2988                 this.element.decorationsElement._isDecorationsElement = true;
2989                 this.element.appendChild(this.element.decorationsElement);
2990             }
2991             this.element.decorationsElement.appendChild(decoration);
2992         }
2993         this._chunkedPanel.endDomUpdates();
2994     },
2995
2996     /**
2997      * @param {string|Element} decoration
2998      */
2999     removeDecoration: function(decoration)
3000     {
3001         this._chunkedPanel.beginDomUpdates();
3002         if (typeof decoration === "string")
3003             this.element.removeStyleClass(decoration);
3004         else if (this.element.decorationsElement)
3005             this.element.decorationsElement.removeChild(decoration);
3006         this._chunkedPanel.endDomUpdates();
3007     },
3008
3009     removeAllDecorations: function()
3010     {
3011         this._chunkedPanel.beginDomUpdates();
3012         this.element.className = "webkit-line-content";
3013         if (this.element.decorationsElement) {
3014             if (this.element.decorationsElement.parentElement)
3015                 this.element.removeChild(this.element.decorationsElement);
3016             delete this.element.decorationsElement;
3017         }
3018         this._chunkedPanel.endDomUpdates();
3019     },
3020
3021     /**
3022      * @return {boolean}
3023      */
3024     isDecorated: function()
3025     {
3026         return this.element.className !== "webkit-line-content" || !!(this.element.decorationsElement && this.element.decorationsElement.firstChild);
3027     },
3028
3029     /**
3030      * @return {number}
3031      */
3032     get startLine()
3033     {
3034         return this._startLine;
3035     },
3036
3037     /**
3038      * @return {number}
3039      */
3040     get endLine()
3041     {
3042         return this._startLine + this.linesCount;
3043     },
3044
3045     set startLine(startLine)
3046     {
3047         this._startLine = startLine;
3048         this.element.lineNumber = startLine;
3049         if (this._expandedLineRows) {
3050             for (var i = 0; i < this._expandedLineRows.length; ++i)
3051                 this._expandedLineRows[i].lineNumber = startLine + i;
3052         }
3053     },
3054
3055     /**
3056      * @return {boolean}
3057      */
3058     expanded: function()
3059     {
3060         return this._expanded;
3061     },
3062
3063     expand: function()
3064     {
3065         if (this._expanded)
3066             return;
3067
3068         this._expanded = true;
3069
3070         if (this.linesCount === 1) {
3071             this._chunkedPanel._paintLines(this.startLine, this.startLine + 1);
3072             return;
3073         }
3074
3075         this._chunkedPanel.beginDomUpdates();
3076
3077         this._expandedLineRows = [];
3078         var parentElement = this.element.parentElement;
3079         for (var i = this.startLine; i < this.startLine + this.linesCount; ++i) {
3080             var lineRow = this._createRow(i);
3081             parentElement.insertBefore(lineRow, this.element);
3082             this._expandedLineRows.push(lineRow);
3083         }
3084         parentElement.removeChild(this.element);
3085         this._chunkedPanel._paintLines(this.startLine, this.startLine + this.linesCount);
3086
3087         this._chunkedPanel.endDomUpdates();
3088     },
3089
3090     collapse: function()
3091     {
3092         if (!this._expanded)
3093             return;
3094
3095         this._expanded = false;
3096         if (this.linesCount === 1)
3097             return;
3098
3099         this._chunkedPanel.beginDomUpdates();
3100
3101         var elementInserted = false;
3102         for (var i = 0; i < this._expandedLineRows.length; ++i) {
3103             var lineRow = this._expandedLineRows[i];
3104             var parentElement = lineRow.parentElement;
3105             if (parentElement) {
3106                 if (!elementInserted) {
3107                     elementInserted = true;
3108                     parentElement.insertBefore(this.element, lineRow);
3109                 }
3110                 parentElement.removeChild(lineRow);
3111             }
3112             this._chunkedPanel._releaseLinesHighlight(lineRow);
3113         }
3114         delete this._expandedLineRows;
3115
3116         this._chunkedPanel.endDomUpdates();
3117     },
3118
3119     /**
3120      * @return {number}
3121      */
3122     get height()
3123     {
3124         if (!this._expandedLineRows)
3125             return this._chunkedPanel.totalHeight(this.element);
3126         return this._chunkedPanel.totalHeight(this._expandedLineRows[0], this._expandedLineRows[this._expandedLineRows.length - 1]);
3127     },
3128
3129     /**
3130      * @return {number}
3131      */
3132     get offsetTop()
3133     {
3134         return (this._expandedLineRows && this._expandedLineRows.length) ? this._expandedLineRows[0].offsetTop : this.element.offsetTop;
3135     },
3136
3137     /**
3138      * @param {number} lineNumber
3139      * @return {Element}
3140      */
3141     _createRow: function(lineNumber)
3142     {
3143         var lineRow = this._chunkedPanel._cachedRows.pop() || document.createElement("div");
3144         lineRow.lineNumber = lineNumber;
3145         lineRow.className = "webkit-line-content";
3146         lineRow.textContent = this._textModel.line(lineNumber);
3147         if (!lineRow.textContent)
3148             lineRow.appendChild(document.createElement("br"));
3149         return lineRow;
3150     },
3151
3152     /**
3153      * Called on potentially damaged / inconsistent chunk
3154      * @param {number} lineNumber
3155      * @return {?Node}
3156      */
3157     lineRowContainingLine: function(lineNumber)
3158     {
3159         if (!this._expanded)
3160             return this.element;
3161         return this.expandedLineRow(lineNumber);
3162     },
3163
3164     /**
3165      * @param {number} lineNumber
3166      * @return {Element}
3167      */
3168     expandedLineRow: function(lineNumber)
3169     {
3170         if (!this._expanded || lineNumber < this.startLine || lineNumber >= this.startLine + this.linesCount)
3171             return null;
3172         if (!this._expandedLineRows)
3173             return this.element;
3174         return this._expandedLineRows[lineNumber - this.startLine];
3175     },
3176
3177     updateCollapsedLineRow: function()
3178     {
3179         if (this.linesCount === 1 && this._expanded)
3180             return;
3181
3182         var lines = [];
3183         for (var i = this.startLine; i < this.startLine + this.linesCount; ++i)
3184             lines.push(this._textModel.line(i));
3185
3186         if (WebInspector.FALSE)
3187             console.log("Rebuilding chunk with " + lines.length + " lines");
3188
3189         this.element.removeChildren();
3190         this.element.textContent = lines.join("\n");
3191         // The last empty line will get swallowed otherwise.
3192         if (!lines[lines.length - 1])
3193             this.element.appendChild(document.createElement("br"));
3194     },
3195
3196     firstElement: function()
3197     {
3198         return this._expandedLineRows ? this._expandedLineRows[0] : this.element;
3199     },
3200
3201     /**
3202      * @return {Element}
3203      */
3204     lastElement: function()
3205     {
3206         return this._expandedLineRows ? this._expandedLineRows[this._expandedLineRows.length - 1] : this.element;
3207     }
3208 }
3209
3210 /**
3211  * @constructor
3212  * @param {WebInspector.TextEditorMainPanel} mainPanel
3213  * @param {WebInspector.TextEditorModel} textModel
3214  */
3215 WebInspector.TextEditorMainPanel.TokenHighlighter = function(mainPanel, textModel)
3216 {
3217     this._mainPanel = mainPanel;
3218     this._textModel = textModel;
3219 }
3220
3221 WebInspector.TextEditorMainPanel.TokenHighlighter._NonWordCharRegex = /[^a-zA-Z0-9_]/;
3222 WebInspector.TextEditorMainPanel.TokenHighlighter._WordRegex = /^[a-zA-Z0-9_]+$/;
3223
3224 WebInspector.TextEditorMainPanel.TokenHighlighter.prototype = {
3225     /**
3226      * @param {WebInspector.TextRange} range
3227      */
3228     handleSelectionChange: function(range)
3229     {
3230         if (!range) {
3231             this._removeHighlight();
3232             return;
3233         }
3234
3235         if (range.startLine !== range.endLine) {
3236             this._removeHighlight();
3237             return;
3238         }
3239
3240         range = range.normalize();
3241         var selectedText = this._textModel.copyRange(range);
3242         if (selectedText === this._selectedWord)
3243             return;
3244
3245         if (selectedText === "") {
3246             this._removeHighlight();
3247             return;
3248         }
3249
3250         if (this._isWord(range, selectedText))
3251             this._highlight(selectedText);
3252         else
3253             this._removeHighlight();
3254     },
3255
3256     /**
3257      * @param {string} word
3258      */
3259     _regexString: function(word)
3260     {
3261         return "\\b" + word + "\\b";
3262     },
3263
3264     /**
3265      * @param {string} selectedWord
3266      */
3267     _highlight: function(selectedWord)
3268     {
3269         this._removeHighlight();