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

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

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

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

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

64 65 66 67 68 69 70 71
	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;
72
	private messageBox!: HTMLElement;
73

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

	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,
92
		@IInstantiationService readonly instantiationService: IInstantiationService,
93 94
		@IContextViewService private readonly contextViewService: IContextViewService,
		@ICommandService private readonly commandService: ICommandService,
95
		@IContextKeyService readonly contextKeyService: IContextKeyService,
96
		@IEditorProgressService readonly progressService: IEditorProgressService,
J
Jackson Kearl 已提交
97 98 99 100
		@ITextResourceConfigurationService textResourceService: ITextResourceConfigurationService,
		@IEditorGroupsService protected editorGroupService: IEditorGroupsService,
		@IEditorService protected editorService: IEditorService,
		@IConfigurationService protected configurationService: IConfigurationService,
101
	) {
J
Jackson Kearl 已提交
102
		super(SearchEditor.ID, telemetryService, instantiationService, storageService, textResourceService, themeService, editorService, editorGroupService);
103 104
		this.container = DOM.$('.search-editor');

105

106 107 108 109 110 111
		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);
112
		this.searchOperation = this._register(new LongRunningOperation(progressService));
J
Jackson Kearl 已提交
113
		this.searchHistoryDelayer = new Delayer<void>(2000);
J
Jackson Kearl 已提交
114 115

		this.searchModel = this._register(this.instantiationService.createInstance(SearchModel));
116 117 118
	}

	createEditor(parent: HTMLElement) {
119
		DOM.append(parent, this.container);
120

121 122
		this.createQueryEditor(this.container);
		this.createResultsEditor(this.container);
123
	}
124

125 126
	private createQueryEditor(parent: HTMLElement) {
		this.queryEditorContainer = DOM.append(parent, DOM.$('.query-container'));
127 128 129
		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()));
130 131 132
		this.queryEditorWidget.onSearchSubmit(({ delay }) => this.triggerSearch({ delay }));
		this.queryEditorWidget.searchInput.onDidOptionChange(() => this.triggerSearch({ resetCursor: false }));
		this.queryEditorWidget.onDidToggleContext(() => this.triggerSearch({ resetCursor: false }));
133 134 135

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

137 138 139 140
		// // Toggle query details button
		this.toggleQueryDetailsButton = DOM.append(this.includesExcludesContainer, DOM.$('.expand.codicon.codicon-ellipsis', { tabindex: 0, role: 'button', title: localize('moreSearch', "Toggle Search Details") }));
		this._register(DOM.addDisposableListener(this.toggleQueryDetailsButton, DOM.EventType.CLICK, e => {
			DOM.EventHelper.stop(e);
141
			this.toggleIncludesExcludes();
142 143 144 145 146
		}));
		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);
147
				this.toggleIncludesExcludes();
148 149 150 151 152 153 154
			}
		}));
		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();
155 156
				}
				else {
157 158 159 160 161 162 163 164 165 166 167 168 169
					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'),
		}));
170
		this.inputPatternIncludes.onSubmit(triggeredOnType => this.triggerSearch({ resetCursor: false, delay: triggeredOnType ? this.searchConfig.searchOnTypeDebouncePeriod : 0 }));
171 172 173 174 175 176 177 178

		// // 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'),
		}));
179 180
		this.inputPatternExcludes.onSubmit(triggeredOnType => this.triggerSearch({ resetCursor: false, delay: triggeredOnType ? this.searchConfig.searchOnTypeDebouncePeriod : 0 }));
		this.inputPatternExcludes.onChangeIgnoreBox(() => this.triggerSearch());
181 182 183

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

		// 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 已提交
195
			const runAgainLink = DOM.append(this.messageBox, DOM.$('a.pointer.prominent.message', {}, localize('runSearch', "Run Search")));
196
			this.messageDisposables.push(DOM.addDisposableListener(runAgainLink, DOM.EventType.CLICK, async () => {
197
				await this.triggerSearch();
J
Jackson Kearl 已提交
198
				this.searchResultEditor.focus();
199 200 201
				this.toggleRunAgainMessage(false);
			}));
		}
202
	}
203

204
	private createResultsEditor(parent: HTMLElement) {
205
		const searchResultContainer = DOM.append(parent, DOM.$('.search-results'));
J
Jackson Kearl 已提交
206 207
		super.createEditor(searchResultContainer);
		this.searchResultEditor = super.getControl() as CodeEditorWidget;
208 209
		this.searchResultEditor.onMouseUp(e => {
			if (e.event.detail === 2) {
210
				const behaviour = this.configurationService.getValue<ISearchConfigurationProperties>('search').searchEditor.doubleClickBehaviour;
211 212 213 214 215 216
				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');
217 218 219
					} else if (line.match(FILE_LINE_REGEX)) {
						this.searchResultEditor.setSelection(Range.fromPositions(position));
						this.commandService.executeCommand('editor.action.peekDefinition');
220 221 222 223
					}
				}
			}
		});
