searchEditor.ts 27.6 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6 7
import * as DOM from 'vs/base/browser/dom';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
8
import { alert } from 'vs/base/browser/ui/aria/aria';
9
import { Delayer } from 'vs/base/common/async';
10 11
import { CancellationToken } from 'vs/base/common/cancellation';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
12
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
13
import { assertIsDefined } from 'vs/base/common/types';
14 15
import { URI } from 'vs/base/common/uri';
import 'vs/css!./media/searchEditor';
J
Jackson Kearl 已提交
16
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
17
import { Position } from 'vs/editor/common/core/position';
18
import { Range } from 'vs/editor/common/core/range';
19 20
import { Selection } from 'vs/editor/common/core/selection';
import { ICodeEditorViewState } from 'vs/editor/common/editorCommon';
21
import { IModelService } from 'vs/editor/common/services/modelService';
22
import { ITextResourceConfigurationService } from 'vs/editor/common/services/textResourceConfigurationService';
23
import { ReferencesController } from 'vs/editor/contrib/gotoSymbol/peek/referencesController';
24 25
import { localize } from 'vs/nls';
import { ICommandService } from 'vs/platform/commands/common/commands';
26
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
27
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
28 29
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
30
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
31
import { ILabelService } from 'vs/platform/label/common/label';
32
import { IEditorProgressService, LongRunningOperation } from 'vs/platform/progress/common/progress';
33 34
import { IStorageService } from 'vs/platform/storage/common/storage';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
35 36
import { inputBorder, registerColor, searchEditorFindMatch, searchEditorFindMatchBorder } from 'vs/platform/theme/common/colorRegistry';
import { attachInputBoxStyler } from 'vs/platform/theme/common/styler';
37
import { IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
38
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
39
import { BaseTextEditor } from 'vs/workbench/browser/parts/editor/textEditor';
40
import { EditorOptions, IEditorOpenContext } from 'vs/workbench/common/editor';
41 42
import { ExcludePatternInputWidget, PatternInputWidget } from 'vs/workbench/contrib/search/browser/patternInputWidget';
import { SearchWidget } from 'vs/workbench/contrib/search/browser/searchWidget';
43
import { InputBoxFocusedKey } from 'vs/workbench/contrib/search/common/constants';
44 45
import { ITextQueryBuilderOptions, QueryBuilder } from 'vs/workbench/contrib/search/common/queryBuilder';
import { getOutOfWorkspaceEditorResources } from 'vs/workbench/contrib/search/common/search';
J
Jackson Kearl 已提交
46
import { SearchModel } from 'vs/workbench/contrib/search/common/searchModel';
47
import { InSearchEditor, SearchEditorFindMatchClass, SearchEditorID } from 'vs/workbench/contrib/searchEditor/browser/constants';
48
import type { SearchConfiguration, SearchEditorInput } from 'vs/workbench/contrib/searchEditor/browser/searchEditorInput';
49
import { serializeSearchResultForEditor } from 'vs/workbench/contrib/searchEditor/browser/searchEditorSerialization';
50
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
J
Jackson Kearl 已提交
51
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
52
import { IPatternInfo, ISearchConfigurationProperties, ITextQuery } from 'vs/workbench/services/search/common/search';
M
Martin Aeschlimann 已提交
53
import { searchDetailsIcon } from 'vs/workbench/contrib/search/browser/searchIcons';
54 55

const RESULT_LINE_REGEX = /^(\s+)(\d+)(:| )(\s+)(.*)$/;
56
const FILE_LINE_REGEX = /^(\S.*):$/;
57

J
Jackson Kearl 已提交
58
type SearchEditorViewState = ICodeEditorViewState & { focused: 'input' | 'editor' };
59

J
Jackson Kearl 已提交
60
export class SearchEditor extends BaseTextEditor {
61
	static readonly ID: string = SearchEditorID;
62

J
Jackson Kearl 已提交
63
	static readonly SEARCH_EDITOR_VIEW_STATE_PREFERENCE_KEY = 'searchEditorViewState';
64

65 66 67 68 69 70 71 72
	private queryEditorWidget!: SearchWidget;
	private searchResultEditor!: CodeEditorWidget;
	private queryEditorContainer!: HTMLElement;
	private dimension?: DOM.Dimension;
	private inputPatternIncludes!: PatternInputWidget;
	private inputPatternExcludes!: ExcludePatternInputWidget;
	private includesExcludesContainer!: HTMLElement;
	private toggleQueryDetailsButton!: HTMLElement;
73
	private messageBox!: HTMLElement;
74

75
	private runSearchDelayer = new Delayer(0);
76
	private pauseSearching: boolean = false;
77
	private showingIncludesExcludes: boolean = false;
78 79
	private inSearchEditorContextKey: IContextKey<boolean>;
	private inputFocusContextKey: IContextKey<boolean>;
80
	private searchOperation: LongRunningOperation;
J
Jackson Kearl 已提交
81
	private searchHistoryDelayer: Delayer<void>;
82
	private messageDisposables: IDisposable[] = [];
83
	private container: HTMLElement;
J
Jackson Kearl 已提交
84
	private searchModel: SearchModel;
85
	private ongoingOperations: number = 0;
86 87 88 89 90 91 92 93

	constructor(
		@ITelemetryService telemetryService: ITelemetryService,
		@IThemeService themeService: IThemeService,
		@IStorageService storageService: IStorageService,
		@IModelService private readonly modelService: IModelService,
		@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
		@ILabelService private readonly labelService: ILabelService,
94
		@IInstantiationService instantiationService: IInstantiationService,
95 96
		@IContextViewService private readonly contextViewService: IContextViewService,
		@ICommandService private readonly commandService: ICommandService,
97
		@IContextKeyService readonly contextKeyService: IContextKeyService,
98
		@IEditorProgressService readonly progressService: IEditorProgressService,
J
Jackson Kearl 已提交
99 100 101 102
		@ITextResourceConfigurationService textResourceService: ITextResourceConfigurationService,
		@IEditorGroupsService protected editorGroupService: IEditorGroupsService,
		@IEditorService protected editorService: IEditorService,
		@IConfigurationService protected configurationService: IConfigurationService,
103
	) {
J
Jackson Kearl 已提交
104
		super(SearchEditor.ID, telemetryService, instantiationService, storageService, textResourceService, themeService, editorService, editorGroupService);
105 106
		this.container = DOM.$('.search-editor');

107

108 109 110 111 112 113
		const scopedContextKeyService = contextKeyService.createScoped(this.container);
		this.instantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, scopedContextKeyService]));

		this.inSearchEditorContextKey = InSearchEditor.bindTo(scopedContextKeyService);
		this.inSearchEditorContextKey.set(true);
		this.inputFocusContextKey = InputBoxFocusedKey.bindTo(scopedContextKeyService);
