searchView.ts 59.2 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';

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

65 66
const $ = dom.$;

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

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

72 73 74
	private static readonly WIDE_CLASS_NAME = 'wide';
	private static readonly WIDE_VIEW_SIZE = 600;

E
Erich Gamma 已提交
75
	private isDisposed: boolean;
76

E
Erich Gamma 已提交
77
	private queryBuilder: QueryBuilder;
78
	private viewModel: SearchModel;
E
Erich Gamma 已提交
79

A
Alex Dima 已提交
80
	private viewletVisible: IContextKey<boolean>;
S
Sandeep Somavarapu 已提交
81
	private viewletFocused: IContextKey<boolean>;
82 83
	private inputBoxFocused: IContextKey<boolean>;
	private inputPatternIncludesFocused: IContextKey<boolean>;
84
	private inputPatternExclusionsFocused: IContextKey<boolean>;
85 86
	private firstMatchFocused: IContextKey<boolean>;
	private fileMatchOrMatchFocused: IContextKey<boolean>;
87
	private fileMatchOrFolderMatchFocus: IContextKey<boolean>;
88
	private fileMatchFocused: IContextKey<boolean>;
89
	private folderMatchFocused: IContextKey<boolean>;
90
	private matchFocused: IContextKey<boolean>;
91
	private hasSearchResultsKey: IContextKey<boolean>;
R
Rob Lourens 已提交
92

S
Sandeep Somavarapu 已提交
93
	private searchSubmitted: boolean;
94
	private searching: boolean;
S
Sandeep Somavarapu 已提交
95

96
	private actions: (RefreshAction | CollapseDeepestExpandedLevelAction | ClearSearchResultsAction | CancelSearchAction)[] = [];
97
	private tree: WorkbenchTree;
E
Erich Gamma 已提交
98
	private viewletSettings: any;
99 100
	private messagesElement: HTMLElement;
	private messageDisposables: IDisposable[] = [];
101
	private searchWidgetsContainerElement: HTMLElement;
102
	private searchWidget: SearchWidget;
103
	private size: dom.Dimension;
E
Erich Gamma 已提交
104
	private queryDetails: HTMLElement;
S
Sandeep Somavarapu 已提交
105
	private toggleQueryDetailsButton: HTMLElement;
106 107
	private inputPatternExcludes: ExcludePatternInputWidget;
	private inputPatternIncludes: PatternInputWidget;
108
	private resultsElement: HTMLElement;
E
Erich Gamma 已提交
109

S
Sandeep Somavarapu 已提交
110 111
	private currentSelectedFileMatch: FileMatch;

M
Matt Bierner 已提交
112
	private readonly selectCurrentMatchEmitter: Emitter<string>;
S
Sandeep Somavarapu 已提交
113
	private delayedRefresh: Delayer<void>;
114
	private changedWhileHidden: boolean;
R
Rob Lourens 已提交
115

116
	private searchWithoutFolderMessageElement: HTMLElement;
117

118
	constructor(
S
Sandeep Somavarapu 已提交
119
		@IPartService partService: IPartService,
120
		@ITelemetryService telemetryService: ITelemetryService,
121
		@IFileService private fileService: IFileService,
122
		@IEditorService private editorService: IEditorService,
123
		@IProgressService private progressService: IProgressService,
124
		@INotificationService private notificationService: INotificationService,
125
		@IDialogService private dialogService: IDialogService,
126 127 128 129 130
		@IStorageService private storageService: IStorageService,
		@IContextViewService private contextViewService: IContextViewService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IConfigurationService private configurationService: IConfigurationService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
S
Sandeep Somavarapu 已提交
131
		@ISearchWorkbenchService private searchWorkbenchService: ISearchWorkbenchService,
132
		@IContextKeyService private contextKeyService: IContextKeyService,
133
		@IReplaceService private replaceService: IReplaceService,
134
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
135
		@IPreferencesService private preferencesService: IPreferencesService,
136
		@IThemeService protected themeService: IThemeService,
R
Rob Lourens 已提交
137 138
		@ISearchHistoryService private searchHistoryService: ISearchHistoryService,
		@IEditorGroupsService private editorGroupsService: IEditorGroupsService
E
Erich Gamma 已提交
139
	) {
I
isidor 已提交
140
		super(VIEW_ID, partService, telemetryService, themeService);
E
Erich Gamma 已提交
141

I
isidor 已提交
142
		this.viewletVisible = Constants.SearchViewVisibleKey.bindTo(contextKeyService);
S
Sandeep Somavarapu 已提交
143
		this.viewletFocused = Constants.SearchViewFocusedKey.bindTo(contextKeyService);
144 145
		this.inputBoxFocused = Constants.InputBoxFocusedKey.bindTo(this.contextKeyService);
		this.inputPatternIncludesFocused = Constants.PatternIncludesFocusedKey.bindTo(this.contextKeyService);
146
		this.inputPatternExclusionsFocused = Constants.PatternExcludesFocusedKey.bindTo(this.contextKeyService);
147 148
		this.firstMatchFocused = Constants.FirstMatchFocusKey.bindTo(contextKeyService);
		this.fileMatchOrMatchFocused = Constants.FileMatchOrMatchFocusKey.bindTo(contextKeyService);
149
		this.fileMatchOrFolderMatchFocus = Constants.FileMatchOrFolderMatchFocusKey.bindTo(contextKeyService);
150
		this.fileMatchFocused = Constants.FileFocusKey.bindTo(contextKeyService);
151
		this.folderMatchFocused = Constants.FolderFocusKey.bindTo(contextKeyService);
152
		this.matchFocused = Constants.MatchFocusKey.bindTo(this.contextKeyService);
153
		this.hasSearchResultsKey = Constants.HasSearchResults.bindTo(this.contextKeyService);
E
Erich Gamma 已提交
154 155 156 157

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

B
Benjamin Pasero 已提交
158 159 160
		this._register(this.fileService.onFileChanges(e => this.onFilesChanged(e)));
		this._register(this.untitledEditorService.onDidChangeDirty(e => this.onUntitledDidChangeDirty(e)));
		this._register(this.contextService.onDidChangeWorkbenchState(() => this.onDidChangeWorkbenchState()));
161
		this._register(this.searchHistoryService.onDidClearHistory(() => this.clearHistory()));
162

R
Rob Lourens 已提交
163 164 165 166
		this.selectCurrentMatchEmitter = new Emitter<string>();
		debounceEvent(this.selectCurrentMatchEmitter.event, (l, e) => e, 100, /*leading=*/true)
			(() => this.selectCurrentMatch());

S
Sandeep Somavarapu 已提交
167
		this.delayedRefresh = new Delayer<void>(250);
E
Erich Gamma 已提交
168 169
	}

170
	private onDidChangeWorkbenchState(): void {
171 172
		if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.searchWithoutFolderMessageElement) {
			dom.hide(this.searchWithoutFolderMessageElement);
173 174 175
		}
	}