224

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

227 228
		this._register(this.searchResultEditor.onKeyDown(e => e.keyCode === KeyCode.Escape && this.queryEditorWidget.searchInput.focus()));

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 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
	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 已提交
275
			// unreachable.
276
		}
277 278
	}

279 280
	toggleWholeWords() {
		this.queryEditorWidget.searchInput.setWholeWords(!this.queryEditorWidget.searchInput.getWholeWords());
281
		this.triggerSearch({ resetCursor: false });
282 283 284 285
	}

	toggleRegex() {
		this.queryEditorWidget.searchInput.setRegex(!this.queryEditorWidget.searchInput.getRegex());
286
		this.triggerSearch({ resetCursor: false });
287 288 289 290
	}

	toggleCaseSensitive() {
		this.queryEditorWidget.searchInput.setCaseSensitive(!this.queryEditorWidget.searchInput.getCaseSensitive());
291
		this.triggerSearch({ resetCursor: false });
292 293
	}

294 295 296 297
	toggleContextLines() {
		this.queryEditorWidget.toggleContextLines();
	}

298 299 300 301
	toggleQueryDetails() {
		this.toggleIncludesExcludes();
	}

302 303 304 305
	cleanState() {
		this.getInput()?.setDirty(false);
	}

306 307 308 309
	private get searchConfig(): ISearchConfigurationProperties {
		return this.configurationService.getValue<ISearchConfigurationProperties>('search');
	}

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
	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();
329 330 331 332 333 334 335 336 337

		const matchLineText = model.getLineContent(matchRange.startLineNumber);
		const matchText = model.getValueInRange(matchRange);
		let file = '';
		for (let line = matchRange.startLineNumber; line >= 1; line--) {
			let lineText = model.getValueInRange(new Range(line, 1, line, 2));
			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)));
338 339 340 341 342 343 344 345 346 347
	}

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

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

348 349 350 351 352 353 354
	focusAllResults() {
		this.searchResultEditor
			.setSelections((this.getInput()?.getMatchRanges() ?? []).map(
				range => new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn)));
		this.searchResultEditor.focus();
	}

355 356 357
	async triggerSearch(_options?: { resetCursor?: boolean; delay?: number; }) {
		const options = { resetCursor: true, delay: 0, ..._options };

358
		if (!this.pauseSearching) {
359
			await this.runSearchDelayer.trigger(async () => {
J
Jackson Kearl 已提交
360
				await this.doRunSearch();
361
				this.toggleRunAgainMessage(false);
362
				if (options.resetCursor) {
363
					this.searchResultEditor.setPosition(new Position(1, 1));
J
Jackson Kearl 已提交
364
					this.searchResultEditor.setScrollPosition({ scrollTop: 0, scrollLeft: 0 });
J
Jackson Kearl 已提交
365
				}
366
			}, options.delay);
367 368 369
		}
	}

J
Jackson Kearl 已提交
370 371
	private readConfigFromWidget() {
		return {
372 373 374 375 376 377 378
			caseSensitive: this.queryEditorWidget.searchInput.getCaseSensitive(),
			contextLines: this.queryEditorWidget.contextLines(),
			excludes: this.inputPatternExcludes.getValue(),
			includes: this.inputPatternIncludes.getValue(),
			query: this.queryEditorWidget.searchInput.getValue(),
			regexp: this.queryEditorWidget.searchInput.getRegex(),
			wholeWord: this.queryEditorWidget.searchInput.getWholeWords(),
379 380
			useIgnores: this.inputPatternExcludes.useExcludesAndIgnoreFiles(),
			showIncludesExcludes: this.showingIncludesExcludes
381
		};
J
Jackson Kearl 已提交
382 383 384
	}

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

J
Jackson Kearl 已提交
387 388 389 390 391 392 393 394 395
		const startInput = this.getInput();

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

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

397 398
		if (!config.query) { return; }

399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
		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,
			disregardIgnoreFiles: !config.useIgnores,
			disregardExcludeSettings: !config.useIgnores,
			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 已提交
433

434
		this.searchOperation.start(500);
J
Jackson Kearl 已提交
435
		await this.searchModel.search(query).finally(() => this.searchOperation.stop());
J
Jackson Kearl 已提交
436
		const input = this.getInput();
J
Jackson Kearl 已提交
437 438 439
		if (!input ||
			input !== startInput ||
			JSON.stringify(config) !== JSON.stringify(this.readConfigFromWidget())) {
440 441 442
			return;
		}

443 444
		const controller = ReferencesController.get(this.searchResultEditor);
		controller.closeWidget(false);
445
		const labelFormatter = (uri: URI): string => this.labelService.getUriLabel(uri, { relative: true });