114
		this.searchOperation = this._register(new LongRunningOperation(progressService));
J
Jackson Kearl 已提交
115
		this.searchHistoryDelayer = new Delayer<void>(2000);
J
Jackson Kearl 已提交
116 117

		this.searchModel = this._register(this.instantiationService.createInstance(SearchModel));
118 119 120
	}

	createEditor(parent: HTMLElement) {
121
		DOM.append(parent, this.container);
122

123 124
		this.createQueryEditor(this.container);
		this.createResultsEditor(this.container);
125
	}
126

127 128
	private createQueryEditor(parent: HTMLElement) {
		this.queryEditorContainer = DOM.append(parent, DOM.$('.query-container'));
129 130 131
		this.queryEditorWidget = this._register(this.instantiationService.createInstance(SearchWidget, this.queryEditorContainer, { _hideReplaceToggle: true, showContextToggle: true }));
		this._register(this.queryEditorWidget.onReplaceToggled(() => this.reLayout()));
		this._register(this.queryEditorWidget.onDidHeightChange(() => this.reLayout()));
132 133 134
		this.queryEditorWidget.onSearchSubmit(({ delay }) => this.triggerSearch({ delay }));
		this.queryEditorWidget.searchInput.onDidOptionChange(() => this.triggerSearch({ resetCursor: false }));
		this.queryEditorWidget.onDidToggleContext(() => this.triggerSearch({ resetCursor: false }));
135 136 137

		// Includes/Excludes Dropdown
		this.includesExcludesContainer = DOM.append(this.queryEditorContainer, DOM.$('.includes-excludes'));
138

139
		// // Toggle query details button
M
Martin Aeschlimann 已提交
140
		this.toggleQueryDetailsButton = DOM.append(this.includesExcludesContainer, DOM.$('.expand' + searchDetailsIcon.cssSelector, { tabindex: 0, role: 'button', title: localize('moreSearch', "Toggle Search Details") }));
141 142
		this._register(DOM.addDisposableListener(this.toggleQueryDetailsButton, DOM.EventType.CLICK, e => {
			DOM.EventHelper.stop(e);
143
			this.toggleIncludesExcludes();
144 145 146 147 148
		}));
		this._register(DOM.addDisposableListener(this.toggleQueryDetailsButton, DOM.EventType.KEY_UP, (e: KeyboardEvent) => {
			const event = new StandardKeyboardEvent(e);
			if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) {
				DOM.EventHelper.stop(e);
149
				this.toggleIncludesExcludes();
150 151 152 153 154 155 156
			}
		}));
		this._register(DOM.addDisposableListener(this.toggleQueryDetailsButton, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => {
			const event = new StandardKeyboardEvent(e);
			if (event.equals(KeyMod.Shift | KeyCode.Tab)) {
				if (this.queryEditorWidget.isReplaceActive()) {
					this.queryEditorWidget.focusReplaceAllAction();
157 158
				}
				else {
159 160 161 162 163 164 165 166 167 168 169 170 171
					this.queryEditorWidget.isReplaceShown() ? this.queryEditorWidget.replaceInput.focusOnPreserve() : this.queryEditorWidget.focusRegexAction();
				}
				DOM.EventHelper.stop(e);
			}
		}));

		// // Includes
		const folderIncludesList = DOM.append(this.includesExcludesContainer, DOM.$('.file-types.includes'));
		const filesToIncludeTitle = localize('searchScope.includes', "files to include");
		DOM.append(folderIncludesList, DOM.$('h4', undefined, filesToIncludeTitle));
		this.inputPatternIncludes = this._register(this.instantiationService.createInstance(PatternInputWidget, folderIncludesList, this.contextViewService, {
			ariaLabel: localize('label.includes', 'Search Include Patterns'),
		}));