176
	public create(parent: HTMLElement): TPromise<void> {
E
Erich Gamma 已提交
177 178
		super.create(parent);

B
Benjamin Pasero 已提交
179
		this.viewModel = this._register(this.searchWorkbenchService.searchModel);
180
		const containerElement = dom.append(parent, $('.search-view'));
E
Erich Gamma 已提交
181

R
Rob Lourens 已提交
182
		this.searchWidgetsContainerElement = dom.append(containerElement, $('.search-widgets-container'));
183
		this.createSearchWidget(this.searchWidgetsContainerElement);
184

185
		const history = this.searchHistoryService.load();
186
		const filePatterns = this.viewletSettings['query.filePatterns'] || '';
R
Rob Lourens 已提交
187 188 189 190
		const patternExclusions = this.viewletSettings['query.folderExclusions'] || '';
		const patternExclusionsHistory: string[] = history.exclude || [];
		const patternIncludes = this.viewletSettings['query.folderIncludes'] || '';
		const patternIncludesHistory: string[] = history.include || [];
A
Amy Qiu 已提交
191
		const queryDetailsExpanded = this.viewletSettings['query.queryDetailsExpanded'] || '';
192 193
		const useExcludesAndIgnoreFiles = typeof this.viewletSettings['query.useExcludesAndIgnoreFiles'] === 'boolean' ?
			this.viewletSettings['query.useExcludesAndIgnoreFiles'] : true;
194

195
		this.queryDetails = dom.append(this.searchWidgetsContainerElement, $('.query-details'));
S
Sandeep Somavarapu 已提交
196

197 198 199
		// Toggle query details button
		this.toggleQueryDetailsButton = dom.append(this.queryDetails,
			$('.more', { tabindex: 0, role: 'button', title: nls.localize('moreSearch', "Toggle Search Details") }));
E
Erich Gamma 已提交
200

201 202
		this._register(dom.addDisposableListener(this.toggleQueryDetailsButton, dom.EventType.CLICK, e => {
			dom.EventHelper.stop(e);
203
			this.toggleQueryDetails(!this.isScreenReaderOptimized());
204 205 206
		}));
		this._register(dom.addDisposableListener(this.toggleQueryDetailsButton, dom.EventType.KEY_UP, (e: KeyboardEvent) => {
			const event = new StandardKeyboardEvent(e);
E
Erich Gamma 已提交
207

208 209 210 211 212 213 214
			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);
E
Erich Gamma 已提交
215

216 217 218 219 220 221 222 223 224
			if (event.equals(KeyMod.Shift | KeyCode.Tab)) {
				if (this.searchWidget.isReplaceActive()) {
					this.searchWidget.focusReplaceAllAction();
				} else {
					this.searchWidget.focusRegexAction();
				}
				dom.EventHelper.stop(e);
			}
		}));
E
Erich Gamma 已提交
225

226 227 228 229 230
		// 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));
231

232 233 234 235
		this.inputPatternIncludes = this._register(this.instantiationService.createInstance(PatternInputWidget, folderIncludesList, this.contextViewService, {
			ariaLabel: nls.localize('label.includes', 'Search Include Patterns'),
			history: patternIncludesHistory,
		}));
236

237
		this.inputPatternIncludes.setValue(patternIncludes);
238

239
		this.inputPatternIncludes.onSubmit(() => this.onQueryChanged(true));
240 241 242 243 244 245 246 247 248 249 250
		this.inputPatternIncludes.onCancel(() => this.viewModel.cancelSearch()); // Cancel search without focusing the search widget
		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,
		}));
251

252 253
		this.inputPatternExcludes.setValue(patternExclusions);
		this.inputPatternExcludes.setUseExcludesAndIgnoreFiles(useExcludesAndIgnoreFiles);
254

255
		this.inputPatternExcludes.onSubmit(() => this.onQueryChanged(true));
256 257 258 259
		this.inputPatternExcludes.onCancel(() => this.viewModel.cancelSearch()); // Cancel search without focusing the search widget
		this.trackInputBox(this.inputPatternExcludes.inputFocusTracker, this.inputPatternExclusionsFocused);

		this.messagesElement = dom.append(containerElement, $('.messages'));
260
		if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
261
			this.showSearchWithoutFolderMessage();
262
		}
263

264
		this.createSearchResultsView(containerElement);
265

S
Sandeep Somavarapu 已提交
266 267 268 269 270
		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)
		];
271

272
		if (filePatterns !== '' || patternExclusions !== '' || patternIncludes !== '' || queryDetailsExpanded !== '' || !useExcludesAndIgnoreFiles) {
273
			this.toggleQueryDetails(true, true, true);
274 275
		}

B
Benjamin Pasero 已提交
276
		this._register(this.viewModel.searchResult.onChange((event) => this.onSearchResultsChanged(event)));
S
Sandeep Somavarapu 已提交
277

S
Sandeep Somavarapu 已提交
278 279 280
		this._register(this.onDidFocus(() => this.viewletFocused.set(true)));
		this._register(this.onDidBlur(() => this.viewletFocused.set(false)));

281 282 283
		return TPromise.as(null);
	}

J
Johannes Rieken 已提交
284
	public get searchAndReplaceWidget(): SearchWidget {
285 286 287
		return this.searchWidget;
	}

288 289 290 291
	public get searchIncludePattern(): PatternInputWidget {
		return this.inputPatternIncludes;
	}

292 293 294 295
	public get searchExcludePattern(): PatternInputWidget {
		return this.inputPatternExcludes;
	}

S
Sandeep Somavarapu 已提交
296 297 298 299 300 301
	private updateActions(): void {
		for (const action of this.actions) {
			action.update();
		}
	}

302 303 304 305 306 307
	private isScreenReaderOptimized() {
		const detected = browser.getAccessibilitySupport() === env.AccessibilitySupport.Enabled;
		const config = this.configurationService.getValue<IEditorOptions>('editor').accessibilitySupport;
		return config === 'on' || (config === 'auto' && detected);
	}

308
	private createSearchWidget(container: HTMLElement): void {
309 310 311 312
		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;
313
		const history = this.searchHistoryService.load();
314 315
		let searchHistory = history.search || this.viewletSettings['query.searchHistory'] || [];
		let replaceHistory = history.replace || this.viewletSettings['query.replaceHistory'] || [];
E
Erich Gamma 已提交
316

317
		this.searchWidget = this._register(this.instantiationService.createInstance(SearchWidget, container, <ISearchWidgetOptions>{
318 319 320
			value: contentPattern,
			isRegex: isRegex,
			isCaseSensitive: isCaseSensitive,
321
			isWholeWords: isWholeWords,
322
			searchHistory: searchHistory,
323
			replaceHistory: replaceHistory
B
Benjamin Pasero 已提交
324
		}));
S
Sandeep Somavarapu 已提交
325

326
		if (this.storageService.getBoolean(SearchView.SHOW_REPLACE_STORAGE_KEY, StorageScope.WORKSPACE, true)) {
S
Sandeep Somavarapu 已提交
327 328 329
			this.searchWidget.toggleReplace(true);
		}

330
		this._register(this.searchWidget.onSearchSubmit(() => this.onQueryChanged()));
B
Benjamin Pasero 已提交
331
		this._register(this.searchWidget.onSearchCancel(() => this.cancelSearch()));
332
		this._register(this.searchWidget.searchInput.onDidOptionChange(() => this.onQueryChanged(true)));
333

B
Benjamin Pasero 已提交
334 335
		this._register(this.searchWidget.onReplaceToggled(() => this.onReplaceToggled()));
		this._register(this.searchWidget.onReplaceStateChange((state) => {
J
Johannes Rieken 已提交
336
			this.viewModel.replaceActive = state;
337
			this.tree.refresh();
S
Sandeep Somavarapu 已提交
338
		}));
B
Benjamin Pasero 已提交
339
		this._register(this.searchWidget.onReplaceValueChanged((value) => {
J
Johannes Rieken 已提交
340
			this.viewModel.replaceString = this.searchWidget.getReplaceValue();
S
Sandeep Somavarapu 已提交
341
			this.delayedRefresh.trigger(() => this.tree.refresh());
S
Sandeep Somavarapu 已提交
342
		}));
343

B
Benjamin Pasero 已提交
344
		this._register(this.searchWidget.onBlur(() => {
S
Sandeep Somavarapu 已提交
345 346 347
			this.toggleQueryDetailsButton.focus();
		}));

B
Benjamin Pasero 已提交
348
		this._register(this.searchWidget.onReplaceAll(() => this.replaceAll()));
349 350 351 352
		this.trackInputBox(this.searchWidget.searchInputFocusTracker);
		this.trackInputBox(this.searchWidget.replaceInputFocusTracker);
	}

