2ae81de2e402f478d697d79e06286a8d556a3dc5
[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     this._braceMatcher = new WebInspector.TextEditorModel.BraceMatcher(textModel);
1373     this._braceHighlighter = new WebInspector.TextEditorMainPanel.BraceHighlightController(this, textModel, this._braceMatcher);
1374
1375     this._freeCachedElements();
1376     this.buildChunks();
1377     this._registerShortcuts();
1378 }
1379
1380 WebInspector.TextEditorMainPanel.prototype = {
1381     _registerShortcuts: function()
1382     {
1383         var keys = WebInspector.KeyboardShortcut.Keys;
1384         var modifiers = WebInspector.KeyboardShortcut.Modifiers;
1385
1386         this._shortcuts = {};
1387
1388         this._shortcuts[WebInspector.KeyboardShortcut.makeKey(keys.Enter.code, WebInspector.KeyboardShortcut.Modifiers.None)] = this._handleEnterKey.bind(this);
1389         this._shortcuts[WebInspector.KeyboardShortcut.makeKey("z", modifiers.CtrlOrMeta)] = this._handleUndoRedo.bind(this, false);
1390
1391         var handleRedo = this._handleUndoRedo.bind(this, true);
1392         this._shortcuts[WebInspector.KeyboardShortcut.makeKey("z", modifiers.Shift | modifiers.CtrlOrMeta)] = handleRedo;
1393         if (!WebInspector.isMac())
1394             this._shortcuts[WebInspector.KeyboardShortcut.makeKey("y", modifiers.CtrlOrMeta)] = handleRedo;
1395
1396         var handleTabKey = this._handleTabKeyPress.bind(this, false);
1397         var handleShiftTabKey = this._handleTabKeyPress.bind(this, true);
1398         this._shortcuts[WebInspector.KeyboardShortcut.makeKey(keys.Tab.code)] = handleTabKey;
1399         this._shortcuts[WebInspector.KeyboardShortcut.makeKey(keys.Tab.code, modifiers.Shift)] = handleShiftTabKey;
1400     },
1401
1402     /**
1403      * @param {string} regex
1404      * @param {string} cssClass
1405      * @return {WebInspector.TextEditorMainPanel.HighlightDescriptor}
1406      */
1407     highlightRegex: function(regex, cssClass)
1408     {
1409         var highlightDescriptor = new WebInspector.TextEditorMainPanel.RegexHighlightDescriptor(new RegExp(regex, "g"), cssClass);
1410         this._highlightDescriptors.push(highlightDescriptor);
1411         this._repaintLineRowsAffectedByHighlightDescriptors([highlightDescriptor]);
1412         return highlightDescriptor;
1413     },
1414
1415     /**
1416      * @param {WebInspector.TextEditorMainPanel.HighlightDescriptor} highlightDescriptor
1417      */
1418     removeHighlight: function(highlightDescriptor)
1419     {
1420         this._highlightDescriptors.remove(highlightDescriptor);
1421         this._repaintLineRowsAffectedByHighlightDescriptors([highlightDescriptor]);
1422     },
1423
1424     /**
1425      * @param {WebInspector.TextRange} range
1426      * @param {string} cssClass
1427      */
1428     highlightRange: function(range, cssClass)
1429     {
1430         var highlightDescriptor = new WebInspector.TextEditorMainPanel.RangeHighlightDescriptor(range, cssClass);
1431         this._highlightDescriptors.push(highlightDescriptor);
1432         this._repaintLineRowsAffectedByHighlightDescriptors([highlightDescriptor]);
1433         return highlightDescriptor;
1434     },
1435
1436     /**
1437      * @param {Array.<WebInspector.TextEditorMainPanel.HighlightDescriptor>} highlightDescriptors
1438      */
1439     _repaintLineRowsAffectedByHighlightDescriptors: function(highlightDescriptors)
1440     {
1441         var visibleFrom = this.scrollTop();
1442         var visibleTo = visibleFrom + this.clientHeight();
1443
1444         var visibleChunks = this.findVisibleChunks(visibleFrom, visibleTo);
1445
1446         var affectedLineRows = [];
1447         for (var i = visibleChunks.start; i < visibleChunks.end; ++i) {
1448             var chunk = this._textChunks[i];
1449             if (!chunk.expanded())
1450                 continue;
1451             for (var lineNumber = chunk.startLine; lineNumber < chunk.startLine + chunk.linesCount; ++lineNumber) {
1452                 var lineRow = chunk.expandedLineRow(lineNumber);
1453                 var line = this._textModel.line(lineNumber);
1454                 for(var j = 0; j < highlightDescriptors.length; ++j) {
1455                     if (highlightDescriptors[j].affectsLine(lineNumber, line)) {
1456                         affectedLineRows.push(lineRow);
1457                         break;
1458                     }
1459                 }
1460             }
1461         }
1462         if (affectedLineRows.length === 0)
1463             return;
1464         var selection = this.selection();
1465         this._paintLineRows(affectedLineRows);
1466         this._restoreSelection(selection);
1467     },
1468
1469     resize: function()
1470     {
1471         WebInspector.TextEditorChunkedPanel.prototype.resize.call(this);
1472         this._repaintLineRowsAffectedByHighlightDescriptors(this._highlightDescriptors);
1473     },
1474
1475     wasShown: function()
1476     {
1477         this._boundSelectionChangeListener = this._handleSelectionChange.bind(this);
1478         document.addEventListener("selectionchange", this._boundSelectionChangeListener, false);
1479
1480         this._isShowing = true;
1481         this._attachMutationObserver();
1482     },
1483
1484     willHide: function()
1485     {
1486         document.removeEventListener("selectionchange", this._boundSelectionChangeListener, false);
1487         delete this._boundSelectionChangeListener;
1488
1489         this._detachMutationObserver();
1490         this._isShowing = false;
1491         this._freeCachedElements();
1492     },
1493
1494     /**
1495      * @param {Element} eventTarget
1496      * @param {WebInspector.ContextMenu} contextMenu
1497      */
1498     populateContextMenu: function(eventTarget, contextMenu)
1499     {
1500         var target = this._enclosingLineRowOrSelf(eventTarget);
1501         this._delegate.populateTextAreaContextMenu(contextMenu, target && target.lineNumber);
1502     },
1503
1504     /**
1505      * @param {WebInspector.TextRange} textRange
1506      */
1507     setSelection: function(textRange)
1508     {
1509         this._lastSelection = textRange;
1510         if (this.element.isAncestor(document.activeElement))
1511             this._restoreSelection(textRange);
1512     },
1513
1514     _handleFocused: function()
1515     {
1516         if (this._lastSelection)
1517             this.setSelection(this._lastSelection);
1518     },
1519
1520     _attachMutationObserver: function()
1521     {
1522         if (!this._isShowing)
1523             return;
1524
1525         if (this._mutationObserver)
1526             this._mutationObserver.disconnect();
1527         this._mutationObserver = new NonLeakingMutationObserver(this._handleMutations.bind(this));
1528         this._mutationObserver.observe(this._container, { subtree: true, childList: true, characterData: true });
1529     },
1530
1531     _detachMutationObserver: function()
1532     {
1533         if (!this._isShowing)
1534             return;
1535
1536         if (this._mutationObserver) {
1537             this._mutationObserver.disconnect();
1538             delete this._mutationObserver;
1539         }
1540     },
1541
1542     /**
1543      * @param {string} mimeType
1544      */
1545     set mimeType(mimeType)
1546     {
1547         this._highlighter.mimeType = mimeType;
1548     },
1549
1550     /**
1551      * @param {boolean} readOnly
1552      * @param {boolean} requestFocus
1553      */
1554     setReadOnly: function(readOnly, requestFocus)
1555     {
1556         if (this._readOnly === readOnly)
1557             return;
1558
1559         this.beginDomUpdates();
1560         this._readOnly = readOnly;
1561         if (this._readOnly)
1562             this._container.removeStyleClass("text-editor-editable");
1563         else {
1564             this._container.addStyleClass("text-editor-editable");
1565             if (requestFocus)
1566                 this._updateSelectionOnStartEditing();
1567         }
1568         this.endDomUpdates();
1569     },
1570
1571     /**
1572      * @return {boolean}
1573      */
1574     readOnly: function()
1575     {
1576         return this._readOnly;
1577     },
1578
1579     _handleElementFocus: function()
1580     {
1581         if (!this._readOnly)
1582             this._container.focus();
1583     },
1584
1585     /**
1586      * @return {Element}
1587      */
1588     defaultFocusedElement: function()
1589     {
1590         if (this._readOnly)
1591             return this.element;
1592         return this._container;
1593     },
1594
1595     _updateSelectionOnStartEditing: function()
1596     {
1597         // focus() needs to go first for the case when the last selection was inside the editor and
1598         // the "Edit" button was clicked. In this case we bail at the check below, but the
1599         // editor does not receive the focus, thus "Esc" does not cancel editing until at least
1600         // one change has been made to the editor contents.
1601         this._container.focus();
1602         var selection = window.getSelection();
1603         if (selection.rangeCount) {
1604             var commonAncestorContainer = selection.getRangeAt(0).commonAncestorContainer;
1605             if (this._container.isSelfOrAncestor(commonAncestorContainer))
1606                 return;
1607         }
1608
1609         selection.removeAllRanges();
1610         var range = document.createRange();
1611         range.setStart(this._container, 0);
1612         range.setEnd(this._container, 0);
1613         selection.addRange(range);
1614     },
1615
1616     /**
1617      * @param {WebInspector.TextRange} range
1618      */
1619     markAndRevealRange: function(range)
1620     {
1621         if (this._rangeToMark) {
1622             var markedLine = this._rangeToMark.startLine;
1623             delete this._rangeToMark;
1624             // Remove the marked region immediately.
1625             this.beginDomUpdates();
1626             var chunk = this.chunkForLine(markedLine);
1627             var wasExpanded = chunk.expanded();
1628             chunk.collapse();
1629             chunk.updateCollapsedLineRow();
1630             if (wasExpanded)
1631                 chunk.expand();
1632             this.endDomUpdates();
1633         }
1634
1635         if (range) {
1636             this._rangeToMark = range;
1637             this.revealLine(range.startLine);
1638             var chunk = this.makeLineAChunk(range.startLine);
1639             this._paintLines(chunk.startLine, chunk.startLine + 1);
1640             if (this._markedRangeElement)
1641                 this._markedRangeElement.scrollIntoViewIfNeeded();
1642         }
1643         delete this._markedRangeElement;
1644     },
1645
1646     /**
1647      * @param {number} lineNumber
1648      */
1649     highlightLine: function(lineNumber)
1650     {
1651         this.clearLineHighlight();
1652         this._highlightedLine = lineNumber;
1653         this.revealLine(lineNumber);
1654
1655         if (!this._readOnly)
1656             this._restoreSelection(WebInspector.TextRange.createFromLocation(lineNumber, 0), false);
1657
1658         this.addDecoration(lineNumber, "webkit-highlighted-line");
1659     },
1660
1661     clearLineHighlight: function()
1662     {
1663         if (typeof this._highlightedLine === "number") {
1664             this.removeDecoration(this._highlightedLine, "webkit-highlighted-line");
1665             delete this._highlightedLine;
1666         }
1667     },
1668
1669     _freeCachedElements: function()
1670     {
1671         this._cachedSpans = [];
1672         this._cachedTextNodes = [];
1673         this._cachedRows = [];
1674     },
1675
1676     /**
1677      * @param {boolean} redo
1678      * @return {boolean}
1679      */
1680     _handleUndoRedo: function(redo)
1681     {
1682         if (this.readOnly())
1683             return false;
1684
1685         this.beginUpdates();
1686
1687         var range = redo ? this._textModel.redo() : this._textModel.undo();
1688
1689         this.endUpdates();
1690
1691         // Restore location post-repaint.
1692         if (range)
1693             this._restoreSelection(range, true);
1694
1695         return true;
1696     },
1697
1698     /**
1699      * @param {boolean} shiftKey
1700      * @return {boolean}
1701      */
1702     _handleTabKeyPress: function(shiftKey)
1703     {
1704         if (this.readOnly())
1705             return false;
1706
1707         var selection = this.selection();
1708         if (!selection)
1709             return false;
1710
1711         var range = selection.normalize();
1712
1713         this.beginUpdates();
1714
1715         var newRange;
1716         var rangeWasEmpty = range.isEmpty();
1717         if (shiftKey)
1718             newRange = this._textModel.unindentLines(range);
1719         else {
1720             if (rangeWasEmpty)
1721                 newRange = this._textModel.editRange(range, WebInspector.settings.textEditorIndent.get());
1722             else
1723                 newRange = this._textModel.indentLines(range);
1724         }
1725
1726         this.endUpdates();
1727         if (rangeWasEmpty)
1728             newRange.startColumn = newRange.endColumn;
1729         this._restoreSelection(newRange, true);
1730         return true;
1731     },
1732
1733     _handleEnterKey: function()
1734     {
1735         if (this.readOnly())
1736             return false;
1737
1738         var range = this.selection();
1739         if (!range)
1740             return false;
1741
1742         range = range.normalize();
1743
1744         if (range.endColumn === 0)
1745             return false;
1746
1747         var line = this._textModel.line(range.startLine);
1748         var linePrefix = line.substring(0, range.startColumn);
1749         var indentMatch = linePrefix.match(/^\s+/);
1750         var currentIndent = indentMatch ? indentMatch[0] : "";
1751
1752         var textEditorIndent = WebInspector.settings.textEditorIndent.get();
1753         var indent = WebInspector.TextEditorModel.endsWithBracketRegex.test(linePrefix) ? currentIndent + textEditorIndent : currentIndent;
1754
1755         if (!indent)
1756             return false;
1757
1758         this.beginDomUpdates();
1759
1760         var lineBreak = this._textModel.lineBreak;
1761         var newRange;
1762         if (range.isEmpty() && line.substr(range.endColumn - 1, 2) === '{}') {
1763             // {|}
1764             // becomes
1765             // {
1766             //     |
1767             // }
1768             newRange = this._textModel.editRange(range, lineBreak + indent + lineBreak + currentIndent);
1769             newRange.endLine--;
1770             newRange.endColumn += textEditorIndent.length;
1771         } else
1772             newRange = this._textModel.editRange(range, lineBreak + indent);
1773
1774         this.endDomUpdates();
1775         this._restoreSelection(newRange.collapseToEnd(), true);
1776
1777         return true;
1778     },
1779
1780     /**
1781      * @param {number} lineNumber
1782      * @param {number} chunkNumber
1783      * @param {boolean=} createSuffixChunk
1784      * @return {Object}
1785      */
1786     splitChunkOnALine: function(lineNumber, chunkNumber, createSuffixChunk)
1787     {
1788         var selection = this.selection();
1789         var chunk = WebInspector.TextEditorChunkedPanel.prototype.splitChunkOnALine.call(this, lineNumber, chunkNumber, createSuffixChunk);
1790         this._restoreSelection(selection);
1791         return chunk;
1792     },
1793
1794     beginDomUpdates: function()
1795     {
1796         if (!this._domUpdateCoalescingLevel)
1797             this._detachMutationObserver();
1798         WebInspector.TextEditorChunkedPanel.prototype.beginDomUpdates.call(this);
1799     },
1800
1801     endDomUpdates: function()
1802     {
1803         WebInspector.TextEditorChunkedPanel.prototype.endDomUpdates.call(this);
1804         if (!this._domUpdateCoalescingLevel)
1805             this._attachMutationObserver();
1806     },
1807
1808     buildChunks: function()
1809     {
1810         for (var i = 0; i < this._textModel.linesCount; ++i)
1811             this._textModel.removeAttribute(i, "highlight");
1812
1813         WebInspector.TextEditorChunkedPanel.prototype.buildChunks.call(this);
1814     },
1815
1816     /**
1817      * @param {number} startLine
1818      * @param {number} endLine
1819      * @return {WebInspector.TextEditorMainChunk}
1820      */
1821     createNewChunk: function(startLine, endLine)
1822     {
1823         return new WebInspector.TextEditorMainChunk(this, startLine, endLine);
1824     },
1825
1826     /**
1827      * @param {number} fromIndex
1828      * @param {number} toIndex
1829      */
1830     expandChunks: function(fromIndex, toIndex)
1831     {
1832         var lastChunk = this._textChunks[toIndex - 1];
1833         var lastVisibleLine = lastChunk.startLine + lastChunk.linesCount;
1834
1835         var selection = this.selection();
1836
1837         this._muteHighlightListener = true;
1838         this._highlighter.highlight(lastVisibleLine);
1839         delete this._muteHighlightListener;
1840
1841         WebInspector.TextEditorChunkedPanel.prototype.expandChunks.call(this, fromIndex, toIndex);
1842
1843         this._restoreSelection(selection);
1844     },
1845
1846     /**
1847      * @param {number} fromLine
1848      * @param {number} toLine
1849      */
1850     _highlightDataReady: function(fromLine, toLine)
1851     {
1852         if (this._muteHighlightListener)
1853             return;
1854         this._paintLines(fromLine, toLine, true /*restoreSelection*/);
1855     },
1856
1857     /**
1858      * @param {number} fromLine
1859      * @param {number} toLine
1860      * @param {boolean=} restoreSelection
1861      */
1862     _paintLines: function(fromLine, toLine, restoreSelection)
1863     {
1864         var lineRows = [];
1865         var chunk;
1866         for (var lineNumber = fromLine; lineNumber < toLine; ++lineNumber) {
1867             if (!chunk || lineNumber < chunk.startLine || lineNumber >= chunk.startLine + chunk.linesCount)
1868                 chunk = this.chunkForLine(lineNumber);
1869             var lineRow = chunk.expandedLineRow(lineNumber);
1870             if (!lineRow)
1871                 continue;
1872             lineRows.push(lineRow);
1873         }
1874         if (lineRows.length === 0)
1875             return;
1876
1877         var selection;
1878         if (restoreSelection)
1879             selection = this.selection();
1880
1881         this._paintLineRows(lineRows);
1882
1883         if (restoreSelection)
1884             this._restoreSelection(selection);
1885     },
1886
1887     /**
1888      * @param {Array.<Element>} lineRows
1889      */
1890     _paintLineRows: function(lineRows)
1891     {
1892         var highlight = {};
1893         this.beginDomUpdates();
1894         for(var i = 0; i < this._highlightDescriptors.length; ++i) {
1895             var highlightDescriptor = this._highlightDescriptors[i];
1896             this._measureHighlightDescriptor(highlight, lineRows, highlightDescriptor);
1897         }
1898
1899         for(var i = 0; i < lineRows.length; ++i)
1900             this._paintLine(lineRows[i], highlight[lineRows[i].lineNumber]);
1901
1902         this.endDomUpdates();
1903     },
1904
1905     /**
1906      * @param {Object.<number, Array.<WebInspector.TextEditorMainPanel.LineOverlayHighlight>>} highlight
1907      * @param {Array.<Element>} lineRows
1908      * @param {WebInspector.TextEditorMainPanel.HighlightDescriptor} highlightDescriptor
1909      */
1910     _measureHighlightDescriptor: function(highlight, lineRows, highlightDescriptor)
1911     {
1912         var rowsToMeasure = [];
1913         for(var i = 0; i < lineRows.length; ++i) {
1914             var lineRow = lineRows[i];
1915             var line = this._textModel.line(lineRow.lineNumber);
1916             var ranges = highlightDescriptor.rangesForLine(lineRow.lineNumber, line);
1917             if (ranges.length === 0)
1918                 continue;
1919
1920             this._renderRanges(lineRow, line, ranges);
1921             rowsToMeasure.push(lineRow);
1922         }
1923
1924         for(var i = 0; i < rowsToMeasure.length; ++i) {
1925             var lineRow = rowsToMeasure[i];
1926             var lineNumber = lineRow.lineNumber;
1927             var metrics = this._measureSpans(lineRow);
1928
1929             if (!highlight[lineNumber])
1930                 highlight[lineNumber] = [];
1931
1932             highlight[lineNumber].push(new WebInspector.TextEditorMainPanel.LineOverlayHighlight(metrics, highlightDescriptor.cssClass()));
1933         }
1934     },
1935
1936     /**
1937      * @param {Element} lineRow
1938      * @return {Array.<WebInspector.TextEditorMainPanel.ElementMetrics>}
1939      */
1940     _measureSpans: function(lineRow)
1941     {
1942         var spans = lineRow.getElementsByTagName("span");
1943         var metrics = [];
1944         for(var i = 0; i < spans.length; ++i)
1945             metrics.push(new WebInspector.TextEditorMainPanel.ElementMetrics(spans[i]));
1946         return metrics;
1947     },
1948
1949     /**
1950      * @param {Element} lineRow
1951      * @param {WebInspector.TextEditorMainPanel.LineOverlayHighlight} highlight
1952      */
1953     _appendOverlayHighlight: function(lineRow, highlight)
1954     {
1955         var metrics = highlight.metrics;
1956         var cssClass = highlight.cssClass;
1957         for(var i = 0; i < metrics.length; ++i) {
1958             var highlightSpan = document.createElement("span");
1959             highlightSpan._isOverlayHighlightElement = true;
1960             highlightSpan.addStyleClass(cssClass);
1961             highlightSpan.style.left = metrics[i].left + "px";
1962             highlightSpan.style.width = metrics[i].width + "px";
1963             highlightSpan.style.height = metrics[i].height + "px";
1964             highlightSpan.addStyleClass("text-editor-overlay-highlight");
1965             lineRow.insertBefore(highlightSpan, lineRow.decorationsElement);
1966         }
1967     },
1968
1969     /**
1970      * @param {Element} lineRow
1971      * @param {string} line
1972      * @param {Array.<{startColumn: number, endColumn: number, token: ?string}>} ranges
1973      */
1974     _renderRanges: function(lineRow, line, ranges)
1975     {
1976         var decorationsElement = lineRow.decorationsElement;
1977
1978         if (!decorationsElement)
1979             lineRow.removeChildren();
1980         else {
1981             while (true) {
1982                 var child = lineRow.firstChild;
1983                 if (!child || child === decorationsElement)
1984                     break;
1985                 lineRow.removeChild(child);
1986             }
1987         }
1988
1989         if (!line)
1990             lineRow.insertBefore(document.createElement("br"), decorationsElement);
1991
1992         var plainTextStart = 0;
1993         for(var i = 0; i < ranges.length; i++) {
1994             var rangeStart = ranges[i].startColumn;
1995             var rangeEnd = ranges[i].endColumn;
1996             var cssClass = ranges[i].token ? "webkit-" + ranges[i].token : "";
1997
1998             if (plainTextStart < rangeStart) {
1999                 this._insertTextNodeBefore(lineRow, decorationsElement, line.substring(plainTextStart, rangeStart));
2000             }
2001             this._insertSpanBefore(lineRow, decorationsElement, line.substring(rangeStart, rangeEnd + 1), cssClass);
2002             plainTextStart = rangeEnd + 1;
2003         }
2004         if (plainTextStart < line.length) {
2005             this._insertTextNodeBefore(lineRow, decorationsElement, line.substring(plainTextStart, line.length));
2006         }
2007     },
2008
2009     /**
2010      * @param {Element} lineRow
2011      * @param {Array.<WebInspector.TextEditorMainPanel.LineOverlayHighlight>} overlayHighlight
2012      */
2013     _paintLine: function(lineRow, overlayHighlight)
2014     {
2015         var lineNumber = lineRow.lineNumber;
2016
2017         this.beginDomUpdates();
2018         try {
2019             var syntaxHighlight = this._textModel.getAttribute(lineNumber, "highlight");
2020             if (!syntaxHighlight)
2021                 return;
2022
2023             var line = this._textModel.line(lineNumber);
2024             var ranges = syntaxHighlight.ranges;
2025             this._renderRanges(lineRow, line, ranges);
2026
2027             if (overlayHighlight)
2028                 for(var i = 0; i < overlayHighlight.length; ++i)
2029                     this._appendOverlayHighlight(lineRow, overlayHighlight[i]);
2030         } finally {
2031             if (this._rangeToMark && this._rangeToMark.startLine === lineNumber)
2032                 this._markedRangeElement = WebInspector.highlightSearchResult(lineRow, this._rangeToMark.startColumn, this._rangeToMark.endColumn - this._rangeToMark.startColumn);
2033             this.endDomUpdates();
2034         }
2035     },
2036
2037     /**
2038      * @param {Element} lineRow
2039      */
2040     _releaseLinesHighlight: function(lineRow)
2041     {
2042         if (!lineRow)
2043             return;
2044         if ("spans" in lineRow) {
2045             var spans = lineRow.spans;
2046             for (var j = 0; j < spans.length; ++j)
2047                 this._cachedSpans.push(spans[j]);
2048             delete lineRow.spans;
2049         }
2050         if ("textNodes" in lineRow) {
2051             var textNodes = lineRow.textNodes;
2052             for (var j = 0; j < textNodes.length; ++j)
2053                 this._cachedTextNodes.push(textNodes[j]);
2054             delete lineRow.textNodes;
2055         }
2056         this._cachedRows.push(lineRow);
2057     },
2058
2059     /**
2060      * @param {?Node=} lastUndamagedLineRow
2061      * @return {WebInspector.TextRange}
2062      */
2063     selection: function(lastUndamagedLineRow)
2064     {
2065         var selection = window.getSelection();
2066         if (!selection.rangeCount)
2067             return null;
2068         // Selection may be outside of the editor.
2069         if (!this._container.isAncestor(selection.anchorNode) || !this._container.isAncestor(selection.focusNode))
2070             return null;
2071         // Selection may be inside one of decorations.
2072         if (selection.focusNode.enclosingNodeOrSelfWithClass("webkit-line-decorations", this._container))
2073             return null;
2074         var start = this._selectionToPosition(selection.anchorNode, selection.anchorOffset, lastUndamagedLineRow);
2075         var end = selection.isCollapsed ? start : this._selectionToPosition(selection.focusNode, selection.focusOffset, lastUndamagedLineRow);
2076         return new WebInspector.TextRange(start.line, start.column, end.line, end.column);
2077     },
2078
2079     lastSelection: function()
2080     {
2081         return this._lastSelection;
2082     },
2083
2084     /**
2085      * @param {boolean=} scrollIntoView
2086      */
2087     _restoreSelection: function(range, scrollIntoView)
2088     {
2089         if (!range)
2090             return;
2091
2092         var start = this._positionToSelection(range.startLine, range.startColumn);
2093         var end = range.isEmpty() ? start : this._positionToSelection(range.endLine, range.endColumn);
2094         window.getSelection().setBaseAndExtent(start.container, start.offset, end.container, end.offset);
2095
2096         if (scrollIntoView) {
2097             for (var node = end.container; node; node = node.parentElement) {
2098                 if (node.scrollIntoViewIfNeeded) {
2099                     node.scrollIntoViewIfNeeded();
2100                     break;
2101                 }
2102             }
2103         }
2104         this._lastSelection = range;
2105     },
2106
2107     /**
2108      * @param {Node} container
2109      * @param {number} offset
2110      * @param {?Node=} lastUndamagedLineRow
2111      * @return {{line: number, column: number}}
2112      */
2113     _selectionToPosition: function(container, offset, lastUndamagedLineRow)
2114     {
2115         if (container === this._container && offset === 0)
2116             return { line: 0, column: 0 };
2117         if (container === this._container && offset === 1)
2118             return { line: this._textModel.linesCount - 1, column: this._textModel.lineLength(this._textModel.linesCount - 1) };
2119
2120         // This method can be called on the damaged DOM (when DOM does not match model).
2121         // We need to start counting lines from the first undamaged line if it is given.
2122         var lineNumber;
2123         var column = 0;
2124         var node;
2125         var scopeNode;
2126         if (lastUndamagedLineRow === null) {
2127              // Last undamaged row is given, but is null - force traverse from the beginning
2128             node = this._container.firstChild;
2129             scopeNode = this._container;
2130             lineNumber = 0;
2131         } else {
2132             var lineRow = this._enclosingLineRowOrSelf(container);
2133             if (!lastUndamagedLineRow || (typeof lineRow.lineNumber === "number" && lineRow.lineNumber <= lastUndamagedLineRow.lineNumber)) {
2134                 // DOM is consistent (or we belong to the first damaged row)- lookup the row we belong to and start with it.
2135                 node = lineRow;
2136                 scopeNode = node;
2137                 lineNumber = node.lineNumber;
2138             } else {
2139                 // Start with the node following undamaged row. It corresponds to lineNumber + 1.
2140                 node = lastUndamagedLineRow.nextSibling;
2141                 scopeNode = this._container;
2142                 lineNumber = lastUndamagedLineRow.lineNumber + 1;
2143             }
2144         }
2145
2146         // Fast return the line start.
2147         if (container === node && offset === 0)
2148             return { line: lineNumber, column: 0 };
2149
2150         // Traverse text and increment lineNumber / column.
2151         for (; node && node !== container; node = node.traverseNextNode(scopeNode)) {
2152             if (node.nodeName.toLowerCase() === "br") {
2153                 lineNumber++;
2154                 column = 0;
2155             } else if (node.nodeType === Node.TEXT_NODE) {
2156                 var text = node.textContent;
2157                 for (var i = 0; i < text.length; ++i) {
2158                     if (text.charAt(i) === "\n") {
2159                         lineNumber++;
2160                         column = 0;
2161                     } else
2162                         column++;
2163                 }
2164             }
2165         }
2166
2167         // We reached our container node, traverse within itself until we reach given offset.
2168         if (node === container && offset) {
2169             var text = node.textContent;
2170             // In case offset == 1 and lineRow is a chunk div, we need to traverse it all.
2171             var textOffset = (node._chunk && offset === 1) ? text.length : offset;
2172             for (var i = 0; i < textOffset; ++i) {
2173                 if (text.charAt(i) === "\n") {
2174                     lineNumber++;
2175                     column = 0;
2176                 } else
2177                     column++;
2178             }
2179         }
2180         return { line: lineNumber, column: column };
2181     },
2182
2183     /**
2184      * @param {number} line
2185      * @param {number} column
2186      * @return {{container: Element, offset: number}}
2187      */
2188     _positionToSelection: function(line, column)
2189     {
2190         var chunk = this.chunkForLine(line);
2191         // One-lined collapsed chunks may still stay highlighted.
2192         var lineRow = chunk.linesCount === 1 ? chunk.element : chunk.expandedLineRow(line);
2193         if (lineRow)
2194             var rangeBoundary = lineRow.rangeBoundaryForOffset(column);
2195         else {
2196             var offset = column;
2197             for (var i = chunk.startLine; i < line && i < this._textModel.linesCount; ++i)
2198                 offset += this._textModel.lineLength(i) + 1; // \n
2199             lineRow = chunk.element;
2200             if (lineRow.firstChild)
2201                 var rangeBoundary = { container: lineRow.firstChild, offset: offset };
2202             else
2203                 var rangeBoundary = { container: lineRow, offset: 0 };
2204         }
2205         return rangeBoundary;
2206     },
2207
2208     /**
2209      * @param {Node} element
2210      * @return {?Node}
2211      */
2212     _enclosingLineRowOrSelf: function(element)
2213     {
2214         var lineRow = element.enclosingNodeOrSelfWithClass("webkit-line-content");
2215         if (lineRow)
2216             return lineRow;
2217
2218         for (lineRow = element; lineRow; lineRow = lineRow.parentElement) {
2219             if (lineRow.parentElement === this._container)
2220                 return lineRow;
2221         }
2222         return null;
2223     },
2224
2225     /**
2226      * @param {Element} element
2227      * @param {Element} oldChild
2228      * @param {string} content
2229      * @param {string} className
2230      */
2231     _insertSpanBefore: function(element, oldChild, content, className)
2232     {
2233         if (className === "html-resource-link" || className === "html-external-link") {
2234             element.insertBefore(this._createLink(content, className === "html-external-link"), oldChild);
2235             return;
2236         }
2237
2238         var span = this._cachedSpans.pop() || document.createElement("span");
2239         span.className = className;
2240         if (WebInspector.FALSE) // For paint debugging.
2241             span.addStyleClass("debug-fadeout");
2242         span.textContent = content;
2243         element.insertBefore(span, oldChild);
2244         if (!("spans" in element))
2245             element.spans = [];
2246         element.spans.push(span);
2247     },
2248
2249     /**
2250      * @param {Element} element
2251      * @param {Element} oldChild
2252      * @param {string} text
2253      */
2254     _insertTextNodeBefore: function(element, oldChild, text)
2255     {
2256         var textNode = this._cachedTextNodes.pop();
2257         if (textNode)
2258             textNode.nodeValue = text;
2259         else
2260             textNode = document.createTextNode(text);
2261         element.insertBefore(textNode, oldChild);
2262         if (!("textNodes" in element))
2263             element.textNodes = [];
2264         element.textNodes.push(textNode);
2265     },
2266
2267     /**
2268      * @param {string} content
2269      * @param {boolean} isExternal
2270      * @return {Element}
2271      */
2272     _createLink: function(content, isExternal)
2273     {
2274         var quote = content.charAt(0);
2275         if (content.length > 1 && (quote === "\"" || quote === "'"))
2276             content = content.substring(1, content.length - 1);
2277         else
2278             quote = null;
2279
2280         var span = document.createElement("span");
2281         span.className = "webkit-html-attribute-value";
2282         if (quote)
2283             span.appendChild(document.createTextNode(quote));
2284         span.appendChild(this._delegate.createLink(content, isExternal));
2285         if (quote)
2286             span.appendChild(document.createTextNode(quote));
2287         return span;
2288     },
2289
2290     /**
2291      * @param {Array.<WebKitMutation>} mutations
2292      */
2293     _handleMutations: function(mutations)
2294     {
2295         if (this._readOnly) {
2296             delete this._keyDownCode;
2297             return;
2298         }
2299
2300         // Annihilate noop BR addition + removal that takes place upon line removal.
2301         var filteredMutations = mutations.slice();
2302         var addedBRs = new Map();
2303         for (var i = 0; i < mutations.length; ++i) {
2304             var mutation = mutations[i];
2305             if (mutation.type !== "childList")
2306                 continue;
2307             if (mutation.addedNodes.length === 1 && mutation.addedNodes[0].nodeName === "BR")
2308                 addedBRs.put(mutation.addedNodes[0], mutation);
2309             else if (mutation.removedNodes.length === 1 && mutation.removedNodes[0].nodeName === "BR") {
2310                 var noopMutation = addedBRs.get(mutation.removedNodes[0]);
2311                 if (noopMutation) {
2312                     filteredMutations.remove(mutation);
2313                     filteredMutations.remove(noopMutation);
2314                 }
2315             }
2316         }
2317
2318         var dirtyLines;
2319         for (var i = 0; i < filteredMutations.length; ++i) {
2320             var mutation = filteredMutations[i];
2321             var changedNodes = [];
2322             if (mutation.type === "childList" && mutation.addedNodes.length)
2323                 changedNodes = Array.prototype.slice.call(mutation.addedNodes);
2324             else if (mutation.type === "childList" && mutation.removedNodes.length)
2325                 changedNodes = Array.prototype.slice.call(mutation.removedNodes);
2326             changedNodes.push(mutation.target);
2327
2328             for (var j = 0; j < changedNodes.length; ++j) {
2329                 var lines = this._collectDirtyLines(mutation, changedNodes[j]);
2330                 if (!lines)
2331                     continue;
2332                 if (!dirtyLines) {
2333                     dirtyLines = lines;
2334                     continue;
2335                 }
2336                 dirtyLines.start = Math.min(dirtyLines.start, lines.start);
2337                 dirtyLines.end = Math.max(dirtyLines.end, lines.end);
2338             }
2339         }
2340         if (dirtyLines) {
2341             delete this._rangeToMark;
2342             this._applyDomUpdates(dirtyLines);
2343         }
2344
2345         this._assertDOMMatchesTextModel();
2346
2347         delete this._keyDownCode;
2348     },
2349
2350     /**
2351      * @param {WebKitMutation} mutation
2352      * @param {Node} target
2353      * @return {?Object}
2354      */
2355     _collectDirtyLines: function(mutation, target)
2356     {
2357         var lineRow = this._enclosingLineRowOrSelf(target);
2358         if (!lineRow)
2359             return null;
2360
2361         if (lineRow.decorationsElement && lineRow.decorationsElement.isSelfOrAncestor(target)) {
2362             if (this._syncDecorationsForLineListener)
2363                 this._syncDecorationsForLineListener(lineRow.lineNumber);
2364             return null;
2365         }
2366
2367         if (typeof lineRow.lineNumber !== "number")
2368             return null;
2369
2370         var startLine = lineRow.lineNumber;
2371         var endLine = lineRow._chunk ? lineRow._chunk.endLine - 1 : lineRow.lineNumber;
2372         return { start: startLine, end: endLine };
2373     },
2374
2375     /**
2376      * @param {Object} dirtyLines
2377      */
2378     _applyDomUpdates: function(dirtyLines)
2379     {
2380         var lastUndamagedLineNumber = dirtyLines.start - 1; // Can be -1
2381         var firstUndamagedLineNumber = dirtyLines.end + 1; // Can be this._textModel.linesCount
2382
2383         var lastUndamagedLineChunk = lastUndamagedLineNumber >= 0 ? this._textChunks[this.chunkNumberForLine(lastUndamagedLineNumber)] : null;
2384         var firstUndamagedLineChunk = firstUndamagedLineNumber < this._textModel.linesCount ? this._textChunks[this.chunkNumberForLine(firstUndamagedLineNumber)] : null;
2385
2386         var collectLinesFromNode = lastUndamagedLineChunk ? lastUndamagedLineChunk.lineRowContainingLine(lastUndamagedLineNumber) : null;
2387         var collectLinesToNode = firstUndamagedLineChunk ? firstUndamagedLineChunk.lineRowContainingLine(firstUndamagedLineNumber) : null;
2388         var lines = this._collectLinesFromDOM(collectLinesFromNode, collectLinesToNode);
2389
2390         var startLine = dirtyLines.start;
2391         var endLine = dirtyLines.end;
2392
2393         var editInfo = this._guessEditRangeBasedOnSelection(startLine, endLine, lines);
2394         if (!editInfo) {
2395             if (WebInspector.debugDefaultTextEditor)
2396                 console.warn("Falling back to expensive edit");
2397             var range = new WebInspector.TextRange(startLine, 0, endLine, this._textModel.lineLength(endLine));
2398             if (!lines.length) {
2399                 // Entire damaged area has collapsed. Replace everything between start and end lines with nothing.
2400                 editInfo = new WebInspector.DefaultTextEditor.EditInfo(this._textModel.growRangeRight(range), "");
2401             } else
2402                 editInfo = new WebInspector.DefaultTextEditor.EditInfo(range, lines.join("\n"));
2403         }
2404
2405         var selection = this.selection(collectLinesFromNode);
2406
2407         // Unindent after block
2408         if (editInfo.text === "}" && editInfo.range.isEmpty() && selection.isEmpty() && !this._textModel.line(editInfo.range.endLine).trim()) {
2409             var offset = this._closingBlockOffset(editInfo.range);
2410             if (offset >= 0) {
2411                 editInfo.range.startColumn = offset;
2412                 selection.startColumn = offset + 1;
2413                 selection.endColumn = offset + 1;
2414             }
2415         }
2416
2417         this._textModel.editRange(editInfo.range, editInfo.text);
2418         this._restoreSelection(selection);
2419     },
2420
2421     /**
2422      * @param {number} startLine
2423      * @param {number} endLine
2424      * @param {Array.<string>} lines
2425      * @return {?WebInspector.DefaultTextEditor.EditInfo}
2426      */
2427     _guessEditRangeBasedOnSelection: function(startLine, endLine, lines)
2428     {
2429         // Analyze input data
2430         var textInputData = this._textInputData;
2431         delete this._textInputData;
2432         var isBackspace = this._keyDownCode === WebInspector.KeyboardShortcut.Keys.Backspace.code;
2433         var isDelete = this._keyDownCode === WebInspector.KeyboardShortcut.Keys.Delete.code;
2434
2435         if (!textInputData && (isDelete || isBackspace))
2436             textInputData = "";
2437
2438         // Return if there is no input data or selection
2439         if (typeof textInputData === "undefined" || !this._lastSelection)
2440             return null;
2441
2442         // Adjust selection based on the keyboard actions (grow for backspace, etc.).
2443         textInputData = textInputData || "";
2444         var range = this._lastSelection.normalize();
2445         if (isBackspace && range.isEmpty())
2446             range = this._textModel.growRangeLeft(range);
2447         else if (isDelete && range.isEmpty())
2448             range = this._textModel.growRangeRight(range);
2449
2450         // Test that selection intersects damaged lines
2451         if (startLine > range.endLine || endLine < range.startLine)
2452             return null;
2453
2454         var replacementLineCount = textInputData.split("\n").length - 1;
2455         var lineCountDelta = replacementLineCount - range.linesCount;
2456         if (startLine + lines.length - endLine - 1 !== lineCountDelta)
2457             return null;
2458
2459         // Clone text model of the size that fits both: selection before edit and the damaged lines after edit.
2460         var cloneFromLine = Math.min(range.startLine, startLine);
2461         var postLastLine = startLine + lines.length + lineCountDelta;
2462         var cloneToLine = Math.min(Math.max(postLastLine, range.endLine) + 1, this._textModel.linesCount);
2463         var domModel = this._textModel.slice(cloneFromLine, cloneToLine);
2464         domModel.editRange(range.shift(-cloneFromLine), textInputData);
2465
2466         // Then we'll test if this new model matches the DOM lines.
2467         for (var i = 0; i < lines.length; ++i) {
2468             if (domModel.line(i + startLine - cloneFromLine) !== lines[i])
2469                 return null;
2470         }
2471         return new WebInspector.DefaultTextEditor.EditInfo(range, textInputData);
2472     },
2473
2474     _assertDOMMatchesTextModel: function()
2475     {
2476         if (!WebInspector.debugDefaultTextEditor)
2477             return;
2478
2479         console.assert(this.element.innerText === this._textModel.text() + "\n", "DOM does not match model.");
2480         for (var lineRow = this._container.firstChild; lineRow; lineRow = lineRow.nextSibling) {
2481             var lineNumber = lineRow.lineNumber;
2482             if (typeof lineNumber !== "number") {
2483                 console.warn("No line number on line row");
2484                 continue;
2485             }
2486             if (lineRow._chunk) {
2487                 var chunk = lineRow._chunk;
2488                 console.assert(lineNumber === chunk.startLine);
2489                 var chunkText = this._textModel.copyRange(new WebInspector.TextRange(chunk.startLine, 0, chunk.endLine - 1, this._textModel.lineLength(chunk.endLine - 1)));
2490                 if (chunkText !== lineRow.textContent)
2491                     console.warn("Chunk is not matching: %d %O", lineNumber, lineRow);
2492             } else if (this._textModel.line(lineNumber) !== lineRow.textContent)
2493                 console.warn("Line is not matching: %d %O", lineNumber, lineRow);
2494         }
2495     },
2496
2497     /**
2498      * @param {WebInspector.TextRange} oldRange
2499      * @return {number}
2500      */
2501     _closingBlockOffset: function(oldRange)
2502     {
2503         var leftBrace = this._braceMatcher.findLeftCandidate(oldRange.startLine, oldRange.startColumn);
2504         if (!leftBrace || leftBrace.token !== "block-start")
2505             return -1;
2506         var lineContent = this._textModel.line(leftBrace.lineNumber);
2507         return lineContent.length - lineContent.trimLeft().length;
2508     },
2509
2510     /**
2511      * @param {WebInspector.TextRange} oldRange
2512      * @param {WebInspector.TextRange} newRange
2513      */
2514     textChanged: function(oldRange, newRange)
2515     {
2516         this.beginDomUpdates();
2517         this._removeDecorationsInRange(oldRange);
2518         this._updateChunksForRanges(oldRange, newRange);
2519         this._updateHighlightsForRange(newRange);
2520         this.endDomUpdates();
2521     },
2522
2523     /**
2524      * @param {WebInspector.TextRange} range
2525      */
2526     _removeDecorationsInRange: function(range)
2527     {
2528         for (var i = this.chunkNumberForLine(range.startLine); i < this._textChunks.length; ++i) {
2529             var chunk = this._textChunks[i];
2530             if (chunk.startLine > range.endLine)
2531                 break;
2532             chunk.removeAllDecorations();
2533         }
2534     },
2535
2536     /**
2537      * @param {WebInspector.TextRange} oldRange
2538      * @param {WebInspector.TextRange} newRange
2539      */
2540     _updateChunksForRanges: function(oldRange, newRange)
2541     {
2542         var firstDamagedChunkNumber = this.chunkNumberForLine(oldRange.startLine);
2543         var lastDamagedChunkNumber = firstDamagedChunkNumber;
2544         while (lastDamagedChunkNumber + 1 < this._textChunks.length) {
2545             if (this._textChunks[lastDamagedChunkNumber + 1].startLine > oldRange.endLine)
2546                 break;
2547             ++lastDamagedChunkNumber;
2548         }
2549
2550         var firstDamagedChunk = this._textChunks[firstDamagedChunkNumber];
2551         var lastDamagedChunk = this._textChunks[lastDamagedChunkNumber];
2552
2553         var linesDiff = newRange.linesCount - oldRange.linesCount;
2554
2555         // First, detect chunks that have not been modified and simply shift them.
2556         if (linesDiff) {
2557             for (var chunkNumber = lastDamagedChunkNumber + 1; chunkNumber < this._textChunks.length; ++chunkNumber)
2558                 this._textChunks[chunkNumber].startLine += linesDiff;
2559         }
2560
2561         // Remove damaged chunks from DOM and from textChunks model.
2562         var lastUndamagedChunk = firstDamagedChunkNumber > 0 ? this._textChunks[firstDamagedChunkNumber - 1] : null;
2563         var firstUndamagedChunk = lastDamagedChunkNumber + 1 < this._textChunks.length ? this._textChunks[lastDamagedChunkNumber + 1] : null;
2564
2565         var removeDOMFromNode = lastUndamagedChunk ? lastUndamagedChunk.lastElement().nextSibling : this._container.firstChild;
2566         var removeDOMToNode = firstUndamagedChunk ? firstUndamagedChunk.firstElement() : null;
2567
2568         // Fast case - patch single expanded chunk that did not grow / shrink during edit.
2569         if (!linesDiff && firstDamagedChunk === lastDamagedChunk && firstDamagedChunk._expandedLineRows) {
2570             var lastUndamagedLineRow = lastDamagedChunk.expandedLineRow(oldRange.startLine - 1);
2571             var firstUndamagedLineRow = firstDamagedChunk.expandedLineRow(oldRange.endLine + 1);
2572             var localRemoveDOMFromNode = lastUndamagedLineRow ? lastUndamagedLineRow.nextSibling : removeDOMFromNode;
2573             var localRemoveDOMToNode = firstUndamagedLineRow || removeDOMToNode;
2574             removeSubsequentNodes(localRemoveDOMFromNode, localRemoveDOMToNode);
2575             for (var i = newRange.startLine; i < newRange.endLine + 1; ++i) {
2576                 var row = firstDamagedChunk._createRow(i);
2577                 firstDamagedChunk._expandedLineRows[i - firstDamagedChunk.startLine] = row;
2578                 this._container.insertBefore(row, localRemoveDOMToNode);
2579             }
2580             firstDamagedChunk.updateCollapsedLineRow();
2581             this._assertDOMMatchesTextModel();
2582             return;
2583         }
2584
2585         removeSubsequentNodes(removeDOMFromNode, removeDOMToNode);
2586         this._textChunks.splice(firstDamagedChunkNumber, lastDamagedChunkNumber - firstDamagedChunkNumber + 1);
2587
2588         // Compute damaged chunks span
2589         var startLine = firstDamagedChunk.startLine;
2590         var endLine = lastDamagedChunk.endLine + linesDiff;
2591         var lineSpan = endLine - startLine;
2592
2593         // Re-create chunks for damaged area.
2594         var insertionIndex = firstDamagedChunkNumber;
2595         var chunkSize = Math.ceil(lineSpan / Math.ceil(lineSpan / this._defaultChunkSize));
2596
2597         for (var i = startLine; i < endLine; i += chunkSize) {
2598             var chunk = this.createNewChunk(i, Math.min(endLine, i + chunkSize));
2599             this._textChunks.splice(insertionIndex++, 0, chunk);
2600             this._container.insertBefore(chunk.element, removeDOMToNode);
2601         }
2602
2603         this._assertDOMMatchesTextModel();
2604     },
2605
2606     /**
2607      * @param {WebInspector.TextRange} range
2608      */
2609     _updateHighlightsForRange: function(range)
2610     {
2611         var visibleFrom = this.scrollTop();
2612         var visibleTo = visibleFrom + this.clientHeight();
2613
2614         var result = this.findVisibleChunks(visibleFrom, visibleTo);
2615         var chunk = this._textChunks[result.end - 1];
2616         var lastVisibleLine = chunk.startLine + chunk.linesCount;
2617
2618         lastVisibleLine = Math.max(lastVisibleLine, range.endLine + 1);
2619         lastVisibleLine = Math.min(lastVisibleLine, this._textModel.linesCount);
2620
2621         var updated = this._highlighter.updateHighlight(range.startLine, lastVisibleLine);
2622         if (!updated) {
2623             // Highlights for the chunks below are invalid, so just collapse them.
2624             for (var i = this.chunkNumberForLine(range.startLine); i < this._textChunks.length; ++i)
2625                 this._textChunks[i].collapse();
2626         }
2627
2628         this.repaintAll();
2629     },
2630
2631     /**
2632      * @param {Node} from
2633      * @param {Node} to
2634      * @return {Array.<string>}
2635      */
2636     _collectLinesFromDOM: function(from, to)
2637     {
2638         var textContents = [];
2639         var hasContent = false;
2640         for (var node = from ? from.nextSibling : this._container; node && node !== to; node = node.traverseNextNode(this._container)) {
2641             // Skip all children of the decoration container and overlay highlight spans.
2642             while (node && node !== to && (node._isDecorationsElement || node._isOverlayHighlightElement))
2643                 node = node.nextSibling;
2644             if (!node || node === to)
2645                 break;
2646
2647             hasContent = true;
2648             if (node.nodeName.toLowerCase() === "br")
2649                 textContents.push("\n");
2650             else if (node.nodeType === Node.TEXT_NODE)
2651                 textContents.push(node.textContent);
2652         }
2653         if (!hasContent)
2654             return [];
2655
2656         var textContent = textContents.join("");
2657         // The last \n (if any) does not "count" in a DIV.
2658         textContent = textContent.replace(/\n$/, "");
2659
2660         return textContent.split("\n");
2661     },
2662
2663     /**
2664      * @param {Event} event
2665      */
2666     _handleSelectionChange: function(event)
2667     {
2668         var textRange = this.selection();
2669         if (textRange)
2670             this._lastSelection = textRange;
2671
2672         this._tokenHighlighter.handleSelectionChange(textRange);
2673         this._braceHighlighter.handleSelectionChange(textRange);
2674         this._delegate.selectionChanged(textRange);
2675     },
2676
2677     /**
2678      * @param {Event} event
2679      */
2680     _handleTextInput: function(event)
2681     {
2682         this._textInputData = event.data;
2683     },
2684
2685     /**
2686      * @param {number} shortcutKey
2687      * @param {Event} event
2688      */
2689     handleKeyDown: function(shortcutKey, event)
2690     {
2691         var handler = this._shortcuts[shortcutKey];
2692         if (handler && handler()) {
2693             event.consume(true);
2694             return;
2695         }
2696
2697         this._keyDownCode = event.keyCode;
2698     },
2699
2700     /**
2701      * @param {Event} event
2702      */
2703     _handleCut: function(event)
2704     {
2705         this._keyDownCode = WebInspector.KeyboardShortcut.Keys.Delete.code;
2706     },
2707
2708     /**
2709      * @param {number} scrollTop
2710      * @param {number} clientHeight
2711      * @param {number} chunkSize
2712      */
2713     overrideViewportForTest: function(scrollTop, clientHeight, chunkSize)
2714     {
2715         this._scrollTopOverrideForTest = scrollTop;
2716         this._clientHeightOverrideForTest = clientHeight;
2717         this._defaultChunkSize = chunkSize;
2718     },
2719
2720     __proto__: WebInspector.TextEditorChunkedPanel.prototype
2721 }
2722
2723 /**
2724  * @interface
2725  */
2726 WebInspector.TextEditorMainPanel.HighlightDescriptor = function() { }
2727
2728 WebInspector.TextEditorMainPanel.HighlightDescriptor.prototype = {
2729     /**
2730      * @param {number} lineNumber
2731      * @param {string} line
2732      * @return {boolean}
2733      */
2734     affectsLine: function(lineNumber, line) { return false; },
2735
2736     /**
2737      * @param {number} lineNumber
2738      * @param {string} line
2739      * @return {Array.<{startColumn: number, endColumn: number}>}
2740      */
2741     rangesForLine: function(lineNumber, line) { return []; },
2742
2743     /**
2744      * @return {string}
2745      */
2746     cssClass: function() { return ""; },
2747 }
2748
2749 /**
2750  * @constructor
2751  * @implements {WebInspector.TextEditorMainPanel.HighlightDescriptor}
2752  */
2753 WebInspector.TextEditorMainPanel.RegexHighlightDescriptor = function(regex, cssClass)
2754 {
2755     this._cssClass = cssClass;
2756     this._regex = regex;
2757 }
2758
2759 WebInspector.TextEditorMainPanel.RegexHighlightDescriptor.prototype = {
2760     /**
2761      * @param {number} lineNumber
2762      * @param {string} line
2763      * @return {boolean}
2764      */
2765     affectsLine: function(lineNumber, line)
2766     {
2767         this._regex.lastIndex = 0;
2768         return this._regex.test(line);
2769     },
2770
2771     /**
2772      * @param {number} lineNumber
2773      * @param {string} line
2774      * @return {Array.<{startColumn: number, endColumn: number}>}
2775      */
2776     rangesForLine: function(lineNumber, line)
2777     {
2778         var ranges = [];
2779         var regexResult;
2780         this._regex.lastIndex = 0;
2781         while (regexResult = this._regex.exec(line)) {
2782             ranges.push({
2783                 startColumn: regexResult.index,
2784                 endColumn: regexResult.index + regexResult[0].length - 1
2785             });
2786         }
2787         return ranges;
2788     },
2789
2790     /**
2791      * @return {string}
2792      */
2793     cssClass: function()
2794     {
2795         return this._cssClass;
2796     }
2797 }
2798
2799 /**
2800  * @constructor
2801  * @implements {WebInspector.TextEditorMainPanel.HighlightDescriptor}
2802  * @param {WebInspector.TextRange} range
2803  * @param {string} cssClass
2804  */
2805 WebInspector.TextEditorMainPanel.RangeHighlightDescriptor = function(range, cssClass)
2806 {
2807     this._cssClass = cssClass;
2808     this._range = range;
2809 }
2810
2811 WebInspector.TextEditorMainPanel.RangeHighlightDescriptor.prototype = {
2812     /**
2813      * @param {number} lineNumber
2814      * @param {string} line
2815      * @return {boolean}
2816      */
2817     affectsLine: function(lineNumber, line)
2818     {
2819         return this._range.startLine <= lineNumber && lineNumber <= this._range.endLine && line.length > 0;
2820     },
2821
2822     /**
2823      * @param {number} lineNumber
2824      * @param {string} line
2825      * @return {Array.<{startColumn: number, endColumn: number}>}
2826      */
2827     rangesForLine: function(lineNumber, line)
2828     {
2829         if (!this.affectsLine(lineNumber, line))
2830             return [];
2831
2832         var startColumn = lineNumber === this._range.startLine ? this._range.startColumn : 0;
2833         var endColumn = lineNumber === this._range.endLine ? Math.min(this._range.endColumn, line.length) : line.length;
2834         return [{
2835             startColumn: startColumn,
2836             endColumn: endColumn
2837         }];
2838     },
2839
2840     /**
2841      * @return {string}
2842      */
2843     cssClass: function()
2844     {
2845         return this._cssClass;
2846     }
2847 }
2848
2849 /**
2850  * @constructor
2851  * @param {Element} element
2852  */
2853 WebInspector.TextEditorMainPanel.ElementMetrics = function(element)
2854 {
2855     this.width = element.offsetWidth;
2856     this.height = element.offsetHeight;
2857     this.left = element.offsetLeft;
2858 }
2859
2860 /**
2861  * @constructor
2862  * @param {Array.<WebInspector.TextEditorMainPanel.ElementMetrics>} metrics
2863  * @param {string} cssClass
2864  */
2865 WebInspector.TextEditorMainPanel.LineOverlayHighlight = function(metrics, cssClass)
2866 {
2867     this.metrics = metrics;
2868     this.cssClass = cssClass;
2869 }
2870
2871 /**
2872  * @constructor
2873  * @param {WebInspector.TextEditorChunkedPanel} chunkedPanel
2874  * @param {number} startLine
2875  * @param {number} endLine
2876  */
2877 WebInspector.TextEditorMainChunk = function(chunkedPanel, startLine, endLine)
2878 {
2879     this._chunkedPanel = chunkedPanel;
2880     this._textModel = chunkedPanel._textModel;
2881
2882     this.element = document.createElement("div");
2883     this.element.lineNumber = startLine;
2884     this.element.className = "webkit-line-content";
2885     this.element._chunk = this;
2886
2887     this._startLine = startLine;
2888     endLine = Math.min(this._textModel.linesCount, endLine);
2889     this.linesCount = endLine - startLine;
2890
2891     this._expanded = false;
2892
2893     this.updateCollapsedLineRow();
2894 }
2895
2896 WebInspector.TextEditorMainChunk.prototype = {
2897     /**
2898      * @param {Element|string} decoration
2899      */
2900     addDecoration: function(decoration)
2901     {
2902         this._chunkedPanel.beginDomUpdates();
2903         if (typeof decoration === "string")
2904             this.element.addStyleClass(decoration);
2905         else {
2906             if (!this.element.decorationsElement) {
2907                 this.element.decorationsElement = document.createElement("div");
2908                 this.element.decorationsElement.className = "webkit-line-decorations";
2909                 this.element.decorationsElement._isDecorationsElement = true;
2910                 this.element.appendChild(this.element.decorationsElement);
2911             }
2912             this.element.decorationsElement.appendChild(decoration);
2913         }
2914         this._chunkedPanel.endDomUpdates();
2915     },
2916
2917     /**
2918      * @param {string|Element} decoration
2919      */
2920     removeDecoration: function(decoration)
2921     {
2922         this._chunkedPanel.beginDomUpdates();
2923         if (typeof decoration === "string")
2924             this.element.removeStyleClass(decoration);
2925         else if (this.element.decorationsElement)
2926             this.element.decorationsElement.removeChild(decoration);
2927         this._chunkedPanel.endDomUpdates();
2928     },
2929
2930     removeAllDecorations: function()
2931     {
2932         this._chunkedPanel.beginDomUpdates();
2933         this.element.className = "webkit-line-content";
2934         if (this.element.decorationsElement) {
2935             if (this.element.decorationsElement.parentElement)
2936                 this.element.removeChild(this.element.decorationsElement);
2937             delete this.element.decorationsElement;
2938         }
2939         this._chunkedPanel.endDomUpdates();
2940     },
2941
2942     /**
2943      * @return {boolean}
2944      */
2945     isDecorated: function()
2946     {
2947         return this.element.className !== "webkit-line-content" || !!(this.element.decorationsElement && this.element.decorationsElement.firstChild);
2948     },
2949
2950     /**
2951      * @return {number}
2952      */
2953     get startLine()
2954     {
2955         return this._startLine;
2956     },
2957
2958     /**
2959      * @return {number}
2960      */
2961     get endLine()
2962     {
2963         return this._startLine + this.linesCount;
2964     },
2965
2966     set startLine(startLine)
2967     {
2968         this._startLine = startLine;
2969         this.element.lineNumber = startLine;
2970         if (this._expandedLineRows) {
2971             for (var i = 0; i < this._expandedLineRows.length; ++i)
2972                 this._expandedLineRows[i].lineNumber = startLine + i;
2973         }
2974     },
2975
2976     /**
2977      * @return {boolean}
2978      */
2979     expanded: function()
2980     {
2981         return this._expanded;
2982     },
2983
2984     expand: function()
2985     {
2986         if (this._expanded)
2987             return;
2988
2989         this._expanded = true;
2990
2991         if (this.linesCount === 1) {
2992             this._chunkedPanel._paintLines(this.startLine, this.startLine + 1);
2993             return;
2994         }
2995
2996         this._chunkedPanel.beginDomUpdates();
2997
2998         this._expandedLineRows = [];
2999         var parentElement = this.element.parentElement;
3000         for (var i = this.startLine; i < this.startLine + this.linesCount; ++i) {
3001             var lineRow = this._createRow(i);
3002             parentElement.insertBefore(lineRow, this.element);
3003             this._expandedLineRows.push(lineRow);
3004         }
3005         parentElement.removeChild(this.element);
3006         this._chunkedPanel._paintLines(this.startLine, this.startLine + this.linesCount);
3007
3008         this._chunkedPanel.endDomUpdates();
3009     },
3010
3011     collapse: function()
3012     {
3013         if (!this._expanded)
3014             return;
3015
3016         this._expanded = false;
3017         if (this.linesCount === 1)
3018             return;
3019
3020         this._chunkedPanel.beginDomUpdates();
3021
3022         var elementInserted = false;
3023         for (var i = 0; i < this._expandedLineRows.length; ++i) {
3024             var lineRow = this._expandedLineRows[i];
3025             var parentElement = lineRow.parentElement;
3026             if (parentElement) {
3027                 if (!elementInserted) {
3028                     elementInserted = true;
3029                     parentElement.insertBefore(this.element, lineRow);
3030                 }
3031                 parentElement.removeChild(lineRow);
3032             }
3033             this._chunkedPanel._releaseLinesHighlight(lineRow);
3034         }
3035         delete this._expandedLineRows;
3036
3037         this._chunkedPanel.endDomUpdates();
3038     },
3039
3040     /**
3041      * @return {number}
3042      */
3043     get height()
3044     {
3045         if (!this._expandedLineRows)
3046             return this._chunkedPanel.totalHeight(this.element);
3047         return this._chunkedPanel.totalHeight(this._expandedLineRows[0], this._expandedLineRows[this._expandedLineRows.length - 1]);
3048     },
3049
3050     /**
3051      * @return {number}
3052      */
3053     get offsetTop()
3054     {
3055         return (this._expandedLineRows && this._expandedLineRows.length) ? this._expandedLineRows[0].offsetTop : this.element.offsetTop;
3056     },
3057
3058     /**
3059      * @param {number} lineNumber
3060      * @return {Element}
3061      */
3062     _createRow: function(lineNumber)
3063     {
3064         var lineRow = this._chunkedPanel._cachedRows.pop() || document.createElement("div");
3065         lineRow.lineNumber = lineNumber;
3066         lineRow.className = "webkit-line-content";
3067         lineRow.textContent = this._textModel.line(lineNumber);
3068         if (!lineRow.textContent)
3069             lineRow.appendChild(document.createElement("br"));
3070         return lineRow;
3071     },
3072
3073     /**
3074      * Called on potentially damaged / inconsistent chunk
3075      * @param {number} lineNumber
3076      * @return {?Node}
3077      */
3078     lineRowContainingLine: function(lineNumber)
3079     {
3080         if (!this._expanded)
3081             return this.element;
3082         return this.expandedLineRow(lineNumber);
3083     },
3084
3085     /**
3086      * @param {number} lineNumber
3087      * @return {Element}
3088      */
3089     expandedLineRow: function(lineNumber)
3090     {
3091         if (!this._expanded || lineNumber < this.startLine || lineNumber >= this.startLine + this.linesCount)
3092             return null;
3093         if (!this._expandedLineRows)
3094             return this.element;
3095         return this._expandedLineRows[lineNumber - this.startLine];
3096     },
3097
3098     updateCollapsedLineRow: function()
3099     {
3100         if (this.linesCount === 1 && this._expanded)
3101             return;
3102
3103         var lines = [];
3104         for (var i = this.startLine; i < this.startLine + this.linesCount; ++i)
3105             lines.push(this._textModel.line(i));
3106
3107         if (WebInspector.FALSE)
3108             console.log("Rebuilding chunk with " + lines.length + " lines");
3109
3110         this.element.removeChildren();
3111         this.element.textContent = lines.join("\n");
3112         // The last empty line will get swallowed otherwise.
3113         if (!lines[lines.length - 1])
3114             this.element.appendChild(document.createElement("br"));
3115     },
3116
3117     firstElement: function()
3118     {
3119         return this._expandedLineRows ? this._expandedLineRows[0] : this.element;
3120     },
3121
3122     /**
3123      * @return {Element}
3124      */
3125     lastElement: function()
3126     {
3127         return this._expandedLineRows ? this._expandedLineRows[this._expandedLineRows.length - 1] : this.element;
3128     }
3129 }
3130
3131 /**
3132  * @constructor
3133  * @param {WebInspector.TextEditorMainPanel} mainPanel
3134  * @param {WebInspector.TextEditorModel} textModel
3135  */
3136 WebInspector.TextEditorMainPanel.TokenHighlighter = function(mainPanel, textModel)
3137 {
3138     this._mainPanel = mainPanel;
3139     this._textModel = textModel;
3140 }
3141
3142 WebInspector.TextEditorMainPanel.TokenHighlighter._NonWordCharRegex = /[^a-zA-Z0-9_]/;
3143 WebInspector.TextEditorMainPanel.TokenHighlighter._WordRegex = /^[a-zA-Z0-9_]+$/;
3144
3145 WebInspector.TextEditorMainPanel.TokenHighlighter.prototype = {
3146     /**
3147      * @param {WebInspector.TextRange} range
3148      */
3149     handleSelectionChange: function(range)
3150     {
3151         if (!range) {
3152             this._removeHighlight();
3153             return;
3154         }
3155
3156         if (range.startLine !== range.endLine) {
3157             this._removeHighlight();
3158             return;
3159         }
3160
3161         range = range.normalize();
3162         var selectedText = this._textModel.copyRange(range);
3163         if (selectedText === this._selectedWord)
3164             return;
3165
3166         if (selectedText === "") {
3167             this._removeHighlight();
3168             return;
3169         }
3170
3171         if (this._isWord(range, selectedText))
3172             this._highlight(selectedText);
3173         else
3174             this._removeHighlight();
3175     },
3176
3177     /**
3178      * @param {string} word
3179      */
3180     _regexString: function(word)
3181     {
3182         return "\\b" + word + "\\b";
3183     },
3184
3185     /**
3186      * @param {string} selectedWord
3187      */
3188     _highlight: function(selectedWord)
3189     {
3190         this._removeHighlight();
3191         this._selectedWord = selectedWord;
3192         this._highlightDescriptor = this._mainPanel.highlightRegex(this._regexString(selectedWord), "text-editor-token-highlight")
3193     },
3194
3195     _removeHighlight: function()
3196     {
3197         if (this._selectedWord) {
3198             this._mainPanel.removeHighlight(this._highlightDescriptor);
3199             delete this._selectedWord;
3200             delete this._highlightDescriptor;
3201         }
3202     },
3203
3204     /**
3205      * @param {WebInspector.TextRange} range
3206      * @param {string} selectedText
3207      * @return {boolean}
3208      */
3209     _isWord: function(range, selectedText)
3210     {
3211         const NonWordChar = WebInspector.TextEditorMainPanel.TokenHighlighter._NonWordCharRegex;
3212         const WordRegex = WebInspector.TextEditorMainPanel.TokenHighlighter._WordRegex;
3213         var line = this._textModel.line(range.startLine);
3214         var leftBound = range.startColumn === 0 || NonWordChar.test(line.charAt(range.startColumn - 1));
3215         var rightBound = range.endColumn === line.length || NonWordChar.test(line.charAt(range.endColumn));
3216         return leftBound && rightBound && WordRegex.test(selectedText);
3217     }
3218 }
3219
3220 /**
3221  * @constructor
3222  * @param {WebInspector.TextEditorModel} textModel
3223  * @param {WebInspector.TextEditor} textEditor
3224  */
3225 WebInspector.DefaultTextEditor.WordMovementController = function(textEditor, textModel)
3226 {
3227     this._textModel = textModel;
3228     this._textEditor = textEditor;
3229 }
3230
3231 WebInspector.DefaultTextEditor.WordMovementController.prototype = {
3232
3233     /**
3234      * @param {Object.<number, function()>} shortcuts
3235      */
3236     _registerShortcuts: function(shortcuts)
3237     {
3238         var keys = WebInspector.KeyboardShortcut.Keys;
3239         var modifiers = WebInspector.KeyboardShortcut.Modifiers;
3240
3241         const wordJumpModifier = WebInspector.isMac() ? modifiers.Alt : modifiers.Ctrl;
3242         shortcuts[WebInspector.KeyboardShortcut.makeKey(keys.Backspace.code, wordJumpModifier)] = this._handleCtrlBackspace.bind(this);
3243         shortcuts[WebInspector.KeyboardShortcut.makeKey(keys.Left.code, wordJumpModifier)] = this._handleCtrlArrow.bind(this, "left");
3244         shortcuts[WebInspector.KeyboardShortcut.makeKey(keys.Right.code, wordJumpModifier)] = this._handleCtrlArrow.bind(this, "right");
3245         shortcuts[WebInspector.KeyboardShortcut.makeKey(keys.Left.code, modifiers.Shift | wordJumpModifier)] = this._handleCtrlShiftArrow.bind(this, "left");
3246         shortcuts[WebInspector.KeyboardShortcut.makeKey(keys.Right.code, modifiers.Shift | wordJumpModifier)] = this._handleCtrlShiftArrow.bind(this, "right");
3247     },
3248
3249     /**
3250      * @param {WebInspector.TextRange} selection
3251      * @param {string} direction
3252      * @return {WebInspector.TextRange}
3253      */
3254     _rangeForCtrlArrowMove: function(selection, direction)
3255     {
3256         /**
3257          * @param {string} char
3258          */
3259         function isStopChar(char)
3260         {
3261             return (char > " " && char < "0") ||
3262                 (char > "9" && char < "A") ||
3263                 (char > "Z" && char < "a") ||
3264                 (char > "z" && char <= "~");
3265         }
3266
3267         /**
3268          * @param {string} char
3269          */
3270         function isSpaceChar(char)
3271         {
3272             return char === "\t" || char === "\r" || char === "\n" || char === " ";
3273         }
3274
3275 &nbs