-
Notifications
You must be signed in to change notification settings - Fork 30.7k
/
Copy pathsearchModel.ts
2566 lines (2159 loc) · 85.3 KB
/
searchModel.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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { RunOnceScheduler } from 'vs/base/common/async';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { compareFileExtensions, compareFileNames, comparePaths } from 'vs/base/common/comparers';
import { memoize } from 'vs/base/common/decorators';
import * as errors from 'vs/base/common/errors';
import { Emitter, Event, PauseableEmitter } from 'vs/base/common/event';
import { Lazy } from 'vs/base/common/lazy';
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { ResourceMap } from 'vs/base/common/map';
import { Schemas } from 'vs/base/common/network';
import { lcut } from 'vs/base/common/strings';
import { TernarySearchTree } from 'vs/base/common/ternarySearchTree';
import { URI } from 'vs/base/common/uri';
import { Range } from 'vs/editor/common/core/range';
import { FindMatch, IModelDeltaDecoration, ITextModel, MinimapPosition, OverviewRulerLane, TrackedRangeStickiness } from 'vs/editor/common/model';
import { ModelDecorationOptions } from 'vs/editor/common/model/textModel';
import { IModelService } from 'vs/editor/common/services/model';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IFileService, IFileStatWithPartialMetadata } from 'vs/platform/files/common/files';
import { createDecorator, IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ILabelService } from 'vs/platform/label/common/label';
import { ILogService } from 'vs/platform/log/common/log';
import { IProgress, IProgressService, IProgressStep, ProgressLocation } from 'vs/platform/progress/common/progress';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { minimapFindMatch, overviewRulerFindMatchForeground } from 'vs/platform/theme/common/colorRegistry';
import { themeColorFromId } from 'vs/platform/theme/common/themeService';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { FindMatchDecorationModel } from 'vs/workbench/contrib/notebook/browser/contrib/find/findMatchDecorationModel';
import { CellFindMatchWithIndex, CellWebviewFindMatch, ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { NotebookEditorWidget } from 'vs/workbench/contrib/notebook/browser/notebookEditorWidget';
import { INotebookEditorService } from 'vs/workbench/contrib/notebook/browser/services/notebookEditorService';
import { NotebookCellsChangeType } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { IReplaceService } from 'vs/workbench/contrib/search/browser/replace';
import { contentMatchesToTextSearchMatches, webviewMatchesToTextSearchMatches, INotebookCellMatchWithModel, isINotebookFileMatchWithModel, isINotebookCellMatchWithModel, getIDFromINotebookCellMatch } from 'vs/workbench/contrib/search/browser/notebookSearch/searchNotebookHelpers';
import { INotebookSearchService } from 'vs/workbench/contrib/search/common/notebookSearch';
import { rawCellPrefix, INotebookCellMatchNoModel, isINotebookFileMatchNoModel } from 'vs/workbench/contrib/search/common/searchNotebookHelpers';
import { ReplacePattern } from 'vs/workbench/services/search/common/replace';
import { IAITextQuery, IFileMatch, IPatternInfo, ISearchComplete, ISearchConfigurationProperties, ISearchProgressItem, ISearchRange, ISearchService, ITextQuery, ITextSearchContext, ITextSearchMatch, ITextSearchPreviewOptions, ITextSearchResult, ITextSearchStats, OneLineRange, QueryType, resultIsMatch, SearchCompletionExitCode, SearchSortOrder } from 'vs/workbench/services/search/common/search';
import { getTextSearchMatchWithModelContext, editorMatchesToTextSearchResults } from 'vs/workbench/services/search/common/searchHelpers';
import { CellSearchModel } from 'vs/workbench/contrib/search/common/cellSearchModel';
import { CellFindMatchModel } from 'vs/workbench/contrib/notebook/browser/contrib/find/findModel';
import { coalesce } from 'vs/base/common/arrays';
export class Match {
private static readonly MAX_PREVIEW_CHARS = 250;
protected _id: string;
protected _range: Range;
private _oneLinePreviewText: string;
private _rangeInPreviewText: ISearchRange;
// For replace
private _fullPreviewRange: ISearchRange;
constructor(protected _parent: FileMatch, private _fullPreviewLines: string[], _fullPreviewRange: ISearchRange, _documentRange: ISearchRange, public readonly aiContributed: boolean) {
this._oneLinePreviewText = _fullPreviewLines[_fullPreviewRange.startLineNumber];
const adjustedEndCol = _fullPreviewRange.startLineNumber === _fullPreviewRange.endLineNumber ?
_fullPreviewRange.endColumn :
this._oneLinePreviewText.length;
this._rangeInPreviewText = new OneLineRange(1, _fullPreviewRange.startColumn + 1, adjustedEndCol + 1);
this._range = new Range(
_documentRange.startLineNumber + 1,
_documentRange.startColumn + 1,
_documentRange.endLineNumber + 1,
_documentRange.endColumn + 1);
this._fullPreviewRange = _fullPreviewRange;
this._id = this._parent.id() + '>' + this._range + this.getMatchString();
}
id(): string {
return this._id;
}
parent(): FileMatch {
return this._parent;
}
text(): string {
return this._oneLinePreviewText;
}
range(): Range {
return this._range;
}
@memoize
preview(): { before: string; fullBefore: string; inside: string; after: string } {
const fullBefore = this._oneLinePreviewText.substring(0, this._rangeInPreviewText.startColumn - 1),
before = lcut(fullBefore, 26, '…');
let inside = this.getMatchString(),
after = this._oneLinePreviewText.substring(this._rangeInPreviewText.endColumn - 1);
let charsRemaining = Match.MAX_PREVIEW_CHARS - before.length;
inside = inside.substr(0, charsRemaining);
charsRemaining -= inside.length;
after = after.substr(0, charsRemaining);
return {
before,
fullBefore,
inside,
after,
};
}
get replaceString(): string {
const searchModel = this.parent().parent().searchModel;
if (!searchModel.replacePattern) {
throw new Error('searchModel.replacePattern must be set before accessing replaceString');
}
const fullMatchText = this.fullMatchText();
let replaceString = searchModel.replacePattern.getReplaceString(fullMatchText, searchModel.preserveCase);
if (replaceString !== null) {
return replaceString;
}
// Search/find normalize line endings - check whether \r prevents regex from matching
const fullMatchTextWithoutCR = fullMatchText.replace(/\r\n/g, '\n');
if (fullMatchTextWithoutCR !== fullMatchText) {
replaceString = searchModel.replacePattern.getReplaceString(fullMatchTextWithoutCR, searchModel.preserveCase);
if (replaceString !== null) {
return replaceString;
}
}
// If match string is not matching then regex pattern has a lookahead expression
const contextMatchTextWithSurroundingContent = this.fullMatchText(true);
replaceString = searchModel.replacePattern.getReplaceString(contextMatchTextWithSurroundingContent, searchModel.preserveCase);
if (replaceString !== null) {
return replaceString;
}
// Search/find normalize line endings, this time in full context
const contextMatchTextWithoutCR = contextMatchTextWithSurroundingContent.replace(/\r\n/g, '\n');
if (contextMatchTextWithoutCR !== contextMatchTextWithSurroundingContent) {
replaceString = searchModel.replacePattern.getReplaceString(contextMatchTextWithoutCR, searchModel.preserveCase);
if (replaceString !== null) {
return replaceString;
}
}
// Match string is still not matching. Could be unsupported matches (multi-line).
return searchModel.replacePattern.pattern;
}
fullMatchText(includeSurrounding = false): string {
let thisMatchPreviewLines: string[];
if (includeSurrounding) {
thisMatchPreviewLines = this._fullPreviewLines;
} else {
thisMatchPreviewLines = this._fullPreviewLines.slice(this._fullPreviewRange.startLineNumber, this._fullPreviewRange.endLineNumber + 1);
thisMatchPreviewLines[thisMatchPreviewLines.length - 1] = thisMatchPreviewLines[thisMatchPreviewLines.length - 1].slice(0, this._fullPreviewRange.endColumn);
thisMatchPreviewLines[0] = thisMatchPreviewLines[0].slice(this._fullPreviewRange.startColumn);
}
return thisMatchPreviewLines.join('\n');
}
rangeInPreview() {
// convert to editor's base 1 positions.
return {
...this._fullPreviewRange,
startColumn: this._fullPreviewRange.startColumn + 1,
endColumn: this._fullPreviewRange.endColumn + 1
};
}
fullPreviewLines(): string[] {
return this._fullPreviewLines.slice(this._fullPreviewRange.startLineNumber, this._fullPreviewRange.endLineNumber + 1);
}
getMatchString(): string {
return this._oneLinePreviewText.substring(this._rangeInPreviewText.startColumn - 1, this._rangeInPreviewText.endColumn - 1);
}
}
export class CellMatch {
private _contentMatches: Map<string, MatchInNotebook>;
private _webviewMatches: Map<string, MatchInNotebook>;
private _context: Map<number, string>;
constructor(
private readonly _parent: FileMatch,
private _cell: ICellViewModel | undefined,
private readonly _cellIndex: number,
) {
this._contentMatches = new Map<string, MatchInNotebook>();
this._webviewMatches = new Map<string, MatchInNotebook>();
this._context = new Map<number, string>();
}
public hasCellViewModel() {
return !(this._cell instanceof CellSearchModel);
}
get context(): Map<number, string> {
return new Map(this._context);
}
matches() {
return [...this._contentMatches.values(), ... this._webviewMatches.values()];
}
get contentMatches(): MatchInNotebook[] {
return Array.from(this._contentMatches.values());
}
get webviewMatches(): MatchInNotebook[] {
return Array.from(this._webviewMatches.values());
}
remove(matches: MatchInNotebook | MatchInNotebook[]): void {
if (!Array.isArray(matches)) {
matches = [matches];
}
for (const match of matches) {
this._contentMatches.delete(match.id());
this._webviewMatches.delete(match.id());
}
}
clearAllMatches() {
this._contentMatches.clear();
this._webviewMatches.clear();
}
addContentMatches(textSearchMatches: ITextSearchMatch[]) {
const contentMatches = textSearchMatchesToNotebookMatches(textSearchMatches, this);
contentMatches.forEach((match) => {
this._contentMatches.set(match.id(), match);
});
this.addContext(textSearchMatches);
}
public addContext(textSearchMatches: ITextSearchMatch[]) {
if (!this.cell) {
// todo: get closed notebook results in search editor
return;
}
this.cell.resolveTextModel().then((textModel) => {
const textResultsWithContext = getTextSearchMatchWithModelContext(textSearchMatches, textModel, this.parent.parent().query!);
const contexts = textResultsWithContext.filter((result => !resultIsMatch(result)) as ((a: any) => a is ITextSearchContext));
contexts.map(context => ({ ...context, lineNumber: context.lineNumber + 1 }))
.forEach((context) => { this._context.set(context.lineNumber, context.text); });
});
}
addWebviewMatches(textSearchMatches: ITextSearchMatch[]) {
const webviewMatches = textSearchMatchesToNotebookMatches(textSearchMatches, this);
webviewMatches.forEach((match) => {
this._webviewMatches.set(match.id(), match);
});
// TODO: add webview results to context
}
setCellModel(cell: ICellViewModel) {
this._cell = cell;
}
get parent(): FileMatch {
return this._parent;
}
get id(): string {
return this._cell?.id ?? `${rawCellPrefix}${this.cellIndex}`;
}
get cellIndex(): number {
return this._cellIndex;
}
get cell(): ICellViewModel | undefined {
return this._cell;
}
}
export class MatchInNotebook extends Match {
private _webviewIndex: number | undefined;
constructor(private readonly _cellParent: CellMatch, _fullPreviewLines: string[], _fullPreviewRange: ISearchRange, _documentRange: ISearchRange, webviewIndex?: number) {
super(_cellParent.parent, _fullPreviewLines, _fullPreviewRange, _documentRange, false);
this._id = this._parent.id() + '>' + this._cellParent.cellIndex + (webviewIndex ? '_' + webviewIndex : '') + '_' + this.notebookMatchTypeString() + this._range + this.getMatchString();
this._webviewIndex = webviewIndex;
}
override parent(): FileMatch { // visible parent in search tree
return this._cellParent.parent;
}
get cellParent(): CellMatch {
return this._cellParent;
}
private notebookMatchTypeString(): string {
return this.isWebviewMatch() ? 'webview' : 'content';
}
public isWebviewMatch() {
return this._webviewIndex !== undefined;
}
public isReadonly() {
return (!this._cellParent.hasCellViewModel()) || this.isWebviewMatch();
}
get cellIndex() {
return this._cellParent.cellIndex;
}
get webviewIndex() {
return this._webviewIndex;
}
get cell() {
return this._cellParent.cell;
}
}
export class FileMatch extends Disposable implements IFileMatch {
private static readonly _CURRENT_FIND_MATCH = ModelDecorationOptions.register({
description: 'search-current-find-match',
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
zIndex: 13,
className: 'currentFindMatch',
overviewRuler: {
color: themeColorFromId(overviewRulerFindMatchForeground),
position: OverviewRulerLane.Center
},
minimap: {
color: themeColorFromId(minimapFindMatch),
position: MinimapPosition.Inline
}
});
private static readonly _FIND_MATCH = ModelDecorationOptions.register({
description: 'search-find-match',
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
className: 'findMatch',
overviewRuler: {
color: themeColorFromId(overviewRulerFindMatchForeground),
position: OverviewRulerLane.Center
},
minimap: {
color: themeColorFromId(minimapFindMatch),
position: MinimapPosition.Inline
}
});
private static getDecorationOption(selected: boolean): ModelDecorationOptions {
return (selected ? FileMatch._CURRENT_FIND_MATCH : FileMatch._FIND_MATCH);
}
protected _onChange = this._register(new Emitter<{ didRemove?: boolean; forceUpdateModel?: boolean }>());
readonly onChange: Event<{ didRemove?: boolean; forceUpdateModel?: boolean }> = this._onChange.event;
private _onDispose = this._register(new Emitter<void>());
readonly onDispose: Event<void> = this._onDispose.event;
private _resource: URI;
private _fileStat?: IFileStatWithPartialMetadata;
private _model: ITextModel | null = null;
private _modelListener: IDisposable | null = null;
private _textMatches: Map<string, Match>;
private _cellMatches: Map<string, CellMatch>;
private _removedTextMatches: Set<string>;
private _selectedMatch: Match | null = null;
private _name: Lazy<string>;
private _updateScheduler: RunOnceScheduler;
private _modelDecorations: string[] = [];
private _context: Map<number, string> = new Map();
public get context(): Map<number, string> {
return new Map(this._context);
}
public get cellContext(): Map<string, Map<number, string>> {
const cellContext = new Map<string, Map<number, string>>();
this._cellMatches.forEach(cellMatch => {
cellContext.set(cellMatch.id, cellMatch.context);
});
return cellContext;
}
// #region notebook fields
private _notebookEditorWidget: NotebookEditorWidget | null = null;
private _editorWidgetListener: IDisposable | null = null;
private _notebookUpdateScheduler: RunOnceScheduler;
private _findMatchDecorationModel: FindMatchDecorationModel | undefined;
private _lastEditorWidgetIdForUpdate: string | undefined;
// #endregion
constructor(
private _query: IPatternInfo,
private _previewOptions: ITextSearchPreviewOptions | undefined,
private _maxResults: number | undefined,
private _parent: FolderMatch,
private rawMatch: IFileMatch,
private _closestRoot: FolderMatchWorkspaceRoot | null,
private readonly searchInstanceID: string,
@IModelService private readonly modelService: IModelService,
@IReplaceService private readonly replaceService: IReplaceService,
@ILabelService labelService: ILabelService,
@INotebookEditorService private readonly notebookEditorService: INotebookEditorService,
) {
super();
this._resource = this.rawMatch.resource;
this._textMatches = new Map<string, Match>();
this._removedTextMatches = new Set<string>();
this._updateScheduler = new RunOnceScheduler(this.updateMatchesForModel.bind(this), 250);
this._name = new Lazy(() => labelService.getUriBasenameLabel(this.resource));
this._cellMatches = new Map<string, CellMatch>();
this._notebookUpdateScheduler = new RunOnceScheduler(this.updateMatchesForEditorWidget.bind(this), 250);
}
addWebviewMatchesToCell(cellID: string, webviewMatches: ITextSearchMatch[]) {
const cellMatch = this.getCellMatch(cellID);
if (cellMatch !== undefined) {
cellMatch.addWebviewMatches(webviewMatches);
}
}
addContentMatchesToCell(cellID: string, contentMatches: ITextSearchMatch[]) {
const cellMatch = this.getCellMatch(cellID);
if (cellMatch !== undefined) {
cellMatch.addContentMatches(contentMatches);
}
}
getCellMatch(cellID: string): CellMatch | undefined {
return this._cellMatches.get(cellID);
}
addCellMatch(rawCell: INotebookCellMatchNoModel | INotebookCellMatchWithModel) {
const cellMatch = new CellMatch(this, isINotebookCellMatchWithModel(rawCell) ? rawCell.cell : undefined, rawCell.index);
this._cellMatches.set(cellMatch.id, cellMatch);
this.addWebviewMatchesToCell(cellMatch.id, rawCell.webviewResults);
this.addContentMatchesToCell(cellMatch.id, rawCell.contentResults);
}
get closestRoot(): FolderMatchWorkspaceRoot | null {
return this._closestRoot;
}
hasReadonlyMatches(): boolean {
return this.matches().some(m => m instanceof MatchInNotebook && m.isReadonly());
}
createMatches(isAiContributed: boolean): void {
const model = this.modelService.getModel(this._resource);
if (model && !isAiContributed) {
// todo: handle better when ai contributed results has model, currently, createMatches does not work for this
this.bindModel(model);
this.updateMatchesForModel();
} else {
const notebookEditorWidgetBorrow = this.notebookEditorService.retrieveExistingWidgetFromURI(this.resource);
if (notebookEditorWidgetBorrow?.value) {
this.bindNotebookEditorWidget(notebookEditorWidgetBorrow.value);
}
if (this.rawMatch.results) {
this.rawMatch.results
.filter(resultIsMatch)
.forEach(rawMatch => {
textSearchResultToMatches(rawMatch, this, isAiContributed)
.forEach(m => this.add(m));
});
}
if (isINotebookFileMatchWithModel(this.rawMatch) || isINotebookFileMatchNoModel(this.rawMatch)) {
this.rawMatch.cellResults?.forEach(cell => this.addCellMatch(cell));
this.setNotebookFindMatchDecorationsUsingCellMatches(this.cellMatches());
this._onChange.fire({ forceUpdateModel: true });
}
this.addContext(this.rawMatch.results);
}
}
bindModel(model: ITextModel): void {
this._model = model;
this._modelListener = this._model.onDidChangeContent(() => {
this._updateScheduler.schedule();
});
this._model.onWillDispose(() => this.onModelWillDispose());
this.updateHighlights();
}
private onModelWillDispose(): void {
// Update matches because model might have some dirty changes
this.updateMatchesForModel();
this.unbindModel();
}
private unbindModel(): void {
if (this._model) {
this._updateScheduler.cancel();
this._model.changeDecorations((accessor) => {
this._modelDecorations = accessor.deltaDecorations(this._modelDecorations, []);
});
this._model = null;
this._modelListener!.dispose();
}
}
private updateMatchesForModel(): void {
// this is called from a timeout and might fire
// after the model has been disposed
if (!this._model) {
return;
}
this._textMatches = new Map<string, Match>();
const wordSeparators = this._query.isWordMatch && this._query.wordSeparators ? this._query.wordSeparators : null;
const matches = this._model
.findMatches(this._query.pattern, this._model.getFullModelRange(), !!this._query.isRegExp, !!this._query.isCaseSensitive, wordSeparators, false, this._maxResults ?? Number.MAX_SAFE_INTEGER);
this.updateMatches(matches, true, this._model, false);
}
protected async updatesMatchesForLineAfterReplace(lineNumber: number, modelChange: boolean): Promise<void> {
if (!this._model) {
return;
}
const range = {
startLineNumber: lineNumber,
startColumn: this._model.getLineMinColumn(lineNumber),
endLineNumber: lineNumber,
endColumn: this._model.getLineMaxColumn(lineNumber)
};
const oldMatches = Array.from(this._textMatches.values()).filter(match => match.range().startLineNumber === lineNumber);
oldMatches.forEach(match => this._textMatches.delete(match.id()));
const wordSeparators = this._query.isWordMatch && this._query.wordSeparators ? this._query.wordSeparators : null;
const matches = this._model.findMatches(this._query.pattern, range, !!this._query.isRegExp, !!this._query.isCaseSensitive, wordSeparators, false, this._maxResults ?? Number.MAX_SAFE_INTEGER);
this.updateMatches(matches, modelChange, this._model, false);
// await this.updateMatchesForEditorWidget();
}
private updateMatches(matches: FindMatch[], modelChange: boolean, model: ITextModel, isAiContributed: boolean): void {
const textSearchResults = editorMatchesToTextSearchResults(matches, model, this._previewOptions);
textSearchResults.forEach(textSearchResult => {
textSearchResultToMatches(textSearchResult, this, isAiContributed).forEach(match => {
if (!this._removedTextMatches.has(match.id())) {
this.add(match);
if (this.isMatchSelected(match)) {
this._selectedMatch = match;
}
}
});
});
this.addContext(getTextSearchMatchWithModelContext(textSearchResults, model, this.parent().parent().query!));
this._onChange.fire({ forceUpdateModel: modelChange });
this.updateHighlights();
}
updateHighlights(): void {
if (!this._model) {
return;
}
this._model.changeDecorations((accessor) => {
const newDecorations = (
this.parent().showHighlights
? this.matches().map((match): IModelDeltaDecoration => ({
range: match.range(),
options: FileMatch.getDecorationOption(this.isMatchSelected(match))
}))
: []
);
this._modelDecorations = accessor.deltaDecorations(this._modelDecorations, newDecorations);
});
}
id(): string {
return this.resource.toString();
}
parent(): FolderMatch {
return this._parent;
}
matches(): Match[] {
const cellMatches: MatchInNotebook[] = Array.from(this._cellMatches.values()).flatMap((e) => e.matches());
return [...this._textMatches.values(), ...cellMatches];
}
textMatches(): Match[] {
return Array.from(this._textMatches.values());
}
cellMatches(): CellMatch[] {
return Array.from(this._cellMatches.values());
}
remove(matches: Match | Match[]): void {
if (!Array.isArray(matches)) {
matches = [matches];
}
for (const match of matches) {
this.removeMatch(match);
this._removedTextMatches.add(match.id());
}
this._onChange.fire({ didRemove: true });
}
private replaceQ = Promise.resolve();
async replace(toReplace: Match): Promise<void> {
return this.replaceQ = this.replaceQ.finally(async () => {
await this.replaceService.replace(toReplace);
await this.updatesMatchesForLineAfterReplace(toReplace.range().startLineNumber, false);
});
}
setSelectedMatch(match: Match | null): void {
if (match) {
if (!this.isMatchSelected(match) && match instanceof MatchInNotebook) {
this._selectedMatch = match;
return;
}
if (!this._textMatches.has(match.id())) {
return;
}
if (this.isMatchSelected(match)) {
return;
}
}
this._selectedMatch = match;
this.updateHighlights();
}
getSelectedMatch(): Match | null {
return this._selectedMatch;
}
isMatchSelected(match: Match): boolean {
return !!this._selectedMatch && this._selectedMatch.id() === match.id();
}
count(): number {
return this.matches().length;
}
get resource(): URI {
return this._resource;
}
name(): string {
return this._name.value;
}
addContext(results: ITextSearchResult[] | undefined) {
if (!results) { return; }
const contexts = results
.filter((result =>
!resultIsMatch(result)) as ((a: any) => a is ITextSearchContext));
return contexts.forEach(context => this._context.set(context.lineNumber, context.text));
}
add(match: Match, trigger?: boolean) {
this._textMatches.set(match.id(), match);
if (trigger) {
this._onChange.fire({ forceUpdateModel: true });
}
}
private removeMatch(match: Match) {
if (match instanceof MatchInNotebook) {
match.cellParent.remove(match);
if (match.cellParent.matches().length === 0) {
this._cellMatches.delete(match.cellParent.id);
}
} else {
this._textMatches.delete(match.id());
}
if (this.isMatchSelected(match)) {
this.setSelectedMatch(null);
this._findMatchDecorationModel?.clearCurrentFindMatchDecoration();
} else {
this.updateHighlights();
}
if (match instanceof MatchInNotebook) {
this.setNotebookFindMatchDecorationsUsingCellMatches(this.cellMatches());
}
}
async resolveFileStat(fileService: IFileService): Promise<void> {
this._fileStat = await fileService.stat(this.resource).catch(() => undefined);
}
public get fileStat(): IFileStatWithPartialMetadata | undefined {
return this._fileStat;
}
public set fileStat(stat: IFileStatWithPartialMetadata | undefined) {
this._fileStat = stat;
}
override dispose(): void {
this.setSelectedMatch(null);
this.unbindModel();
this.unbindNotebookEditorWidget();
this._onDispose.fire();
super.dispose();
}
hasOnlyReadOnlyMatches(): boolean {
return this.matches().every(match => (match instanceof MatchInNotebook && match.isReadonly()));
}
// #region strictly notebook methods
bindNotebookEditorWidget(widget: NotebookEditorWidget) {
if (this._notebookEditorWidget === widget) {
return;
}
this._notebookEditorWidget = widget;
this._editorWidgetListener = this._notebookEditorWidget.textModel?.onDidChangeContent((e) => {
if (!e.rawEvents.some(event => event.kind === NotebookCellsChangeType.ChangeCellContent || event.kind === NotebookCellsChangeType.ModelChange)) {
return;
}
this._notebookUpdateScheduler.schedule();
}) ?? null;
this._addNotebookHighlights();
}
unbindNotebookEditorWidget(widget?: NotebookEditorWidget) {
if (widget && this._notebookEditorWidget !== widget) {
return;
}
if (this._notebookEditorWidget) {
this._notebookUpdateScheduler.cancel();
this._editorWidgetListener?.dispose();
}
this._removeNotebookHighlights();
this._notebookEditorWidget = null;
}
updateNotebookHighlights(): void {
if (this.parent().showHighlights) {
this._addNotebookHighlights();
this.setNotebookFindMatchDecorationsUsingCellMatches(Array.from(this._cellMatches.values()));
} else {
this._removeNotebookHighlights();
}
}
private _addNotebookHighlights(): void {
if (!this._notebookEditorWidget) {
return;
}
this._findMatchDecorationModel?.stopWebviewFind();
this._findMatchDecorationModel?.dispose();
this._findMatchDecorationModel = new FindMatchDecorationModel(this._notebookEditorWidget, this.searchInstanceID);
if (this._selectedMatch instanceof MatchInNotebook) {
this.highlightCurrentFindMatchDecoration(this._selectedMatch);
}
}
private _removeNotebookHighlights(): void {
if (this._findMatchDecorationModel) {
this._findMatchDecorationModel?.stopWebviewFind();
this._findMatchDecorationModel?.dispose();
this._findMatchDecorationModel = undefined;
}
}
private updateNotebookMatches(matches: CellFindMatchWithIndex[], modelChange: boolean): void {
if (!this._notebookEditorWidget) {
return;
}
const oldCellMatches = new Map<string, CellMatch>(this._cellMatches);
if (this._notebookEditorWidget.getId() !== this._lastEditorWidgetIdForUpdate) {
this._cellMatches.clear();
this._lastEditorWidgetIdForUpdate = this._notebookEditorWidget.getId();
}
matches.forEach(match => {
let existingCell = this._cellMatches.get(match.cell.id);
if (this._notebookEditorWidget && !existingCell) {
const index = this._notebookEditorWidget.getCellIndex(match.cell);
const existingRawCell = oldCellMatches.get(`${rawCellPrefix}${index}`);
if (existingRawCell) {
existingRawCell.setCellModel(match.cell);
existingRawCell.clearAllMatches();
existingCell = existingRawCell;
}
}
existingCell?.clearAllMatches();
const cell = existingCell ?? new CellMatch(this, match.cell, match.index);
cell.addContentMatches(contentMatchesToTextSearchMatches(match.contentMatches, match.cell));
cell.addWebviewMatches(webviewMatchesToTextSearchMatches(match.webviewMatches));
this._cellMatches.set(cell.id, cell);
});
this._findMatchDecorationModel?.setAllFindMatchesDecorations(matches);
if (this._selectedMatch instanceof MatchInNotebook) {
this.highlightCurrentFindMatchDecoration(this._selectedMatch);
}
this._onChange.fire({ forceUpdateModel: modelChange });
}
private setNotebookFindMatchDecorationsUsingCellMatches(cells: CellMatch[]): void {
if (!this._findMatchDecorationModel) {
return;
}
const cellFindMatch = coalesce(cells.map((cell): CellFindMatchModel | undefined => {
const webviewMatches: CellWebviewFindMatch[] = coalesce(cell.webviewMatches.map((match): CellWebviewFindMatch | undefined => {
if (!match.webviewIndex) {
return undefined;
}
return {
index: match.webviewIndex,
};
}));
if (!cell.cell) {
return undefined;
}
const findMatches: FindMatch[] = cell.contentMatches.map(match => {
return new FindMatch(match.range(), [match.text()]);
});
return new CellFindMatchModel(cell.cell, cell.cellIndex, findMatches, webviewMatches);
}));
try {
this._findMatchDecorationModel.setAllFindMatchesDecorations(cellFindMatch);
} catch (e) {
// no op, might happen due to bugs related to cell output regex search
}
}
async updateMatchesForEditorWidget(): Promise<void> {
if (!this._notebookEditorWidget) {
return;
}
this._textMatches = new Map<string, Match>();
const wordSeparators = this._query.isWordMatch && this._query.wordSeparators ? this._query.wordSeparators : null;
const allMatches = await this._notebookEditorWidget
.find(this._query.pattern, {
regex: this._query.isRegExp,
wholeWord: this._query.isWordMatch,
caseSensitive: this._query.isCaseSensitive,
wordSeparators: wordSeparators ?? undefined,
includeMarkupInput: this._query.notebookInfo?.isInNotebookMarkdownInput,
includeMarkupPreview: this._query.notebookInfo?.isInNotebookMarkdownPreview,
includeCodeInput: this._query.notebookInfo?.isInNotebookCellInput,
includeOutput: this._query.notebookInfo?.isInNotebookCellOutput,
}, CancellationToken.None, false, true, this.searchInstanceID);
this.updateNotebookMatches(allMatches, true);
}
public async showMatch(match: MatchInNotebook) {
const offset = await this.highlightCurrentFindMatchDecoration(match);
this.setSelectedMatch(match);
this.revealCellRange(match, offset);
}
private async highlightCurrentFindMatchDecoration(match: MatchInNotebook): Promise<number | null> {
if (!this._findMatchDecorationModel || !match.cell) {
// match cell should never be a CellSearchModel if the notebook is open
return null;
}
if (match.webviewIndex === undefined) {
return this._findMatchDecorationModel.highlightCurrentFindMatchDecorationInCell(match.cell, match.range());
} else {
return this._findMatchDecorationModel.highlightCurrentFindMatchDecorationInWebview(match.cell, match.webviewIndex);
}
}
private revealCellRange(match: MatchInNotebook, outputOffset: number | null) {
if (!this._notebookEditorWidget || !match.cell) {
// match cell should never be a CellSearchModel if the notebook is open
return;
}
if (match.webviewIndex !== undefined) {
const index = this._notebookEditorWidget.getCellIndex(match.cell);
if (index !== undefined) {
this._notebookEditorWidget.revealCellOffsetInCenter(match.cell, outputOffset ?? 0);
}
} else {
match.cell.updateEditState(match.cell.getEditState(), 'focusNotebookCell');
this._notebookEditorWidget.setCellEditorSelection(match.cell, match.range());
this._notebookEditorWidget.revealRangeInCenterIfOutsideViewportAsync(match.cell, match.range());
}
}
//#endregion
}
export interface IChangeEvent {
elements: FileMatch[];
added?: boolean;
removed?: boolean;
clearingAll?: boolean;
}
export class FolderMatch extends Disposable {
protected _onChange = this._register(new Emitter<IChangeEvent>());
readonly onChange: Event<IChangeEvent> = this._onChange.event;
private _onDispose = this._register(new Emitter<void>());
readonly onDispose: Event<void> = this._onDispose.event;
protected _fileMatches: ResourceMap<FileMatch>;
protected _folderMatches: ResourceMap<FolderMatchWithResource>;
protected _folderMatchesMap: TernarySearchTree<URI, FolderMatchWithResource>;
protected _unDisposedFileMatches: ResourceMap<FileMatch>;
protected _unDisposedFolderMatches: ResourceMap<FolderMatchWithResource>;
private _replacingAll: boolean = false;
private _name: Lazy<string>;
constructor(
protected _resource: URI | null,
private _id: string,
protected _index: number,
protected _query: ITextQuery,
private _parent: SearchResult | FolderMatch,
private _searchResult: SearchResult,
private _closestRoot: FolderMatchWorkspaceRoot | null,
@IReplaceService private readonly replaceService: IReplaceService,
@IInstantiationService protected readonly instantiationService: IInstantiationService,
@ILabelService labelService: ILabelService,
@IUriIdentityService protected readonly uriIdentityService: IUriIdentityService
) {
super();
this._fileMatches = new ResourceMap<FileMatch>();
this._folderMatches = new ResourceMap<FolderMatchWithResource>();
this._folderMatchesMap = TernarySearchTree.forUris<FolderMatchWithResource>(key => this.uriIdentityService.extUri.ignorePathCasing(key));
this._unDisposedFileMatches = new ResourceMap<FileMatch>();
this._unDisposedFolderMatches = new ResourceMap<FolderMatchWithResource>();
this._name = new Lazy(() => this.resource ? labelService.getUriBasenameLabel(this.resource) : '');
}
get searchModel(): SearchModel {
return this._searchResult.searchModel;
}
get showHighlights(): boolean {
return this._parent.showHighlights;
}
get closestRoot(): FolderMatchWorkspaceRoot | null {
return this._closestRoot;
}
set replacingAll(b: boolean) {
this._replacingAll = b;
}
id(): string {
return this._id;
}
get resource(): URI | null {
return this._resource;
}
index(): number {
return this._index;
}
name(): string {
return this._name.value;
}