searchView.ts 53.6 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

I
isidor 已提交
8
import 'vs/css!./media/searchview';
9
import * as nls from 'vs/nls';
J
Johannes Rieken 已提交
10
import { TPromise } from 'vs/base/common/winjs.base';
R
Rob Lourens 已提交
11
import { Emitter, debounceEvent } from 'vs/base/common/event';
12 13 14
import * as errors from 'vs/base/common/errors';
import * as aria from 'vs/base/browser/ui/aria/aria';
import * as env from 'vs/base/common/platform';
S
Sandeep Somavarapu 已提交
15
import { Delayer } from 'vs/base/common/async';
E
Erich Gamma 已提交
16
import URI from 'vs/base/common/uri';
17
import * as strings from 'vs/base/common/strings';
18
import * as paths from 'vs/base/common/paths';
19
import * as dom from 'vs/base/browser/dom';
S
Sandeep Somavarapu 已提交
20
import { IAction } from 'vs/base/common/actions';
J
Johannes Rieken 已提交
21 22
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { Dimension, Builder, $ } from 'vs/base/browser/builder';
23
import { FindInput } from 'vs/base/browser/ui/findinput/findInput';
R
Rob Lourens 已提交
24
import { ITree, IFocusEvent } from 'vs/base/parts/tree/browser/tree';
J
Johannes Rieken 已提交
25
import { Scope } from 'vs/workbench/common/memento';
26
import { IPreferencesService } from 'vs/workbench/parts/preferences/common/preferences';
J
Johannes Rieken 已提交
27
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
28
import { FileChangeType, FileChangesEvent, IFileService } from 'vs/platform/files/common/files';
29
import { Match, FileMatch, SearchModel, FileMatchOrMatch, IChangeEvent, ISearchWorkbenchService, FolderMatch } from 'vs/workbench/parts/search/common/searchModel';
30
import { QueryBuilder } from 'vs/workbench/parts/search/common/queryBuilder';
31
import { MessageType } from 'vs/base/browser/ui/inputbox/inputBox';
32
import { ISearchProgressItem, ISearchComplete, ISearchQuery, IQueryOptions, ISearchConfiguration, IPatternInfo, VIEW_ID } from 'vs/platform/search/common/search';
J
Johannes Rieken 已提交
33 34 35 36 37 38
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IProgressService } from 'vs/platform/progress/common/progress';
39
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
J
Johannes Rieken 已提交
40 41 42
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { KeyCode } from 'vs/base/common/keyCodes';
43
import { PatternInputWidget, ExcludePatternInputWidget } from 'vs/workbench/parts/search/browser/patternInputWidget';
R
Rob Lourens 已提交
44
import { SearchRenderer, SearchDataSource, SearchSorter, SearchAccessibilityProvider, SearchFilter, SearchTreeController } from 'vs/workbench/parts/search/browser/searchResultsView';
45
import { SearchWidget, ISearchWidgetOptions } from 'vs/workbench/parts/search/browser/searchWidget';
46
import { RefreshAction, CollapseDeepestExpandedLevelAction, ClearSearchResultsAction, CancelSearchAction } from 'vs/workbench/parts/search/browser/searchActions';
47
import { IReplaceService } from 'vs/workbench/parts/search/common/replace';
J
Johannes Rieken 已提交
48
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
B
Benjamin Pasero 已提交
49
import { OpenFolderAction, OpenFileFolderAction } from 'vs/workbench/browser/actions/workspaceActions';
50
import * as Constants from 'vs/workbench/parts/search/common/constants';
51
import { IThemeService, ITheme, ICssStyleCollector, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
52
import { editorFindMatchHighlight, diffInserted, diffRemoved, diffInsertedOutline, diffRemovedOutline, editorFindMatchHighlightBorder } from 'vs/platform/theme/common/colorRegistry';
53
import { getOutOfWorkspaceEditorResources } from 'vs/workbench/parts/search/common/search';
B
Benjamin Pasero 已提交
54
import { PreferencesEditor } from 'vs/workbench/parts/preferences/browser/preferencesEditor';
55
import { isDiffEditor, isCodeEditor, ICodeEditor } from 'vs/editor/browser/editorBrowser';
B
Benjamin Pasero 已提交
56
import { TreeResourceNavigator, WorkbenchTree } from 'vs/platform/list/browser/listService';
57
import { IEditorOptions } from 'vs/editor/common/config/editorOptions';
58
import { SimpleFileResourceDragAndDrop } from 'vs/workbench/browser/dnd';
59
import { IConfirmation, IDialogService } from 'vs/platform/dialogs/common/dialogs';
60
import { INotificationService } from 'vs/platform/notification/common/notification';
61 62 63
import { IPanel } from 'vs/workbench/common/panel';
import { IViewlet } from 'vs/workbench/common/viewlet';
import { Viewlet } from 'vs/workbench/browser/viewlet';
S
Sandeep Somavarapu 已提交
64
import { IPartService } from 'vs/workbench/services/part/common/partService';
65
import { splitGlobAware } from 'vs/base/common/glob';
E
Erich Gamma 已提交
66

67
export class SearchView extends Viewlet implements IViewlet, IPanel {
E
Erich Gamma 已提交
68

69 70
	private static readonly MAX_TEXT_RESULTS = 10000;
	private static readonly SHOW_REPLACE_STORAGE_KEY = 'vs.search.show.replace';
S
Sandeep Somavarapu 已提交
71

E
Erich Gamma 已提交
72
	private isDisposed: boolean;
73

E
Erich Gamma 已提交
74
	private queryBuilder: QueryBuilder;
75
	private viewModel: SearchModel;
E
Erich Gamma 已提交
76

A
Alex Dima 已提交
77
	private viewletVisible: IContextKey<boolean>;
78 79 80 81 82
	private inputBoxFocused: IContextKey<boolean>;
	private inputPatternIncludesFocused: IContextKey<boolean>;
	private firstMatchFocused: IContextKey<boolean>;
	private fileMatchOrMatchFocused: IContextKey<boolean>;
	private fileMatchFocused: IContextKey<boolean>;
83
	private folderMatchFocused: IContextKey<boolean>;
84
	private matchFocused: IContextKey<boolean>;
85
	private hasSearchResultsKey: IContextKey<boolean>;
R
Rob Lourens 已提交
86

S
Sandeep Somavarapu 已提交
87
	private searchSubmitted: boolean;
88
	private searching: boolean;
S
Sandeep Somavarapu 已提交
89

90
	private actions: (RefreshAction | CollapseDeepestExpandedLevelAction | ClearSearchResultsAction | CancelSearchAction)[] = [];
91
	private tree: WorkbenchTree;
E
Erich Gamma 已提交
92 93
	private viewletSettings: any;
	private messages: Builder;
94 95
	private searchWidgetsContainer: Builder;
	private searchWidget: SearchWidget;
E
Erich Gamma 已提交
96 97
	private size: Dimension;
	private queryDetails: HTMLElement;
98
	private inputPatternIncludes: ExcludePatternInputWidget;
E
Erich Gamma 已提交
99 100
	private results: Builder;

S
Sandeep Somavarapu 已提交
101 102
	private currentSelectedFileMatch: FileMatch;

M
Matt Bierner 已提交
103
	private readonly selectCurrentMatchEmitter: Emitter<string>;
S
Sandeep Somavarapu 已提交
104
	private delayedRefresh: Delayer<void>;
105
	private changedWhileHidden: boolean;
R
Rob Lourens 已提交
106

107 108
	private searchWithoutFolderMessageBuilder: Builder;

109
	constructor(
S
Sandeep Somavarapu 已提交
110
		@IPartService partService: IPartService,
111
		@ITelemetryService telemetryService: ITelemetryService,
112
		@IFileService private fileService: IFileService,
113
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
114
		@IEditorGroupService private editorGroupService: IEditorGroupService,
115
		@IProgressService private progressService: IProgressService,
116
		@INotificationService private notificationService: INotificationService,
117
		@IDialogService private dialogService: IDialogService,
118 119 120 121 122
		@IStorageService private storageService: IStorageService,
		@IContextViewService private contextViewService: IContextViewService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IConfigurationService private configurationService: IConfigurationService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
S
Sandeep Somavarapu 已提交
123
		@ISearchWorkbenchService private searchWorkbenchService: ISearchWorkbenchService,
124
		@IContextKeyService private contextKeyService: IContextKeyService,
125
		@IReplaceService private replaceService: IReplaceService,
126
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
127
		@IPreferencesService private preferencesService: IPreferencesService,
128
		@IThemeService protected themeService: IThemeService
E
Erich Gamma 已提交
129
	) {
I
isidor 已提交
130
		super(VIEW_ID, partService, telemetryService, themeService);
E
Erich Gamma 已提交
131

I
isidor 已提交
132
		this.viewletVisible = Constants.SearchViewVisibleKey.bindTo(contextKeyService);
133 134 135 136 137
		this.inputBoxFocused = Constants.InputBoxFocusedKey.bindTo(this.contextKeyService);
		this.inputPatternIncludesFocused = Constants.PatternIncludesFocusedKey.bindTo(this.contextKeyService);
		this.firstMatchFocused = Constants.FirstMatchFocusKey.bindTo(contextKeyService);
		this.fileMatchOrMatchFocused = Constants.FileMatchOrMatchFocusKey.bindTo(contextKeyService);
		this.fileMatchFocused = Constants.FileFocusKey.bindTo(contextKeyService);
138
		this.folderMatchFocused = Constants.FolderFocusKey.bindTo(contextKeyService);
139
		this.matchFocused = Constants.MatchFocusKey.bindTo(this.contextKeyService);
140
		this.hasSearchResultsKey = Constants.HasSearchResults.bindTo(this.contextKeyService);
E
Erich Gamma 已提交
141 142 143 144

		this.queryBuilder = this.instantiationService.createInstance(QueryBuilder);
		this.viewletSettings = this.getMemento(storageService, Scope.WORKSPACE);

145
		this.toUnbind.push(this.fileService.onFileChanges(e => this.onFilesChanged(e)));
146
		this.toUnbind.push(this.untitledEditorService.onDidChangeDirty(e => this.onUntitledDidChangeDirty(e)));
147
		this.toUnbind.push(this.contextService.onDidChangeWorkbenchState(() => this.onDidChangeWorkbenchState()));
148

R
Rob Lourens 已提交
149 150 151 152
		this.selectCurrentMatchEmitter = new Emitter<string>();
		debounceEvent(this.selectCurrentMatchEmitter.event, (l, e) => e, 100, /*leading=*/true)
			(() => this.selectCurrentMatch());

S
Sandeep Somavarapu 已提交
153
		this.delayedRefresh = new Delayer<void>(250);
E
Erich Gamma 已提交
154 155
	}

156 157 158 159 160 161
	private onDidChangeWorkbenchState(): void {
		if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.searchWithoutFolderMessageBuilder) {
			this.searchWithoutFolderMessageBuilder.hide();
		}
	}

E
Erich Gamma 已提交
162 163 164
	public create(parent: Builder): TPromise<void> {
		super.create(parent);

S
Sandeep Somavarapu 已提交
165
		this.viewModel = this.searchWorkbenchService.searchModel;
E
Erich Gamma 已提交
166
		let builder: Builder;
S
Sandeep Somavarapu 已提交
167
		parent.div({
I
isidor 已提交
168
			'class': 'search-view'
E
Erich Gamma 已提交
169 170 171 172
		}, (div) => {
			builder = div;
		});

J
Johannes Rieken 已提交
173 174
		builder.div({ 'class': ['search-widgets-container'] }, (div) => {
			this.searchWidgetsContainer = div;
175 176 177
		});
		this.createSearchWidget(this.searchWidgetsContainer);

178
		const filePatterns = this.viewletSettings['query.filePatterns'] || '';
179
		const patternExclusions = this.viewletSettings['query.folderExclusions'] || '';
180
		delete this.viewletSettings['query.folderExclusions']; // Migrating from versions that have dedicated exclusions persisted
181
		const patternIncludes = this.viewletSettings['query.folderIncludes'] || '';
182
		const patternIncludesHistory = this.viewletSettings['query.folderIncludesHistory'] || [];
A
Amy Qiu 已提交
183
		const queryDetailsExpanded = this.viewletSettings['query.queryDetailsExpanded'] || '';
184 185
		const useExcludesAndIgnoreFiles = typeof this.viewletSettings['query.useExcludesAndIgnoreFiles'] === 'boolean' ?
			this.viewletSettings['query.useExcludesAndIgnoreFiles'] : true;
186 187

		this.queryDetails = this.searchWidgetsContainer.div({ 'class': ['query-details'] }, (builder) => {
188
			builder.div({ 'class': 'more', 'tabindex': 0, 'role': 'button', 'title': nls.localize('moreSearch', "Toggle Search Details") })
189 190
				.on(dom.EventType.CLICK, (e) => {
					dom.EventHelper.stop(e);
191
					this.toggleQueryDetails(true);
192 193 194
				}).on(dom.EventType.KEY_UP, (e: KeyboardEvent) => {
					let event = new StandardKeyboardEvent(e);

A
Alexandru Dima 已提交
195
					if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) {
196
						dom.EventHelper.stop(e);
197
						this.toggleQueryDetails();
198 199
					}
				});
E
Erich Gamma 已提交
200 201 202

			//folder includes list
			builder.div({ 'class': 'file-types' }, (builder) => {
203
				let title = nls.localize('searchIncludeExclude.label', "files to include/exclude");
E
Erich Gamma 已提交
204 205
				builder.element('h4', { text: title });

206 207 208
				this.inputPatternIncludes = new ExcludePatternInputWidget(builder.getContainer(), this.contextViewService, this.themeService, {
					ariaLabel: nls.localize('searchIncludeExclude.ariaLabel', 'Search Include/Exclude Patterns'),
					placeholder: nls.localize('searchIncludeExclude.placeholder', "Examples: src, !*.ts, test/**/*.log")
E
Erich Gamma 已提交
209 210
				});

211
				// For migrating from versions that have dedicated exclusions persisted
212 213 214 215 216 217
				let mergedIncludeExcludes = patternIncludes;
				if (patternExclusions) {
					if (mergedIncludeExcludes) {
						mergedIncludeExcludes += ', ';
					}

218 219 220 221 222
					mergedIncludeExcludes += splitGlobAware(patternExclusions, ',')
						.map(s => s.trim())
						.filter(s => !!s.length)
						.map(s => '!' + s)
						.join(', ');
223 224 225
				}

				this.inputPatternIncludes.setValue(mergedIncludeExcludes);
226
				this.inputPatternIncludes.setHistory(patternIncludesHistory);
227
				this.inputPatternIncludes.setUseExcludesAndIgnoreFiles(useExcludesAndIgnoreFiles);
E
Erich Gamma 已提交
228 229

				this.inputPatternIncludes
230
					.on(FindInput.OPTION_CHANGE, (e) => {
E
Erich Gamma 已提交
231 232
						this.onQueryChanged(false);
					});
233

234
				this.inputPatternIncludes.onSubmit(() => this.onQueryChanged(true, true));
235
				this.inputPatternIncludes.onCancel(() => this.viewModel.cancelSearch()); // Cancel search without focusing the search widget
236
				this.trackInputBox(this.inputPatternIncludes.inputFocusTracker, this.inputPatternIncludesFocused);
E
Erich Gamma 已提交
237 238 239
			});
		}).getHTMLElement();

240
		this.messages = builder.div({ 'class': 'messages' }).hide().clone();
241
		if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
242 243
			this.searchWithoutFolderMessage(this.clearMessage());
		}
