-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathSearchAddon.ts
More file actions
316 lines (274 loc) · 10.2 KB
/
Copy pathSearchAddon.ts
File metadata and controls
316 lines (274 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/**
* Copyright (c) 2017 The xterm.js authors. All rights reserved.
* @license MIT
*/
import type { Terminal, IDisposable, ITerminalAddon } from "@xterm/xterm";
import type {
SearchAddon as ISearchApi,
ISearchOptions,
ISearchAddonOptions,
ISearchResultChangeEvent,
ISearchDecorationOptions,
} from "@xterm/addon-search";
import { Emitter, type IEvent } from "common/Event";
import { Disposable, MutableDisposable, toDisposable } from "common/Lifecycle";
import { disposableTimeout } from "common/Async";
import { SearchLineCache } from "./SearchLineCache";
import { SearchState } from "./SearchState";
import { SearchEngine, type ISearchResult } from "./SearchEngine";
import { DecorationManager } from "./DecorationManager";
import { SearchResultTracker } from "./SearchResultTracker";
interface IInternalSearchOptions {
noScroll: boolean;
}
/**
* Configuration constants for the search addon functionality.
*/
const enum Constants {
/**
* Default maximum number of search results to highlight simultaneously. This limit prevents
* performance degradation when searching for very common terms that would result in excessive
* highlighting decorations.
*/
DEFAULT_HIGHLIGHT_LIMIT = 1000,
}
export class SearchAddon extends Disposable implements ITerminalAddon, ISearchApi {
private _terminal: Terminal | undefined;
private _highlightLimit: number;
private _highlightTimeout = this._register(new MutableDisposable<IDisposable>());
private _lineCache = this._register(new MutableDisposable<SearchLineCache>());
// Component instances
private _state = new SearchState();
private _engine: SearchEngine | undefined;
private _decorationManager: DecorationManager | undefined;
private _resultTracker = this._register(new SearchResultTracker());
private readonly _onAfterSearch = this._register(new Emitter<void>());
public readonly onAfterSearch = this._onAfterSearch.event;
private readonly _onBeforeSearch = this._register(new Emitter<void>());
public readonly onBeforeSearch = this._onBeforeSearch.event;
public get onDidChangeResults(): IEvent<ISearchResultChangeEvent> {
return this._resultTracker.onDidChangeResults;
}
constructor(options?: Partial<ISearchAddonOptions>) {
super();
this._highlightLimit = options?.highlightLimit ?? Constants.DEFAULT_HIGHLIGHT_LIMIT;
}
public activate(terminal: Terminal): void {
this._terminal = terminal;
this._lineCache.value = new SearchLineCache(terminal);
this._engine = new SearchEngine(terminal, this._lineCache.value);
this._decorationManager = new DecorationManager(terminal);
this._register(this._terminal.onWriteParsed(() => this._updateMatches()));
this._register(this._terminal.onResize(() => this._updateMatches()));
this._register(toDisposable(() => this.clearDecorations()));
}
private _updateMatches(): void {
this._highlightTimeout.clear();
if (this._state.cachedSearchTerm && this._state.lastSearchOptions?.decorations) {
this._highlightTimeout.value = disposableTimeout(() => {
const term = this._state.cachedSearchTerm;
this._state.clearCachedTerm();
this.findPrevious(
term!,
{ ...this._state.lastSearchOptions, incremental: true },
{ noScroll: true }
);
}, 200);
}
}
public clearDecorations(retainCachedSearchTerm?: boolean): void {
this._resultTracker.clearSelectedDecoration();
this._decorationManager?.clearHighlightDecorations();
this._resultTracker.clearResults();
if (!retainCachedSearchTerm) {
this._state.clearCachedTerm();
}
}
public clearActiveDecoration(): void {
this._resultTracker.clearSelectedDecoration();
}
/**
* Find the next instance of the term, then scroll to and select it. If it
* doesn't exist, do nothing.
* @param term The search term.
* @param searchOptions Search options.
* @returns Whether a result was found.
*/
public findNext(
term: string,
searchOptions?: ISearchOptions,
internalSearchOptions?: IInternalSearchOptions
): boolean {
if (!this._terminal || !this._engine) {
throw new Error("Cannot use addon until it has been loaded");
}
this._onBeforeSearch.fire();
this._state.lastSearchOptions = searchOptions;
if (this._state.shouldUpdateHighlighting(term, searchOptions)) {
this._highlightAllMatches(term, searchOptions!);
}
const found = this._findNextAndSelect(term, searchOptions, internalSearchOptions);
this._fireResults(searchOptions);
this._state.cachedSearchTerm = term;
this._onAfterSearch.fire();
return found;
}
private _highlightAllMatches(term: string, searchOptions: ISearchOptions): void {
if (!this._terminal || !this._engine || !this._decorationManager) {
throw new Error("Cannot use addon until it has been loaded");
}
if (!this._state.isValidSearchTerm(term)) {
this.clearDecorations();
return;
}
// If the new term is just an extension of the previous term (e.g. "hel" → "hell"),
// filter the existing results instead of scanning the entire buffer again.
const existingResults = this._resultTracker.searchResults;
if (this._state.isIncrementalExtension(term, searchOptions) && existingResults.length > 0) {
const compare = searchOptions?.caseSensitive
? (s: string) => s
: (s: string) => s.toLowerCase();
const needle = compare(term);
const filtered = (existingResults as ISearchResult[]).filter(
(r) => compare(r.term) === needle
);
this.clearDecorations(true);
this._resultTracker.updateResults(filtered, this._highlightLimit);
if (searchOptions.decorations) {
this._decorationManager.createHighlightDecorations(filtered, searchOptions.decorations);
}
return;
}
// Full search — original behavior
this.clearDecorations(true);
const results: ISearchResult[] = [];
let prevResult: ISearchResult | undefined = undefined;
let result = this._engine.find(term, 0, 0, searchOptions);
while (result && (prevResult?.row !== result.row || prevResult?.col !== result.col)) {
if (results.length >= this._highlightLimit) {
break;
}
prevResult = result;
results.push(prevResult);
result = this._engine.find(
term,
prevResult.col + prevResult.term.length >= this._terminal.cols
? prevResult.row + 1
: prevResult.row,
prevResult.col + prevResult.term.length >= this._terminal.cols ? 0 : prevResult.col + 1,
searchOptions
);
}
this._resultTracker.updateResults(results, this._highlightLimit);
if (searchOptions.decorations) {
this._decorationManager.createHighlightDecorations(results, searchOptions.decorations);
}
}
private _findNextAndSelect(
term: string,
searchOptions?: ISearchOptions,
internalSearchOptions?: IInternalSearchOptions
): boolean {
if (!this._terminal || !this._engine) {
return false;
}
if (!this._state.isValidSearchTerm(term)) {
this._terminal.clearSelection();
this.clearDecorations();
return false;
}
const result = this._engine.findNextWithSelection(
term,
searchOptions,
this._state.cachedSearchTerm
);
return this._selectResult(result, searchOptions?.decorations, internalSearchOptions?.noScroll);
}
/**
* Find the previous instance of the term, then scroll to and select it. If it
* doesn't exist, do nothing.
* @param term The search term.
* @param searchOptions Search options.
* @returns Whether a result was found.
*/
public findPrevious(
term: string,
searchOptions?: ISearchOptions,
internalSearchOptions?: IInternalSearchOptions
): boolean {
if (!this._terminal || !this._engine) {
throw new Error("Cannot use addon until it has been loaded");
}
this._onBeforeSearch.fire();
this._state.lastSearchOptions = searchOptions;
if (this._state.shouldUpdateHighlighting(term, searchOptions)) {
this._highlightAllMatches(term, searchOptions!);
}
const found = this._findPreviousAndSelect(term, searchOptions, internalSearchOptions);
this._fireResults(searchOptions);
this._state.cachedSearchTerm = term;
this._onAfterSearch.fire();
return found;
}
private _fireResults(searchOptions?: ISearchOptions): void {
this._resultTracker.fireResultsChanged(!!searchOptions?.decorations);
}
private _findPreviousAndSelect(
term: string,
searchOptions?: ISearchOptions,
internalSearchOptions?: IInternalSearchOptions
): boolean {
if (!this._terminal || !this._engine) {
return false;
}
if (!this._state.isValidSearchTerm(term)) {
this._terminal.clearSelection();
this.clearDecorations();
return false;
}
const result = this._engine.findPreviousWithSelection(
term,
searchOptions,
this._state.cachedSearchTerm
);
return this._selectResult(result, searchOptions?.decorations, internalSearchOptions?.noScroll);
}
/**
* Selects and scrolls to a result.
* @param result The result to select.
* @returns Whether a result was selected.
*/
private _selectResult(
result: ISearchResult | undefined,
options?: ISearchDecorationOptions,
noScroll?: boolean
): boolean {
if (!this._terminal || !this._decorationManager) {
return false;
}
this._resultTracker.clearSelectedDecoration();
if (!result) {
this._terminal.clearSelection();
return false;
}
this._terminal.select(result.col, result.row, result.size);
if (options) {
const activeDecoration = this._decorationManager.createActiveDecoration(result, options);
if (activeDecoration) {
this._resultTracker.selectedDecoration = activeDecoration;
}
}
if (!noScroll) {
// If it is not in the viewport then we scroll else it just gets selected
if (
result.row >= this._terminal.buffer.active.viewportY + this._terminal.rows ||
result.row < this._terminal.buffer.active.viewportY
) {
let scroll = result.row - this._terminal.buffer.active.viewportY;
scroll -= Math.floor(this._terminal.rows / 2);
this._terminal.scrollLines(scroll);
}
}
return true;
}
}