Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(265)

Side by Side Diff: third_party/WebKit/Source/devtools/front_end/source_frame/SourcesTextEditor.js

Issue 2238883004: DevTools: Split off SourcesTextEditor from CodeMirrorTextEditor (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Fix copyright Created 4 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright (c) 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 /**
6 * @constructor
7 * @extends {WebInspector.CodeMirrorTextEditor}
8 * @param {!WebInspector.SourcesTextEditorDelegate} delegate
9 */
10 WebInspector.SourcesTextEditor = function(delegate)
11 {
12 WebInspector.CodeMirrorTextEditor.call(this);
13
14 this._codeMirror.addKeyMap({
lushnikov 2016/08/18 21:43:03 we should either codeMirror() all over the place;
einbinder 2016/08/18 22:52:22 It is protected, I just missed one _codeMirror.
15 "Enter": "smartNewlineAndIndent",
16 "Esc": "sourcesDismiss"
17 });
18
19 this._delegate = delegate;
20
21 this.codeMirror().on("changes", this._removeWidgetsOnChanges.bind(this));
22 this.codeMirror().on("changes", this._changesForDelegate.bind(this));
23 this.codeMirror().on("cursorActivity", this._cursorActivity.bind(this));
24 this.codeMirror().on("gutterClick", this._gutterClick.bind(this));
25 this.codeMirror().on("scroll", this._scroll.bind(this));
26 this.codeMirror().on("focus", this._focus.bind(this));
27 this.codeMirror().on("beforeSelectionChange", this._beforeSelectionChangeFor Delegate.bind(this));
28 this.element.addEventListener("contextmenu", this._contextMenu.bind(this), f alse);
29
30 this._blockIndentController = new WebInspector.SourcesTextEditor.BlockIndent Controller(this.codeMirror());
31 this._tokenHighlighter = new WebInspector.SourcesTextEditor.TokenHighlighter (this, this._codeMirror);
32
33 /** @type {!Array<string>} */
34 this._gutters = ["CodeMirror-linenumbers"];
35 this._elementToWidget = new Map();
lushnikov 2016/08/18 21:43:03 this has to be rebased atop of your previous CM ch
einbinder 2016/08/18 22:52:22 Yep, I'm waiting for it to land.
36
37 /**
38 * @this {WebInspector.SourcesTextEditor}
39 */
40 function updateAnticipateJumpFlag(value)
41 {
42 this._isHandlingMouseDownEvent = value;
43 }
44
45 this.element.addEventListener("mousedown", updateAnticipateJumpFlag.bind(thi s, true), true);
46 this.element.addEventListener("mousedown", updateAnticipateJumpFlag.bind(thi s, false), false);
47 WebInspector.moduleSetting("textEditorIndent").addChangeListener(this._onUpd ateEditorIndentation, this);
48 WebInspector.moduleSetting("textEditorAutoDetectIndent").addChangeListener(t his._onUpdateEditorIndentation, this);
49 WebInspector.moduleSetting("showWhitespacesInEditor").addChangeListener(this ._updateWhitespace, this);
50
51 this._onUpdateEditorIndentation();
52 this._setupWhitespaceHighlight();
53 }
54 WebInspector.SourcesTextEditor.prototype = {
55
56 /**
57 * @return {boolean}
58 */
59 _isSearchActive: function()
60 {
61 return !!this._tokenHighlighter.highlightedRegex();
62 },
63
64 /**
65 * @param {!RegExp} regex
66 * @param {?WebInspector.TextRange} range
67 */
68 highlightSearchResults: function(regex, range)
69 {
70 /**
71 * @this {WebInspector.CodeMirrorTextEditor}
72 */
73 function innerHighlightRegex()
74 {
75 if (range) {
76 this.scrollLineIntoView(range.startLine);
77 if (range.endColumn > WebInspector.CodeMirrorTextEditor.maxHighl ightLength)
78 this.setSelection(range);
79 else
80 this.setSelection(WebInspector.TextRange.createFromLocation( range.startLine, range.startColumn));
81 }
82 this._tokenHighlighter.highlightSearchResults(regex, range);
83 }
84
85 if (!this._selectionBeforeSearch)
86 this._selectionBeforeSearch = this.selection();
87
88 this.codeMirror().operation(innerHighlightRegex.bind(this));
89 },
90
91 cancelSearchResultsHighlight: function()
92 {
93 this.codeMirror().operation(this._tokenHighlighter.highlightSelectedToke ns.bind(this._tokenHighlighter));
94
95 if (this._selectionBeforeSearch) {
96 this._reportJump(this._selectionBeforeSearch, this.selection());
97 delete this._selectionBeforeSearch;
98 }
99 },
100
101 /**
102 * @param {!Object} highlightDescriptor
103 */
104 removeHighlight: function(highlightDescriptor)
105 {
106 highlightDescriptor.clear();
107 },
108
109 /**
110 * @param {!WebInspector.TextRange} range
111 * @param {string} cssClass
112 * @return {!Object}
113 */
114 highlightRange: function(range, cssClass)
115 {
116 cssClass = "CodeMirror-persist-highlight " + cssClass;
117 var pos = WebInspector.CodeMirrorUtils.toPos(range);
118 ++pos.end.ch;
119 return this.codeMirror().markText(pos.start, pos.end, {
120 className: cssClass,
121 startStyle: cssClass + "-start",
122 endStyle: cssClass + "-end"
123 });
124 },
125
126 /**
127 * @param {number} lineNumber
128 * @param {boolean} disabled
129 * @param {boolean} conditional
130 */
131 addBreakpoint: function(lineNumber, disabled, conditional)
132 {
133 if (lineNumber < 0 || lineNumber >= this.codeMirror().lineCount())
134 return;
135
136 var className = "cm-breakpoint" + (conditional ? " cm-breakpoint-conditi onal" : "") + (disabled ? " cm-breakpoint-disabled" : "");
137 this.codeMirror().addLineClass(lineNumber, "wrap", className);
138 },
139
140 /**
141 * @param {number} lineNumber
142 */
143 removeBreakpoint: function(lineNumber)
144 {
145 if (lineNumber < 0 || lineNumber >= this.codeMirror().lineCount())
146 return;
147
148 var wrapClasses = this.codeMirror().getLineHandle(lineNumber).wrapClass;
149 if (!wrapClasses)
150 return;
151
152 var classes = wrapClasses.split(" ");
153 for (var i = 0; i < classes.length; ++i) {
154 if (classes[i].startsWith("cm-breakpoint"))
155 this.codeMirror().removeLineClass(lineNumber, "wrap", classes[i] );
156 }
157 },
158
159 /**
160 * @param {string} type
161 * @param {boolean} leftToNumbers
162 */
163 installGutter: function(type, leftToNumbers)
164 {
165 if (this._gutters.indexOf(type) !== -1)
166 return;
167
168 if (leftToNumbers)
169 this._gutters.unshift(type);
170 else
171 this._gutters.push(type);
172
173 this.codeMirror().setOption("gutters", this._gutters.slice());
174 this.codeMirror().refresh();
175 },
176
177 /**
178 * @param {string} type
179 */
180 uninstallGutter: function(type)
181 {
182 this._gutters = this._gutters.filter(gutter => gutter !== type);
183 this.codeMirror().setOption("gutters", this._gutters.slice());
184 this.codeMirror().refresh();
185 },
186
187 /**
188 * @param {number} lineNumber
189 * @param {string} type
190 * @param {?Element} element
191 */
192 setGutterDecoration: function(lineNumber, type, element)
193 {
194 console.assert(this._gutters.indexOf(type) !== -1, "Cannot decorate unex isting gutter.")
195 this.codeMirror().setGutterMarker(lineNumber, type, element);
196 },
197
198 /**
199 * @param {number} lineNumber
200 * @param {number} columnNumber
201 */
202 setExecutionLocation: function(lineNumber, columnNumber)
203 {
204 this.clearPositionHighlight();
205
206 this._executionLine = this.codeMirror().getLineHandle(lineNumber);
207 if (!this._executionLine)
208 return;
209
210 this.codeMirror().addLineClass(this._executionLine, "wrap", "cm-executio n-line");
211 this._executionLineTailMarker = this.codeMirror().markText({ line: lineN umber, ch: columnNumber }, { line: lineNumber, ch: this.codeMirror().getLine(lin eNumber).length }, { className: "cm-execution-line-tail" });
212 },
213
214 clearExecutionLine: function()
215 {
216 this.clearPositionHighlight();
217
218 if (this._executionLine)
219 this.codeMirror().removeLineClass(this._executionLine, "wrap", "cm-e xecution-line");
220 delete this._executionLine;
221
222 if (this._executionLineTailMarker)
223 this._executionLineTailMarker.clear();
224 delete this._executionLineTailMarker;
225 },
226
227 /**
228 * @param {number} lineNumber
229 * @param {string} className
230 * @param {boolean} toggled
231 */
232 toggleLineClass: function(lineNumber, className, toggled)
233 {
234 if (this.hasLineClass(lineNumber, className) === toggled)
235 return;
236
237 var lineHandle = this.codeMirror().getLineHandle(lineNumber);
238 if (!lineHandle)
239 return;
240
241 if (toggled) {
242 this.codeMirror().addLineClass(lineHandle, "gutter", className);
243 this.codeMirror().addLineClass(lineHandle, "wrap", className);
244 } else {
245 this.codeMirror().removeLineClass(lineHandle, "gutter", className);
246 this.codeMirror().removeLineClass(lineHandle, "wrap", className);
247 }
248 },
249
250 /**
251 * @param {number} lineNumber
252 * @param {string} className
253 * @return {boolean}
254 */
255 hasLineClass: function(lineNumber, className)
256 {
257 var lineInfo = this.codeMirror().lineInfo(lineNumber);
258 var wrapClass = lineInfo.wrapClass || "";
259 var classNames = wrapClass.split(" ");
260 return classNames.indexOf(className) !== -1;
261 },
262
263 /**
264 * @param {number} lineNumber
265 * @param {!Element} element
266 */
267 addDecoration: function(lineNumber, element)
268 {
269 var widget = this.codeMirror().addLineWidget(lineNumber, element);
270 this._elementToWidget.set(element, widget);
271 },
272
273 /**
274 * @param {number} lineNumber
275 * @param {!Element} element
276 */
277 removeDecoration: function(lineNumber, element)
278 {
279 var widget = this._elementToWidget.remove(element);
280 if (widget)
281 this.codeMirror().removeLineWidget(widget);
282 },
283
284 _removeWidgetsOnChanges: function(){
285 var widgets = this._elementToWidget.valuesArray();
286 for (var i = 0; i < widgets.length; ++i)
287 this.codeMirror().removeLineWidget(widgets[i]);
288
289 this._elementToWidget.clear();
290 },
291
292 _gutterClick: function(instance, lineNumber, gutter, event)
293 {
294 this.dispatchEventToListeners(WebInspector.SourcesTextEditor.Events.Gutt erClick, { lineNumber: lineNumber, event: event });
295 },
296
297 _contextMenu: function(event)
298 {
299 var contextMenu = new WebInspector.ContextMenu(event);
300 event.consume(true); // Consume event now to prevent document from handl ing the async menu
301 var target = event.target.enclosingNodeOrSelfWithClass("CodeMirror-gutte r-elt");
302 var promise;
303 if (target) {
304 promise = this._delegate.populateLineGutterContextMenu(contextMenu, parseInt(target.textContent, 10) - 1);
305 } else {
306 var textSelection = this.selection();
307 promise = this._delegate.populateTextAreaContextMenu(contextMenu, te xtSelection.startLine, textSelection.startColumn);
308 }
309 promise.then(showAsync.bind(this));
310
311 /**
312 * @this {WebInspector.SourcesTextEditor}
313 */
314 function showAsync()
315 {
316 contextMenu.appendApplicableItems(this);
317 contextMenu.show();
318 }
319 },
320
321 /**
322 * @param {!WebInspector.TextRange} range
323 * @param {string} text
324 * @param {string=} origin
325 * @return {!WebInspector.TextRange}
326 */
327 editRange: function(range, text, origin)
328 {
329 var pos = WebInspector.CodeMirrorUtils.toPos(range);
330 this.codeMirror().replaceRange(text, pos.start, pos.end, origin);
331 var newRange = WebInspector.CodeMirrorUtils.toRange(pos.start, this.code Mirror().posFromIndex(this.codeMirror().indexFromPos(pos.start) + text.length));
332 this._delegate.onTextChanged(range, newRange);
333
334 if (WebInspector.moduleSetting("textEditorAutoDetectIndent").get())
335 this._onUpdateEditorIndentation();
336
337 return newRange;
338 },
339
340 _onUpdateEditorIndentation: function()
341 {
342 this._setEditorIndentation(WebInspector.CodeMirrorUtils.pullLines(this._ codeMirror, WebInspector.SourcesTextEditor.LinesToScanForIndentationGuessing));
343 },
344
345 /**
346 * @param {!Array.<string>} lines
347 */
348 _setEditorIndentation: function(lines)
349 {
350 var extraKeys = {};
351 var indent = WebInspector.moduleSetting("textEditorIndent").get();
352 if (WebInspector.moduleSetting("textEditorAutoDetectIndent").get())
353 indent = WebInspector.SourcesTextEditor._guessIndentationLevel(lines );
354
355 if (indent === WebInspector.TextUtils.Indent.TabCharacter) {
356 this.codeMirror().setOption("indentWithTabs", true);
357 this.codeMirror().setOption("indentUnit", 4);
358 } else {
359 this.codeMirror().setOption("indentWithTabs", false);
360 this.codeMirror().setOption("indentUnit", indent.length);
361 extraKeys.Tab = function(codeMirror)
362 {
363 if (codeMirror.somethingSelected())
364 return CodeMirror.Pass;
365 var pos = codeMirror.getCursor("head");
366 codeMirror.replaceRange(indent.substring(pos.ch % indent.length) , codeMirror.getCursor());
367 }
368 }
369
370 this.codeMirror().setOption("extraKeys", extraKeys);
371 this._indentationLevel = indent;
372 },
373
374 /**
375 * @return {string}
376 */
377 _indent: function()
378 {
379 return this._indentationLevel;
380 },
381
382 _onAutoAppendedSpaces: function()
383 {
384 this._autoAppendedSpaces = this._autoAppendedSpaces || [];
385
386 for (var i = 0; i < this._autoAppendedSpaces.length; ++i) {
387 var position = this._autoAppendedSpaces[i].resolve();
388 if (!position)
389 continue;
390 var line = this.line(position.lineNumber);
391 if (line.length === position.columnNumber && WebInspector.TextUtils. lineIndent(line).length === line.length)
392 this._codeMirror.replaceRange("", new CodeMirror.Pos(position.li neNumber, 0), new CodeMirror.Pos(position.lineNumber, position.columnNumber));
393 }
394
395 this._autoAppendedSpaces = [];
396 var selections = this.selections();
397 for (var i = 0; i < selections.length; ++i) {
398 var selection = selections[i];
399 this._autoAppendedSpaces.push(this.textEditorPositionHandle(selectio n.startLine, selection.startColumn));
400 }
401 },
402
403 /**
404 * @param {!CodeMirror} codeMirror
405 * @param {!Array.<!CodeMirror.ChangeObject>} changes
406 */
407 _changesForDelegate: function(codeMirror, changes)
408 {
409 if (!changes.length || this._muteTextChangedEvent)
410 return;
411 var edits = [];
412 var currentEdit;
413
414 for (var changeIndex = 0; changeIndex < changes.length; ++changeIndex) {
415 var changeObject = changes[changeIndex];
416 var edit = WebInspector.CodeMirrorUtils.changeObjectToEditOperation( changeObject);
417 if (currentEdit && edit.oldRange.equal(currentEdit.newRange)) {
418 currentEdit.newRange = edit.newRange;
419 } else {
420 currentEdit = edit;
421 edits.push(currentEdit);
422 }
423 }
424
425 for (var i = 0; i < edits.length; ++i) {
426 var edit = edits[i];
427 this._delegate.onTextChanged(edit.oldRange, edit.newRange);
428 }
429 },
430
431 _cursorActivity: function()
432 {
433 if (!this._isSearchActive())
434 this._codeMirror.operation(this._tokenHighlighter.highlightSelectedT okens.bind(this._tokenHighlighter));
435
436 var start = this._codeMirror.getCursor("anchor");
437 var end = this._codeMirror.getCursor("head");
438 this._delegate.selectionChanged(WebInspector.CodeMirrorUtils.toRange(sta rt, end));
439 },
440
441 /**
442 * @param {?WebInspector.TextRange} from
443 * @param {?WebInspector.TextRange} to
444 */
445 _reportJump: function(from, to)
446 {
447 if (from && to && from.equal(to))
448 return;
449 this._delegate.onJumpToPosition(from, to);
450 },
451
452 _scroll: function()
453 {
454 var topmostLineNumber = this._codeMirror.lineAtHeight(this._codeMirror.g etScrollInfo().top, "local");
455 this._delegate.scrollChanged(topmostLineNumber);
456 },
457
458 _focus: function()
459 {
460 this._delegate.editorFocused();
461 },
462
463 /**
464 * @param {!CodeMirror} codeMirror
465 * @param {{ranges: !Array.<{head: !CodeMirror.Pos, anchor: !CodeMirror.Pos} >}} selection
466 */
467 _beforeSelectionChangeForDelegate: function(codeMirror, selection)
468 {
469 if (!this._isHandlingMouseDownEvent)
470 return;
471 if (!selection.ranges.length)
472 return;
473
474 var primarySelection = selection.ranges[0];
475 this._reportJump(this.selection(), WebInspector.CodeMirrorUtils.toRange( primarySelection.anchor, primarySelection.head));
476 },
477
478 /**
479 * @override
480 */
481 dispose: function()
482 {
483 WebInspector.CodeMirrorTextEditor.prototype.dispose.call(this);
484 WebInspector.moduleSetting("textEditorIndent").removeChangeListener(this ._onUpdateEditorIndentation, this);
485 WebInspector.moduleSetting("textEditorAutoDetectIndent").removeChangeLis tener(this._onUpdateEditorIndentation, this);
486 WebInspector.moduleSetting("showWhitespacesInEditor").removeChangeListen er(this._updateWhitespace, this);
487 },
488
489 /**
490 * @override
491 * @param {string} text
492 */
493 setText: function(text)
494 {
495 this._muteTextChangedEvent = true;
496 this._setEditorIndentation(text.split("\n").slice(0, WebInspector.Source sTextEditor.LinesToScanForIndentationGuessing));
497 WebInspector.CodeMirrorTextEditor.prototype.setText.call(this, text);
498 delete this._muteTextChangedEvent;
499 },
500
501 /**
502 * @override
503 * @param {string} mimeType
504 */
505 setMimeType: function(mimeType)
506 {
507 this._mimeType = mimeType;
508 WebInspector.CodeMirrorTextEditor.prototype.setMimeType.call(this, this. _applyWhitespaceMimetype(mimeType));
509 },
510
511 _updateWhitespace: function()
512 {
513 if (this._mimeType)
514 this.setMimeType(this._mimeType);
515 },
516
517 /**
518 * @param {string} mimeType
519 * @return {string}
520 */
521 _applyWhitespaceMimetype: function(mimeType)
522 {
523 this._setupWhitespaceHighlight();
524 var whitespaceMode = WebInspector.moduleSetting("showWhitespacesInEditor ").get();
525 this.element.classList.toggle("show-whitespaces", whitespaceMode === "al l");
526
527 if (whitespaceMode === "all")
528 return this._allWhitespaceOverlayMode(mimeType);
529 else if (whitespaceMode === "trailing")
530 return this._trailingWhitespaceOverlayMode(mimeType);
531
532 return mimeType;
533 },
534
535 /**
536 * @param {string} mimeType
537 * @return {string}
538 */
539 _allWhitespaceOverlayMode: function(mimeType)
540 {
541 var modeName = CodeMirror.mimeModes[mimeType] ? (CodeMirror.mimeModes[mi meType].name || CodeMirror.mimeModes[mimeType]) : CodeMirror.mimeModes["text/pla in"];
542 modeName += "+all-whitespaces";
543 if (CodeMirror.modes[modeName])
544 return modeName;
545
546 function modeConstructor(config, parserConfig)
547 {
548 function nextToken(stream)
549 {
550 if (stream.peek() === " ") {
551 var spaces = 0;
552 while (spaces < WebInspector.SourcesTextEditor.MaximumNumber OfWhitespacesPerSingleSpan && stream.peek() === " ") {
553 ++spaces;
554 stream.next();
555 }
556 return "whitespace whitespace-" + spaces;
557 }
558 while (!stream.eol() && stream.peek() !== " ")
559 stream.next();
560 return null;
561 }
562 var whitespaceMode = {
563 token: nextToken
564 };
565 return CodeMirror.overlayMode(CodeMirror.getMode(config, mimeType), whitespaceMode, false);
566 }
567 CodeMirror.defineMode(modeName, modeConstructor);
568 return modeName;
569 },
570
571 /**
572 * @param {string} mimeType
573 * @return {string}
574 */
575 _trailingWhitespaceOverlayMode: function(mimeType)
576 {
577 var modeName = CodeMirror.mimeModes[mimeType] ? (CodeMirror.mimeModes[mi meType].name || CodeMirror.mimeModes[mimeType]) : CodeMirror.mimeModes["text/pla in"];
578 modeName += "+trailing-whitespaces";
579 if (CodeMirror.modes[modeName])
580 return modeName;
581
582 function modeConstructor(config, parserConfig)
583 {
584 function nextToken(stream)
585 {
586 var pos = stream.pos;
587 if (stream.match(/^\s+$/, true))
588 return true ? "trailing-whitespace" : null;
589 do {
590 stream.next();
591 } while (!stream.eol() && stream.peek() !== " ");
592 return null;
593 }
594 var whitespaceMode = {
595 token: nextToken
596 };
597 return CodeMirror.overlayMode(CodeMirror.getMode(config, mimeType), whitespaceMode, false);
598 }
599 CodeMirror.defineMode(modeName, modeConstructor);
600 return modeName;
601 },
602
603 _setupWhitespaceHighlight: function()
604 {
605 var doc = this.element.ownerDocument;
606 if (doc._codeMirrorWhitespaceStyleInjected || !WebInspector.moduleSettin g("showWhitespacesInEditor").get())
607 return;
608 doc._codeMirrorWhitespaceStyleInjected = true;
609 const classBase = ".show-whitespaces .CodeMirror .cm-whitespace-";
610 const spaceChar = "·";
611 var spaceChars = "";
612 var rules = "";
613 for (var i = 1; i <= WebInspector.SourcesTextEditor.MaximumNumberOfWhite spacesPerSingleSpan; ++i) {
614 spaceChars += spaceChar;
615 var rule = classBase + i + "::before { content: '" + spaceChars + "' ;}\n";
616 rules += rule;
617 }
618 var style = doc.createElement("style");
619 style.textContent = rules;
620 doc.head.appendChild(style);
621 },
622
623 __proto__: WebInspector.CodeMirrorTextEditor.prototype
624 }
625
626 /** @typedef {{lineNumber: number, event: !Event}} */
627 WebInspector.SourcesTextEditor.GutterClickEventData;
628
629 /** @enum {string} */
630 WebInspector.SourcesTextEditor.Events = {
631 GutterClick: "GutterClick"
632 }
633 /**
634 * @interface
635 */
636 WebInspector.SourcesTextEditorDelegate = function() { }
637 WebInspector.SourcesTextEditorDelegate.prototype = {
638
639 /**
640 * @param {!WebInspector.TextRange} oldRange
641 * @param {!WebInspector.TextRange} newRange
642 */
643 onTextChanged: function(oldRange, newRange) { },
644
645 /**
646 * @param {!WebInspector.TextRange} textRange
647 */
648 selectionChanged: function(textRange) { },
649
650 /**
651 * @param {number} lineNumber
652 */
653 scrollChanged: function(lineNumber) { },
654
655 editorFocused: function() { },
656
657 /**
658 * @param {!WebInspector.ContextMenu} contextMenu
659 * @param {number} lineNumber
660 * @return {!Promise}
661 */
662 populateLineGutterContextMenu: function(contextMenu, lineNumber) { },
663
664 /**
665 * @param {!WebInspector.ContextMenu} contextMenu
666 * @param {number} lineNumber
667 * @param {number} columnNumber
668 * @return {!Promise}
669 */
670 populateTextAreaContextMenu: function(contextMenu, lineNumber, columnNumber) { },
671
672 /**
673 * @param {?WebInspector.TextRange} from
674 * @param {?WebInspector.TextRange} to
675 */
676 onJumpToPosition: function(from, to) { }
677 }
678
679 /**
680 * @param {!CodeMirror} codeMirror
681 */
682 CodeMirror.commands.smartNewlineAndIndent = function(codeMirror)
683 {
684 codeMirror.operation(innerSmartNewlineAndIndent.bind(null, codeMirror));
685 function innerSmartNewlineAndIndent(codeMirror)
686 {
687 var selections = codeMirror.listSelections();
688 var replacements = [];
689 for (var i = 0; i < selections.length; ++i) {
690 var selection = selections[i];
691 var cur = CodeMirror.cmpPos(selection.head, selection.anchor) < 0 ? selection.head : selection.anchor;
692 var line = codeMirror.getLine(cur.line);
693 var indent = WebInspector.TextUtils.lineIndent(line);
694 replacements.push("\n" + indent.substring(0, Math.min(cur.ch, indent .length)));
695 }
696 codeMirror.replaceSelections(replacements);
697 codeMirror._codeMirrorTextEditor._onAutoAppendedSpaces();
698 }
699 }
700
701 /**
702 * @return {!Object|undefined}
703 */
704 CodeMirror.commands.sourcesDismiss = function(codemirror)
705 {
706 if (codemirror.listSelections().length === 1 && codemirror._codeMirrorTextEd itor._isSearchActive())
707 return CodeMirror.Pass;
708 return CodeMirror.commands.dismiss(codemirror);
709 }
710
711 /**
712 * @constructor
713 * @param {!CodeMirror} codeMirror
714 */
715 WebInspector.SourcesTextEditor.BlockIndentController = function(codeMirror)
716 {
717 codeMirror.addKeyMap(this);
718 }
719
720 WebInspector.SourcesTextEditor.BlockIndentController.prototype = {
721 name: "blockIndentKeymap",
722
723 /**
724 * @return {*}
725 */
726 Enter: function(codeMirror)
727 {
728 var selections = codeMirror.listSelections();
729 var replacements = [];
730 var allSelectionsAreCollapsedBlocks = false;
731 for (var i = 0; i < selections.length; ++i) {
732 var selection = selections[i];
733 var start = CodeMirror.cmpPos(selection.head, selection.anchor) < 0 ? selection.head : selection.anchor;
734 var line = codeMirror.getLine(start.line);
735 var indent = WebInspector.TextUtils.lineIndent(line);
736 var indentToInsert = "\n" + indent + codeMirror._codeMirrorTextEdito r._indent();
737 var isCollapsedBlock = false;
738 if (selection.head.ch === 0)
739 return CodeMirror.Pass;
740 if (line.substr(selection.head.ch - 1, 2) === "{}") {
741 indentToInsert += "\n" + indent;
742 isCollapsedBlock = true;
743 } else if (line.substr(selection.head.ch - 1, 1) !== "{") {
744 return CodeMirror.Pass;
745 }
746 if (i > 0 && allSelectionsAreCollapsedBlocks !== isCollapsedBlock)
747 return CodeMirror.Pass;
748 replacements.push(indentToInsert);
749 allSelectionsAreCollapsedBlocks = isCollapsedBlock;
750 }
751 codeMirror.replaceSelections(replacements);
752 if (!allSelectionsAreCollapsedBlocks) {
753 codeMirror._codeMirrorTextEditor._onAutoAppendedSpaces();
754 return;
755 }
756 selections = codeMirror.listSelections();
757 var updatedSelections = [];
758 for (var i = 0; i < selections.length; ++i) {
759 var selection = selections[i];
760 var line = codeMirror.getLine(selection.head.line - 1);
761 var position = new CodeMirror.Pos(selection.head.line - 1, line.leng th);
762 updatedSelections.push({
763 head: position,
764 anchor: position
765 });
766 }
767 codeMirror.setSelections(updatedSelections);
768 codeMirror._codeMirrorTextEditor._onAutoAppendedSpaces();
769 },
770
771 /**
772 * @return {*}
773 */
774 "'}'": function(codeMirror)
775 {
776 if (codeMirror.somethingSelected())
777 return CodeMirror.Pass;
778 var selections = codeMirror.listSelections();
779 var replacements = [];
780 for (var i = 0; i < selections.length; ++i) {
781 var selection = selections[i];
782 var line = codeMirror.getLine(selection.head.line);
783 if (line !== WebInspector.TextUtils.lineIndent(line))
784 return CodeMirror.Pass;
785 replacements.push("}");
786 }
787 codeMirror.replaceSelections(replacements);
788 selections = codeMirror.listSelections();
789 replacements = [];
790 var updatedSelections = [];
791 for (var i = 0; i < selections.length; ++i) {
792 var selection = selections[i];
793 var matchingBracket = codeMirror.findMatchingBracket(selection.head) ;
794 if (!matchingBracket || !matchingBracket.match)
795 return;
796 updatedSelections.push({
797 head: selection.head,
798 anchor: new CodeMirror.Pos(selection.head.line, 0)
799 });
800 var line = codeMirror.getLine(matchingBracket.to.line);
801 var indent = WebInspector.TextUtils.lineIndent(line);
802 replacements.push(indent + "}");
803 }
804 codeMirror.setSelections(updatedSelections);
805 codeMirror.replaceSelections(replacements);
806 }
807 }
808
809 /**
810 * @param {!Array.<string>} lines
811 * @return {string}
812 */
813 WebInspector.SourcesTextEditor._guessIndentationLevel = function(lines)
814 {
815 var tabRegex = /^\t+/;
816 var tabLines = 0;
817 var indents = {};
818 for (var lineNumber = 0; lineNumber < lines.length; ++lineNumber) {
819 var text = lines[lineNumber];
820 if (text.length === 0 || !WebInspector.TextUtils.isSpaceChar(text[0]))
821 continue;
822 if (tabRegex.test(text)) {
823 ++tabLines;
824 continue;
825 }
826 var i = 0;
827 while (i < text.length && WebInspector.TextUtils.isSpaceChar(text[i]))
828 ++i;
829 if (i % 2 !== 0)
830 continue;
831 indents[i] = 1 + (indents[i] || 0);
832 }
833 var linesCountPerIndentThreshold = 3 * lines.length / 100;
834 if (tabLines && tabLines > linesCountPerIndentThreshold)
835 return "\t";
836 var minimumIndent = Infinity;
837 for (var i in indents) {
838 if (indents[i] < linesCountPerIndentThreshold)
839 continue;
840 var indent = parseInt(i, 10);
841 if (minimumIndent > indent)
842 minimumIndent = indent;
843 }
844 if (minimumIndent === Infinity)
845 return WebInspector.moduleSetting("textEditorIndent").get();
846 return " ".repeat(minimumIndent);
847 }
848
849 /**
850 * @constructor
851 * @param {!WebInspector.SourcesTextEditor} textEditor
852 * @param {!CodeMirror} codeMirror
853 */
854 WebInspector.SourcesTextEditor.TokenHighlighter = function(textEditor, codeMirro r)
855 {
856 this._textEditor = textEditor;
857 this._codeMirror = codeMirror;
858 }
859
860 WebInspector.SourcesTextEditor.TokenHighlighter.prototype = {
861 /**
862 * @param {!RegExp} regex
863 * @param {?WebInspector.TextRange} range
864 */
865 highlightSearchResults: function(regex, range)
866 {
867 var oldRegex = this._highlightRegex;
868 this._highlightRegex = regex;
869 this._highlightRange = range;
870 if (this._searchResultMarker) {
871 this._searchResultMarker.clear();
872 delete this._searchResultMarker;
873 }
874 if (this._highlightDescriptor && this._highlightDescriptor.selectionStar t)
875 this._codeMirror.removeLineClass(this._highlightDescriptor.selection Start.line, "wrap", "cm-line-with-selection");
876 var selectionStart = this._highlightRange ? new CodeMirror.Pos(this._hig hlightRange.startLine, this._highlightRange.startColumn) : null;
877 if (selectionStart)
878 this._codeMirror.addLineClass(selectionStart.line, "wrap", "cm-line- with-selection");
879 if (this._highlightRegex === oldRegex) {
880 // Do not re-add overlay mode if regex did not change for better per formance.
881 if (this._highlightDescriptor)
882 this._highlightDescriptor.selectionStart = selectionStart;
883 } else {
884 this._removeHighlight();
885 this._setHighlighter(this._searchHighlighter.bind(this, this._highli ghtRegex), selectionStart);
886 }
887 if (this._highlightRange) {
888 var pos = WebInspector.CodeMirrorUtils.toPos(this._highlightRange);
889 this._searchResultMarker = this._codeMirror.markText(pos.start, pos. end, {className: "cm-column-with-selection"});
890 }
891 },
892
893 /**
894 * @return {!RegExp|undefined}
895 */
896 highlightedRegex: function()
897 {
898 return this._highlightRegex;
899 },
900
901 highlightSelectedTokens: function()
902 {
903 delete this._highlightRegex;
904 delete this._highlightRange;
905 if (this._highlightDescriptor && this._highlightDescriptor.selectionStar t)
906 this._codeMirror.removeLineClass(this._highlightDescriptor.selection Start.line, "wrap", "cm-line-with-selection");
907 this._removeHighlight();
908 var selectionStart = this._codeMirror.getCursor("start");
909 var selectionEnd = this._codeMirror.getCursor("end");
910 if (selectionStart.line !== selectionEnd.line)
911 return;
912 if (selectionStart.ch === selectionEnd.ch)
913 return;
914 var selections = this._codeMirror.getSelections();
915 if (selections.length > 1)
916 return;
917 var selectedText = selections[0];
918 if (this._isWord(selectedText, selectionStart.line, selectionStart.ch, s electionEnd.ch)) {
919 if (selectionStart)
920 this._codeMirror.addLineClass(selectionStart.line, "wrap", "cm-l ine-with-selection");
921 this._setHighlighter(this._tokenHighlighter.bind(this, selectedText, selectionStart), selectionStart);
922 }
923 },
924
925 /**
926 * @param {string} selectedText
927 * @param {number} lineNumber
928 * @param {number} startColumn
929 * @param {number} endColumn
930 */
931 _isWord: function(selectedText, lineNumber, startColumn, endColumn)
932 {
933 var line = this._codeMirror.getLine(lineNumber);
934 var leftBound = startColumn === 0 || !WebInspector.TextUtils.isWordChar( line.charAt(startColumn - 1));
935 var rightBound = endColumn === line.length || !WebInspector.TextUtils.is WordChar(line.charAt(endColumn));
936 return leftBound && rightBound && WebInspector.TextUtils.isWord(selected Text);
937 },
938
939 _removeHighlight: function()
940 {
941 if (this._highlightDescriptor) {
942 this._codeMirror.removeOverlay(this._highlightDescriptor.overlay);
943 delete this._highlightDescriptor;
944 }
945 },
946
947 /**
948 * @param {!RegExp} regex
949 * @param {!CodeMirror.StringStream} stream
950 */
951 _searchHighlighter: function(regex, stream)
952 {
953 if (stream.column() === 0)
954 delete this._searchMatchLength;
955 if (this._searchMatchLength) {
956 if (this._searchMatchLength > 2) {
957 for (var i = 0; i < this._searchMatchLength - 2; ++i)
958 stream.next();
959 this._searchMatchLength = 1;
960 return "search-highlight";
961 } else {
962 stream.next();
963 delete this._searchMatchLength;
964 return "search-highlight search-highlight-end";
965 }
966 }
967 var match = stream.match(regex, false);
968 if (match) {
969 stream.next();
970 var matchLength = match[0].length;
971 if (matchLength === 1)
972 return "search-highlight search-highlight-full";
973 this._searchMatchLength = matchLength;
974 return "search-highlight search-highlight-start";
975 }
976 while (!stream.match(regex, false) && stream.next()) {}
977 },
978
979 /**
980 * @param {string} token
981 * @param {!CodeMirror.Pos} selectionStart
982 * @param {!CodeMirror.StringStream} stream
983 */
984 _tokenHighlighter: function(token, selectionStart, stream)
985 {
986 var tokenFirstChar = token.charAt(0);
987 if (stream.match(token) && (stream.eol() || !WebInspector.TextUtils.isWo rdChar(stream.peek())))
988 return stream.column() === selectionStart.ch ? "token-highlight colu mn-with-selection" : "token-highlight";
989 var eatenChar;
990 do {
991 eatenChar = stream.next();
992 } while (eatenChar && (WebInspector.TextUtils.isWordChar(eatenChar) || s tream.peek() !== tokenFirstChar));
993 },
994
995 /**
996 * @param {function(!CodeMirror.StringStream)} highlighter
997 * @param {?CodeMirror.Pos} selectionStart
998 */
999 _setHighlighter: function(highlighter, selectionStart)
1000 {
1001 var overlayMode = {
1002 token: highlighter
1003 };
1004 this._codeMirror.addOverlay(overlayMode);
1005 this._highlightDescriptor = {
1006 overlay: overlayMode,
1007 selectionStart: selectionStart
1008 };
1009 }
1010 }
1011
1012 WebInspector.SourcesTextEditor.LinesToScanForIndentationGuessing = 1000;
1013 WebInspector.SourcesTextEditor.MaximumNumberOfWhitespacesPerSingleSpan = 16;
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698