353
	private trackInputBox(inputFocusTracker: dom.IFocusTracker, contextKey?: IContextKey<boolean>): void {
B
Benjamin Pasero 已提交
354
		this._register(inputFocusTracker.onDidFocus(() => {
355
			this.inputBoxFocused.set(true);
356 357 358
			if (contextKey) {
				contextKey.set(true);
			}
359
		}));
B
Benjamin Pasero 已提交
360
		this._register(inputFocusTracker.onDidBlur(() => {
361
			this.inputBoxFocused.set(this.searchWidget.searchInputHasFocus()
362
				|| this.searchWidget.replaceInputHasFocus()
363 364
				|| this.inputPatternIncludes.inputHasFocus()
				|| this.inputPatternExcludes.inputHasFocus());
365 366 367
			if (contextKey) {
				contextKey.set(false);
			}
368
		}));
S
Sandeep Somavarapu 已提交
369 370
	}

S
Sandeep Somavarapu 已提交
371 372
	private onReplaceToggled(): void {
		this.layout(this.size);
373 374 375

		const isReplaceShown = this.searchAndReplaceWidget.isReplaceShown();
		if (!isReplaceShown) {
376
			this.storageService.store(SearchView.SHOW_REPLACE_STORAGE_KEY, false, StorageScope.WORKSPACE);
377
		} else {
378
			this.storageService.remove(SearchView.SHOW_REPLACE_STORAGE_KEY, StorageScope.WORKSPACE);
379
		}
S
Sandeep Somavarapu 已提交
380 381
	}

S
Sandeep Somavarapu 已提交
382
	private onSearchResultsChanged(event?: IChangeEvent): TPromise<any> {
383 384 385 386 387 388 389 390 391
		if (this.isVisible()) {
			return this.refreshAndUpdateCount(event);
		} else {
			this.changedWhileHidden = true;
			return TPromise.wrap(null);
		}
	}

	private refreshAndUpdateCount(event?: IChangeEvent): TPromise<void> {
S
Sandeep Somavarapu 已提交
392
		return this.refreshTree(event).then(() => {
S
Sandeep Somavarapu 已提交
393
			this.searchWidget.setReplaceAllActionState(!this.viewModel.searchResult.isEmpty());
394
			this.updateSearchResultCount();
S
Sandeep Somavarapu 已提交
395
		});
396 397
	}

S
Sandeep Somavarapu 已提交
398
	private refreshTree(event?: IChangeEvent): TPromise<any> {
399
		if (!event || event.added || event.removed) {
S
Sandeep Somavarapu 已提交
400
			return this.tree.refresh(this.viewModel.searchResult);
401 402
		} else {
			if (event.elements.length === 1) {
S
Sandeep Somavarapu 已提交
403
				return this.tree.refresh(event.elements[0]);
404
			} else {
S
Sandeep Somavarapu 已提交
405
				return this.tree.refresh(event.elements);
406 407 408 409
			}
		}
	}