244 245 246

		this.createSearchResultsView(builder);

S
Sandeep Somavarapu 已提交
247 248 249 250 251
		this.actions = [
			this.instantiationService.createInstance(RefreshAction, RefreshAction.ID, RefreshAction.LABEL),
			this.instantiationService.createInstance(CollapseDeepestExpandedLevelAction, CollapseDeepestExpandedLevelAction.ID, CollapseDeepestExpandedLevelAction.LABEL),
			this.instantiationService.createInstance(ClearSearchResultsAction, ClearSearchResultsAction.ID, ClearSearchResultsAction.LABEL)
		];
252

253
		if (filePatterns !== '' || patternExclusions !== '' || patternIncludes !== '' || queryDetailsExpanded !== '' || !useExcludesAndIgnoreFiles) {
254
			this.toggleQueryDetails(true, true, true);
255 256
		}

S
Sandeep Somavarapu 已提交
257
		this.toUnbind.push(this.viewModel.searchResult.onChange((event) => this.onSearchResultsChanged(event)));
S
Sandeep Somavarapu 已提交
258

259 260 261
		return TPromise.as(null);
	}

J
Johannes Rieken 已提交
262
	public get searchAndReplaceWidget(): SearchWidget {
263 264 265
		return this.searchWidget;
	}

266 267 268 269
	public get searchIncludePattern(): PatternInputWidget {
		return this.inputPatternIncludes;
	}

S
Sandeep Somavarapu 已提交
270 271 272 273 274 275
	private updateActions(): void {
		for (const action of this.actions) {
			action.update();
		}
	}