172
		this.inputPatternIncludes.onSubmit(triggeredOnType => this.triggerSearch({ resetCursor: false, delay: triggeredOnType ? this.searchConfig.searchOnTypeDebouncePeriod : 0 }));
173 174 175 176 177 178 179 180

		// // Excludes
		const excludesList = DOM.append(this.includesExcludesContainer, DOM.$('.file-types.excludes'));
		const excludesTitle = localize('searchScope.excludes', "files to exclude");
		DOM.append(excludesList, DOM.$('h4', undefined, excludesTitle));
		this.inputPatternExcludes = this._register(this.instantiationService.createInstance(ExcludePatternInputWidget, excludesList, this.contextViewService, {
			ariaLabel: localize('label.excludes', 'Search Exclude Patterns'),
		}));
181 182
		this.inputPatternExcludes.onSubmit(triggeredOnType => this.triggerSearch({ resetCursor: false, delay: triggeredOnType ? this.searchConfig.searchOnTypeDebouncePeriod : 0 }));
		this.inputPatternExcludes.onChangeIgnoreBox(() => this.triggerSearch());
183 184 185

		[this.queryEditorWidget.searchInput, this.inputPatternIncludes, this.inputPatternExcludes].map(input =>
			this._register(attachInputBoxStyler(input, this.themeService, { inputBorder: searchEditorTextInputBorder })));
186 187 188 189 190 191 192 193 194 195 196

		// Messages
		this.messageBox = DOM.append(this.queryEditorContainer, DOM.$('.messages'));
	}

	private toggleRunAgainMessage(show: boolean) {
		DOM.clearNode(this.messageBox);
		dispose(this.messageDisposables);
		this.messageDisposables = [];

		if (show) {
J
Naming  
Jackson Kearl 已提交
197
			const runAgainLink = DOM.append(this.messageBox, DOM.$('a.pointer.prominent.message', {}, localize('runSearch', "Run Search")));
198
			this.messageDisposables.push(DOM.addDisposableListener(runAgainLink, DOM.EventType.CLICK, async () => {
199
				await this.triggerSearch();
J
Jackson Kearl 已提交
200
				this.searchResultEditor.focus();
201 202 203
				this.toggleRunAgainMessage(false);
			}));
		}
204
	}