410
	private replaceAll(): void {
411
		if (this.viewModel.searchResult.count() === 0) {
S
Sandeep Somavarapu 已提交
412 413 414
			return;
		}

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

J
Johannes Rieken 已提交
417 418 419
		let occurrences = this.viewModel.searchResult.count();
		let fileCount = this.viewModel.searchResult.fileCount();
		let replaceValue = this.searchWidget.getReplaceValue() || '';
420
		let afterReplaceAllMessage = this.buildAfterReplaceAllMessage(occurrences, fileCount, replaceValue);
421

B
Benjamin Pasero 已提交
422
		let confirmation: IConfirmation = {
423
			title: nls.localize('replaceAll.confirmation.title', "Replace All"),
424
			message: this.buildReplaceAllConfirmationMessage(occurrences, fileCount, replaceValue),
425
			primaryButton: nls.localize('replaceAll.confirm.button', "&&Replace"),
B
Benjamin Pasero 已提交
426
			type: 'question'
427 428
		};

429
		this.dialogService.confirm(confirmation).then(res => {
430
			if (res.confirmed) {
431 432 433
				this.searchWidget.setReplaceAllActionState(false);
				this.viewModel.searchResult.replaceAll(progressRunner).then(() => {
					progressRunner.done();
434
					const messageEl = this.clearMessage();
435
					dom.append(messageEl, $('p', undefined, afterReplaceAllMessage));
436 437 438
				}, (error) => {
					progressRunner.done();
					errors.isPromiseCanceledError(error);
439
					this.notificationService.error(error);
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
	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);
	}

509 510
	private clearMessage(): HTMLElement {
		this.searchWithoutFolderMessageElement = void 0;
511

512 513 514 515 516
		dom.clearNode(this.messagesElement);
		dom.show(this.messagesElement);
		dispose(this.messageDisposables);
		this.messageDisposables = [];

517
		return dom.append(this.messagesElement, $('.message'));
518 519
	}

520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
	private createSearchResultsView(container: HTMLElement): void {
		this.resultsElement = dom.append(container, $('.results.show-file-icons'));
		const dataSource = this._register(this.instantiationService.createInstance(SearchDataSource));
		const renderer = this._register(this.instantiationService.createInstance(SearchRenderer, this.getActionRunner(), this));
		const dnd = this.instantiationService.createInstance(SimpleFileResourceDragAndDrop, (obj: any) => obj instanceof FileMatch ? obj.resource() : void 0);

		this.tree = this._register(this.instantiationService.createInstance(WorkbenchTree, this.resultsElement, {
			dataSource: dataSource,
			renderer: renderer,
			sorter: new SearchSorter(),
			filter: new SearchFilter(),
			controller: this.instantiationService.createInstance(SearchTreeController),
			accessibilityProvider: this.instantiationService.createInstance(SearchAccessibilityProvider),
			dnd
		}, {
				ariaLabel: nls.localize('treeAriaLabel', "Search Results"),
				showLoading: false
S
Sandeep Somavarapu 已提交
537
			}));
538

539 540 541 542 543 544 545 546
		this.tree.setInput(this.viewModel.searchResult);

		const searchResultsNavigator = this._register(new TreeResourceNavigator(this.tree, { openOnFocus: true }));
		this._register(debounceEvent(searchResultsNavigator.openResource, (last, event) => event, 75, true)(options => {
			if (options.element instanceof Match) {
				let selectedMatch: Match = options.element;
				if (this.currentSelectedFileMatch) {
					this.currentSelectedFileMatch.setSelectedMatch(null);
547
				}
548 549 550 551 552 553 554
				this.currentSelectedFileMatch = selectedMatch.parent();
				this.currentSelectedFileMatch.setSelectedMatch(selectedMatch);
				if (!(options.payload && options.payload.preventEditorOpen)) {
					this.onFocus(selectedMatch, options.editorOptions.preserveFocus, options.sideBySide, options.editorOptions.pinned);
				}
			}
		}));
S
Sandeep Somavarapu 已提交
555

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
		this._register(anyEvent<any>(this.tree.onDidFocus, this.tree.onDidChangeFocus)(() => {
			if (this.tree.isDOMFocused()) {
				const focus = this.tree.getFocus();
				this.firstMatchFocused.set(this.tree.getNavigator().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._register(this.tree.onDidBlur(e => {
			this.firstMatchFocused.reset();
			this.fileMatchOrMatchFocused.reset();
			this.fileMatchFocused.reset();
			this.folderMatchFocused.reset();
			this.matchFocused.reset();
			this.fileMatchOrFolderMatchFocus.reset();
		}));
E
Erich Gamma 已提交
576 577
	}

R
Rob Lourens 已提交
578 579
	public selectCurrentMatch(): void {
		const focused = this.tree.getFocus();
580
		const eventPayload = { focusEditor: true };
R
Rob Lourens 已提交
581 582 583 584
		this.tree.setSelection([focused], eventPayload);
	}

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

R
Rob Lourens 已提交
587 588 589 590 591 592 593 594 595 596
		// 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();
597
		if (!next) {
R
Rob Lourens 已提交
598 599 600 601
			// 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();
602 603 604
		}

		// Expand and go past FileMatch nodes
R
Rob Lourens 已提交
605
		while (!(next instanceof Match)) {
606 607
			if (!this.tree.isExpanded(next)) {
				this.tree.expand(next);
608 609 610
			}

			// Select the FileMatch's first child
611
			next = navigator.next();
612 613 614
		}

		// Reveal the newly selected element
615 616 617 618 619 620 621
		if (next) {
			const eventPayload = { preventEditorOpen: true };
			this.tree.setFocus(next, eventPayload);
			this.tree.setSelection([next], eventPayload);
			this.tree.reveal(next);
			this.selectCurrentMatchEmitter.fire();
		}
622 623
	}

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

628
		let prev = navigator.previous();
629 630

		// Expand and go past FileMatch nodes
631 632
		if (!(prev instanceof Match)) {
			prev = navigator.previous();
R
Rob Lourens 已提交
633 634 635 636 637 638 639 640 641 642 643 644 645 646
			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;
				}
			}

647 648 649 650 651 652
			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();
653 654 655 656
			}
		}

		// Reveal the newly selected element
657
		if (prev) {
R
Rob Lourens 已提交
658
			const eventPayload = { preventEditorOpen: true };
659 660 661
			this.tree.setFocus(prev, eventPayload);
			this.tree.setSelection([prev], eventPayload);
			this.tree.reveal(prev);
R
Rob Lourens 已提交
662
			this.selectCurrentMatchEmitter.fire();
663
		}
664 665
	}

E
Erich Gamma 已提交
666 667
	public setVisible(visible: boolean): TPromise<void> {
		let promise: TPromise<void>;
668
		this.viewletVisible.set(visible);
E
Erich Gamma 已提交
669
		if (visible) {
670 671 672 673 674 675
			if (this.changedWhileHidden) {
				// Render if results changed while viewlet was hidden - #37818
				this.refreshAndUpdateCount();
				this.changedWhileHidden = false;
			}

E
Erich Gamma 已提交
676 677 678 679 680 681 682 683 684
			promise = super.setVisible(visible);
			this.tree.onVisible();
		} else {
			this.tree.onHidden();
			promise = super.setVisible(visible);
		}

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

688
		// Open focused element from results in case the editor area is otherwise empty
B
Benjamin Pasero 已提交
689
		if (visible && !this.editorService.activeEditor) {
E
Erich Gamma 已提交
690 691
			let focus = this.tree.getFocus();
			if (focus) {
S
Sandeep Somavarapu 已提交
692
				this.onFocus(focus, true);
E
Erich Gamma 已提交
693 694 695 696 697 698
			}
		}

		return promise;
	}

Y
Yogesh 已提交
699 700 701 702
	public moveFocusToResults(): void {
		this.tree.domFocus();
	}

E
Erich Gamma 已提交
703 704 705
	public focus(): void {
		super.focus();

R
Rob Lourens 已提交
706 707 708 709 710
		const updatedText = this.updateTextFromSelection();
		this.searchWidget.focus(undefined, undefined, updatedText);
	}

	public updateTextFromSelection(allowUnselectedWord = true): boolean {
711
		let updatedText = false;
712 713
		const seedSearchStringFromSelection = this.configurationService.getValue<IEditorOptions>('editor').find.seedSearchStringFromSelection;
		if (seedSearchStringFromSelection) {
R
Rob Lourens 已提交
714
			let selectedText = this.getSearchTextFromEditor(allowUnselectedWord);
715
			if (selectedText) {
716 717 718 719
				if (this.searchWidget.searchInput.getRegex()) {
					selectedText = strings.escapeRegExpCharacters(selectedText);
				}

720
				this.searchWidget.searchInput.setValue(selectedText);
721
				updatedText = true;
722
			}
723
		}
R
Rob Lourens 已提交
724

R
Rob Lourens 已提交
725
		return updatedText;
726 727
	}

728 729
	public focusNextInputBox(): void {
		if (this.searchWidget.searchInputHasFocus()) {
730 731 732 733 734
			if (this.searchWidget.isReplaceShown()) {
				this.searchWidget.focus(true, true);
			} else {
				this.moveFocusFromSearchOrReplace();
			}
735 736 737 738
			return;
		}

		if (this.searchWidget.replaceInputHasFocus()) {
739
			this.moveFocusFromSearchOrReplace();
740 741 742 743
			return;
		}

		if (this.inputPatternIncludes.inputHasFocus()) {
744 745 746 747 748 749
			this.inputPatternExcludes.focus();
			this.inputPatternExcludes.select();
			return;
		}

		if (this.inputPatternExcludes.inputHasFocus()) {
750 751 752 753 754
			this.selectTreeIfNotSelected();
			return;
		}
	}

755 756
	private moveFocusFromSearchOrReplace() {
		if (this.showsFileTypes()) {
757
			this.toggleQueryDetails(true, this.showsFileTypes());
758 759 760 761 762
		} else {
			this.selectTreeIfNotSelected();
		}
	}

763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
	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;
		}

778 779 780 781 782 783
		if (this.inputPatternExcludes.inputHasFocus()) {
			this.inputPatternIncludes.focus();
			this.inputPatternIncludes.select();
			return;
		}

S
Sandeep Somavarapu 已提交
784 785 786 787
		if (this.tree.isDOMFocused()) {
			this.moveFocusFromResults();
			return;
		}
788 789
	}

S
Sandeep Somavarapu 已提交
790
	private moveFocusFromResults(): void {
791
		if (this.showsFileTypes()) {
792
			this.toggleQueryDetails(true, true, false, true);
793 794 795
		} else {
			this.searchWidget.focus(true, true);
		}
E
Erich Gamma 已提交
796 797 798 799 800 801 802
	}

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

803
		if (this.size.width >= SearchView.WIDE_VIEW_SIZE) {
804
			dom.addClass(this.getContainer(), SearchView.WIDE_CLASS_NAME);
805
		} else {
806
			dom.removeClass(this.getContainer(), SearchView.WIDE_CLASS_NAME);
807 808
		}

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

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

814 815 816 817
		const messagesSize = this.messagesElement.style.display === 'none' ?
			0 :
			dom.getTotalHeight(this.messagesElement);

818 819
		const searchResultContainerSize = this.size.height -
			messagesSize -
820
			dom.getTotalHeight(this.searchWidgetsContainerElement);
821

822
		this.resultsElement.style.height = searchResultContainerSize + 'px';
E
Erich Gamma 已提交
823 824 825 826

		this.tree.layout(searchResultContainerSize);
	}

827
	public layout(dimension: dom.Dimension): void {
E
Erich Gamma 已提交
828
		this.size = dimension;
B
Benjamin Pasero 已提交
829
		this.reLayout();
E
Erich Gamma 已提交
830 831 832 833 834 835
	}

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

S
Sandeep Somavarapu 已提交
836 837 838 839
	public isSearchSubmitted(): boolean {
		return this.searchSubmitted;
	}

840 841 842 843
	public isSearching(): boolean {
		return this.searching;
	}

S
Sandeep Somavarapu 已提交
844 845 846 847
	public hasSearchResults(): boolean {
		return !this.viewModel.searchResult.isEmpty();
	}

E
Erich Gamma 已提交
848
	public clearSearchResults(): void {
849
		this.viewModel.searchResult.clear();
E
Erich Gamma 已提交
850
		this.showEmptyStage();
851
		if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
852
			this.showSearchWithoutFolderMessage();
853
		}
854
		this.searchWidget.clear();
S
Sandeep Somavarapu 已提交
855
		this.viewModel.cancelSearch();
E
Erich Gamma 已提交
856 857
	}

858
	public cancelSearch(): boolean {
S
Sandeep Somavarapu 已提交
859
		if (this.viewModel.cancelSearch()) {
860
			this.searchWidget.focus();
861 862 863 864 865
			return true;
		}
		return false;
	}