276 277 278 279 280
	private createSearchWidget(builder: Builder): void {
		let contentPattern = this.viewletSettings['query.contentPattern'] || '';
		let isRegex = this.viewletSettings['query.regex'] === true;
		let isWholeWords = this.viewletSettings['query.wholeWords'] === true;
		let isCaseSensitive = this.viewletSettings['query.caseSensitive'] === true;
281
		let searchHistory = this.viewletSettings['query.searchHistory'] || [];
E
Erich Gamma 已提交
282

283
		this.searchWidget = this.instantiationService.createInstance(SearchWidget, builder, <ISearchWidgetOptions>{
284 285 286
			value: contentPattern,
			isRegex: isRegex,
			isCaseSensitive: isCaseSensitive,
287 288
			isWholeWords: isWholeWords,
			history: searchHistory
289
		});
S
Sandeep Somavarapu 已提交
290

291
		if (this.storageService.getBoolean(SearchView.SHOW_REPLACE_STORAGE_KEY, StorageScope.WORKSPACE, true)) {
S
Sandeep Somavarapu 已提交
292 293 294
			this.searchWidget.toggleReplace(true);
		}

S
Sandeep Somavarapu 已提交
295
		this.toUnbind.push(this.searchWidget);
296

S
Sandeep Somavarapu 已提交
297 298 299
		this.toUnbind.push(this.searchWidget.onSearchSubmit((refresh) => this.onQueryChanged(refresh)));
		this.toUnbind.push(this.searchWidget.onSearchCancel(() => this.cancelSearch()));
		this.toUnbind.push(this.searchWidget.searchInput.onDidOptionChange((viaKeyboard) => this.onQueryChanged(true, viaKeyboard)));
300

S
Sandeep Somavarapu 已提交
301
		this.toUnbind.push(this.searchWidget.onReplaceToggled(() => this.onReplaceToggled()));
S
Sandeep Somavarapu 已提交
302
		this.toUnbind.push(this.searchWidget.onReplaceStateChange((state) => {
J
Johannes Rieken 已提交
303
			this.viewModel.replaceActive = state;
304
			this.tree.refresh();
S
Sandeep Somavarapu 已提交
305 306
		}));
		this.toUnbind.push(this.searchWidget.onReplaceValueChanged((value) => {
J
Johannes Rieken 已提交
307
			this.viewModel.replaceString = this.searchWidget.getReplaceValue();
S
Sandeep Somavarapu 已提交
308
			this.delayedRefresh.trigger(() => this.tree.refresh());
S
Sandeep Somavarapu 已提交
309
		}));
310

S
Sandeep Somavarapu 已提交
311
		this.toUnbind.push(this.searchWidget.onReplaceAll(() => this.replaceAll()));
312 313 314 315
		this.trackInputBox(this.searchWidget.searchInputFocusTracker);
		this.trackInputBox(this.searchWidget.replaceInputFocusTracker);
	}

316
	private trackInputBox(inputFocusTracker: dom.IFocusTracker, contextKey?: IContextKey<boolean>): void {
317
		this.toUnbind.push(inputFocusTracker.onDidFocus(() => {
318
			this.inputBoxFocused.set(true);
319 320 321
			if (contextKey) {
				contextKey.set(true);
			}
322
		}));
323
		this.toUnbind.push(inputFocusTracker.onDidBlur(() => {
324
			this.inputBoxFocused.set(this.searchWidget.searchInputHasFocus()
325
				|| this.searchWidget.replaceInputHasFocus()
326
				|| this.inputPatternIncludes.inputHasFocus());
327 328 329
			if (contextKey) {
				contextKey.set(false);
			}
330
		}));
S
Sandeep Somavarapu 已提交
331 332
	}

S
Sandeep Somavarapu 已提交
333 334
	private onReplaceToggled(): void {
		this.layout(this.size);
335 336 337

		const isReplaceShown = this.searchAndReplaceWidget.isReplaceShown();
		if (!isReplaceShown) {
338
			this.storageService.store(SearchView.SHOW_REPLACE_STORAGE_KEY, false, StorageScope.WORKSPACE);
339
		} else {
340
			this.storageService.remove(SearchView.SHOW_REPLACE_STORAGE_KEY);
341
		}
S
Sandeep Somavarapu 已提交
342 343
	}

S
Sandeep Somavarapu 已提交
344
	private onSearchResultsChanged(event?: IChangeEvent): TPromise<any> {
345 346 347 348 349 350 351 352 353
		if (this.isVisible()) {
			return this.refreshAndUpdateCount(event);
		} else {
			this.changedWhileHidden = true;
			return TPromise.wrap(null);
		}
	}

	private refreshAndUpdateCount(event?: IChangeEvent): TPromise<void> {
S
Sandeep Somavarapu 已提交
354
		return this.refreshTree(event).then(() => {
S
Sandeep Somavarapu 已提交
355
			this.searchWidget.setReplaceAllActionState(!this.viewModel.searchResult.isEmpty());
356
			this.updateSearchResultCount();
S
Sandeep Somavarapu 已提交
357
		});
358 359
	}

S
Sandeep Somavarapu 已提交
360
	private refreshTree(event?: IChangeEvent): TPromise<any> {
361
		if (!event || event.added || event.removed) {
S
Sandeep Somavarapu 已提交
362
			return this.tree.refresh(this.viewModel.searchResult);
363 364
		} else {
			if (event.elements.length === 1) {
S
Sandeep Somavarapu 已提交
365
				return this.tree.refresh(event.elements[0]);
366
			} else {
S
Sandeep Somavarapu 已提交
367
				return this.tree.refresh(event.elements);
368 369 370 371
			}
		}
	}