205

206
	private createResultsEditor(parent: HTMLElement) {
207
		const searchResultContainer = DOM.append(parent, DOM.$('.search-results'));
J
Jackson Kearl 已提交
208 209
		super.createEditor(searchResultContainer);
		this.searchResultEditor = super.getControl() as CodeEditorWidget;
210 211
		this.searchResultEditor.onMouseUp(e => {
			if (e.event.detail === 2) {
212
				const behaviour = this.configurationService.getValue<ISearchConfigurationProperties>('search').searchEditor.doubleClickBehaviour;
213 214 215 216 217 218
				const position = e.target.position;
				if (position && behaviour !== 'selectWord') {
					const line = this.searchResultEditor.getModel()?.getLineContent(position.lineNumber) ?? '';
					if (line.match(RESULT_LINE_REGEX)) {
						this.searchResultEditor.setSelection(Range.fromPositions(position));
						this.commandService.executeCommand(behaviour === 'goToLocation' ? 'editor.action.goToDeclaration' : 'editor.action.openDeclarationToTheSide');
219 220 221
					} else if (line.match(FILE_LINE_REGEX)) {
						this.searchResultEditor.setSelection(Range.fromPositions(position));
						this.commandService.executeCommand('editor.action.peekDefinition');
222 223 224 225
					}
				}
			}
		});
226

J
Jackson Kearl 已提交
227
		this._register(this.onDidBlur(() => this.saveViewState()));
J
Jackson Kearl 已提交
228

229
		this._register(this.searchResultEditor.onDidChangeModelContent(() => this.getInput()?.setDirty(true)));
230 231 232 233 234 235 236 237

		[this.queryEditorWidget.searchInputFocusTracker, this.queryEditorWidget.replaceInputFocusTracker, this.inputPatternExcludes.inputFocusTracker, this.inputPatternIncludes.inputFocusTracker]
			.map(tracker => {
				this._register(tracker.onDidFocus(() => setTimeout(() => this.inputFocusContextKey.set(true), 0)));
				this._register(tracker.onDidBlur(() => this.inputFocusContextKey.set(false)));
			});
	}

J
Jackson Kearl 已提交
238 239 240 241
	getControl() {
		return this.searchResultEditor;
	}

J
Jackson Kearl 已提交
242
	focus() {
243 244
		const viewState = this.loadViewState();
		if (viewState && viewState.focused === 'editor') {
J
Jackson Kearl 已提交
245 246 247 248
			this.searchResultEditor.focus();
		} else {
			this.queryEditorWidget.focus();
		}
J
Jackson Kearl 已提交
249 250
	}

251
	focusSearchInput() {
J
Jackson Kearl 已提交
252
		this.queryEditorWidget.searchInput.focus();
253 254
	}

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
	focusNextInput() {
		if (this.queryEditorWidget.searchInputHasFocus()) {
			if (this.showingIncludesExcludes) {
				this.inputPatternIncludes.focus();
			} else {
				this.searchResultEditor.focus();
			}
		} else if (this.inputPatternIncludes.inputHasFocus()) {
			this.inputPatternExcludes.focus();
		} else if (this.inputPatternExcludes.inputHasFocus()) {
			this.searchResultEditor.focus();
		} else if (this.searchResultEditor.hasWidgetFocus()) {
			// pass
		}
	}

	focusPrevInput() {
		if (this.queryEditorWidget.searchInputHasFocus()) {
			this.searchResultEditor.focus(); // wrap
		} else if (this.inputPatternIncludes.inputHasFocus()) {
			this.queryEditorWidget.searchInput.focus();
		} else if (this.inputPatternExcludes.inputHasFocus()) {
			this.inputPatternIncludes.focus();
		} else if (this.searchResultEditor.hasWidgetFocus()) {
J
Jackson Kearl 已提交
279
			// unreachable.
280
		}
281 282
	}