866
	private selectTreeIfNotSelected(): void {
E
Erich Gamma 已提交
867
		if (this.tree.getInput()) {
868
			this.tree.domFocus();
E
Erich Gamma 已提交
869 870 871 872 873 874 875
			let selection = this.tree.getSelection();
			if (selection.length === 0) {
				this.tree.focusNext();
			}
		}
	}

R
Rob Lourens 已提交
876
	private getSearchTextFromEditor(allowUnselectedWord: boolean): string {
B
Benjamin Pasero 已提交
877
		if (!this.editorService.activeEditor) {
E
Erich Gamma 已提交
878 879 880
			return null;
		}

R
Rob Lourens 已提交
881 882 883 884
		if (dom.isAncestor(document.activeElement, this.getContainer())) {
			return null;
		}

885 886 887 888
		let activeTextEditorWidget = this.editorService.activeTextEditorWidget;
		if (isDiffEditor(activeTextEditorWidget)) {
			if (activeTextEditorWidget.getOriginalEditor().hasTextFocus()) {
				activeTextEditorWidget = activeTextEditorWidget.getOriginalEditor();
889
			} else {
890
				activeTextEditorWidget = activeTextEditorWidget.getModifiedEditor();
891 892 893
			}
		}

894
		if (!isCodeEditor(activeTextEditorWidget)) {
E
Erich Gamma 已提交
895 896 897
			return null;
		}

898
		const range = activeTextEditorWidget.getSelection();
R
Rob Lourens 已提交
899 900 901 902
		if (!range) {
			return null;
		}

R
Rob Lourens 已提交
903
		if (range.isEmpty() && !this.searchWidget.searchInput.getValue() && allowUnselectedWord) {
904
			const wordAtPosition = activeTextEditorWidget.getModel().getWordAtPosition(range.getStartPosition());
R
Rob Lourens 已提交
905 906 907 908 909 910
			if (wordAtPosition) {
				return wordAtPosition.word;
			}
		}

		if (!range.isEmpty() && range.startLineNumber === range.endLineNumber) {
911
			let searchText = activeTextEditorWidget.getModel().getLineContent(range.startLineNumber);
912 913
			searchText = searchText.substring(range.startColumn - 1, range.endColumn - 1);
			return searchText;
E
Erich Gamma 已提交
914
		}
915

E
Erich Gamma 已提交
916 917 918 919 920 921 922
		return null;
	}

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

S
Sandeep Somavarapu 已提交
923 924
	public toggleCaseSensitive(): void {
		this.searchWidget.searchInput.setCaseSensitive(!this.searchWidget.searchInput.getCaseSensitive());
925
		this.onQueryChanged(true);
S
Sandeep Somavarapu 已提交
926 927 928 929
	}

	public toggleWholeWords(): void {
		this.searchWidget.searchInput.setWholeWords(!this.searchWidget.searchInput.getWholeWords());
930
		this.onQueryChanged(true);
S
Sandeep Somavarapu 已提交
931 932 933 934
	}

	public toggleRegex(): void {
		this.searchWidget.searchInput.setRegex(!this.searchWidget.searchInput.getRegex());
935
		this.onQueryChanged(true);
S
Sandeep Somavarapu 已提交
936 937
	}

938
	public toggleQueryDetails(moveFocus = true, show?: boolean, skipLayout?: boolean, reverse?: boolean): void {
E
Erich Gamma 已提交
939 940
		let cls = 'more';
		show = typeof show === 'undefined' ? !dom.hasClass(this.queryDetails, cls) : Boolean(show);
A
Amy Qiu 已提交
941
		this.viewletSettings['query.queryDetailsExpanded'] = show;
E
Erich Gamma 已提交
942 943 944
		skipLayout = Boolean(skipLayout);

		if (show) {
945
			this.toggleQueryDetailsButton.setAttribute('aria-expanded', 'true');
E
Erich Gamma 已提交
946
			dom.addClass(this.queryDetails, cls);
947
			if (moveFocus) {
948 949 950 951 952 953 954
				if (reverse) {
					this.inputPatternExcludes.focus();
					this.inputPatternExcludes.select();
				} else {
					this.inputPatternIncludes.focus();
					this.inputPatternIncludes.select();
				}
955
			}
E
Erich Gamma 已提交
956
		} else {
957
			this.toggleQueryDetailsButton.setAttribute('aria-expanded', 'false');
E
Erich Gamma 已提交
958
			dom.removeClass(this.queryDetails, cls);
959
			if (moveFocus) {
960
				this.searchWidget.focus();
961
			}
E
Erich Gamma 已提交
962
		}
B
Benjamin Pasero 已提交
963

E
Erich Gamma 已提交
964 965 966 967 968
		if (!skipLayout && this.size) {
			this.layout(this.size);
		}
	}

969
	public searchInFolders(resources: URI[], pathToRelative: (from: string, to: string) => string): void {
970
		const folderPaths: string[] = [];
971
		const workspace = this.contextService.getWorkspace();
972 973 974 975 976 977 978 979 980 981 982 983 984

		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) {
985
						const owningRootName = owningFolder.name;
986 987

						// If this root is the only one with its basename, use a relative ./ path. If there is another, use an absolute path
988
						const isUniqueFolder = workspace.folders.filter(folder => folder.name === owningRootName).length === 1;
989
						if (isUniqueFolder) {
990 991 992 993 994 995
							const relativePath = paths.normalize(pathToRelative(owningFolder.uri.fsPath, resource.fsPath));
							if (relativePath === '.') {
								folderPath = `./${owningFolder.name}`;
							} else {
								folderPath = `./${owningFolder.name}/${relativePath}`;
							}
996 997 998
						} else {
							folderPath = resource.fsPath;
						}
999 1000
					}
				}
1001 1002 1003 1004 1005

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

1008
		if (!folderPaths.length || folderPaths.some(folderPath => folderPath === '.')) {
S
Sandeep Somavarapu 已提交
1009 1010 1011 1012 1013
			this.inputPatternIncludes.setValue('');
			this.searchWidget.focus();
			return;
		}

1014
		// Show 'files to include' box
E
Erich Gamma 已提交
1015
		if (!this.showsFileTypes()) {
1016
			this.toggleQueryDetails(true, true);
E
Erich Gamma 已提交
1017
		}
B
Benjamin Pasero 已提交
1018

1019
		this.inputPatternIncludes.setValue(folderPaths.join(', '));
B
Benjamin Pasero 已提交
1020
		this.searchWidget.focus(false);
E
Erich Gamma 已提交
1021 1022
	}