372
	private replaceAll(): void {
373
		if (this.viewModel.searchResult.count() === 0) {
S
Sandeep Somavarapu 已提交
374 375 376
			return;
		}

J
Johannes Rieken 已提交
377
		let progressRunner = this.progressService.show(100);
378

J
Johannes Rieken 已提交
379 380 381
		let occurrences = this.viewModel.searchResult.count();
		let fileCount = this.viewModel.searchResult.fileCount();
		let replaceValue = this.searchWidget.getReplaceValue() || '';
382
		let afterReplaceAllMessage = this.buildAfterReplaceAllMessage(occurrences, fileCount, replaceValue);
383

B
Benjamin Pasero 已提交
384
		let confirmation: IConfirmation = {
385
			title: nls.localize('replaceAll.confirmation.title', "Replace All"),
386
			message: this.buildReplaceAllConfirmationMessage(occurrences, fileCount, replaceValue),
387
			primaryButton: nls.localize('replaceAll.confirm.button', "&&Replace"),
B
Benjamin Pasero 已提交
388
			type: 'question'
389 390
		};

391
		this.dialogService.confirm(confirmation).then(res => {
392
			if (res.confirmed) {
393 394 395 396 397 398 399 400
				this.searchWidget.setReplaceAllActionState(false);
				this.viewModel.searchResult.replaceAll(progressRunner).then(() => {
					progressRunner.done();
					this.clearMessage()
						.p({ text: afterReplaceAllMessage });
				}, (error) => {
					progressRunner.done();
					errors.isPromiseCanceledError(error);
401
					this.notificationService.error(error);
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
	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);
	}

471
	private clearMessage(): Builder {
472 473
		this.searchWithoutFolderMessageBuilder = void 0;

474 475 476
		return this.messages.empty().show()
			.asContainer().div({ 'class': 'message' })
			.asContainer();
477 478 479
	}

	private createSearchResultsView(builder: Builder): void {
E
Erich Gamma 已提交
480 481
		builder.div({ 'class': 'results' }, (div) => {
			this.results = div;
482
			this.results.addClass('show-file-icons');
E
Erich Gamma 已提交
483

484 485 486
			let dataSource = this.instantiationService.createInstance(SearchDataSource);
			this.toUnbind.push(dataSource);

487
			let renderer = this.instantiationService.createInstance(SearchRenderer, this.getActionRunner(), this);
488 489
			this.toUnbind.push(renderer);

490
			let dnd = this.instantiationService.createInstance(SimpleFileResourceDragAndDrop, (obj: any) => obj instanceof FileMatch ? obj.resource() : void 0);
E
Erich Gamma 已提交
491

492
			this.tree = this.instantiationService.createInstance(WorkbenchTree, div.getHTMLElement(), {
E
Erich Gamma 已提交
493 494 495 496
				dataSource: dataSource,
				renderer: renderer,
				sorter: new SearchSorter(),
				filter: new SearchFilter(),
R
Rob Lourens 已提交
497
				controller: this.instantiationService.createInstance(SearchTreeController),
B
Benjamin Pasero 已提交
498 499
				accessibilityProvider: this.instantiationService.createInstance(SearchAccessibilityProvider),
				dnd
B
Benjamin Pasero 已提交
500
			}, {
501
					ariaLabel: nls.localize('treeAriaLabel', "Search Results")
502
				});
B
Benjamin Pasero 已提交
503

504
			this.tree.setInput(this.viewModel.searchResult);
A
Alex Dima 已提交
505
			this.toUnbind.push(renderer);
E
Erich Gamma 已提交
506

B
Benjamin Pasero 已提交
507 508
			const searchResultsNavigator = this._register(new TreeResourceNavigator(this.tree, { openOnFocus: true }));
			this._register(debounceEvent(searchResultsNavigator.openResource, (last, event) => event, 75, true)(options => {
S
Sandeep Somavarapu 已提交
509 510 511 512 513 514 515 516
				if (options.element instanceof Match) {
					let selectedMatch: Match = options.element;
					if (this.currentSelectedFileMatch) {
						this.currentSelectedFileMatch.setSelectedMatch(null);
					}
					this.currentSelectedFileMatch = selectedMatch.parent();
					this.currentSelectedFileMatch.setSelectedMatch(selectedMatch);
					if (!(options.payload && options.payload.preventEditorOpen)) {
517
						this.onFocus(selectedMatch, options.editorOptions.preserveFocus, options.sideBySide, options.editorOptions.pinned);
S
Sandeep Somavarapu 已提交
518
					}
519
				}
S
Sandeep Somavarapu 已提交
520
			}));
521

522 523 524 525 526
			let treeHasFocus = false;
			this.tree.onDidFocus(() => {
				treeHasFocus = true;
			});

527
			this.toUnbind.push(this.tree.onDidChangeFocus((e: IFocusEvent) => {
528 529 530 531 532 533 534 535
				if (treeHasFocus) {
					const focus = e.focus;
					this.firstMatchFocused.set(this.tree.getNavigator().first() === focus);
					this.fileMatchOrMatchFocused.set(true);
					this.fileMatchFocused.set(focus instanceof FileMatch);
					this.folderMatchFocused.set(focus instanceof FolderMatch);
					this.matchFocused.set(focus instanceof Match);
				}
E
Erich Gamma 已提交
536
			}));
S
Sandeep Somavarapu 已提交
537

538
			this.toUnbind.push(this.tree.onDidBlur(e => {
539
				treeHasFocus = false;
540 541 542
				this.firstMatchFocused.reset();
				this.fileMatchOrMatchFocused.reset();
				this.fileMatchFocused.reset();
543
				this.folderMatchFocused.reset();
544
				this.matchFocused.reset();
S
Sandeep Somavarapu 已提交
545 546 547
			}));


E
Erich Gamma 已提交
548 549 550
		});
	}

R
Rob Lourens 已提交
551 552
	public selectCurrentMatch(): void {
		const focused = this.tree.getFocus();
553
		const eventPayload = { focusEditor: true };
R
Rob Lourens 已提交
554 555 556 557
		this.tree.setSelection([focused], eventPayload);
	}

	public selectNextMatch(): void {
558
		const [selected]: FileMatchOrMatch[] = this.tree.getSelection();
559

R
Rob Lourens 已提交
560 561 562 563 564 565 566 567 568 569
		// Expand the initial selected node, if needed
		if (selected instanceof FileMatch) {
			if (!this.tree.isExpanded(selected)) {
				this.tree.expand(selected);
			}
		}

		let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false);

		let next = navigator.next();
570
		if (!next) {
R
Rob Lourens 已提交
571 572 573 574
			// Reached the end - get a new navigator from the root.
			// .first and .last only work when subTreeOnly = true. Maybe there's a simpler way.
			navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true);
			next = navigator.first();
575 576 577
		}

		// Expand and go past FileMatch nodes
578 579 580
		if (!(next instanceof Match)) {
			if (!this.tree.isExpanded(next)) {
				this.tree.expand(next);
581 582 583
			}

			// Select the FileMatch's first child
584
			next = navigator.next();
585 586 587
		}

		// Reveal the newly selected element
588 589 590 591 592 593 594
		if (next) {
			const eventPayload = { preventEditorOpen: true };
			this.tree.setFocus(next, eventPayload);
			this.tree.setSelection([next], eventPayload);
			this.tree.reveal(next);
			this.selectCurrentMatchEmitter.fire();
		}
595 596
	}

R
Rob Lourens 已提交
597
	public selectPreviousMatch(): void {
598
		const [selected]: FileMatchOrMatch[] = this.tree.getSelection();
R
Rob Lourens 已提交
599
		let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false);
600

601
		let prev = navigator.previous();
602 603

		// Expand and go past FileMatch nodes
604 605
		if (!(prev instanceof Match)) {
			prev = navigator.previous();
R
Rob Lourens 已提交
606 607 608 609 610 611 612 613 614 615 616 617 618 619
			if (!prev) {
				// Wrap around. Get a new tree starting from the root
				navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true);
				prev = navigator.last();

				// This is complicated because .last will set the navigator to the last FileMatch,
				// so expand it and FF to its last child
				this.tree.expand(prev);
				let tmp;
				while (tmp = navigator.next()) {
					prev = tmp;
				}
			}

620 621 622 623 624 625
			if (!(prev instanceof Match)) {
				// There is a second non-Match result, which must be a collapsed FileMatch.
				// Expand it then select its last child.
				navigator.next();
				this.tree.expand(prev);
				prev = navigator.previous();
626 627 628 629
			}
		}

		// Reveal the newly selected element
630
		if (prev) {
R
Rob Lourens 已提交
631
			const eventPayload = { preventEditorOpen: true };
632 633 634
			this.tree.setFocus(prev, eventPayload);
			this.tree.setSelection([prev], eventPayload);
			this.tree.reveal(prev);
R
Rob Lourens 已提交
635
			this.selectCurrentMatchEmitter.fire();
636
		}
637 638
	}

E
Erich Gamma 已提交
639 640
	public setVisible(visible: boolean): TPromise<void> {
		let promise: TPromise<void>;
641
		this.viewletVisible.set(visible);
E
Erich Gamma 已提交
642
		if (visible) {
643 644 645 646 647 648
			if (this.changedWhileHidden) {
				// Render if results changed while viewlet was hidden - #37818
				this.refreshAndUpdateCount();
				this.changedWhileHidden = false;
			}

E
Erich Gamma 已提交
649 650 651 652 653 654 655 656 657
			promise = super.setVisible(visible);
			this.tree.onVisible();
		} else {
			this.tree.onHidden();
			promise = super.setVisible(visible);
		}

		// Enable highlights if there are searchresults
		if (this.viewModel) {
658
			this.viewModel.searchResult.toggleHighlights(visible);
E
Erich Gamma 已提交
659 660
		}

661
		// Open focused element from results in case the editor area is otherwise empty
662
		if (visible && !this.editorService.getActiveEditor()) {
E
Erich Gamma 已提交
663 664
			let focus = this.tree.getFocus();
			if (focus) {
S
Sandeep Somavarapu 已提交
665
				this.onFocus(focus, true);
E
Erich Gamma 已提交
666 667 668 669 670 671 672 673 674
			}
		}

		return promise;
	}

	public focus(): void {
		super.focus();

675
		let updatedText = false;
676 677 678 679 680
		const seedSearchStringFromSelection = this.configurationService.getValue<IEditorOptions>('editor').find.seedSearchStringFromSelection;
		if (seedSearchStringFromSelection) {
			const selectedText = this.getSearchTextFromEditor();
			if (selectedText) {
				this.searchWidget.searchInput.setValue(selectedText);
681
				updatedText = true;
682
			}
683
		}
R
Rob Lourens 已提交
684

685
		this.searchWidget.focus(undefined, undefined, updatedText);
686 687
	}

688 689
	public focusNextInputBox(): void {
		if (this.searchWidget.searchInputHasFocus()) {
690 691 692 693 694
			if (this.searchWidget.isReplaceShown()) {
				this.searchWidget.focus(true, true);
			} else {
				this.moveFocusFromSearchOrReplace();
			}
695 696 697 698
			return;
		}

		if (this.searchWidget.replaceInputHasFocus()) {
699
			this.moveFocusFromSearchOrReplace();
700 701 702 703 704 705 706 707 708
			return;
		}

		if (this.inputPatternIncludes.inputHasFocus()) {
			this.selectTreeIfNotSelected();
			return;
		}
	}

709 710
	private moveFocusFromSearchOrReplace() {
		if (this.showsFileTypes()) {
711
			this.toggleQueryDetails(true, this.showsFileTypes());
712 713 714 715 716
		} else {
			this.selectTreeIfNotSelected();
		}
	}

717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
	public 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;
		}

S
Sandeep Somavarapu 已提交
732 733 734 735
		if (this.tree.isDOMFocused()) {
			this.moveFocusFromResults();
			return;
		}
736 737
	}

