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