283 284 285 286 287 288 289 290
	setQuery(query: string) {
		this.queryEditorWidget.searchInput.setValue(query);
	}

	selectQuery() {
		this.queryEditorWidget.searchInput.select();
	}

291 292
	toggleWholeWords() {
		this.queryEditorWidget.searchInput.setWholeWords(!this.queryEditorWidget.searchInput.getWholeWords());
293
		this.triggerSearch({ resetCursor: false });
294 295 296 297
	}

	toggleRegex() {
		this.queryEditorWidget.searchInput.setRegex(!this.queryEditorWidget.searchInput.getRegex());
298
		this.triggerSearch({ resetCursor: false });
299 300 301 302
	}

	toggleCaseSensitive() {
		this.queryEditorWidget.searchInput.setCaseSensitive(!this.queryEditorWidget.searchInput.getCaseSensitive());
303
		this.triggerSearch({ resetCursor: false });
304 305
	}

306 307 308 309
	toggleContextLines() {
		this.queryEditorWidget.toggleContextLines();
	}

310 311 312 313
	modifyContextLines(increase: boolean) {
		this.queryEditorWidget.modifyContextLines(increase);
	}

314 315 316 317
	toggleQueryDetails() {
		this.toggleIncludesExcludes();
	}

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
	deleteResultBlock() {
		const linesToDelete = new Set<number>();

		const selections = this.searchResultEditor.getSelections();
		const model = this.searchResultEditor.getModel();
		if (!(selections && model)) { return; }

		const maxLine = model.getLineCount();
		const minLine = 1;

		const deleteUp = (start: number) => {
			for (let cursor = start; cursor >= minLine; cursor--) {
				const line = model.getLineContent(cursor);
				linesToDelete.add(cursor);
				if (line[0] !== undefined && line[0] !== ' ') {
					break;
				}
			}
		};

		const deleteDown = (start: number): number | undefined => {
			linesToDelete.add(start);
			for (let cursor = start + 1; cursor <= maxLine; cursor++) {
				const line = model.getLineContent(cursor);
				if (line[0] !== undefined && line[0] !== ' ') {
					return cursor;
				}
				linesToDelete.add(cursor);
			}
			return;
		};

		const endingCursorLines: Array<number | undefined> = [];
		for (const selection of selections) {
			const lineNumber = selection.startLineNumber;
			endingCursorLines.push(deleteDown(lineNumber));
			deleteUp(lineNumber);
			for (let inner = selection.startLineNumber; inner <= selection.endLineNumber; inner++) {
				linesToDelete.add(inner);
			}
		}

		if (endingCursorLines.length === 0) { endingCursorLines.push(1); }

		const isDefined = <T>(x: T | undefined): x is T => x !== undefined;

		model.pushEditOperations(this.searchResultEditor.getSelections(),
			[...linesToDelete].map(line => ({ range: new Range(line, 1, line + 1, 1), text: '' })),
			() => endingCursorLines.filter(isDefined).map(line => new Selection(line, 1, line, 1)));
	}

369 370 371 372
	cleanState() {
		this.getInput()?.setDirty(false);
	}

373 374 375 376
	private get searchConfig(): ISearchConfigurationProperties {
		return this.configurationService.getValue<ISearchConfigurationProperties>('search');
	}

377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
	private iterateThroughMatches(reverse: boolean) {
		const model = this.searchResultEditor.getModel();
		if (!model) { return; }

		const lastLine = model.getLineCount() ?? 1;
		const lastColumn = model.getLineLength(lastLine);

		const fallbackStart = reverse ? new Position(lastLine, lastColumn) : new Position(1, 1);

		const currentPosition = this.searchResultEditor.getSelection()?.getStartPosition() ?? fallbackStart;

		const matchRanges = this.getInput()?.getMatchRanges();
		if (!matchRanges) { return; }

		const matchRange = (reverse ? findPrevRange : findNextRange)(matchRanges, currentPosition);

		this.searchResultEditor.setSelection(matchRange);
		this.searchResultEditor.revealLineInCenterIfOutsideViewport(matchRange.startLineNumber);
		this.searchResultEditor.focus();
396 397 398 399 400

		const matchLineText = model.getLineContent(matchRange.startLineNumber);
		const matchText = model.getValueInRange(matchRange);
		let file = '';
		for (let line = matchRange.startLineNumber; line >= 1; line--) {
R
Rob Lourens 已提交
401
			const lineText = model.getValueInRange(new Range(line, 1, line, 2));
402 403 404
			if (lineText !== ' ') { file = model.getLineContent(line); break; }
		}
		alert(localize('searchResultItem', "Matched {0} at {1} in file {2}", matchText, matchLineText, file.slice(0, file.length - 1)));
405 406 407 408 409 410 411 412 413 414
	}

	focusNextResult() {
		this.iterateThroughMatches(false);
	}

	focusPreviousResult() {
		this.iterateThroughMatches(true);
	}