1023
	public onQueryChanged(preserveFocus?: boolean): void {
1024 1025 1026 1027
		const isRegex = this.searchWidget.searchInput.getRegex();
		const isWholeWords = this.searchWidget.searchInput.getWholeWords();
		const isCaseSensitive = this.searchWidget.searchInput.getCaseSensitive();
		const contentPattern = this.searchWidget.searchInput.getValue();
1028 1029 1030
		const excludePatternText = this.inputPatternExcludes.getValue().trim();
		const includePatternText = this.inputPatternIncludes.getValue().trim();
		const useExcludesAndIgnoreFiles = this.inputPatternExcludes.useExcludesAndIgnoreFiles();
E
Erich Gamma 已提交
1031 1032 1033 1034 1035

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

1036
		// Validate regex is OK
E
Erich Gamma 已提交
1037 1038 1039 1040 1041
		if (isRegex) {
			let regExp: RegExp;
			try {
				regExp = new RegExp(contentPattern);
			} catch (e) {
1042
				return; // malformed regex
E
Erich Gamma 已提交
1043
			}
1044

E
Erich Gamma 已提交
1045
			if (strings.regExpLeadsToEndlessLoop(regExp)) {
1046
				return; // endless regex
E
Erich Gamma 已提交
1047 1048 1049
			}
		}

1050
		const content: IPatternInfo = {
E
Erich Gamma 已提交
1051 1052 1053
			pattern: contentPattern,
			isRegExp: isRegex,
			isCaseSensitive: isCaseSensitive,
1054
			isWordMatch: isWholeWords,
1055
			isSmartCase: this.configurationService.getValue<ISearchConfiguration>().search.smartCase
E
Erich Gamma 已提交
1056 1057
		};

1058 1059
		const excludePattern = this.inputPatternExcludes.getValue();
		const includePattern = this.inputPatternIncludes.getValue();
E
Erich Gamma 已提交
1060

R
Rob Lourens 已提交
1061 1062 1063
		// Need the full match line to correctly calculate replace text, if this is a search/replace with regex group references ($1, $2, ...).
		// 10000 chars is enough to avoid sending huge amounts of text around, if you do a replace with a longer match, it may or may not resolve the group refs correctly.
		// https://github.com/Microsoft/vscode/issues/58374
R
Rob Lourens 已提交
1064
		const charsPerLine = content.isRegExp ? 10000 :
1065
			250;
R
Rob Lourens 已提交
1066

1067
		const options: IQueryOptions = {
1068
			extraFileResources: getOutOfWorkspaceEditorResources(this.editorService, this.contextService),
1069
			maxResults: SearchView.MAX_TEXT_RESULTS,
1070 1071
			disregardIgnoreFiles: !useExcludesAndIgnoreFiles,
			disregardExcludeSettings: !useExcludesAndIgnoreFiles,
R
Rob Lourens 已提交
1072
			excludePattern,
1073 1074
			includePattern,
			previewOptions: {
R
Rob Lourens 已提交
1075 1076
				matchLines: 1,
				charsPerLine
1077
			}
E
Erich Gamma 已提交
1078
		};
S
Sandeep Somavarapu 已提交
1079
		const folderResources = this.contextService.getWorkspace().folders;
1080 1081 1082 1083 1084 1085 1086 1087

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

		let query: ISearchQuery;
		try {
1088
			query = this.queryBuilder.text(content, folderResources.map(folder => folder.uri), options);
1089 1090
		} catch (err) {
			onQueryValidationError(err);
1091
			return;
1092
		}
1093

1094
		this.validateQuery(query).then(() => {
1095
			this.onQueryTriggered(query, excludePatternText, includePatternText);
1096

1097 1098 1099
			if (!preserveFocus) {
				this.searchWidget.focus(false); // focus back to input field
			}
1100
		}, onQueryValidationError);
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
	}

	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 已提交
1111 1112
			// If no folders exist, show an error message about the first one
			const existingFolderQueries = query.folderQueries.filter((folderQuery, i) => existResults[i]);
1113
			if (!query.folderQueries.length || existingFolderQueries.length) {
R
Rob Lourens 已提交
1114 1115 1116
				query.folderQueries = existingFolderQueries;
			} else {
				const nonExistantPath = query.folderQueries[0].folder.fsPath;
1117 1118 1119 1120 1121 1122
				const searchPathNotFoundError = nls.localize('searchPathNotFoundError', "Search path not found: {0}", nonExistantPath);
				return TPromise.wrapError(new Error(searchPathNotFoundError));
			}

			return undefined;
		});
E
Erich Gamma 已提交
1123 1124
	}

R
Rob Lourens 已提交
1125
	private onQueryTriggered(query: ISearchQuery, excludePatternText: string, includePatternText: string): void {
1126
		this.inputPatternExcludes.onSearchSubmit();
1127 1128
		this.inputPatternIncludes.onSearchSubmit();

S
Sandeep Somavarapu 已提交
1129 1130
		this.viewModel.cancelSearch();

1131 1132 1133 1134 1135 1136 1137
		// 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 已提交
1138

1139
		this.searchWidget.searchInput.clearMessage();
1140 1141 1142 1143 1144 1145
		this.searching = true;
		setTimeout(() => {
			if (this.searching) {
				this.changeActionAtPosition(0, this.instantiationService.createInstance(CancelSearchAction, CancelSearchAction.ID, CancelSearchAction.LABEL));
			}
		}, 2000);
E
Erich Gamma 已提交
1146 1147
		this.showEmptyStage();

1148
		let onComplete = (completed?: ISearchComplete) => {
1149 1150
			this.searching = false;
			this.changeActionAtPosition(0, this.instantiationService.createInstance(RefreshAction, RefreshAction.ID, RefreshAction.LABEL));
1151 1152 1153 1154 1155 1156 1157 1158

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

1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
			// 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;
1170
			});
1171

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

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

S
Sandeep Somavarapu 已提交
1176 1177
			this.searchSubmitted = true;
			this.updateActions();
E
Erich Gamma 已提交
1178

