-
Notifications
You must be signed in to change notification settings - Fork 30.7k
/
Copy pathsearchView.ts
1917 lines (1596 loc) · 74.5 KB
/
searchView.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 * as dom from 'vs/base/browser/dom';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { MessageType } from 'vs/base/browser/ui/inputbox/inputBox';
import { IIdentityProvider } from 'vs/base/browser/ui/list/list';
import { ITreeContextMenuEvent, ITreeElement } from 'vs/base/browser/ui/tree/tree';
import { IAction, ActionRunner } from 'vs/base/common/actions';
import { Delayer } from 'vs/base/common/async';
import * as errors from 'vs/base/common/errors';
import { Event } from 'vs/base/common/event';
import { Iterable } from 'vs/base/common/iterator';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import * as env from 'vs/base/common/platform';
import * as strings from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import 'vs/css!./media/searchview';
import { ICodeEditor, isCodeEditor, isDiffEditor, getCodeEditor } from 'vs/editor/browser/editorBrowser';
import { IEditorOptions } from 'vs/editor/common/config/editorOptions';
import * as nls from 'vs/nls';
import { createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { IMenu, IMenuService, MenuId } from 'vs/platform/actions/common/actions';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IConfirmation, IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { TreeResourceNavigator, WorkbenchObjectTree, getSelectionKeyboardEvent } from 'vs/platform/list/browser/listService';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IProgressService, IProgressStep, IProgress } from 'vs/platform/progress/common/progress';
import { IPatternInfo, ISearchComplete, ISearchConfiguration, ISearchConfigurationProperties, ITextQuery, SearchSortOrder, SearchCompletionExitCode } from 'vs/workbench/services/search/common/search';
import { ISearchHistoryService, ISearchHistoryValues } from 'vs/workbench/contrib/search/common/searchHistoryService';
import { diffInserted, diffInsertedOutline, diffRemoved, diffRemovedOutline, editorFindMatchHighlight, editorFindMatchHighlightBorder, listActiveSelectionForeground, foreground } from 'vs/platform/theme/common/colorRegistry';
import { ICssStyleCollector, IColorTheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { OpenFileFolderAction, OpenFolderAction } from 'vs/workbench/browser/actions/workspaceActions';
import { ResourceLabels } from 'vs/workbench/browser/labels';
import { IEditorPane } from 'vs/workbench/common/editor';
import { ExcludePatternInputWidget, PatternInputWidget } from 'vs/workbench/contrib/search/browser/patternInputWidget';
import { CancelSearchAction, ClearSearchResultsAction, CollapseDeepestExpandedLevelAction, RefreshAction, IFindInFilesArgs, appendKeyBindingLabel, ExpandAllAction, ToggleCollapseAndExpandAction } from 'vs/workbench/contrib/search/browser/searchActions';
import { FileMatchRenderer, FolderMatchRenderer, MatchRenderer, SearchAccessibilityProvider, SearchDelegate, SearchDND } from 'vs/workbench/contrib/search/browser/searchResultsView';
import { ISearchWidgetOptions, SearchWidget } from 'vs/workbench/contrib/search/browser/searchWidget';
import * as Constants from 'vs/workbench/contrib/search/common/constants';
import { ITextQueryBuilderOptions, QueryBuilder } from 'vs/workbench/contrib/search/common/queryBuilder';
import { IReplaceService } from 'vs/workbench/contrib/search/common/replace';
import { getOutOfWorkspaceEditorResources } from 'vs/workbench/contrib/search/common/search';
import { FileMatch, FileMatchOrMatch, IChangeEvent, ISearchWorkbenchService, Match, RenderableMatch, searchMatchComparer, SearchModel, SearchResult, FolderMatch, FolderMatchWithResource } from 'vs/workbench/contrib/search/common/searchModel';
import { ACTIVE_GROUP, IEditorService, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { IPreferencesService, ISettingsEditorOptions } from 'vs/workbench/services/preferences/common/preferences';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { relativePath } from 'vs/base/common/resources';
import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility';
import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPaneContainer';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { Memento, MementoObject } from 'vs/workbench/common/memento';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { MultiCursorSelectionController } from 'vs/editor/contrib/multicursor/multicursor';
import { Selection } from 'vs/editor/common/core/selection';
import { Color, RGBA } from 'vs/base/common/color';
import { IViewDescriptorService } from 'vs/workbench/common/views';
import { OpenSearchEditorAction, createEditorFromSearchResult } from 'vs/workbench/contrib/searchEditor/browser/searchEditorActions';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { Orientation } from 'vs/base/browser/ui/sash/sash';
import { searchDetailsIcon } from 'vs/workbench/contrib/search/browser/searchIcons';
const $ = dom.$;
enum SearchUIState {
Idle,
Searching,
SlowSearch
}
export enum SearchViewPosition {
SideBar,
Panel
}
const SEARCH_CANCELLED_MESSAGE = nls.localize('searchCanceled', "Search was canceled before any results could be found - ");
export class SearchView extends ViewPane {
private static readonly MAX_TEXT_RESULTS = 10000;
private static readonly ACTIONS_RIGHT_CLASS_NAME = 'actions-right';
private isDisposed = false;
private container!: HTMLElement;
private queryBuilder: QueryBuilder;
private viewModel: SearchModel;
private memento: Memento;
private viewletVisible: IContextKey<boolean>;
private inputBoxFocused: IContextKey<boolean>;
private inputPatternIncludesFocused: IContextKey<boolean>;
private inputPatternExclusionsFocused: IContextKey<boolean>;
private firstMatchFocused: IContextKey<boolean>;
private fileMatchOrMatchFocused: IContextKey<boolean>;
private fileMatchOrFolderMatchFocus: IContextKey<boolean>;
private fileMatchOrFolderMatchWithResourceFocus: IContextKey<boolean>;
private fileMatchFocused: IContextKey<boolean>;
private folderMatchFocused: IContextKey<boolean>;
private matchFocused: IContextKey<boolean>;
private hasSearchResultsKey: IContextKey<boolean>;
private state: SearchUIState = SearchUIState.Idle;
private actions: Array<CollapseDeepestExpandedLevelAction | ClearSearchResultsAction | OpenSearchEditorAction> = [];
private toggleCollapseAction: ToggleCollapseAndExpandAction;
private cancelAction: CancelSearchAction;
private refreshAction: RefreshAction;
private contextMenu: IMenu | null = null;
private tree!: WorkbenchObjectTree<RenderableMatch>;
private treeLabels!: ResourceLabels;
private viewletState: MementoObject;
private messagesElement!: HTMLElement;
private messageDisposables: IDisposable[] = [];
private searchWidgetsContainerElement!: HTMLElement;
private searchWidget!: SearchWidget;
private size!: dom.Dimension;
private queryDetails!: HTMLElement;
private toggleQueryDetailsButton!: HTMLElement;
private inputPatternExcludes!: ExcludePatternInputWidget;
private inputPatternIncludes!: PatternInputWidget;
private resultsElement!: HTMLElement;
private currentSelectedFileMatch: FileMatch | undefined;
private delayedRefresh: Delayer<void>;
private changedWhileHidden: boolean = false;
private updatedActionsWhileHidden = false;
private searchWithoutFolderMessageElement: HTMLElement | undefined;
private currentSearchQ = Promise.resolve();
private addToSearchHistoryDelayer: Delayer<void>;
private toggleCollapseStateDelayer: Delayer<void>;
private triggerQueryDelayer: Delayer<void>;
private pauseSearching = false;
private treeAccessibilityProvider: SearchAccessibilityProvider;
constructor(
options: IViewPaneOptions,
@IFileService private readonly fileService: IFileService,
@IEditorService private readonly editorService: IEditorService,
@IProgressService private readonly progressService: IProgressService,
@INotificationService private readonly notificationService: INotificationService,
@IDialogService private readonly dialogService: IDialogService,
@IContextViewService private readonly contextViewService: IContextViewService,
@IInstantiationService instantiationService: IInstantiationService,
@IViewDescriptorService viewDescriptorService: IViewDescriptorService,
@IConfigurationService configurationService: IConfigurationService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@ISearchWorkbenchService private readonly searchWorkbenchService: ISearchWorkbenchService,
@IContextKeyService readonly contextKeyService: IContextKeyService,
@IReplaceService private readonly replaceService: IReplaceService,
@ITextFileService private readonly textFileService: ITextFileService,
@IPreferencesService private readonly preferencesService: IPreferencesService,
@IThemeService themeService: IThemeService,
@ISearchHistoryService private readonly searchHistoryService: ISearchHistoryService,
@IContextMenuService contextMenuService: IContextMenuService,
@IMenuService private readonly menuService: IMenuService,
@IAccessibilityService private readonly accessibilityService: IAccessibilityService,
@IKeybindingService keybindingService: IKeybindingService,
@IStorageService storageService: IStorageService,
@IOpenerService openerService: IOpenerService,
@ITelemetryService telemetryService: ITelemetryService,
) {
super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService);
this.container = dom.$('.search-view');
// globals
this.viewletVisible = Constants.SearchViewVisibleKey.bindTo(this.contextKeyService);
this.firstMatchFocused = Constants.FirstMatchFocusKey.bindTo(this.contextKeyService);
this.fileMatchOrMatchFocused = Constants.FileMatchOrMatchFocusKey.bindTo(this.contextKeyService);
this.fileMatchOrFolderMatchFocus = Constants.FileMatchOrFolderMatchFocusKey.bindTo(this.contextKeyService);
this.fileMatchOrFolderMatchWithResourceFocus = Constants.FileMatchOrFolderMatchWithResourceFocusKey.bindTo(this.contextKeyService);
this.fileMatchFocused = Constants.FileFocusKey.bindTo(this.contextKeyService);
this.folderMatchFocused = Constants.FolderFocusKey.bindTo(this.contextKeyService);
this.hasSearchResultsKey = Constants.HasSearchResults.bindTo(this.contextKeyService);
this.matchFocused = Constants.MatchFocusKey.bindTo(this.contextKeyService);
// scoped
this.contextKeyService = this._register(this.contextKeyService.createScoped(this.container));
Constants.SearchViewFocusedKey.bindTo(this.contextKeyService).set(true);
this.inputBoxFocused = Constants.InputBoxFocusedKey.bindTo(this.contextKeyService);
this.inputPatternIncludesFocused = Constants.PatternIncludesFocusedKey.bindTo(this.contextKeyService);
this.inputPatternExclusionsFocused = Constants.PatternExcludesFocusedKey.bindTo(this.contextKeyService);
this.instantiationService = this.instantiationService.createChild(
new ServiceCollection([IContextKeyService, this.contextKeyService]));
this.configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('search.sortOrder')) {
if (this.searchConfig.sortOrder === SearchSortOrder.Modified) {
// If changing away from modified, remove all fileStats
// so that updated files are re-retrieved next time.
this.removeFileStats();
}
this.refreshTree();
}
});
this.viewModel = this._register(this.searchWorkbenchService.searchModel);
this.queryBuilder = this.instantiationService.createInstance(QueryBuilder);
this.memento = new Memento(this.id, storageService);
this.viewletState = this.memento.getMemento(StorageScope.WORKSPACE);
this._register(this.fileService.onDidFilesChange(e => this.onFilesChanged(e)));
this._register(this.textFileService.untitled.onDidDispose(model => this.onUntitledDidDispose(model.resource)));
this._register(this.contextService.onDidChangeWorkbenchState(() => this.onDidChangeWorkbenchState()));
this._register(this.searchHistoryService.onDidClearHistory(() => this.clearHistory()));
this.delayedRefresh = this._register(new Delayer<void>(250));
this.addToSearchHistoryDelayer = this._register(new Delayer<void>(2000));
this.toggleCollapseStateDelayer = this._register(new Delayer<void>(100));
this.triggerQueryDelayer = this._register(new Delayer<void>(0));
const collapseDeepestExpandedLevelAction = this.instantiationService.createInstance(CollapseDeepestExpandedLevelAction, CollapseDeepestExpandedLevelAction.ID, CollapseDeepestExpandedLevelAction.LABEL);
const expandAllAction = this.instantiationService.createInstance(ExpandAllAction, ExpandAllAction.ID, ExpandAllAction.LABEL);
this.actions = [
this._register(this.instantiationService.createInstance(ClearSearchResultsAction, ClearSearchResultsAction.ID, ClearSearchResultsAction.LABEL)),
this._register(this.instantiationService.createInstance(OpenSearchEditorAction, OpenSearchEditorAction.ID, OpenSearchEditorAction.LABEL))
];
this.refreshAction = this._register(this.instantiationService.createInstance(RefreshAction, RefreshAction.ID, RefreshAction.LABEL));
this.cancelAction = this._register(this.instantiationService.createInstance(CancelSearchAction, CancelSearchAction.ID, CancelSearchAction.LABEL));
this.toggleCollapseAction = this._register(this.instantiationService.createInstance(ToggleCollapseAndExpandAction, ToggleCollapseAndExpandAction.ID, ToggleCollapseAndExpandAction.LABEL, collapseDeepestExpandedLevelAction, expandAllAction));
this.treeAccessibilityProvider = this.instantiationService.createInstance(SearchAccessibilityProvider, this.viewModel);
}
getContainer(): HTMLElement {
return this.container;
}
get searchResult(): SearchResult {
return this.viewModel && this.viewModel.searchResult;
}
private onDidChangeWorkbenchState(): void {
if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.searchWithoutFolderMessageElement) {
dom.hide(this.searchWithoutFolderMessageElement);
}
}
renderBody(parent: HTMLElement): void {
super.renderBody(parent);
this.container = dom.append(parent, dom.$('.search-view'));
this.searchWidgetsContainerElement = dom.append(this.container, $('.search-widgets-container'));
this.createSearchWidget(this.searchWidgetsContainerElement);
const history = this.searchHistoryService.load();
const filePatterns = this.viewletState['query.filePatterns'] || '';
const patternExclusions = this.viewletState['query.folderExclusions'] || '';
const patternExclusionsHistory: string[] = history.exclude || [];
const patternIncludes = this.viewletState['query.folderIncludes'] || '';
const patternIncludesHistory: string[] = history.include || [];
const queryDetailsExpanded = this.viewletState['query.queryDetailsExpanded'] || '';
const useExcludesAndIgnoreFiles = typeof this.viewletState['query.useExcludesAndIgnoreFiles'] === 'boolean' ?
this.viewletState['query.useExcludesAndIgnoreFiles'] : true;
this.queryDetails = dom.append(this.searchWidgetsContainerElement, $('.query-details'));
// Toggle query details button
this.toggleQueryDetailsButton = dom.append(this.queryDetails,
$('.more' + searchDetailsIcon.cssSelector, { tabindex: 0, role: 'button', title: nls.localize('moreSearch', "Toggle Search Details") }));
this._register(dom.addDisposableListener(this.toggleQueryDetailsButton, dom.EventType.CLICK, e => {
dom.EventHelper.stop(e);
this.toggleQueryDetails(!this.accessibilityService.isScreenReaderOptimized());
}));
this._register(dom.addDisposableListener(this.toggleQueryDetailsButton, dom.EventType.KEY_UP, (e: KeyboardEvent) => {
const event = new StandardKeyboardEvent(e);
if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) {
dom.EventHelper.stop(e);
this.toggleQueryDetails(false);
}
}));
this._register(dom.addDisposableListener(this.toggleQueryDetailsButton, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => {
const event = new StandardKeyboardEvent(e);
if (event.equals(KeyMod.Shift | KeyCode.Tab)) {
if (this.searchWidget.isReplaceActive()) {
this.searchWidget.focusReplaceAllAction();
} else {
this.searchWidget.isReplaceShown() ? this.searchWidget.replaceInput.focusOnPreserve() : this.searchWidget.focusRegexAction();
}
dom.EventHelper.stop(e);
}
}));
// folder includes list
const folderIncludesList = dom.append(this.queryDetails,
$('.file-types.includes'));
const filesToIncludeTitle = nls.localize('searchScope.includes', "files to include");
dom.append(folderIncludesList, $('h4', undefined, filesToIncludeTitle));
this.inputPatternIncludes = this._register(this.instantiationService.createInstance(PatternInputWidget, folderIncludesList, this.contextViewService, {
ariaLabel: nls.localize('label.includes', 'Search Include Patterns'),
history: patternIncludesHistory,
}));
this.inputPatternIncludes.setValue(patternIncludes);
this.inputPatternIncludes.onSubmit(triggeredOnType => this.triggerQueryChange({ triggeredOnType, delay: this.searchConfig.searchOnTypeDebouncePeriod }));
this.inputPatternIncludes.onCancel(() => this.cancelSearch(false));
this.trackInputBox(this.inputPatternIncludes.inputFocusTracker, this.inputPatternIncludesFocused);
// excludes list
const excludesList = dom.append(this.queryDetails, $('.file-types.excludes'));
const excludesTitle = nls.localize('searchScope.excludes', "files to exclude");
dom.append(excludesList, $('h4', undefined, excludesTitle));
this.inputPatternExcludes = this._register(this.instantiationService.createInstance(ExcludePatternInputWidget, excludesList, this.contextViewService, {
ariaLabel: nls.localize('label.excludes', 'Search Exclude Patterns'),
history: patternExclusionsHistory,
}));
this.inputPatternExcludes.setValue(patternExclusions);
this.inputPatternExcludes.setUseExcludesAndIgnoreFiles(useExcludesAndIgnoreFiles);
this.inputPatternExcludes.onSubmit(triggeredOnType => this.triggerQueryChange({ triggeredOnType, delay: this.searchConfig.searchOnTypeDebouncePeriod }));
this.inputPatternExcludes.onCancel(() => this.cancelSearch(false));
this.inputPatternExcludes.onChangeIgnoreBox(() => this.triggerQueryChange());
this.trackInputBox(this.inputPatternExcludes.inputFocusTracker, this.inputPatternExclusionsFocused);
this.messagesElement = dom.append(this.container, $('.messages'));
if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
this.showSearchWithoutFolderMessage();
}
this.createSearchResultsView(this.container);
if (filePatterns !== '' || patternExclusions !== '' || patternIncludes !== '' || queryDetailsExpanded !== '' || !useExcludesAndIgnoreFiles) {
this.toggleQueryDetails(true, true, true);
}
this._register(this.viewModel.searchResult.onChange((event) => this.onSearchResultsChanged(event)));
this._register(this.searchWidget.searchInput.onInput(() => this.updateActions()));
this._register(this.searchWidget.replaceInput.onInput(() => this.updateActions()));
this._register(this.onDidChangeBodyVisibility(visible => this.onVisibilityChanged(visible)));
}
private onVisibilityChanged(visible: boolean): void {
this.viewletVisible.set(visible);
if (visible) {
if (this.changedWhileHidden) {
// Render if results changed while viewlet was hidden - #37818
this.refreshAndUpdateCount();
this.changedWhileHidden = false;
}
if (this.updatedActionsWhileHidden) {
// The actions can only run or update their enablement when the view is visible,
// because they can only access the view when it's visible
this.updateActions();
this.updatedActionsWhileHidden = false;
}
}
// Enable highlights if there are searchresults
if (this.viewModel) {
this.viewModel.searchResult.toggleHighlights(visible);
}
}
get searchAndReplaceWidget(): SearchWidget {
return this.searchWidget;
}
get searchIncludePattern(): PatternInputWidget {
return this.inputPatternIncludes;
}
get searchExcludePattern(): PatternInputWidget {
return this.inputPatternExcludes;
}
/**
* Warning: a bit expensive due to updating the view title
*/
protected updateActions(): void {
if (!this.isVisible()) {
this.updatedActionsWhileHidden = true;
}
for (const action of this.actions) {
action.update();
}
this.refreshAction.update();
this.cancelAction.update();
this.toggleCollapseAction.update();
super.updateActions();
}
private createSearchWidget(container: HTMLElement): void {
const contentPattern = this.viewletState['query.contentPattern'] || '';
const replaceText = this.viewletState['query.replaceText'] || '';
const isRegex = this.viewletState['query.regex'] === true;
const isWholeWords = this.viewletState['query.wholeWords'] === true;
const isCaseSensitive = this.viewletState['query.caseSensitive'] === true;
const history = this.searchHistoryService.load();
const searchHistory = history.search || this.viewletState['query.searchHistory'] || [];
const replaceHistory = history.replace || this.viewletState['query.replaceHistory'] || [];
const showReplace = typeof this.viewletState['view.showReplace'] === 'boolean' ? this.viewletState['view.showReplace'] : true;
const preserveCase = this.viewletState['query.preserveCase'] === true;
this.searchWidget = this._register(this.instantiationService.createInstance(SearchWidget, container, <ISearchWidgetOptions>{
value: contentPattern,
replaceValue: replaceText,
isRegex: isRegex,
isCaseSensitive: isCaseSensitive,
isWholeWords: isWholeWords,
searchHistory: searchHistory,
replaceHistory: replaceHistory,
preserveCase: preserveCase
}));
if (showReplace) {
this.searchWidget.toggleReplace(true);
}
this._register(this.searchWidget.onSearchSubmit(options => this.triggerQueryChange(options)));
this._register(this.searchWidget.onSearchCancel(({ focus }) => this.cancelSearch(focus)));
this._register(this.searchWidget.searchInput.onDidOptionChange(() => this.triggerQueryChange()));
this._register(this.searchWidget.onDidHeightChange(() => this.reLayout()));
this._register(this.searchWidget.onReplaceToggled(() => this.reLayout()));
this._register(this.searchWidget.onReplaceStateChange((state) => {
this.viewModel.replaceActive = state;
this.refreshTree();
}));
this._register(this.searchWidget.onPreserveCaseChange((state) => {
this.viewModel.preserveCase = state;
this.refreshTree();
}));
this._register(this.searchWidget.onReplaceValueChanged(() => {
this.viewModel.replaceString = this.searchWidget.getReplaceValue();
this.delayedRefresh.trigger(() => this.refreshTree());
}));
this._register(this.searchWidget.onBlur(() => {
this.toggleQueryDetailsButton.focus();
}));
this._register(this.searchWidget.onReplaceAll(() => this.replaceAll()));
this.trackInputBox(this.searchWidget.searchInputFocusTracker);
this.trackInputBox(this.searchWidget.replaceInputFocusTracker);
}
private trackInputBox(inputFocusTracker: dom.IFocusTracker, contextKey?: IContextKey<boolean>): void {
this._register(inputFocusTracker.onDidFocus(() => {
this.inputBoxFocused.set(true);
if (contextKey) {
contextKey.set(true);
}
}));
this._register(inputFocusTracker.onDidBlur(() => {
this.inputBoxFocused.set(this.searchWidget.searchInputHasFocus()
|| this.searchWidget.replaceInputHasFocus()
|| this.inputPatternIncludes.inputHasFocus()
|| this.inputPatternExcludes.inputHasFocus());
if (contextKey) {
contextKey.set(false);
}
}));
}
private onSearchResultsChanged(event?: IChangeEvent): void {
if (this.isVisible()) {
return this.refreshAndUpdateCount(event);
} else {
this.changedWhileHidden = true;
}
}
private refreshAndUpdateCount(event?: IChangeEvent): void {
this.searchWidget.setReplaceAllActionState(!this.viewModel.searchResult.isEmpty());
this.updateSearchResultCount(this.viewModel.searchResult.query!.userDisabledExcludesAndIgnoreFiles);
return this.refreshTree(event);
}
refreshTree(event?: IChangeEvent): void {
const collapseResults = this.searchConfig.collapseResults;
if (!event || event.added || event.removed) {
// Refresh whole tree
if (this.searchConfig.sortOrder === SearchSortOrder.Modified) {
// Ensure all matches have retrieved their file stat
this.retrieveFileStats()
.then(() => this.tree.setChildren(null, this.createResultIterator(collapseResults)));
} else {
this.tree.setChildren(null, this.createResultIterator(collapseResults));
}
} else {
// If updated counts affect our search order, re-sort the view.
if (this.searchConfig.sortOrder === SearchSortOrder.CountAscending ||
this.searchConfig.sortOrder === SearchSortOrder.CountDescending) {
this.tree.setChildren(null, this.createResultIterator(collapseResults));
} else {
// FileMatch modified, refresh those elements
event.elements.forEach(element => {
this.tree.setChildren(element, this.createIterator(element, collapseResults));
this.tree.rerender(element);
});
}
}
}
private createResultIterator(collapseResults: ISearchConfigurationProperties['collapseResults']): Iterable<ITreeElement<RenderableMatch>> {
const folderMatches = this.searchResult.folderMatches()
.filter(fm => !fm.isEmpty())
.sort(searchMatchComparer);
if (folderMatches.length === 1) {
return this.createFolderIterator(folderMatches[0], collapseResults);
}
return Iterable.map(folderMatches, folderMatch => {
const children = this.createFolderIterator(folderMatch, collapseResults);
return <ITreeElement<RenderableMatch>>{ element: folderMatch, children };
});
}
private createFolderIterator(folderMatch: FolderMatch, collapseResults: ISearchConfigurationProperties['collapseResults']): Iterable<ITreeElement<RenderableMatch>> {
const sortOrder = this.searchConfig.sortOrder;
const matches = folderMatch.matches().sort((a, b) => searchMatchComparer(a, b, sortOrder));
return Iterable.map(matches, fileMatch => {
const children = this.createFileIterator(fileMatch);
let nodeExists = true;
try { this.tree.getNode(fileMatch); } catch (e) { nodeExists = false; }
const collapsed = nodeExists ? undefined :
(collapseResults === 'alwaysCollapse' || (fileMatch.matches().length > 10 && collapseResults !== 'alwaysExpand'));
return <ITreeElement<RenderableMatch>>{ element: fileMatch, children, collapsed };
});
}
private createFileIterator(fileMatch: FileMatch): Iterable<ITreeElement<RenderableMatch>> {
const matches = fileMatch.matches().sort(searchMatchComparer);
return Iterable.map(matches, r => (<ITreeElement<RenderableMatch>>{ element: r }));
}
private createIterator(match: FolderMatch | FileMatch | SearchResult, collapseResults: ISearchConfigurationProperties['collapseResults']): Iterable<ITreeElement<RenderableMatch>> {
return match instanceof SearchResult ? this.createResultIterator(collapseResults) :
match instanceof FolderMatch ? this.createFolderIterator(match, collapseResults) :
this.createFileIterator(match);
}
private replaceAll(): void {
if (this.viewModel.searchResult.count() === 0) {
return;
}
const occurrences = this.viewModel.searchResult.count();
const fileCount = this.viewModel.searchResult.fileCount();
const replaceValue = this.searchWidget.getReplaceValue() || '';
const afterReplaceAllMessage = this.buildAfterReplaceAllMessage(occurrences, fileCount, replaceValue);
let progressComplete: () => void;
let progressReporter: IProgress<IProgressStep>;
this.progressService.withProgress({ location: this.getProgressLocation(), delay: 100, total: occurrences }, p => {
progressReporter = p;
return new Promise(resolve => progressComplete = resolve);
});
const confirmation: IConfirmation = {
title: nls.localize('replaceAll.confirmation.title', "Replace All"),
message: this.buildReplaceAllConfirmationMessage(occurrences, fileCount, replaceValue),
primaryButton: nls.localize('replaceAll.confirm.button', "&&Replace"),
type: 'question'
};
this.dialogService.confirm(confirmation).then(res => {
if (res.confirmed) {
this.searchWidget.setReplaceAllActionState(false);
this.viewModel.searchResult.replaceAll(progressReporter).then(() => {
progressComplete();
const messageEl = this.clearMessage();
dom.append(messageEl, $('p', undefined, afterReplaceAllMessage));
this.reLayout();
}, (error) => {
progressComplete();
errors.isPromiseCanceledError(error);
this.notificationService.error(error);
});
}
});
}
private buildAfterReplaceAllMessage(occurrences: number, fileCount: number, replaceValue?: string) {
if (occurrences === 1) {
if (fileCount === 1) {
if (replaceValue) {
return nls.localize('replaceAll.occurrence.file.message', "Replaced {0} occurrence across {1} file with '{2}'.", occurrences, fileCount, replaceValue);
}
return nls.localize('removeAll.occurrence.file.message', "Replaced {0} occurrence across {1} file.", occurrences, fileCount);
}
if (replaceValue) {
return nls.localize('replaceAll.occurrence.files.message', "Replaced {0} occurrence across {1} files with '{2}'.", occurrences, fileCount, replaceValue);
}
return nls.localize('removeAll.occurrence.files.message', "Replaced {0} occurrence across {1} files.", occurrences, fileCount);
}
if (fileCount === 1) {
if (replaceValue) {
return nls.localize('replaceAll.occurrences.file.message', "Replaced {0} occurrences across {1} file with '{2}'.", occurrences, fileCount, replaceValue);
}
return nls.localize('removeAll.occurrences.file.message', "Replaced {0} occurrences across {1} file.", occurrences, fileCount);
}
if (replaceValue) {
return nls.localize('replaceAll.occurrences.files.message', "Replaced {0} occurrences across {1} files with '{2}'.", occurrences, fileCount, replaceValue);
}
return nls.localize('removeAll.occurrences.files.message', "Replaced {0} occurrences across {1} files.", occurrences, fileCount);
}
private buildReplaceAllConfirmationMessage(occurrences: number, fileCount: number, replaceValue?: string) {
if (occurrences === 1) {
if (fileCount === 1) {
if (replaceValue) {
return nls.localize('removeAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file with '{2}'?", occurrences, fileCount, replaceValue);
}
return nls.localize('replaceAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file?", occurrences, fileCount);
}
if (replaceValue) {
return nls.localize('removeAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files with '{2}'?", occurrences, fileCount, replaceValue);
}
return nls.localize('replaceAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files?", occurrences, fileCount);
}
if (fileCount === 1) {
if (replaceValue) {
return nls.localize('removeAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file with '{2}'?", occurrences, fileCount, replaceValue);
}
return nls.localize('replaceAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file?", occurrences, fileCount);
}
if (replaceValue) {
return nls.localize('removeAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files with '{2}'?", occurrences, fileCount, replaceValue);
}
return nls.localize('replaceAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files?", occurrences, fileCount);
}
private clearMessage(): HTMLElement {
this.searchWithoutFolderMessageElement = undefined;
dom.clearNode(this.messagesElement);
dom.show(this.messagesElement);
dispose(this.messageDisposables);
this.messageDisposables = [];
return dom.append(this.messagesElement, $('.message'));
}
private createSearchResultsView(container: HTMLElement): void {
this.resultsElement = dom.append(container, $('.results.show-file-icons'));
const delegate = this.instantiationService.createInstance(SearchDelegate);
const identityProvider: IIdentityProvider<RenderableMatch> = {
getId(element: RenderableMatch) {
return element.id();
}
};
this.treeLabels = this._register(this.instantiationService.createInstance(ResourceLabels, { onDidChangeVisibility: this.onDidChangeBodyVisibility }));
this.tree = this._register(<WorkbenchObjectTree<RenderableMatch>>this.instantiationService.createInstance(WorkbenchObjectTree,
'SearchView',
this.resultsElement,
delegate,
[
this._register(this.instantiationService.createInstance(FolderMatchRenderer, this.viewModel, this, this.treeLabels)),
this._register(this.instantiationService.createInstance(FileMatchRenderer, this.viewModel, this, this.treeLabels)),
this._register(this.instantiationService.createInstance(MatchRenderer, this.viewModel, this)),
],
{
identityProvider,
accessibilityProvider: this.treeAccessibilityProvider,
dnd: this.instantiationService.createInstance(SearchDND),
multipleSelectionSupport: false,
overrideStyles: {
listBackground: this.getBackgroundColor()
}
}));
this._register(this.tree.onContextMenu(e => this.onContextMenu(e)));
this._register(this.tree.onDidChangeCollapseState(() =>
this.toggleCollapseStateDelayer.trigger(() => this.toggleCollapseAction.onTreeCollapseStateChange())
));
const resourceNavigator = this._register(new TreeResourceNavigator(this.tree, { openOnFocus: true, openOnSelection: false }));
this._register(Event.debounce(resourceNavigator.onDidOpenResource, (last, event) => event, 75, true)(options => {
if (options.element instanceof Match) {
const selectedMatch: Match = options.element;
if (this.currentSelectedFileMatch) {
this.currentSelectedFileMatch.setSelectedMatch(null);
}
this.currentSelectedFileMatch = selectedMatch.parent();
this.currentSelectedFileMatch.setSelectedMatch(selectedMatch);
this.onFocus(selectedMatch, options.editorOptions.preserveFocus, options.sideBySide, options.editorOptions.pinned);
}
}));
this._register(Event.any<any>(this.tree.onDidFocus, this.tree.onDidChangeFocus)(() => {
if (this.tree.isDOMFocused()) {
const focus = this.tree.getFocus()[0];
this.firstMatchFocused.set(this.tree.navigate().first() === focus);
this.fileMatchOrMatchFocused.set(!!focus);
this.fileMatchFocused.set(focus instanceof FileMatch);
this.folderMatchFocused.set(focus instanceof FolderMatch);
this.matchFocused.set(focus instanceof Match);
this.fileMatchOrFolderMatchFocus.set(focus instanceof FileMatch || focus instanceof FolderMatch);
this.fileMatchOrFolderMatchWithResourceFocus.set(focus instanceof FileMatch || focus instanceof FolderMatchWithResource);
}
}));
this._register(this.tree.onDidBlur(() => {
this.firstMatchFocused.reset();
this.fileMatchOrMatchFocused.reset();
this.fileMatchFocused.reset();
this.folderMatchFocused.reset();
this.matchFocused.reset();
this.fileMatchOrFolderMatchFocus.reset();
this.fileMatchOrFolderMatchWithResourceFocus.reset();
}));
}
private onContextMenu(e: ITreeContextMenuEvent<RenderableMatch | null>): void {
if (!this.contextMenu) {
this.contextMenu = this._register(this.menuService.createMenu(MenuId.SearchContext, this.contextKeyService));
}
e.browserEvent.preventDefault();
e.browserEvent.stopPropagation();
const actions: IAction[] = [];
const actionsDisposable = createAndFillInContextMenuActions(this.contextMenu, { shouldForwardArgs: true }, actions, this.contextMenuService);
this.contextMenuService.showContextMenu({
getAnchor: () => e.anchor,
getActions: () => actions,
getActionsContext: () => e.element,
onHide: () => dispose(actionsDisposable)
});
}
selectNextMatch(): void {
if (!this.hasSearchResults()) {
return;
}
const [selected] = this.tree.getSelection();
// Expand the initial selected node, if needed
if (selected && !(selected instanceof Match)) {
if (this.tree.isCollapsed(selected)) {
this.tree.expand(selected);
}
}
let navigator = this.tree.navigate(selected);
let next = navigator.next();
if (!next) {
next = navigator.first();
}
// Expand until first child is a Match
while (next && !(next instanceof Match)) {
if (this.tree.isCollapsed(next)) {
this.tree.expand(next);
}
// Select the first child
next = navigator.next();
}
// Reveal the newly selected element
if (next) {
if (next === selected) {
this.tree.setFocus([]);
}
this.tree.setFocus([next], getSelectionKeyboardEvent(undefined, false));
this.tree.reveal(next);
const ariaLabel = this.treeAccessibilityProvider.getAriaLabel(next);
if (ariaLabel) { aria.alert(ariaLabel); }
}
}
selectPreviousMatch(): void {
if (!this.hasSearchResults()) {
return;
}
const [selected] = this.tree.getSelection();
let navigator = this.tree.navigate(selected);
let prev = navigator.previous();
// Select previous until find a Match or a collapsed item
while (!prev || (!(prev instanceof Match) && !this.tree.isCollapsed(prev))) {
const nextPrev = prev ? navigator.previous() : navigator.last();
if (!prev && !nextPrev) {
return;
}
prev = nextPrev;
}
// Expand until last child is a Match
while (!(prev instanceof Match)) {
const nextItem = navigator.next();
this.tree.expand(prev);
navigator = this.tree.navigate(nextItem); // recreate navigator because modifying the tree can invalidate it
prev = nextItem ? navigator.previous() : navigator.last(); // select last child
}
// Reveal the newly selected element
if (prev) {
if (prev === selected) {
this.tree.setFocus([]);
}
this.tree.setFocus([prev], getSelectionKeyboardEvent(undefined, false));
this.tree.reveal(prev);
const ariaLabel = this.treeAccessibilityProvider.getAriaLabel(prev);
if (ariaLabel) { aria.alert(ariaLabel); }
}
}
moveFocusToResults(): void {
this.tree.domFocus();
}
focus(): void {
super.focus();
const updatedText = this.searchConfig.seedOnFocus ? this.updateTextFromSelection({ allowSearchOnType: false }) : false;
this.searchWidget.focus(undefined, undefined, updatedText);
}
updateTextFromSelection({ allowUnselectedWord = true, allowSearchOnType = true }): boolean {
let updatedText = false;
const seedSearchStringFromSelection = this.configurationService.getValue<IEditorOptions>('editor').find!.seedSearchStringFromSelection;
if (seedSearchStringFromSelection) {
let selectedText = this.getSearchTextFromEditor(allowUnselectedWord);
if (selectedText) {
if (this.searchWidget.searchInput.getRegex()) {
selectedText = strings.escapeRegExpCharacters(selectedText);
}
if (allowSearchOnType && !this.viewModel.searchResult.isDirty) {
this.searchWidget.setValue(selectedText);
} else {
this.pauseSearching = true;
this.searchWidget.setValue(selectedText);
this.pauseSearching = false;
}
updatedText = true;
}
}
return updatedText;
}
focusNextInputBox(): void {
if (this.searchWidget.searchInputHasFocus()) {
if (this.searchWidget.isReplaceShown()) {
this.searchWidget.focus(true, true);
} else {
this.moveFocusFromSearchOrReplace();
}
return;
}
if (this.searchWidget.replaceInputHasFocus()) {
this.moveFocusFromSearchOrReplace();
return;
}
if (this.inputPatternIncludes.inputHasFocus()) {
this.inputPatternExcludes.focus();
this.inputPatternExcludes.select();
return;
}
if (this.inputPatternExcludes.inputHasFocus()) {
this.selectTreeIfNotSelected();
return;
}
}
private moveFocusFromSearchOrReplace() {
if (this.showsFileTypes()) {
this.toggleQueryDetails(true, this.showsFileTypes());
} else {
this.selectTreeIfNotSelected();
}
}
focusPreviousInputBox(): void {
if (this.searchWidget.searchInputHasFocus()) {
return;
}
if (this.searchWidget.replaceInputHasFocus()) {
this.searchWidget.focus(true);
return;
}
if (this.inputPatternIncludes.inputHasFocus()) {
this.searchWidget.focus(true, true);
return;
}
if (this.inputPatternExcludes.inputHasFocus()) {
this.inputPatternIncludes.focus();
this.inputPatternIncludes.select();
return;
}
if (this.tree.isDOMFocused()) {
this.moveFocusFromResults();
return;
}
}
private moveFocusFromResults(): void {
if (this.showsFileTypes()) {
this.toggleQueryDetails(true, true, false, true);
} else {
this.searchWidget.focus(true, true);
}
}
private reLayout(): void {
if (this.isDisposed) {
return;
}
const actionsPosition = this.searchConfig.actionsPosition;
dom.toggleClass(this.getContainer(), SearchView.ACTIONS_RIGHT_CLASS_NAME, actionsPosition === 'right');
this.searchWidget.setWidth(this.size.width - 28 /* container margin */);
this.inputPatternExcludes.setWidth(this.size.width - 28 /* container margin */);
this.inputPatternIncludes.setWidth(this.size.width - 28 /* container margin */);
const messagesSize = this.messagesElement.style.display === 'none' ?
0 :
dom.getTotalHeight(this.messagesElement);
const searchResultContainerHeight = this.size.height -
messagesSize -
dom.getTotalHeight(this.searchWidgetsContainerElement);
this.resultsElement.style.height = searchResultContainerHeight + 'px';
this.tree.layout(searchResultContainerHeight, this.size.width);
}