415 416 417 418 419 420 421
	focusAllResults() {
		this.searchResultEditor
			.setSelections((this.getInput()?.getMatchRanges() ?? []).map(
				range => new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn)));
		this.searchResultEditor.focus();
	}

422
	async triggerSearch(_options?: { resetCursor?: boolean; delay?: number; focusResults?: boolean }) {
423 424
		const options = { resetCursor: true, delay: 0, ..._options };

425
		if (!this.pauseSearching) {
426
			await this.runSearchDelayer.trigger(async () => {
J
Jackson Kearl 已提交
427
				await this.doRunSearch();
428
				this.toggleRunAgainMessage(false);
429
				if (options.resetCursor) {
430
					this.searchResultEditor.setPosition(new Position(1, 1));
J
Jackson Kearl 已提交
431
					this.searchResultEditor.setScrollPosition({ scrollTop: 0, scrollLeft: 0 });
J
Jackson Kearl 已提交
432
				}
433 434 435
				if (options.focusResults) {
					this.searchResultEditor.focus();
				}
436
			}, options.delay);
437 438 439
		}
	}

J
Jackson Kearl 已提交
440 441
	private readConfigFromWidget() {
		return {
442
			caseSensitive: this.queryEditorWidget.searchInput.getCaseSensitive(),
443
			contextLines: this.queryEditorWidget.getContextLines(),
444 445 446 447 448
			excludes: this.inputPatternExcludes.getValue(),
			includes: this.inputPatternIncludes.getValue(),
			query: this.queryEditorWidget.searchInput.getValue(),
			regexp: this.queryEditorWidget.searchInput.getRegex(),
			wholeWord: this.queryEditorWidget.searchInput.getWholeWords(),
449 450
			useIgnores: this.inputPatternExcludes.useExcludesAndIgnoreFiles(),
			showIncludesExcludes: this.showingIncludesExcludes
451
		};
J
Jackson Kearl 已提交
452 453 454
	}

	private async doRunSearch() {
J
Jackson Kearl 已提交
455 456
		this.searchModel.cancelSearch(true);

J
Jackson Kearl 已提交
457 458 459 460 461 462 463 464 465
		const startInput = this.getInput();

		this.searchHistoryDelayer.trigger(() => {
			this.queryEditorWidget.searchInput.onSearchSubmit();
			this.inputPatternExcludes.onSearchSubmit();
			this.inputPatternIncludes.onSearchSubmit();
		});

		const config: SearchConfiguration = this.readConfigFromWidget();
466

467 468
		if (!config.query) { return; }

469 470 471 472 473 474 475 476 477 478 479
		const content: IPatternInfo = {
			pattern: config.query,
			isRegExp: config.regexp,
			isCaseSensitive: config.caseSensitive,
			isWordMatch: config.wholeWord,
		};

		const options: ITextQueryBuilderOptions = {
			_reason: 'searchEditor',
			extraFileResources: this.instantiationService.invokeFunction(getOutOfWorkspaceEditorResources),
			maxResults: 10000,
480 481
			disregardIgnoreFiles: !config.useIgnores || undefined,
			disregardExcludeSettings: !config.useIgnores || undefined,
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
			excludePattern: config.excludes,
			includePattern: config.includes,
			previewOptions: {
				matchLines: 1,
				charsPerLine: 1000
			},
			afterContext: config.contextLines,
			beforeContext: config.contextLines,
			isSmartCase: this.configurationService.getValue<ISearchConfigurationProperties>('search').smartCase,
			expandPatterns: true
		};

		const folderResources = this.contextService.getWorkspace().folders;
		let query: ITextQuery;
		try {
			const queryBuilder = this.instantiationService.createInstance(QueryBuilder);
			query = queryBuilder.text(content, folderResources.map(folder => folder.uri), options);
		}
		catch (err) {
			return;
		}
J
Jackson Kearl 已提交
503

504
		this.searchOperation.start(500);
505 506 507 508 509 510 511 512
		this.ongoingOperations++;
		const exit = await this.searchModel.search(query).finally(() => {
			this.ongoingOperations--;
			if (this.ongoingOperations === 0) {
				this.searchOperation.stop();
			}
		});

J
Jackson Kearl 已提交
513
		const input = this.getInput();
J
Jackson Kearl 已提交
514 515 516
		if (!input ||
			input !== startInput ||
			JSON.stringify(config) !== JSON.stringify(this.readConfigFromWidget())) {
517 518 519
			return;
		}

520
		const sortOrder = this.configurationService.getValue<ISearchConfigurationProperties>('search').sortOrder;
521 522
		const controller = ReferencesController.get(this.searchResultEditor);
		controller.closeWidget(false);
523
		const labelFormatter = (uri: URI): string => this.labelService.getUriLabel(uri, { relative: true });
524
		const results = serializeSearchResultForEditor(this.searchModel.searchResult, config.includes, config.excludes, config.contextLines, labelFormatter, sortOrder, exit?.limitHit);
525
		const { body } = await input.getModels();
526
		this.modelService.updateModel(body, results.text);
527
		input.config = config;
528

529
		input.setDirty(!input.isUntitled());
530
		input.setMatchRanges(results.matchRanges);
531 532 533 534 535 536 537
	}

	layout(dimension: DOM.Dimension) {
		this.dimension = dimension;
		this.reLayout();
	}