1179
			if (completed && completed.limitHit) {
1180
				this.searchWidget.searchInput.showMessage({
E
Erich Gamma 已提交
1181 1182 1183 1184 1185 1186
					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) {
1187 1188
				let hasExcludes = !!excludePatternText;
				let hasIncludes = !!includePatternText;
E
Erich Gamma 已提交
1189 1190
				let message: string;

1191 1192 1193
				if (!completed) {
					message = nls.localize('searchCanceled', "Search was canceled before any results could be found - ");
				} else if (hasIncludes && hasExcludes) {
R
Rob Lourens 已提交
1194
					message = nls.localize('noResultsIncludesExcludes', "No results found in '{0}' excluding '{1}' - ", includePatternText, excludePatternText);
E
Erich Gamma 已提交
1195
				} else if (hasIncludes) {
R
Rob Lourens 已提交
1196
					message = nls.localize('noResultsIncludes', "No results found in '{0}' - ", includePatternText);
E
Erich Gamma 已提交
1197
				} else if (hasExcludes) {
R
Rob Lourens 已提交
1198
					message = nls.localize('noResultsExcludes', "No results found excluding '{0}' - ", excludePatternText);
E
Erich Gamma 已提交
1199
				} else {
1200
					message = nls.localize('noResultsFound', "No results found. Review your settings for configured exclusions and ignore files - ");
E
Erich Gamma 已提交
1201 1202
				}

1203 1204 1205
				// Indicate as status to ARIA
				aria.status(message);

E
Erich Gamma 已提交
1206
				this.tree.onHidden();
1207
				dom.hide(this.resultsElement);
1208 1209

				const messageEl = this.clearMessage();
1210
				const p = dom.append(messageEl, $('p', undefined, message));
E
Erich Gamma 已提交
1211

1212
				if (!completed) {
1213
					const searchAgainLink = dom.append(p, $('a.pointer.prominent', undefined, nls.localize('rerunSearch.message', "Search again")));
1214
					this.messageDisposables.push(dom.addDisposableListener(searchAgainLink, dom.EventType.CLICK, (e: MouseEvent) => {
1215
						dom.EventHelper.stop(e, false);
1216
						this.onQueryChanged();
1217
					}));
1218
				} else if (hasIncludes || hasExcludes) {
1219
					const searchAgainLink = dom.append(p, $('a.pointer.prominent', { tabindex: 0 }, nls.localize('rerunSearchInAll.message', "Search again in all files")));
1220
					this.messageDisposables.push(dom.addDisposableListener(searchAgainLink, dom.EventType.CLICK, (e: MouseEvent) => {
E
Erich Gamma 已提交
1221 1222
						dom.EventHelper.stop(e, false);

1223
						this.inputPatternExcludes.setValue('');
E
Erich Gamma 已提交
1224 1225
						this.inputPatternIncludes.setValue('');

1226
						this.onQueryChanged();
1227
					}));
E
Erich Gamma 已提交
1228
				} else {
1229
					const openSettingsLink = dom.append(p, $('a.pointer.prominent', { tabindex: 0 }, nls.localize('openSettings.message', "Open Settings")));
1230
					this.messageDisposables.push(dom.addDisposableListener(openSettingsLink, dom.EventType.CLICK, (e: MouseEvent) => {
E
Erich Gamma 已提交
1231 1232
						dom.EventHelper.stop(e, false);

1233 1234 1235 1236
						const options: ISettingsEditorOptions = { query: '.exclude' };
						this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY ?
							this.preferencesService.openWorkspaceSettings(undefined, options) :
							this.preferencesService.openGlobalSettings(undefined, options);
1237
					}));
E
Erich Gamma 已提交
1238
				}
1239 1240

				if (completed) {
1241
					dom.append(p, $('span', undefined, ' - '));
1242

1243
					const learnMoreLink = dom.append(p, $('a.pointer.prominent', { tabindex: 0 }, nls.localize('openSettings.learnMore', "Learn More")));
1244
					this.messageDisposables.push(dom.addDisposableListener(learnMoreLink, dom.EventType.CLICK, (e: MouseEvent) => {
1245 1246 1247
						dom.EventHelper.stop(e, false);

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

1251
				if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
1252
					this.showSearchWithoutFolderMessage();
1253
				}
E
Erich Gamma 已提交
1254
			} else {
R
Rob Lourens 已提交
1255
				this.viewModel.searchResult.toggleHighlights(this.isVisible()); // show highlights
1256

1257
				// Indicate final search result count for ARIA
1258
				aria.status(nls.localize('ariaSearchResultsStatus', "Search returned {0} results in {1} files", this.viewModel.searchResult.count(), this.viewModel.searchResult.fileCount()));
E
Erich Gamma 已提交
1259 1260 1261 1262
			}
		};

		let onError = (e: any) => {
1263 1264 1265
			if (errors.isPromiseCanceledError(e)) {
				onComplete(null);
			} else {
1266 1267
				this.searching = false;
				this.changeActionAtPosition(0, this.instantiationService.createInstance(RefreshAction, RefreshAction.ID, RefreshAction.LABEL));
1268
				progressRunner.done();
1269
				this.searchWidget.searchInput.showMessage({ content: e.message, type: MessageType.ERROR });
1270
				this.viewModel.searchResult.clear();
E
Erich Gamma 已提交
1271 1272 1273
			}
		};

1274 1275
		let total: number = 0;
		let worked: number = 0;
E
Erich Gamma 已提交
1276
		let visibleMatches = 0;
1277 1278 1279 1280 1281 1282 1283 1284 1285
		let onProgress = (p: ISearchProgressItem) => {
			// Progress
			if (p.total) {
				total = p.total;
			}
			if (p.worked) {
				worked = p.worked;
			}
		};
E
Erich Gamma 已提交
1286 1287 1288

		// Handle UI updates in an interval to show frequent progress and results
		let uiRefreshHandle = setInterval(() => {
1289
			if (!this.searching) {
E
Erich Gamma 已提交
1290 1291 1292 1293
				window.clearInterval(uiRefreshHandle);
				return;
			}

1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
			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 已提交
1318
			// Search result tree update
1319 1320 1321
			const fileCount = this.viewModel.searchResult.fileCount();
			if (visibleMatches !== fileCount) {
				visibleMatches = fileCount;
1322
				this.tree.refresh();
1323

1324
				this.updateSearchResultCount();
1325
			}
1326
			if (fileCount > 0) {
S
Sandeep Somavarapu 已提交
1327
				this.updateActions();
E
Erich Gamma 已提交
1328
			}
1329
		}, 100);
E
Erich Gamma 已提交
1330

S
Sandeep Somavarapu 已提交
1331
		this.searchWidget.setReplaceAllActionState(false);
1332

1333
		this.viewModel.search(query, onProgress).then(onComplete, onError);
E
Erich Gamma 已提交
1334 1335
	}

1336
	private updateSearchResultCount(): void {
1337
		const fileCount = this.viewModel.searchResult.fileCount();
1338 1339
		this.hasSearchResultsKey.set(fileCount > 0);

1340
		const msgWasHidden = this.messagesElement.style.display === 'none';
1341
		if (fileCount > 0) {
1342
			const messageEl = this.clearMessage();
1343
			dom.append(messageEl, $('p', undefined, this.buildResultCountMessage(this.viewModel.searchResult.count(), fileCount)));
1344 1345 1346
			if (msgWasHidden) {
				this.reLayout();
			}
1347
		} else if (!msgWasHidden) {
1348
			dom.hide(this.messagesElement);
1349 1350 1351
		}
	}

1352 1353 1354 1355 1356 1357 1358
	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);
1359
		} else {
1360
			return nls.localize('search.files.results', "{0} results in {1} files", resultCount, fileCount);
1361 1362 1363
		}
	}

1364 1365 1366 1367
	private showSearchWithoutFolderMessage(): void {
		this.searchWithoutFolderMessageElement = this.clearMessage();

		const textEl = dom.append(this.searchWithoutFolderMessageElement,
1368
			$('p', undefined, nls.localize('searchWithoutFolder', "You have not yet opened a folder. Only open files are currently searched - ")));
1369 1370

		const openFolderLink = dom.append(textEl,
1371
			$('a.pointer.prominent', { tabindex: 0 }, nls.localize('openFolder', "Open Folder")));
1372 1373 1374 1375 1376 1377

		this.messageDisposables.push(dom.addDisposableListener(openFolderLink, 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);
1378
			this.actionRunner.run(action).then(() => {
1379 1380 1381 1382
				action.dispose();
			}, err => {
				action.dispose();
				errors.onUnexpectedError(err);
1383
			});
1384
		}));
1385 1386
	}

E
Erich Gamma 已提交
1387
	private showEmptyStage(): void {
1388

E
Erich Gamma 已提交
1389
		// disable 'result'-actions
S
Sandeep Somavarapu 已提交
1390 1391
		this.searchSubmitted = false;
		this.updateActions();
E
Erich Gamma 已提交
1392 1393

		// clean up ui
S
Sandeep Somavarapu 已提交
1394
		// this.replaceService.disposeAllReplacePreviews();
1395
		dom.hide(this.messagesElement);
1396
		dom.show(this.resultsElement);
E
Erich Gamma 已提交
1397
		this.tree.onVisible();
S
Sandeep Somavarapu 已提交
1398
		this.currentSelectedFileMatch = null;
E
Erich Gamma 已提交
1399 1400
	}

