forked from microsoft/vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wordHighlighter.ts
920 lines (780 loc) · 32.7 KB
/
wordHighlighter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as arrays from 'vs/base/common/arrays';
import { alert } from 'vs/base/browser/ui/aria/aria';
import { CancelablePromise, createCancelablePromise, first, timeout } from 'vs/base/common/async';
import { CancellationToken } from 'vs/base/common/cancellation';
import { onUnexpectedError, onUnexpectedExternalError } from 'vs/base/common/errors';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { IActiveCodeEditor, ICodeEditor, isDiffEditor } from 'vs/editor/browser/editorBrowser';
import { EditorAction, EditorContributionInstantiation, IActionOptions, registerEditorAction, registerEditorContribution, registerModelAndPositionCommand } from 'vs/editor/browser/editorExtensions';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { EditorOption } from 'vs/editor/common/config/editorOptions';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { IWordAtPosition } from 'vs/editor/common/core/wordHelper';
import { CursorChangeReason, ICursorPositionChangedEvent } from 'vs/editor/common/cursorEvents';
import { IDiffEditor, IEditorContribution, IEditorDecorationsCollection } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { LanguageFeatureRegistry } from 'vs/editor/common/languageFeatureRegistry';
import { DocumentHighlight, DocumentHighlightKind, DocumentHighlightProvider, MultiDocumentHighlightProvider } from 'vs/editor/common/languages';
import { IModelDeltaDecoration, ITextModel } from 'vs/editor/common/model';
import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures';
import { getHighlightDecorationOptions } from 'vs/editor/contrib/wordHighlighter/browser/highlightDecorations';
import { IContextKey, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { Schemas } from 'vs/base/common/network';
import { ResourceMap } from 'vs/base/common/map';
const ctxHasWordHighlights = new RawContextKey<boolean>('hasWordHighlights', false);
export function getOccurrencesAtPosition(registry: LanguageFeatureRegistry<DocumentHighlightProvider>, model: ITextModel, position: Position, token: CancellationToken): Promise<ResourceMap<DocumentHighlight[]> | null | undefined> {
const orderedByScore = registry.ordered(model);
// in order of score ask the occurrences provider
// until someone response with a good result
// (good = none empty array)
return first<DocumentHighlight[] | null | undefined>(orderedByScore.map(provider => () => {
return Promise.resolve(provider.provideDocumentHighlights(model, position, token))
.then(undefined, onUnexpectedExternalError);
}), arrays.isNonEmptyArray).then(result => {
if (result) {
const map = new ResourceMap<DocumentHighlight[]>();
map.set(model.uri, result);
return map;
}
return new ResourceMap<DocumentHighlight[]>();
});
}
export function getOccurrencesAcrossMultipleModels(registry: LanguageFeatureRegistry<MultiDocumentHighlightProvider>, model: ITextModel, position: Position, wordSeparators: string, token: CancellationToken, otherModels: ITextModel[]): Promise<ResourceMap<DocumentHighlight[]> | null | undefined> {
const orderedByScore = registry.ordered(model);
// in order of score ask the occurrences provider
// until someone response with a good result
// (good = none empty array)
return first<ResourceMap<DocumentHighlight[]> | null | undefined>(orderedByScore.map(provider => () => {
return Promise.resolve(provider.provideMultiDocumentHighlights(model, position, otherModels, token))
.then(undefined, onUnexpectedExternalError);
}), (t: ResourceMap<DocumentHighlight[]> | null | undefined): t is ResourceMap<DocumentHighlight[]> => t instanceof Map && t.size > 0);
}
interface IOccurenceAtPositionRequest {
readonly result: Promise<ResourceMap<DocumentHighlight[]>>;
isValid(model: ITextModel, selection: Selection, decorations: IEditorDecorationsCollection): boolean;
cancel(): void;
}
interface IWordHighlighterQuery {
modelInfo: {
model: ITextModel;
selection: Selection;
} | null;
readonly word: IWordAtPosition | null;
}
abstract class OccurenceAtPositionRequest implements IOccurenceAtPositionRequest {
private readonly _wordRange: Range | null;
private _result: CancelablePromise<ResourceMap<DocumentHighlight[]>> | null;
constructor(private readonly _model: ITextModel, private readonly _selection: Selection, private readonly _wordSeparators: string) {
this._wordRange = this._getCurrentWordRange(_model, _selection);
this._result = null;
}
get result() {
if (!this._result) {
this._result = createCancelablePromise(token => this._compute(this._model, this._selection, this._wordSeparators, token));
}
return this._result;
}
protected abstract _compute(model: ITextModel, selection: Selection, wordSeparators: string, token: CancellationToken): Promise<ResourceMap<DocumentHighlight[]>>;
private _getCurrentWordRange(model: ITextModel, selection: Selection): Range | null {
const word = model.getWordAtPosition(selection.getPosition());
if (word) {
return new Range(selection.startLineNumber, word.startColumn, selection.startLineNumber, word.endColumn);
}
return null;
}
public isValid(model: ITextModel, selection: Selection, decorations: IEditorDecorationsCollection): boolean {
const lineNumber = selection.startLineNumber;
const startColumn = selection.startColumn;
const endColumn = selection.endColumn;
const currentWordRange = this._getCurrentWordRange(model, selection);
let requestIsValid = Boolean(this._wordRange && this._wordRange.equalsRange(currentWordRange));
// Even if we are on a different word, if that word is in the decorations ranges, the request is still valid
// (Same symbol)
for (let i = 0, len = decorations.length; !requestIsValid && i < len; i++) {
const range = decorations.getRange(i);
if (range && range.startLineNumber === lineNumber) {
if (range.startColumn <= startColumn && range.endColumn >= endColumn) {
requestIsValid = true;
}
}
}
return requestIsValid;
}
public cancel(): void {
this.result.cancel();
}
}
class SemanticOccurenceAtPositionRequest extends OccurenceAtPositionRequest {
private readonly _providers: LanguageFeatureRegistry<DocumentHighlightProvider>;
constructor(model: ITextModel, selection: Selection, wordSeparators: string, providers: LanguageFeatureRegistry<DocumentHighlightProvider>) {
super(model, selection, wordSeparators);
this._providers = providers;
}
protected _compute(model: ITextModel, selection: Selection, wordSeparators: string, token: CancellationToken): Promise<ResourceMap<DocumentHighlight[]>> {
return getOccurrencesAtPosition(this._providers, model, selection.getPosition(), token).then(value => {
if (!value) {
return new ResourceMap<DocumentHighlight[]>();
}
return value;
});
}
}
class MultiModelOccurenceRequest extends OccurenceAtPositionRequest {
private readonly _providers: LanguageFeatureRegistry<MultiDocumentHighlightProvider>;
private readonly _otherModels: ITextModel[];
constructor(model: ITextModel, selection: Selection, wordSeparators: string, providers: LanguageFeatureRegistry<MultiDocumentHighlightProvider>, otherModels: ITextModel[]) {
super(model, selection, wordSeparators);
this._providers = providers;
this._otherModels = otherModels;
}
protected override _compute(model: ITextModel, selection: Selection, wordSeparators: string, token: CancellationToken): Promise<ResourceMap<DocumentHighlight[]>> {
return getOccurrencesAcrossMultipleModels(this._providers, model, selection.getPosition(), wordSeparators, token, this._otherModels).then(value => {
if (!value) {
return new ResourceMap<DocumentHighlight[]>();
}
return value;
});
}
}
class TextualOccurenceRequest extends OccurenceAtPositionRequest {
private readonly _otherModels: ITextModel[];
private readonly _selectionIsEmpty: boolean;
private readonly _word: IWordAtPosition | null;
constructor(model: ITextModel, selection: Selection, word: IWordAtPosition | null, wordSeparators: string, otherModels: ITextModel[]) {
super(model, selection, wordSeparators);
this._otherModels = otherModels;
this._selectionIsEmpty = selection.isEmpty();
this._word = word;
}
protected _compute(model: ITextModel, selection: Selection, wordSeparators: string, token: CancellationToken): Promise<ResourceMap<DocumentHighlight[]>> {
return timeout(250, token).then(() => {
const result = new ResourceMap<DocumentHighlight[]>();
let wordResult;
if (this._word) {
wordResult = this._word;
} else {
wordResult = model.getWordAtPosition(selection.getPosition());
}
if (!wordResult) {
return new ResourceMap<DocumentHighlight[]>();
}
const allModels = [model, ...this._otherModels];
for (const otherModel of allModels) {
if (otherModel.isDisposed()) {
continue;
}
const matches = otherModel.findMatches(wordResult.word, true, false, true, wordSeparators, false);
const highlights = matches.map(m => ({
range: m.range,
kind: DocumentHighlightKind.Text
}));
if (highlights) {
result.set(otherModel.uri, highlights);
}
}
return result;
});
}
public override isValid(model: ITextModel, selection: Selection, decorations: IEditorDecorationsCollection): boolean {
const currentSelectionIsEmpty = selection.isEmpty();
if (this._selectionIsEmpty !== currentSelectionIsEmpty) {
return false;
}
return super.isValid(model, selection, decorations);
}
}
function computeOccurencesAtPosition(registry: LanguageFeatureRegistry<DocumentHighlightProvider>, model: ITextModel, selection: Selection, word: IWordAtPosition | null, wordSeparators: string): IOccurenceAtPositionRequest {
if (registry.has(model)) {
return new SemanticOccurenceAtPositionRequest(model, selection, wordSeparators, registry);
}
return new TextualOccurenceRequest(model, selection, word, wordSeparators, []);
}
function computeOccurencesMultiModel(registry: LanguageFeatureRegistry<MultiDocumentHighlightProvider>, model: ITextModel, selection: Selection, word: IWordAtPosition | null, wordSeparators: string, otherModels: ITextModel[]): IOccurenceAtPositionRequest {
if (registry.has(model)) {
return new MultiModelOccurenceRequest(model, selection, wordSeparators, registry, otherModels);
}
return new TextualOccurenceRequest(model, selection, word, wordSeparators, otherModels);
}
registerModelAndPositionCommand('_executeDocumentHighlights', (accessor, model, position) => {
const languageFeaturesService = accessor.get(ILanguageFeaturesService);
return getOccurrencesAtPosition(languageFeaturesService.documentHighlightProvider, model, position, CancellationToken.None);
});
class WordHighlighter {
private readonly editor: IActiveCodeEditor;
private readonly providers: LanguageFeatureRegistry<DocumentHighlightProvider>;
private readonly multiDocumentProviders: LanguageFeatureRegistry<MultiDocumentHighlightProvider>;
private occurrencesHighlight: boolean;
private multiDocumentOccurrencesHighlight: boolean;
private readonly model: ITextModel;
private readonly decorations: IEditorDecorationsCollection;
private readonly toUnhook = new DisposableStore();
private readonly codeEditorService: ICodeEditorService;
private workerRequestTokenId: number = 0;
private workerRequest: IOccurenceAtPositionRequest | null;
private workerRequestCompleted: boolean = false;
private workerRequestValue: ResourceMap<DocumentHighlight[]> = new ResourceMap();
private lastCursorPositionChangeTime: number = 0;
private renderDecorationsTimer: any = -1;
private readonly _hasWordHighlights: IContextKey<boolean>;
private _ignorePositionChangeEvent: boolean;
private static storedDecorations: ResourceMap<string[]> = new ResourceMap();
private static query: IWordHighlighterQuery | null = null;
constructor(editor: IActiveCodeEditor, providers: LanguageFeatureRegistry<DocumentHighlightProvider>, multiProviders: LanguageFeatureRegistry<MultiDocumentHighlightProvider>, contextKeyService: IContextKeyService, @ICodeEditorService codeEditorService: ICodeEditorService) {
this.editor = editor;
this.providers = providers;
this.multiDocumentProviders = multiProviders;
this.codeEditorService = codeEditorService;
this._hasWordHighlights = ctxHasWordHighlights.bindTo(contextKeyService);
this._ignorePositionChangeEvent = false;
this.occurrencesHighlight = this.editor.getOption(EditorOption.occurrencesHighlight);
this.multiDocumentOccurrencesHighlight = this.editor.getOption(EditorOption.multiDocumentOccurrencesHighlight);
this.model = this.editor.getModel();
this.toUnhook.add(editor.onDidChangeCursorPosition((e: ICursorPositionChangedEvent) => {
if (this._ignorePositionChangeEvent) {
// We are changing the position => ignore this event
return;
}
if (!this.occurrencesHighlight) {
// Early exit if nothing needs to be done!
// Leave some form of early exit check here if you wish to continue being a cursor position change listener ;)
return;
}
this._onPositionChanged(e);
}));
this.toUnhook.add(editor.onDidChangeModelContent((e) => {
this._stopAll();
}));
this.toUnhook.add(editor.onDidChangeModel((e) => {
if (!e.newModelUrl && e.oldModelUrl) {
this._stopSingular();
} else {
if (WordHighlighter.query) {
this._run();
}
}
}));
this.toUnhook.add(editor.onDidChangeConfiguration((e) => {
const newValue = this.editor.getOption(EditorOption.occurrencesHighlight);
if (this.occurrencesHighlight !== newValue) {
this.occurrencesHighlight = newValue;
this._stopAll();
}
const newMultiDocumentValue = this.editor.getOption(EditorOption.multiDocumentOccurrencesHighlight);
if (this.multiDocumentOccurrencesHighlight !== newMultiDocumentValue) {
this.multiDocumentOccurrencesHighlight = newMultiDocumentValue;
this._stopAll();
}
}));
this.decorations = this.editor.createDecorationsCollection();
this.workerRequestTokenId = 0;
this.workerRequest = null;
this.workerRequestCompleted = false;
this.lastCursorPositionChangeTime = 0;
this.renderDecorationsTimer = -1;
// if there is a query already, highlight off that query
if (WordHighlighter.query) {
this._run();
}
}
public hasDecorations(): boolean {
return (this.decorations.length > 0);
}
public restore(): void {
if (!this.occurrencesHighlight) {
return;
}
this._run();
}
public stop(): void {
if (!this.occurrencesHighlight) {
return;
}
this._stopAll();
}
private _getSortedHighlights(): Range[] {
return (
this.decorations.getRanges()
.sort(Range.compareRangesUsingStarts)
);
}
public moveNext() {
const highlights = this._getSortedHighlights();
const index = highlights.findIndex((range) => range.containsPosition(this.editor.getPosition()));
const newIndex = ((index + 1) % highlights.length);
const dest = highlights[newIndex];
try {
this._ignorePositionChangeEvent = true;
this.editor.setPosition(dest.getStartPosition());
this.editor.revealRangeInCenterIfOutsideViewport(dest);
const word = this._getWord();
if (word) {
const lineContent = this.editor.getModel().getLineContent(dest.startLineNumber);
alert(`${lineContent}, ${newIndex + 1} of ${highlights.length} for '${word.word}'`);
}
} finally {
this._ignorePositionChangeEvent = false;
}
}
public moveBack() {
const highlights = this._getSortedHighlights();
const index = highlights.findIndex((range) => range.containsPosition(this.editor.getPosition()));
const newIndex = ((index - 1 + highlights.length) % highlights.length);
const dest = highlights[newIndex];
try {
this._ignorePositionChangeEvent = true;
this.editor.setPosition(dest.getStartPosition());
this.editor.revealRangeInCenterIfOutsideViewport(dest);
const word = this._getWord();
if (word) {
const lineContent = this.editor.getModel().getLineContent(dest.startLineNumber);
alert(`${lineContent}, ${newIndex + 1} of ${highlights.length} for '${word.word}'`);
}
} finally {
this._ignorePositionChangeEvent = false;
}
}
private _removeSingleDecorations(): void {
// return if no model
if (!this.editor.hasModel()) {
return;
}
const currentDecorationIDs = WordHighlighter.storedDecorations.get(this.editor.getModel().uri);
if (!currentDecorationIDs) {
return;
}
this.editor.removeDecorations(currentDecorationIDs);
WordHighlighter.storedDecorations.delete(this.editor.getModel().uri);
if (this.decorations.length > 0) {
this.decorations.clear();
this._hasWordHighlights.set(false);
}
}
private _removeAllDecorations(): void {
const currentEditors = this.codeEditorService.listCodeEditors();
// iterate over editors and store models in currentModels
for (const editor of currentEditors) {
if (!editor.hasModel()) {
continue;
}
const currentDecorationIDs = WordHighlighter.storedDecorations.get(editor.getModel().uri);
if (!currentDecorationIDs) {
continue;
}
editor.removeDecorations(currentDecorationIDs);
WordHighlighter.storedDecorations.delete(editor.getModel().uri);
const editorHighlighterContrib = WordHighlighterContribution.get(editor);
if (!editorHighlighterContrib?.wordHighlighter) {
continue;
}
if (editorHighlighterContrib.wordHighlighter.decorations.length > 0) {
editorHighlighterContrib.wordHighlighter.decorations.clear();
editorHighlighterContrib.wordHighlighter._hasWordHighlights.set(false);
}
}
}
private _stopSingular(): void {
// Remove any existing decorations + a possible query, and re - run to update decorations
this._removeSingleDecorations();
if (this.editor.hasWidgetFocus()) {
if (this.editor.getModel()?.uri.scheme !== Schemas.vscodeNotebookCell && WordHighlighter.query?.modelInfo?.model.uri.scheme !== Schemas.vscodeNotebookCell) { // clear query if focused non-nb editor
WordHighlighter.query = null;
this._run();
} else { // remove modelInfo to account for nb cell being disposed
if (WordHighlighter.query?.modelInfo) {
WordHighlighter.query.modelInfo = null;
}
}
}
// Cancel any renderDecorationsTimer
if (this.renderDecorationsTimer !== -1) {
clearTimeout(this.renderDecorationsTimer);
this.renderDecorationsTimer = -1;
}
// Cancel any worker request
if (this.workerRequest !== null) {
this.workerRequest.cancel();
this.workerRequest = null;
}
// Invalidate any worker request callback
if (!this.workerRequestCompleted) {
this.workerRequestTokenId++;
this.workerRequestCompleted = true;
}
}
private _stopAll(): void {
// Remove any existing decorations
this._removeAllDecorations();
// Cancel any renderDecorationsTimer
if (this.renderDecorationsTimer !== -1) {
clearTimeout(this.renderDecorationsTimer);
this.renderDecorationsTimer = -1;
}
// Cancel any worker request
if (this.workerRequest !== null) {
this.workerRequest.cancel();
this.workerRequest = null;
}
// Invalidate any worker request callback
if (!this.workerRequestCompleted) {
this.workerRequestTokenId++;
this.workerRequestCompleted = true;
}
}
private _onPositionChanged(e: ICursorPositionChangedEvent): void {
// disabled
if (!this.occurrencesHighlight) {
this._stopAll();
return;
}
// ignore typing & other
// need to check if the model is a notebook cell, should not stop if nb
if (e.reason !== CursorChangeReason.Explicit && this.editor.getModel()?.uri.scheme !== Schemas.vscodeNotebookCell) {
this._stopAll();
return;
}
this._run();
}
private _getWord(): IWordAtPosition | null {
const editorSelection = this.editor.getSelection();
const lineNumber = editorSelection.startLineNumber;
const startColumn = editorSelection.startColumn;
if (this.model.isDisposed()) {
return null;
}
return this.model.getWordAtPosition({
lineNumber: lineNumber,
column: startColumn
});
}
private getOtherModelsToHighlight(model: ITextModel): ITextModel[] {
if (!model) {
return [];
}
// notebook case
const isNotebookEditor = model.uri.scheme === Schemas.vscodeNotebookCell;
if (isNotebookEditor) {
const currentModels: ITextModel[] = [];
const currentEditors = this.codeEditorService.listCodeEditors();
for (const editor of currentEditors) {
const tempModel = editor.getModel();
if (tempModel && tempModel !== model && tempModel.uri.scheme === Schemas.vscodeNotebookCell) {
currentModels.push(tempModel);
}
}
return currentModels;
}
// inline case
// ? current works when highlighting outside of an inline diff, highlighting in.
// ? broken when highlighting within a diff editor. highlighting the main editor does not work
// ? editor group service could be useful here
const currentModels: ITextModel[] = [];
const currentEditors = this.codeEditorService.listCodeEditors();
for (const editor of currentEditors) {
if (!isDiffEditor(editor)) {
continue;
}
const diffModel = (editor as IDiffEditor).getModel();
if (!diffModel) {
continue;
}
if (model === diffModel.modified) { // embedded inline chat diff would pass this, allowing highlights
//? currentModels.push(diffModel.original);
currentModels.push(diffModel.modified);
}
}
if (currentModels.length) { // no matching editors have been found
return currentModels;
}
// multi-doc OFF
if (!this.multiDocumentOccurrencesHighlight) {
return [];
}
// multi-doc ON
for (const editor of currentEditors) {
const tempModel = editor.getModel();
if (tempModel && tempModel !== model) {
currentModels.push(tempModel);
}
}
return currentModels;
}
private _run(): void {
let workerRequestIsValid;
if (!this.editor.hasWidgetFocus()) { // no focus (new nb cell, etc)
if (WordHighlighter.query === null) {
// no previous query, nothing to highlight
return;
}
} else {
const editorSelection = this.editor.getSelection();
// ignore multiline selection
if (!editorSelection || editorSelection.startLineNumber !== editorSelection.endLineNumber) {
this._stopAll();
return;
}
const startColumn = editorSelection.startColumn;
const endColumn = editorSelection.endColumn;
const word = this._getWord();
// The selection must be inside a word or surround one word at most
if (!word || word.startColumn > startColumn || word.endColumn < endColumn) {
// no previous query, nothing to highlight
this._stopAll();
return;
}
// All the effort below is trying to achieve this:
// - when cursor is moved to a word, trigger immediately a findOccurrences request
// - 250ms later after the last cursor move event, render the occurrences
// - no flickering!
workerRequestIsValid = (this.workerRequest && this.workerRequest.isValid(this.model, editorSelection, this.decorations));
WordHighlighter.query = {
modelInfo: {
model: this.model,
selection: editorSelection,
},
word: word
};
}
// There are 4 cases:
// a) old workerRequest is valid & completed, renderDecorationsTimer fired
// b) old workerRequest is valid & completed, renderDecorationsTimer not fired
// c) old workerRequest is valid, but not completed
// d) old workerRequest is not valid
// For a) no action is needed
// For c), member 'lastCursorPositionChangeTime' will be used when installing the timer so no action is needed
this.lastCursorPositionChangeTime = (new Date()).getTime();
if (workerRequestIsValid) {
if (this.workerRequestCompleted && this.renderDecorationsTimer !== -1) {
// case b)
// Delay the firing of renderDecorationsTimer by an extra 250 ms
clearTimeout(this.renderDecorationsTimer);
this.renderDecorationsTimer = -1;
this._beginRenderDecorations();
}
} else {
// case d)
// Stop all previous actions and start fresh
this._stopAll();
const myRequestId = ++this.workerRequestTokenId;
this.workerRequestCompleted = false;
const otherModelsToHighlight = this.getOtherModelsToHighlight(this.editor.getModel());
// 2 cases where we want to send the word
// a) there is no stored query model, but there is a word. This signals the editor that drove the highlight is disposed (cell out of viewport, etc)
// b) the queried model is not the current model. This signals that the editor that drove the highlight is still in the viewport, but we are highlighting a different cell
// otherwise, we send null in place of the word, and the model and selection are used to compute the word
const sendWord = (!WordHighlighter.query.modelInfo && WordHighlighter.query.word) ||
(WordHighlighter.query.modelInfo?.model.uri !== this.model.uri)
? true : false;
if (!WordHighlighter.query.modelInfo || (WordHighlighter.query.modelInfo.model.uri !== this.model.uri)) { // use this.model
this.workerRequest = this.computeWithModel(this.model, this.editor.getSelection(), sendWord ? WordHighlighter.query.word : null, otherModelsToHighlight);
} else { // use stored query model + selection
this.workerRequest = this.computeWithModel(WordHighlighter.query.modelInfo.model, WordHighlighter.query.modelInfo.selection, WordHighlighter.query.word, otherModelsToHighlight);
}
this.workerRequest?.result.then(data => {
if (myRequestId === this.workerRequestTokenId) {
this.workerRequestCompleted = true;
this.workerRequestValue = data || [];
this._beginRenderDecorations();
}
}, onUnexpectedError);
}
}
private computeWithModel(model: ITextModel, selection: Selection, word: IWordAtPosition | null, otherModels: ITextModel[]): IOccurenceAtPositionRequest | null {
if (!otherModels.length) {
return computeOccurencesAtPosition(this.providers, model, selection, word, this.editor.getOption(EditorOption.wordSeparators));
} else {
return computeOccurencesMultiModel(this.multiDocumentProviders, model, selection, word, this.editor.getOption(EditorOption.wordSeparators), otherModels);
}
}
private _beginRenderDecorations(): void {
const currentTime = (new Date()).getTime();
const minimumRenderTime = this.lastCursorPositionChangeTime + 250;
if (currentTime >= minimumRenderTime) {
// Synchronous
this.renderDecorationsTimer = -1;
this.renderDecorations();
} else {
// Asynchronous
this.renderDecorationsTimer = setTimeout(() => {
this.renderDecorations();
}, (minimumRenderTime - currentTime));
}
}
private renderDecorations(): void {
this.renderDecorationsTimer = -1;
// create new loop, iterate over current editors using this.codeEditorService.listCodeEditors(),
// if the URI of that codeEditor is in the map, then add the decorations to the decorations array
// then set the decorations for the editor
const currentEditors = this.codeEditorService.listCodeEditors();
for (const editor of currentEditors) {
const editorHighlighterContrib = WordHighlighterContribution.get(editor);
if (!editorHighlighterContrib) {
continue;
}
const newDecorations: IModelDeltaDecoration[] = [];
const uri = editor.getModel()?.uri;
if (uri && this.workerRequestValue.has(uri)) {
const oldDecorationIDs: string[] | undefined = WordHighlighter.storedDecorations.get(uri);
const newDocumentHighlights = this.workerRequestValue.get(uri);
if (newDocumentHighlights) {
for (const highlight of newDocumentHighlights) {
newDecorations.push({
range: highlight.range,
options: getHighlightDecorationOptions(highlight.kind)
});
}
}
let newDecorationIDs: string[] = [];
editor.changeDecorations((changeAccessor) => {
newDecorationIDs = changeAccessor.deltaDecorations(oldDecorationIDs ?? [], newDecorations);
});
WordHighlighter.storedDecorations = WordHighlighter.storedDecorations.set(uri, newDecorationIDs);
if (newDecorations.length > 0) {
editorHighlighterContrib.wordHighlighter?.decorations.set(newDecorations);
editorHighlighterContrib.wordHighlighter?._hasWordHighlights.set(true);
}
}
}
}
public dispose(): void {
this._stopSingular();
this.toUnhook.dispose();
}
}
export class WordHighlighterContribution extends Disposable implements IEditorContribution {
public static readonly ID = 'editor.contrib.wordHighlighter';
public static get(editor: ICodeEditor): WordHighlighterContribution | null {
return editor.getContribution<WordHighlighterContribution>(WordHighlighterContribution.ID);
}
private _wordHighlighter: WordHighlighter | null;
constructor(editor: ICodeEditor, @IContextKeyService contextKeyService: IContextKeyService, @ILanguageFeaturesService languageFeaturesService: ILanguageFeaturesService, @ICodeEditorService codeEditorService: ICodeEditorService) {
super();
this._wordHighlighter = null;
const createWordHighlighterIfPossible = () => {
if (editor.hasModel() && !editor.getModel().isTooLargeForTokenization()) {
this._wordHighlighter = new WordHighlighter(editor, languageFeaturesService.documentHighlightProvider, languageFeaturesService.multiDocumentHighlightProvider, contextKeyService, codeEditorService);
}
};
this._register(editor.onDidChangeModel((e) => {
if (this._wordHighlighter) {
this._wordHighlighter.dispose();
this._wordHighlighter = null;
}
createWordHighlighterIfPossible();
}));
createWordHighlighterIfPossible();
}
public get wordHighlighter(): WordHighlighter | null {
return this._wordHighlighter;
}
public saveViewState(): boolean {
if (this._wordHighlighter && this._wordHighlighter.hasDecorations()) {
return true;
}
return false;
}
public moveNext() {
this._wordHighlighter?.moveNext();
}
public moveBack() {
this._wordHighlighter?.moveBack();
}
public restoreViewState(state: boolean | undefined): void {
if (this._wordHighlighter && state) {
this._wordHighlighter.restore();
}
}
public stopHighlighting() {
this._wordHighlighter?.stop();
}
public override dispose(): void {
if (this._wordHighlighter) {
this._wordHighlighter.dispose();
this._wordHighlighter = null;
}
super.dispose();
}
}
class WordHighlightNavigationAction extends EditorAction {
private readonly _isNext: boolean;
constructor(next: boolean, opts: IActionOptions) {
super(opts);
this._isNext = next;
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
const controller = WordHighlighterContribution.get(editor);
if (!controller) {
return;
}
if (this._isNext) {
controller.moveNext();
} else {
controller.moveBack();
}
}
}
class NextWordHighlightAction extends WordHighlightNavigationAction {
constructor() {
super(true, {
id: 'editor.action.wordHighlight.next',
label: nls.localize('wordHighlight.next.label', "Go to Next Symbol Highlight"),
alias: 'Go to Next Symbol Highlight',
precondition: ctxHasWordHighlights,
kbOpts: {
kbExpr: EditorContextKeys.editorTextFocus,
primary: KeyCode.F7,
weight: KeybindingWeight.EditorContrib
}
});
}
}
class PrevWordHighlightAction extends WordHighlightNavigationAction {
constructor() {
super(false, {
id: 'editor.action.wordHighlight.prev',
label: nls.localize('wordHighlight.previous.label', "Go to Previous Symbol Highlight"),
alias: 'Go to Previous Symbol Highlight',
precondition: ctxHasWordHighlights,
kbOpts: {
kbExpr: EditorContextKeys.editorTextFocus,
primary: KeyMod.Shift | KeyCode.F7,
weight: KeybindingWeight.EditorContrib
}
});
}
}
class TriggerWordHighlightAction extends EditorAction {
constructor() {
super({
id: 'editor.action.wordHighlight.trigger',
label: nls.localize('wordHighlight.trigger.label', "Trigger Symbol Highlight"),
alias: 'Trigger Symbol Highlight',
precondition: ctxHasWordHighlights.toNegated(),
kbOpts: {
kbExpr: EditorContextKeys.editorTextFocus,
primary: 0,
weight: KeybindingWeight.EditorContrib
}
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor, args: any): void {
const controller = WordHighlighterContribution.get(editor);
if (!controller) {
return;
}
controller.restoreViewState(true);
}
}
registerEditorContribution(WordHighlighterContribution.ID, WordHighlighterContribution, EditorContributionInstantiation.Eager); // eager because it uses `saveViewState`/`restoreViewState`
registerEditorAction(NextWordHighlightAction);
registerEditorAction(PrevWordHighlightAction);
registerEditorAction(TriggerWordHighlightAction);