538 539 540 541 542 543 544 545
	getSelected() {
		const selection = this.searchResultEditor.getSelection();
		if (selection) {
			return this.searchResultEditor.getModel()?.getValueInRange(selection) ?? '';
		}
		return '';
	}

546 547 548 549 550 551 552 553 554
	private reLayout() {
		if (this.dimension) {
			this.queryEditorWidget.setWidth(this.dimension.width - 28 /* container margin */);
			this.searchResultEditor.layout({ height: this.dimension.height - DOM.getTotalHeight(this.queryEditorContainer), width: this.dimension.width });
			this.inputPatternExcludes.setWidth(this.dimension.width - 28 /* container margin */);
			this.inputPatternIncludes.setWidth(this.dimension.width - 28 /* container margin */);
		}
	}

J
Jackson Kearl 已提交
555 556 557 558
	private getInput(): SearchEditorInput | undefined {
		return this._input as SearchEditorInput;
	}

559
	async setInput(newInput: SearchEditorInput, options: EditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> {
J
Jackson Kearl 已提交
560 561
		this.saveViewState();

562
		await super.setInput(newInput, options, context, token);
J
Jackson Kearl 已提交
563
		if (token.isCancellationRequested) { return; }
564

565
		const { body, config } = await newInput.getModels();
J
Jackson Kearl 已提交
566
		if (token.isCancellationRequested) { return; }
567

568
		this.searchResultEditor.setModel(body);
569
		this.pauseSearching = true;
570

571
		this.toggleRunAgainMessage(body.getLineCount() === 1 && body.getValue() === '' && config.query !== '');
572

573
		this.queryEditorWidget.setValue(config.query);
574 575 576 577 578 579 580 581
		this.queryEditorWidget.searchInput.setCaseSensitive(config.caseSensitive);
		this.queryEditorWidget.searchInput.setRegex(config.regexp);
		this.queryEditorWidget.searchInput.setWholeWords(config.wholeWord);
		this.queryEditorWidget.setContextLines(config.contextLines);
		this.inputPatternExcludes.setValue(config.excludes);
		this.inputPatternIncludes.setValue(config.includes);
		this.inputPatternExcludes.setUseExcludesAndIgnoreFiles(config.useIgnores);
		this.toggleIncludesExcludes(config.showIncludesExcludes);
582

J
Jackson Kearl 已提交
583
		this.restoreViewState();
J
Jackson Kearl 已提交
584 585 586 587 588

		if (!options?.preserveFocus) {
			this.focus();
		}

589 590 591
		this.pauseSearching = false;
	}

592
	private toggleIncludesExcludes(_shouldShow?: boolean): void {
593
		const cls = 'expanded';
594
		const shouldShow = _shouldShow ?? !DOM.hasClass(this.includesExcludesContainer, cls);
595 596 597 598 599 600 601 602 603

		if (shouldShow) {
			this.toggleQueryDetailsButton.setAttribute('aria-expanded', 'true');
			DOM.addClass(this.includesExcludesContainer, cls);
		} else {
			this.toggleQueryDetailsButton.setAttribute('aria-expanded', 'false');
			DOM.removeClass(this.includesExcludesContainer, cls);
		}

604 605
		this.showingIncludesExcludes = DOM.hasClass(this.includesExcludesContainer, cls);

606 607 608
		this.reLayout();
	}

609 610 611
	saveState() {
		this.saveViewState();
		super.saveState();
612
	}
613

J
Jackson Kearl 已提交
614
	private saveViewState() {
615
		const resource = this.getInput()?.modelUri;
J
Jackson Kearl 已提交
616 617
		if (resource) { this.saveTextEditorViewState(resource); }
	}
J
Jackson Kearl 已提交
618

J
Jackson Kearl 已提交
619 620 621 622
	protected retrieveTextEditorViewState(resource: URI): SearchEditorViewState | null {
		const control = this.getControl();
		const editorViewState = control.saveViewState();
		if (!editorViewState) { return null; }
623
		if (resource.toString() !== this.getInput()?.modelUri.toString()) { return null; }
J
Jackson Kearl 已提交
624 625

		return { ...editorViewState, focused: this.searchResultEditor.hasWidgetFocus() ? 'editor' : 'input' };
J
Jackson Kearl 已提交
626 627
	}

628
	private loadViewState() {
629
		const resource = assertIsDefined(this.getInput()?.modelUri);
J
Jackson Kearl 已提交
630
		return this.loadTextEditorViewState(resource) as SearchEditorViewState;
631 632 633 634
	}

	private restoreViewState() {
		const viewState = this.loadViewState();
J
Jackson Kearl 已提交
635
		if (viewState) { this.searchResultEditor.restoreViewState(viewState); }
J
Jackson Kearl 已提交
636 637
	}

638
	clearInput() {
J
Jackson Kearl 已提交
639
		this.saveViewState();
640
		super.clearInput();
641
	}
J
Jackson Kearl 已提交
642 643

	getAriaLabel() {
I
isidor 已提交
644
		return this.getInput()?.getName() ?? localize('searchEditor', "Search");
J
Jackson Kearl 已提交
645
	}
646
}
647 648