S
Sandeep Somavarapu 已提交
1401
	private onFocus(lineMatch: any, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> {
E
Erich Gamma 已提交
1402
		if (!(lineMatch instanceof Match)) {
1403
			this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange();
A
Alex Dima 已提交
1404
			return TPromise.as(true);
E
Erich Gamma 已提交
1405 1406
		}

R
Rob Lourens 已提交
1407 1408 1409
		return (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) ?
			this.replaceService.openReplacePreview(lineMatch, preserveFocus, sideBySide, pinned) :
			this.open(lineMatch, preserveFocus, sideBySide, pinned);
1410 1411 1412
	}

	public open(element: FileMatchOrMatch, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> {
R
Rob Lourens 已提交
1413 1414
		const selection = this.getSelectionFrom(element);
		const resource = element instanceof Match ? element.parent().resource() : (<FileMatch>element).resource();
E
Erich Gamma 已提交
1415
		return this.editorService.openEditor({
1416
			resource: resource,
E
Erich Gamma 已提交
1417
			options: {
1418 1419
				preserveFocus,
				pinned,
S
Sandeep Somavarapu 已提交
1420
				selection,
1421
				revealIfVisible: true
E
Erich Gamma 已提交
1422
			}
B
Benjamin Pasero 已提交
1423
		}, sideBySide ? SIDE_GROUP : ACTIVE_GROUP).then(editor => {
S
Sandeep Somavarapu 已提交
1424
			if (editor && element instanceof Match && preserveFocus) {
1425 1426 1427 1428
				this.viewModel.searchResult.rangeHighlightDecorations.highlightRange(
					(<ICodeEditor>editor.getControl()).getModel(),
					element.range()
				);
S
Sandeep Somavarapu 已提交
1429
			} else {
1430
				this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange();
S
Sandeep Somavarapu 已提交
1431
			}
R
Rob Lourens 已提交
1432 1433

			return this.editorGroupsService.activateGroup(editor.group);
S
Sandeep Somavarapu 已提交
1434
		}, errors.onUnexpectedError);
E
Erich Gamma 已提交
1435 1436
	}

1437
	private getSelectionFrom(element: FileMatchOrMatch): any {
J
Johannes Rieken 已提交
1438
		let match: Match = null;
1439
		if (element instanceof Match) {
J
Johannes Rieken 已提交
1440
			match = element;
1441 1442
		}
		if (element instanceof FileMatch && element.count() > 0) {
J
Johannes Rieken 已提交
1443
			match = element.matches()[element.matches().length - 1];
1444 1445
		}
		if (match) {
J
Johannes Rieken 已提交
1446
			let range = match.range();
S
Sandeep Somavarapu 已提交
1447
			if (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) {
J
Johannes Rieken 已提交
1448
				let replaceString = match.replaceString;
1449 1450
				return {
					startLineNumber: range.startLineNumber,
S
Sandeep Somavarapu 已提交
1451
					startColumn: range.startColumn,
1452
					endLineNumber: range.startLineNumber,
S
Sandeep Somavarapu 已提交
1453
					endColumn: range.startColumn + replaceString.length
1454 1455 1456 1457 1458 1459 1460
				};
			}
			return range;
		}
		return void 0;
	}

B
Benjamin Pasero 已提交
1461
	private onUntitledDidChangeDirty(resource: URI): void {
E
Erich Gamma 已提交
1462 1463 1464 1465
		if (!this.viewModel) {
			return;
		}

1466
		// remove search results from this resource as it got disposed
B
Benjamin Pasero 已提交
1467
		if (!this.untitledEditorService.isDirty(resource)) {
1468 1469
			let matches = this.viewModel.searchResult.matches();
			for (let i = 0, len = matches.length; i < len; i++) {
B
Benjamin Pasero 已提交
1470
				if (resource.toString() === matches[i].resource().toString()) {
1471 1472
					this.viewModel.searchResult.remove(matches[i]);
				}
E
Erich Gamma 已提交
1473 1474 1475 1476 1477 1478 1479 1480 1481
			}
		}
	}

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

1482
		let matches = this.viewModel.searchResult.matches();
E
Erich Gamma 已提交
1483 1484 1485

		for (let i = 0, len = matches.length; i < len; i++) {
			if (e.contains(matches[i].resource(), FileChangeType.DELETED)) {
1486
				this.viewModel.searchResult.remove(matches[i]);
E
Erich Gamma 已提交
1487 1488 1489 1490 1491
			}
		}
	}

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

1495
	private changeActionAtPosition(index: number, newAction: ClearSearchResultsAction | CancelSearchAction | RefreshAction | CollapseDeepestExpandedLevelAction): void {
1496 1497 1498 1499
		this.actions.splice(index, 1, newAction);
		this.updateTitleArea();
	}

1500
	private clearHistory(): void {
1501 1502 1503 1504 1505
		this.searchWidget.clearHistory();
		this.inputPatternExcludes.clearHistory();
		this.inputPatternIncludes.clearHistory();
	}

A
Amy Qiu 已提交
1506
	public shutdown(): void {
A
Amy Qiu 已提交
1507 1508 1509 1510
		const isRegex = this.searchWidget.searchInput.getRegex();
		const isWholeWords = this.searchWidget.searchInput.getWholeWords();
		const isCaseSensitive = this.searchWidget.searchInput.getCaseSensitive();
		const contentPattern = this.searchWidget.searchInput.getValue();
1511
		const patternExcludes = this.inputPatternExcludes.getValue().trim();
A
Amy Qiu 已提交
1512
		const patternIncludes = this.inputPatternIncludes.getValue().trim();
1513
		const useExcludesAndIgnoreFiles = this.inputPatternExcludes.useExcludesAndIgnoreFiles();
A
Amy Qiu 已提交
1514 1515 1516 1517 1518 1519

		// store memento
		this.viewletSettings['query.contentPattern'] = contentPattern;
		this.viewletSettings['query.regex'] = isRegex;
		this.viewletSettings['query.wholeWords'] = isWholeWords;
		this.viewletSettings['query.caseSensitive'] = isCaseSensitive;
1520
		this.viewletSettings['query.folderExclusions'] = patternExcludes;
A
Amy Qiu 已提交
1521
		this.viewletSettings['query.folderIncludes'] = patternIncludes;
1522
		this.viewletSettings['query.useExcludesAndIgnoreFiles'] = useExcludesAndIgnoreFiles;
A
Amy Qiu 已提交
1523

1524 1525 1526 1527 1528
		const searchHistory = this.searchWidget.getSearchHistory();
		const replaceHistory = this.searchWidget.getReplaceHistory();
		const patternExcludesHistory = this.inputPatternExcludes.getHistory();
		const patternIncludesHistory = this.inputPatternIncludes.getHistory();

1529
		this.searchHistoryService.save({
1530 1531 1532 1533
			search: searchHistory,
			replace: replaceHistory,
			exclude: patternExcludesHistory,
			include: patternIncludesHistory
1534 1535
		});

A
Amy Qiu 已提交
1536 1537 1538
		super.shutdown();
	}

E
Erich Gamma 已提交
1539 1540 1541 1542 1543
	public dispose(): void {
		this.isDisposed = true;

		super.dispose();
	}
1544 1545 1546
}

registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
B
Benjamin Pasero 已提交
1547
	const matchHighlightColor = theme.getColor(editorFindMatchHighlight);
1548
	if (matchHighlightColor) {
I
isidor 已提交
1549
		collector.addRule(`.monaco-workbench .search-view .findInFileMatch { background-color: ${matchHighlightColor}; }`);
B
Benjamin Pasero 已提交
1550 1551 1552 1553
	}

	const diffInsertedColor = theme.getColor(diffInserted);
	if (diffInsertedColor) {
I
isidor 已提交
1554
		collector.addRule(`.monaco-workbench .search-view .replaceMatch { background-color: ${diffInsertedColor}; }`);
B
Benjamin Pasero 已提交
1555 1556 1557 1558
	}

	const diffRemovedColor = theme.getColor(diffRemoved);
	if (diffRemovedColor) {
I
isidor 已提交
1559
		collector.addRule(`.monaco-workbench .search-view .replace.findInFileMatch { background-color: ${diffRemovedColor}; }`);
B
Benjamin Pasero 已提交
1560 1561 1562 1563
	}

	const diffInsertedOutlineColor = theme.getColor(diffInsertedOutline);
	if (diffInsertedOutlineColor) {
1564
		collector.addRule(`.monaco-workbench .search-view .replaceMatch:not(:empty) { border: 1px ${theme.type === 'hc' ? 'dashed' : 'solid'} ${diffInsertedOutlineColor}; }`);
B
Benjamin Pasero 已提交
1565 1566 1567 1568
	}

	const diffRemovedOutlineColor = theme.getColor(diffRemovedOutline);
	if (diffRemovedOutlineColor) {
1569
		collector.addRule(`.monaco-workbench .search-view .replace.findInFileMatch { border: 1px ${theme.type === 'hc' ? 'dashed' : 'solid'} ${diffRemovedOutlineColor}; }`);
B
Benjamin Pasero 已提交
1570 1571
	}

1572 1573
	const findMatchHighlightBorder = theme.getColor(editorFindMatchHighlightBorder);
	if (findMatchHighlightBorder) {
1574
		collector.addRule(`.monaco-workbench .search-view .findInFileMatch { border: 1px ${theme.type === 'hc' ? 'dashed' : 'solid'} ${findMatchHighlightBorder}; }`);
1575
	}
1576 1577 1578 1579 1580

	const outlineSelectionColor = theme.getColor(listActiveSelectionForeground);
	if (outlineSelectionColor) {
		collector.addRule(`.monaco-workbench .search-view .monaco-tree.focused .monaco-tree-row.focused.selected:not(.highlighted) .action-label:focus { outline-color: ${outlineSelectionColor} }`);
	}
1581
});