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