S
Sandeep Somavarapu 已提交
738
	private moveFocusFromResults(): void {
739
		if (this.showsFileTypes()) {
740
			this.toggleQueryDetails(true, true, false);
741 742 743
		} else {
			this.searchWidget.focus(true, true);
		}
E
Erich Gamma 已提交
744 745 746 747 748 749 750
	}

	private reLayout(): void {
		if (this.isDisposed) {
			return;
		}

751
		this.searchWidget.setWidth(this.size.width - 28 /* container margin */);
E
Erich Gamma 已提交
752

S
Sandeep Somavarapu 已提交
753
		this.inputPatternIncludes.setWidth(this.size.width - 28 /* container margin */);
E
Erich Gamma 已提交
754

755 756 757
		const messagesSize = this.messages.isHidden() ? 0 : dom.getTotalHeight(this.messages.getHTMLElement());
		const searchResultContainerSize = this.size.height -
			messagesSize -
758 759
			dom.getTotalHeight(this.searchWidgetsContainer.getContainer());

E
Erich Gamma 已提交
760 761 762 763 764 765 766
		this.results.style({ height: searchResultContainerSize + 'px' });

		this.tree.layout(searchResultContainerSize);
	}

	public layout(dimension: Dimension): void {
		this.size = dimension;
B
Benjamin Pasero 已提交
767
		this.reLayout();
E
Erich Gamma 已提交
768 769 770 771 772 773
	}

	public getControl(): ITree {
		return this.tree;
	}

S
Sandeep Somavarapu 已提交
774 775 776 777
	public isSearchSubmitted(): boolean {
		return this.searchSubmitted;
	}

778 779 780 781
	public isSearching(): boolean {
		return this.searching;
	}

S
Sandeep Somavarapu 已提交
782 783 784 785
	public hasSearchResults(): boolean {
		return !this.viewModel.searchResult.isEmpty();
	}

E
Erich Gamma 已提交
786
	public clearSearchResults(): void {
787
		this.viewModel.searchResult.clear();
E
Erich Gamma 已提交
788
		this.showEmptyStage();
789
		if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
790 791
			this.searchWithoutFolderMessage(this.clearMessage());
		}
792
		this.searchWidget.clear();
S
Sandeep Somavarapu 已提交
793
		this.viewModel.cancelSearch();
E
Erich Gamma 已提交
794 795
	}

796
	public cancelSearch(): boolean {
S
Sandeep Somavarapu 已提交
797
		if (this.viewModel.cancelSearch()) {
798
			this.searchWidget.focus();
799 800 801 802 803
			return true;
		}
		return false;
	}

804
	private selectTreeIfNotSelected(): void {
E
Erich Gamma 已提交
805
		if (this.tree.getInput()) {
806
			this.tree.domFocus();
E
Erich Gamma 已提交
807 808 809 810 811 812 813
			let selection = this.tree.getSelection();
			if (selection.length === 0) {
				this.tree.focusNext();
			}
		}
	}

814
	private getSearchTextFromEditor(): string {
E
Erich Gamma 已提交
815 816 817 818
		if (!this.editorService.getActiveEditor()) {
			return null;
		}

819
		let editorControl = this.editorService.getActiveEditor().getControl();
820
		if (isDiffEditor(editorControl)) {
821 822 823 824 825 826 827
			if (editorControl.getOriginalEditor().isFocused()) {
				editorControl = editorControl.getOriginalEditor();
			} else {
				editorControl = editorControl.getModifiedEditor();
			}
		}

828
		if (!isCodeEditor(editorControl)) {
E
Erich Gamma 已提交
829 830 831
			return null;
		}

832
		const codeEditor: ICodeEditor = <ICodeEditor>editorControl;
R
Rob Lourens 已提交
833 834 835 836 837 838 839 840 841 842 843 844 845
		const range = codeEditor.getSelection();
		if (!range) {
			return null;
		}

		if (range.isEmpty() && !this.searchWidget.searchInput.getValue()) {
			const wordAtPosition = codeEditor.getModel().getWordAtPosition(range.getStartPosition());
			if (wordAtPosition) {
				return wordAtPosition.word;
			}
		}

		if (!range.isEmpty() && range.startLineNumber === range.endLineNumber) {
846 847 848
			let searchText = editorControl.getModel().getLineContent(range.startLineNumber);
			searchText = searchText.substring(range.startColumn - 1, range.endColumn - 1);
			return searchText;
E
Erich Gamma 已提交
849
		}
850

E
Erich Gamma 已提交
851 852 853 854 855 856 857
		return null;
	}

	private showsFileTypes(): boolean {
		return dom.hasClass(this.queryDetails, 'more');
	}

S
Sandeep Somavarapu 已提交
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
	public toggleCaseSensitive(): void {
		this.searchWidget.searchInput.setCaseSensitive(!this.searchWidget.searchInput.getCaseSensitive());
		this.onQueryChanged(true, true);
	}

	public toggleWholeWords(): void {
		this.searchWidget.searchInput.setWholeWords(!this.searchWidget.searchInput.getWholeWords());
		this.onQueryChanged(true, true);
	}

	public toggleRegex(): void {
		this.searchWidget.searchInput.setRegex(!this.searchWidget.searchInput.getRegex());
		this.onQueryChanged(true, true);
	}

873
	public toggleQueryDetails(moveFocus?: boolean, show?: boolean, skipLayout?: boolean): void {
E
Erich Gamma 已提交
874 875
		let cls = 'more';
		show = typeof show === 'undefined' ? !dom.hasClass(this.queryDetails, cls) : Boolean(show);
A
Amy Qiu 已提交
876
		this.viewletSettings['query.queryDetailsExpanded'] = show;
E
Erich Gamma 已提交
877 878 879 880
		skipLayout = Boolean(skipLayout);

		if (show) {
			dom.addClass(this.queryDetails, cls);
881
			if (moveFocus) {
882 883
				this.inputPatternIncludes.focus();
				this.inputPatternIncludes.select();
884
			}
E
Erich Gamma 已提交
885 886
		} else {
			dom.removeClass(this.queryDetails, cls);
887
			if (moveFocus) {
888
				this.searchWidget.focus();
889
			}
E
Erich Gamma 已提交
890
		}
B
Benjamin Pasero 已提交
891

E
Erich Gamma 已提交
892 893 894 895 896
		if (!skipLayout && this.size) {
			this.layout(this.size);
		}
	}

897
	public searchInFolders(resources: URI[], pathToRelative: (from: string, to: string) => string): void {
898
		const folderPaths: string[] = [];
899
		const workspace = this.contextService.getWorkspace();
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921

		if (resources) {
			resources.forEach(resource => {
				let folderPath: string;
				if (this.contextService.getWorkbenchState() === WorkbenchState.FOLDER) {
					// Show relative path from the root for single-root mode
					folderPath = paths.normalize(pathToRelative(workspace.folders[0].uri.fsPath, resource.fsPath));
					if (folderPath && folderPath !== '.') {
						folderPath = './' + folderPath;
					}
				} else {
					const owningFolder = this.contextService.getWorkspaceFolder(resource);
					if (owningFolder) {
						const owningRootBasename = paths.basename(owningFolder.uri.fsPath);

						// If this root is the only one with its basename, use a relative ./ path. If there is another, use an absolute path
						const isUniqueFolder = workspace.folders.filter(folder => paths.basename(folder.uri.fsPath) === owningRootBasename).length === 1;
						if (isUniqueFolder) {
							folderPath = `./${owningRootBasename}/${paths.normalize(pathToRelative(owningFolder.uri.fsPath, resource.fsPath))}`;
						} else {
							folderPath = resource.fsPath;
						}
922 923
					}
				}
924 925 926 927 928

				if (folderPath) {
					folderPaths.push(folderPath);
				}
			});
S
Sandeep Somavarapu 已提交
929 930
		}

931
		if (!folderPaths.length || folderPaths.some(folderPath => folderPath === '.')) {
S
Sandeep Somavarapu 已提交
932 933 934 935 936
			this.inputPatternIncludes.setValue('');
			this.searchWidget.focus();
			return;
		}

937
		// Show 'files to include' box
E
Erich Gamma 已提交
938
		if (!this.showsFileTypes()) {
939
			this.toggleQueryDetails(true, true);
E
Erich Gamma 已提交
940
		}
B
Benjamin Pasero 已提交
941

942
		this.inputPatternIncludes.setValue(folderPaths.join(', '));
B
Benjamin Pasero 已提交
943
		this.searchWidget.focus(false);
E
Erich Gamma 已提交
944 945
	}