registerThemingParticipant((theme, collector) => {
649
	collector.addRule(`.monaco-editor .${SearchEditorFindMatchClass} { background-color: ${theme.getColor(searchEditorFindMatch)}; }`);
650 651 652

	const findMatchHighlightBorder = theme.getColor(searchEditorFindMatchBorder);
	if (findMatchHighlightBorder) {
653
		collector.addRule(`.monaco-editor .${SearchEditorFindMatchClass} { border: 1px ${theme.type === 'hc' ? 'dotted' : 'solid'} ${findMatchHighlightBorder}; box-sizing: border-box; }`);
654 655
	}
});
656 657

export const searchEditorTextInputBorder = registerColor('searchEditor.textInputBorder', { dark: inputBorder, light: inputBorder, hc: inputBorder }, localize('textInputBoxBorder', "Search editor text input box border."));
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678

function findNextRange(matchRanges: Range[], currentPosition: Position) {
	for (const matchRange of matchRanges) {
		if (Position.isBefore(currentPosition, matchRange.getStartPosition())) {
			return matchRange;
		}
	}
	return matchRanges[0];
}

function findPrevRange(matchRanges: Range[], currentPosition: Position) {
	for (let i = matchRanges.length - 1; i >= 0; i--) {
		const matchRange = matchRanges[i];
		if (Position.isBefore(matchRange.getStartPosition(), currentPosition)) {
			{
				return matchRange;
			}
		}
	}
	return matchRanges[matchRanges.length - 1];
}