J
Jackson Kearl 已提交
446
		const results = serializeSearchResultForEditor(this.searchModel.searchResult, config.includes, config.excludes, config.contextLines, labelFormatter, false);
J
Jackson Kearl 已提交
447
		const { header, body } = await input.getModels();
448 449
		this.modelService.updateModel(body, results.text);
		header.setValue(serializeSearchConfiguration(config));
450

J
Jackson Kearl 已提交
451
		input.setDirty(input.resource.scheme !== 'search-editor');
452
		input.setMatchRanges(results.matchRanges);
453 454 455 456 457 458 459
	}

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

460 461 462 463 464 465 466 467
	getSelected() {
		const selection = this.searchResultEditor.getSelection();
		if (selection) {
			return this.searchResultEditor.getModel()?.getValueInRange(selection) ?? '';
		}
		return '';
	}

468 469 470 471 472 473 474 475 476
	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 已提交
477 478 479 480
	private getInput(): SearchEditorInput | undefined {
		return this._input as SearchEditorInput;
	}

481
	async setInput(newInput: SearchEditorInput, options: EditorOptions | undefined, token: CancellationToken): Promise<void> {
J
Jackson Kearl 已提交
482 483
		this.saveViewState();

484 485
		await super.setInput(newInput, options, token);

486
		const { body, header } = await newInput.getModels();
487

488
		this.searchResultEditor.setModel(body);
489
		this.pauseSearching = true;
490

491
		const config = extractSearchQuery(header);
492
		this.toggleRunAgainMessage(body.getLineCount() === 1 && body.getValue() === '' && config.query !== '');
493

494
		this.queryEditorWidget.setValue(config.query);
495 496 497 498 499 500 501 502
		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);
503

J
Jackson Kearl 已提交
504
		this.restoreViewState();
J
Jackson Kearl 已提交
505 506 507 508 509

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

510 511 512
		this.pauseSearching = false;
	}

513
	private toggleIncludesExcludes(_shouldShow?: boolean): void {
514
		const cls = 'expanded';
515
		const shouldShow = _shouldShow ?? !DOM.hasClass(this.includesExcludesContainer, cls);
516 517 518 519 520 521 522 523 524

		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);
		}

525 526
		this.showingIncludesExcludes = DOM.hasClass(this.includesExcludesContainer, cls);

527 528 529
		this.reLayout();
	}

530 531 532
	saveState() {
		this.saveViewState();
		super.saveState();
533
	}
534

J
Jackson Kearl 已提交
535
	private saveViewState() {
J
Jackson Kearl 已提交
536 537 538
		const resource = this.getInput()?.resource;
		if (resource) { this.saveTextEditorViewState(resource); }
	}
J
Jackson Kearl 已提交
539

J
Jackson Kearl 已提交
540 541 542 543 544 545 546
	protected retrieveTextEditorViewState(resource: URI): SearchEditorViewState | null {
		const control = this.getControl();
		const editorViewState = control.saveViewState();
		if (!editorViewState) { return null; }
		if (resource.toString() !== this.getInput()?.resource.toString()) { return null; }

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

549
	private loadViewState() {
550
		const resource = assertIsDefined(this.input?.resource);
J
Jackson Kearl 已提交
551
		return this.loadTextEditorViewState(resource) as SearchEditorViewState;
552 553 554 555
	}

	private restoreViewState() {
		const viewState = this.loadViewState();
J
Jackson Kearl 已提交
556
		if (viewState) { this.searchResultEditor.restoreViewState(viewState); }
J
Jackson Kearl 已提交
557 558
	}

559
	clearInput() {
J
Jackson Kearl 已提交
560
		this.saveViewState();
561
		super.clearInput();
562
	}
J
Jackson Kearl 已提交
563 564 565 566

	getAriaLabel() {
		return this.getInput()?.getName() ?? localize('searchEditor', "Search Editor");
	}
567
}
568 569

registerThemingParticipant((theme, collector) => {
570
	collector.addRule(`.monaco-editor .${SearchEditorFindMatchClass} { background-color: ${theme.getColor(searchEditorFindMatch)}; }`);
571 572 573

	const findMatchHighlightBorder = theme.getColor(searchEditorFindMatchBorder);
	if (findMatchHighlightBorder) {
574
		collector.addRule(`.monaco-editor .${SearchEditorFindMatchClass} { border: 1px ${theme.type === 'hc' ? 'dotted' : 'solid'} ${findMatchHighlightBorder}; box-sizing: border-box; }`);
575 576
	}
});
577 578

export const searchEditorTextInputBorder = registerColor('searchEditor.textInputBorder', { dark: inputBorder, light: inputBorder, hc: inputBorder }, localize('textInputBoxBorder', "Search editor text input box border."));
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599

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];
}