946
	public onQueryChanged(rerunQuery: boolean, preserveFocus?: boolean): void {
947 948 949 950
		const isRegex = this.searchWidget.searchInput.getRegex();
		const isWholeWords = this.searchWidget.searchInput.getWholeWords();
		const isCaseSensitive = this.searchWidget.searchInput.getCaseSensitive();
		const contentPattern = this.searchWidget.searchInput.getValue();
951
		const useExcludesAndIgnoreFiles = this.inputPatternIncludes.useExcludesAndIgnoreFiles();
E
Erich Gamma 已提交
952 953 954 955 956 957 958 959 960

		if (!rerunQuery) {
			return;
		}

		if (contentPattern.length === 0) {
			return;
		}

961
		// Validate regex is OK
E
Erich Gamma 已提交
962 963 964 965 966
		if (isRegex) {
			let regExp: RegExp;
			try {
				regExp = new RegExp(contentPattern);
			} catch (e) {
967
				return; // malformed regex
E
Erich Gamma 已提交
968
			}
969

E
Erich Gamma 已提交
970
			if (strings.regExpLeadsToEndlessLoop(regExp)) {
971
				return; // endless regex
E
Erich Gamma 已提交
972 973 974
			}
		}

975
		const content: IPatternInfo = {
E
Erich Gamma 已提交
976 977 978
			pattern: contentPattern,
			isRegExp: isRegex,
			isCaseSensitive: isCaseSensitive,
979
			isWordMatch: isWholeWords,
980 981
			wordSeparators: this.configurationService.getValue<ISearchConfiguration>().editor.wordSeparators,
			isSmartCase: this.configurationService.getValue<ISearchConfiguration>().search.smartCase
E
Erich Gamma 已提交
982 983
		};

984 985
		const includeExcludePattern = this.inputPatternIncludes.getValue().trim();
		const { includePattern, excludePattern } = this.queryBuilder.parseIncludeExcludePattern(includeExcludePattern);
E
Erich Gamma 已提交
986

987
		const options: IQueryOptions = {
988
			extraFileResources: getOutOfWorkspaceEditorResources(this.editorGroupService, this.contextService),
989
			maxResults: SearchView.MAX_TEXT_RESULTS,
990 991
			disregardIgnoreFiles: !useExcludesAndIgnoreFiles,
			disregardExcludeSettings: !useExcludesAndIgnoreFiles,
R
Rob Lourens 已提交
992 993
			excludePattern,
			includePattern
E
Erich Gamma 已提交
994
		};
S
Sandeep Somavarapu 已提交
995
		const folderResources = this.contextService.getWorkspace().folders;
996 997 998 999 1000 1001 1002 1003

		const onQueryValidationError = (err: Error) => {
			this.searchWidget.searchInput.showMessage({ content: err.message, type: MessageType.ERROR });
			this.viewModel.searchResult.clear();
		};

		let query: ISearchQuery;
		try {
1004
			query = this.queryBuilder.text(content, folderResources.map(folder => folder.uri), options);
1005 1006
		} catch (err) {
			onQueryValidationError(err);
1007
			return;
1008
		}
1009

1010
		this.validateQuery(query).then(() => {
1011
			this.onQueryTriggered(query, excludePattern, includePattern);
1012

1013 1014 1015
			if (!preserveFocus) {
				this.searchWidget.focus(false); // focus back to input field
			}
1016
		}, onQueryValidationError);
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
	}

	private validateQuery(query: ISearchQuery): TPromise<void> {
		// Validate folderQueries
		const folderQueriesExistP =
			query.folderQueries.map(fq => {
				return this.fileService.existsFile(fq.folder);
			});

		return TPromise.join(folderQueriesExistP).then(existResults => {
R
Rob Lourens 已提交
1027 1028
			// If no folders exist, show an error message about the first one
			const existingFolderQueries = query.folderQueries.filter((folderQuery, i) => existResults[i]);
1029
			if (!query.folderQueries.length || existingFolderQueries.length) {
R
Rob Lourens 已提交
1030 1031 1032
				query.folderQueries = existingFolderQueries;
			} else {
				const nonExistantPath = query.folderQueries[0].folder.fsPath;
1033 1034 1035 1036 1037 1038
				const searchPathNotFoundError = nls.localize('searchPathNotFoundError', "Search path not found: {0}", nonExistantPath);
				return TPromise.wrapError(new Error(searchPathNotFoundError));
			}

			return undefined;
		});
E
Erich Gamma 已提交
1039 1040
	}

R
Rob Lourens 已提交
1041
	private onQueryTriggered(query: ISearchQuery, excludePatternText: string, includePatternText: string): void {
1042 1043
		this.inputPatternIncludes.onSearchSubmit();

S
Sandeep Somavarapu 已提交
1044 1045
		this.viewModel.cancelSearch();

1046 1047 1048 1049 1050 1051 1052
		// Progress total is 100.0% for more progress bar granularity
		let progressTotal = 1000;
		let progressWorked = 0;

		let progressRunner = query.useRipgrep ?
			this.progressService.show(/*infinite=*/true) :
			this.progressService.show(progressTotal);
E
Erich Gamma 已提交
1053

1054
		this.searchWidget.searchInput.clearMessage();
1055 1056 1057 1058 1059 1060
		this.searching = true;
		setTimeout(() => {
			if (this.searching) {
				this.changeActionAtPosition(0, this.instantiationService.createInstance(CancelSearchAction, CancelSearchAction.ID, CancelSearchAction.LABEL));
			}
		}, 2000);
E
Erich Gamma 已提交
1061 1062
		this.showEmptyStage();

1063
		let onComplete = (completed?: ISearchComplete) => {
1064 1065
			this.searching = false;
			this.changeActionAtPosition(0, this.instantiationService.createInstance(RefreshAction, RefreshAction.ID, RefreshAction.LABEL));
1066 1067 1068 1069 1070 1071 1072 1073

			// Complete up to 100% as needed
			if (completed && !query.useRipgrep) {
				progressRunner.worked(progressTotal - progressWorked);
				setTimeout(() => progressRunner.done(), 200);
			} else {
				progressRunner.done();
			}
E
Erich Gamma 已提交
1074

1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
			// Do final render, then expand if just 1 file with less than 50 matches
			this.onSearchResultsChanged().then(() => {
				if (this.viewModel.searchResult.count() === 1) {
					const onlyMatch = this.viewModel.searchResult.matches()[0];
					if (onlyMatch.count() < 50) {
						return this.tree.expand(onlyMatch);
					}
				}

				return null;
			}).done(null, errors.onUnexpectedError);

J
Johannes Rieken 已提交
1087
			this.viewModel.replaceString = this.searchWidget.getReplaceValue();
E
Erich Gamma 已提交
1088

1089
			let hasResults = !this.viewModel.searchResult.isEmpty();
E
Erich Gamma 已提交
1090

S
Sandeep Somavarapu 已提交
1091 1092
			this.searchSubmitted = true;
			this.updateActions();
E
Erich Gamma 已提交
1093

1094
			if (completed && completed.limitHit) {
1095
				this.searchWidget.searchInput.showMessage({
E
Erich Gamma 已提交
1096 1097 1098 1099 1100 1101
					content: nls.localize('searchMaxResultsWarning', "The result set only contains a subset of all matches. Please be more specific in your search to narrow down the results."),
					type: MessageType.WARNING
				});
			}

			if (!hasResults) {
1102 1103
				let hasExcludes = !!query.excludePattern;
				let hasIncludes = !!query.includePattern;
E
Erich Gamma 已提交
1104 1105
				let message: string;

1106 1107 1108
				if (!completed) {
					message = nls.localize('searchCanceled', "Search was canceled before any results could be found - ");
				} else if (hasIncludes && hasExcludes) {
R
Rob Lourens 已提交
1109
					message = nls.localize('noResultsIncludesExcludes', "No results found in '{0}' excluding '{1}' - ", includePatternText, excludePatternText);
E
Erich Gamma 已提交
1110
				} else if (hasIncludes) {
R
Rob Lourens 已提交
1111
					message = nls.localize('noResultsIncludes', "No results found in '{0}' - ", includePatternText);
E
Erich Gamma 已提交
1112
				} else if (hasExcludes) {
R
Rob Lourens 已提交
1113
					message = nls.localize('noResultsExcludes', "No results found excluding '{0}' - ", excludePatternText);
E
Erich Gamma 已提交
1114
				} else {
1115
					message = nls.localize('noResultsFound', "No results found. Review your settings for configured exclusions and ignore files - ");
E
Erich Gamma 已提交
1116 1117
				}

1118 1119 1120
				// Indicate as status to ARIA
				aria.status(message);

E
Erich Gamma 已提交
1121 1122
				this.tree.onHidden();
				this.results.hide();
1123 1124
				const div = this.clearMessage();
				const p = $(div).p({ text: message });
E
Erich Gamma 已提交
1125

1126
				if (!completed) {
1127
					$(p).a({
1128 1129 1130 1131 1132 1133 1134 1135
						'class': ['pointer', 'prominent'],
						text: nls.localize('rerunSearch.message', "Search again")
					}).on(dom.EventType.CLICK, (e: MouseEvent) => {
						dom.EventHelper.stop(e, false);

						this.onQueryChanged(true);
					});
				} else if (hasIncludes || hasExcludes) {
1136
					$(p).a({
E
Erich Gamma 已提交
1137
						'class': ['pointer', 'prominent'],
1138
						'tabindex': '0',
1139
						text: nls.localize('rerunSearchInAll.message', "Search again in all files")
E
Erich Gamma 已提交
1140 1141 1142 1143 1144 1145 1146 1147
					}).on(dom.EventType.CLICK, (e: MouseEvent) => {
						dom.EventHelper.stop(e, false);

						this.inputPatternIncludes.setValue('');

						this.onQueryChanged(true);
					});
				} else {
1148
					$(p).a({
E
Erich Gamma 已提交
1149
						'class': ['pointer', 'prominent'],
1150
						'tabindex': '0',
E
Erich Gamma 已提交
1151 1152 1153 1154
						text: nls.localize('openSettings.message', "Open Settings")
					}).on(dom.EventType.CLICK, (e: MouseEvent) => {
						dom.EventHelper.stop(e, false);

1155
						let editorPromise = this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY ? this.preferencesService.openWorkspaceSettings() : this.preferencesService.openGlobalSettings();
1156 1157 1158 1159 1160
						editorPromise.done(editor => {
							if (editor instanceof PreferencesEditor) {
								editor.focusSearch('.exclude');
							}
						}, errors.onUnexpectedError);
E
Erich Gamma 已提交
1161 1162
					});
				}
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178

				if (completed) {
					$(p).span({
						text: ' - '
					});

					$(p).a({
						'class': ['pointer', 'prominent'],
						'tabindex': '0',
						text: nls.localize('openSettings.learnMore', "Learn More")
					}).on(dom.EventType.CLICK, (e: MouseEvent) => {
						dom.EventHelper.stop(e, false);

						window.open('https://go.microsoft.com/fwlink/?linkid=853977');
					});
				}
1179

1180
				if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
1181 1182
					this.searchWithoutFolderMessage(div);
				}
E
Erich Gamma 已提交
1183
			} else {
1184
				this.viewModel.searchResult.toggleHighlights(true); // show highlights
1185

1186
				// Indicate final search result count for ARIA
1187
				aria.status(nls.localize('ariaSearchResultsStatus', "Search returned {0} results in {1} files", this.viewModel.searchResult.count(), this.viewModel.searchResult.fileCount()));
E
Erich Gamma 已提交
1188 1189 1190 1191
			}
		};

		let onError = (e: any) => {
1192 1193 1194
			if (errors.isPromiseCanceledError(e)) {
				onComplete(null);
			} else {
1195 1196
				this.searching = false;
				this.changeActionAtPosition(0, this.instantiationService.createInstance(RefreshAction, RefreshAction.ID, RefreshAction.LABEL));
1197
				progressRunner.done();
1198
				this.searchWidget.searchInput.showMessage({ content: e.message, type: MessageType.ERROR });
1199
				this.viewModel.searchResult.clear();
E
Erich Gamma 已提交
1200 1201 1202
			}
		};

1203 1204
		let total: number = 0;
		let worked: number = 0;
E
Erich Gamma 已提交
1205
		let visibleMatches = 0;
1206 1207 1208 1209 1210 1211 1212 1213 1214
		let onProgress = (p: ISearchProgressItem) => {
			// Progress
			if (p.total) {
				total = p.total;
			}
			if (p.worked) {
				worked = p.worked;
			}
		};
E
Erich Gamma 已提交
1215 1216 1217

		// Handle UI updates in an interval to show frequent progress and results
		let uiRefreshHandle = setInterval(() => {
1218
			if (!this.searching) {
E
Erich Gamma 已提交
1219 1220 1221 1222
				window.clearInterval(uiRefreshHandle);
				return;
			}

1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
			if (!query.useRipgrep) {
				// Progress bar update
				let fakeProgress = true;
				if (total > 0 && worked > 0) {
					let ratio = Math.round((worked / total) * progressTotal);
					if (ratio > progressWorked) { // never show less progress than what we have already
						progressRunner.worked(ratio - progressWorked);
						progressWorked = ratio;
						fakeProgress = false;
					}
				}

				// Fake progress up to 90%, or when actual progress beats it
				const fakeMax = 900;
				const fakeMultiplier = 12;
				if (fakeProgress && progressWorked < fakeMax) {
					// Linearly decrease the rate of fake progress.
					// 1 is the smallest allowed amount of progress.
					const fakeAmt = Math.round((fakeMax - progressWorked) / fakeMax * fakeMultiplier) || 1;
					progressWorked += fakeAmt;
					progressRunner.worked(fakeAmt);
				}
			}

E
Erich Gamma 已提交
1247
			// Search result tree update
1248 1249 1250
			const fileCount = this.viewModel.searchResult.fileCount();
			if (visibleMatches !== fileCount) {
				visibleMatches = fileCount;
1251
				this.tree.refresh().done(null, errors.onUnexpectedError);
1252

1253
				this.updateSearchResultCount();
1254
			}
1255
			if (fileCount > 0) {
S
Sandeep Somavarapu 已提交
1256
				this.updateActions();
E
Erich Gamma 已提交
1257
			}
1258
		}, 100);
E
Erich Gamma 已提交
1259

S
Sandeep Somavarapu 已提交
1260
		this.searchWidget.setReplaceAllActionState(false);
1261 1262

		this.viewModel.search(query).done(onComplete, onError, onProgress);
E
Erich Gamma 已提交
1263 1264
	}

1265
	private updateSearchResultCount(): void {
1266
		const fileCount = this.viewModel.searchResult.fileCount();
1267 1268
		this.hasSearchResultsKey.set(fileCount > 0);

1269
		const msgWasHidden = this.messages.isHidden();
1270 1271
		if (fileCount > 0) {
			const div = this.clearMessage();
1272
			$(div).p({ text: this.buildResultCountMessage(this.viewModel.searchResult.count(), fileCount) });
1273 1274 1275
			if (msgWasHidden) {
				this.reLayout();
			}
1276 1277
		} else if (!msgWasHidden) {
			this.messages.hide();
1278 1279 1280
		}
	}

1281 1282 1283 1284 1285 1286 1287
	private buildResultCountMessage(resultCount: number, fileCount: number): string {
		if (resultCount === 1 && fileCount === 1) {
			return nls.localize('search.file.result', "{0} result in {1} file", resultCount, fileCount);
		} else if (resultCount === 1) {
			return nls.localize('search.files.result', "{0} result in {1} files", resultCount, fileCount);
		} else if (fileCount === 1) {
			return nls.localize('search.file.results', "{0} results in {1} file", resultCount, fileCount);
1288
		} else {
1289
			return nls.localize('search.files.results', "{0} results in {1} files", resultCount, fileCount);
1290 1291 1292
		}
	}

1293
	private searchWithoutFolderMessage(div: Builder): void {
1294 1295 1296
		this.searchWithoutFolderMessageBuilder = $(div);

		this.searchWithoutFolderMessageBuilder.p({ text: nls.localize('searchWithoutFolder', "You have not yet opened a folder. Only open files are currently searched - ") })
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
			.asContainer().a({
				'class': ['pointer', 'prominent'],
				'tabindex': '0',
				text: nls.localize('openFolder', "Open Folder")
			}).on(dom.EventType.CLICK, (e: MouseEvent) => {
				dom.EventHelper.stop(e, false);

				const actionClass = env.isMacintosh ? OpenFileFolderAction : OpenFolderAction;
				const action = this.instantiationService.createInstance<string, string, IAction>(actionClass, actionClass.ID, actionClass.LABEL);
				this.actionRunner.run(action).done(() => {
					action.dispose();
				}, err => {
					action.dispose();
					errors.onUnexpectedError(err);
				});
			});
	}

E
Erich Gamma 已提交
1315
	private showEmptyStage(): void {
1316

E
Erich Gamma 已提交
1317
		// disable 'result'-actions
S
Sandeep Somavarapu 已提交
1318 1319
		this.searchSubmitted = false;
		this.updateActions();
E
Erich Gamma 已提交
1320 1321

		// clean up ui
S
Sandeep Somavarapu 已提交
1322
		// this.replaceService.disposeAllReplacePreviews();
E
Erich Gamma 已提交
1323 1324 1325
		this.messages.hide();
		this.results.show();
		this.tree.onVisible();
S
Sandeep Somavarapu 已提交
1326
		this.currentSelectedFileMatch = null;
E
Erich Gamma 已提交
1327 1328
	}

S
Sandeep Somavarapu 已提交
1329
	private onFocus(lineMatch: any, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> {
E
Erich Gamma 已提交
1330
		if (!(lineMatch instanceof Match)) {
1331
			this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange();
A
Alex Dima 已提交
1332
			return TPromise.as(true);
E
Erich Gamma 已提交
1333 1334
		}

R
Rob Lourens 已提交
1335 1336 1337
		return (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) ?
			this.replaceService.openReplacePreview(lineMatch, preserveFocus, sideBySide, pinned) :
			this.open(lineMatch, preserveFocus, sideBySide, pinned);
1338 1339 1340
	}

	public open(element: FileMatchOrMatch, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> {
J
Johannes Rieken 已提交
1341 1342
		let selection = this.getSelectionFrom(element);
		let resource = element instanceof Match ? element.parent().resource() : (<FileMatch>element).resource();
E
Erich Gamma 已提交
1343
		return this.editorService.openEditor({
1344
			resource: resource,
E
Erich Gamma 已提交
1345
			options: {
1346 1347
				preserveFocus,
				pinned,
S
Sandeep Somavarapu 已提交
1348
				selection,
1349
				revealIfVisible: true
E
Erich Gamma 已提交
1350
			}
S
Sandeep Somavarapu 已提交
1351 1352
		}, sideBySide).then(editor => {
			if (editor && element instanceof Match && preserveFocus) {
1353 1354 1355 1356
				this.viewModel.searchResult.rangeHighlightDecorations.highlightRange(
					(<ICodeEditor>editor.getControl()).getModel(),
					element.range()
				);
S
Sandeep Somavarapu 已提交
1357
			} else {
1358
				this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange();
S
Sandeep Somavarapu 已提交
1359 1360
			}
		}, errors.onUnexpectedError);
E
Erich Gamma 已提交
1361 1362
	}

1363
	private getSelectionFrom(element: FileMatchOrMatch): any {
J
Johannes Rieken 已提交
1364
		let match: Match = null;
1365
		if (element instanceof Match) {
J
Johannes Rieken 已提交
1366
			match = element;
1367 1368
		}
		if (element instanceof FileMatch && element.count() > 0) {
J
Johannes Rieken 已提交
1369
			match = element.matches()[element.matches().length - 1];
1370 1371
		}
		if (match) {
J
Johannes Rieken 已提交
1372
			let range = match.range();
S
Sandeep Somavarapu 已提交
1373
			if (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) {
J
Johannes Rieken 已提交
1374
				let replaceString = match.replaceString;
1375 1376
				return {
					startLineNumber: range.startLineNumber,
S
Sandeep Somavarapu 已提交
1377
					startColumn: range.startColumn,
1378
					endLineNumber: range.startLineNumber,
S
Sandeep Somavarapu 已提交
1379
					endColumn: range.startColumn + replaceString.length
1380 1381 1382 1383 1384 1385 1386
				};
			}
			return range;
		}
		return void 0;
	}

B
Benjamin Pasero 已提交
1387
	private onUntitledDidChangeDirty(resource: URI): void {
E
Erich Gamma 已提交
1388 1389 1390 1391
		if (!this.viewModel) {
			return;
		}

1392
		// remove search results from this resource as it got disposed
B
Benjamin Pasero 已提交
1393
		if (!this.untitledEditorService.isDirty(resource)) {
1394 1395
			let matches = this.viewModel.searchResult.matches();
			for (let i = 0, len = matches.length; i < len; i++) {
B
Benjamin Pasero 已提交
1396
				if (resource.toString() === matches[i].resource().toString()) {
1397 1398
					this.viewModel.searchResult.remove(matches[i]);
				}
E
Erich Gamma 已提交
1399 1400 1401 1402 1403 1404 1405 1406 1407
			}
		}
	}

	private onFilesChanged(e: FileChangesEvent): void {
		if (!this.viewModel) {
			return;
		}

1408
		let matches = this.viewModel.searchResult.matches();
E
Erich Gamma 已提交
1409 1410 1411

		for (let i = 0, len = matches.length; i < len; i++) {
			if (e.contains(matches[i].resource(), FileChangeType.DELETED)) {
1412
				this.viewModel.searchResult.remove(matches[i]);
E
Erich Gamma 已提交
1413 1414 1415 1416 1417
			}
		}
	}

	public getActions(): IAction[] {
S
Sandeep Somavarapu 已提交
1418
		return this.actions;
E
Erich Gamma 已提交
1419 1420
	}

1421
	private changeActionAtPosition(index: number, newAction: ClearSearchResultsAction | CancelSearchAction | RefreshAction | CollapseDeepestExpandedLevelAction): void {
1422 1423 1424 1425
		this.actions.splice(index, 1, newAction);
		this.updateTitleArea();
	}

A
Amy Qiu 已提交
1426
	public shutdown(): void {
A
Amy Qiu 已提交
1427 1428 1429 1430 1431
		const isRegex = this.searchWidget.searchInput.getRegex();
		const isWholeWords = this.searchWidget.searchInput.getWholeWords();
		const isCaseSensitive = this.searchWidget.searchInput.getCaseSensitive();
		const contentPattern = this.searchWidget.searchInput.getValue();
		const patternIncludes = this.inputPatternIncludes.getValue().trim();
1432
		const useExcludesAndIgnoreFiles = this.inputPatternIncludes.useExcludesAndIgnoreFiles();
1433
		const searchHistory = this.searchWidget.getHistory();
1434
		const patternIncludesHistory = this.inputPatternIncludes.getHistory();
A
Amy Qiu 已提交
1435 1436 1437

		// store memento
		this.viewletSettings['query.contentPattern'] = contentPattern;
1438
		this.viewletSettings['query.searchHistory'] = searchHistory;
A
Amy Qiu 已提交
1439 1440 1441 1442
		this.viewletSettings['query.regex'] = isRegex;
		this.viewletSettings['query.wholeWords'] = isWholeWords;
		this.viewletSettings['query.caseSensitive'] = isCaseSensitive;
		this.viewletSettings['query.folderIncludes'] = patternIncludes;
1443
		this.viewletSettings['query.folderIncludesHistory'] = patternIncludesHistory;
1444
		this.viewletSettings['query.useExcludesAndIgnoreFiles'] = useExcludesAndIgnoreFiles;
A
Amy Qiu 已提交
1445 1446 1447 1448

		super.shutdown();
	}

E
Erich Gamma 已提交
1449 1450 1451 1452 1453 1454 1455
	public dispose(): void {
		this.isDisposed = true;

		if (this.tree) {
			this.tree.dispose();
		}

1456
		this.searchWidget.dispose();
1457 1458
		this.inputPatternIncludes.dispose();

1459
		this.viewModel.dispose();
E
Erich Gamma 已提交
1460 1461 1462

		super.dispose();
	}
1463 1464 1465
}

registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
B
Benjamin Pasero 已提交
1466
	const matchHighlightColor = theme.getColor(editorFindMatchHighlight);
1467
	if (matchHighlightColor) {
I
isidor 已提交
1468
		collector.addRule(`.monaco-workbench .search-view .findInFileMatch { background-color: ${matchHighlightColor}; }`);
B
Benjamin Pasero 已提交
1469 1470 1471 1472
	}

	const diffInsertedColor = theme.getColor(diffInserted);
	if (diffInsertedColor) {
I
isidor 已提交
1473
		collector.addRule(`.monaco-workbench .search-view .replaceMatch { background-color: ${diffInsertedColor}; }`);
B
Benjamin Pasero 已提交
1474 1475 1476 1477
	}

	const diffRemovedColor = theme.getColor(diffRemoved);
	if (diffRemovedColor) {
I
isidor 已提交
1478
		collector.addRule(`.monaco-workbench .search-view .replace.findInFileMatch { background-color: ${diffRemovedColor}; }`);
B
Benjamin Pasero 已提交
1479 1480 1481 1482
	}

	const diffInsertedOutlineColor = theme.getColor(diffInsertedOutline);
	if (diffInsertedOutlineColor) {
I
isidor 已提交
1483
		collector.addRule(`.monaco-workbench .search-view .replaceMatch:not(:empty) { border: 1px dashed ${diffInsertedOutlineColor}; }`);
B
Benjamin Pasero 已提交
1484 1485 1486 1487
	}

	const diffRemovedOutlineColor = theme.getColor(diffRemovedOutline);
	if (diffRemovedOutlineColor) {
I
isidor 已提交
1488
		collector.addRule(`.monaco-workbench .search-view .replace.findInFileMatch { border: 1px dashed ${diffRemovedOutlineColor}; }`);
B
Benjamin Pasero 已提交
1489 1490
	}

1491 1492
	const findMatchHighlightBorder = theme.getColor(editorFindMatchHighlightBorder);
	if (findMatchHighlightBorder) {
I
isidor 已提交
1493
		collector.addRule(`.monaco-workbench .search-view .findInFileMatch { border: 1px dashed ${findMatchHighlightBorder}; }`);
1494
	}
1495
});