-
Notifications
You must be signed in to change notification settings - Fork 30.4k
/
Copy pathgotoSymbolHandler.ts
586 lines (471 loc) · 17.7 KB
/
gotoSymbolHandler.ts
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
317
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/css!vs/editor/contrib/documentSymbols/media/symbol-icons';
import { TPromise } from 'vs/base/common/winjs.base';
import * as nls from 'vs/nls';
import * as types from 'vs/base/common/types';
import * as strings from 'vs/base/common/strings';
import { IEntryRunContext, Mode, IAutoFocus } from 'vs/base/parts/quickopen/common/quickOpen';
import { QuickOpenModel, IHighlight } from 'vs/base/parts/quickopen/browser/quickOpenModel';
import { QuickOpenHandler, EditorQuickOpenEntryGroup, QuickOpenAction } from 'vs/workbench/browser/quickopen';
import * as filters from 'vs/base/common/filters';
import { IEditor, IDiffEditorModel, IEditorViewState, ScrollType } from 'vs/editor/common/editorCommon';
import { IModelDecorationsChangeAccessor, OverviewRulerLane, IModelDeltaDecoration, ITextModel } from 'vs/editor/common/model';
import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen';
import { ITextEditorOptions } from 'vs/platform/editor/common/editor';
import { getDocumentSymbols } from 'vs/editor/contrib/quickOpen/quickOpen';
import { DocumentSymbolProviderRegistry, DocumentSymbol, symbolKindToCssClass } from 'vs/editor/common/modes';
import { IRange } from 'vs/editor/common/core/range';
import { themeColorFromId } from 'vs/platform/theme/common/themeService';
import { overviewRulerRangeHighlight } from 'vs/editor/common/view/editorColorRegistry';
import { GroupIdentifier, IEditorInput } from 'vs/workbench/common/editor';
import { IEditorService, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { IEditorGroup } from 'vs/workbench/services/group/common/editorGroupsService';
import { asWinJsPromise } from 'vs/base/common/async';
export const GOTO_SYMBOL_PREFIX = '@';
export const SCOPE_PREFIX = ':';
export class GotoSymbolAction extends QuickOpenAction {
static readonly ID = 'workbench.action.gotoSymbol';
static readonly LABEL = nls.localize('gotoSymbol', "Go to Symbol in File...");
constructor(actionId: string, actionLabel: string, @IQuickOpenService quickOpenService: IQuickOpenService) {
super(actionId, actionLabel, GOTO_SYMBOL_PREFIX, quickOpenService);
}
}
class OutlineModel extends QuickOpenModel {
applyFilter(searchValue: string): void {
// Normalize search
let normalizedSearchValue = searchValue;
if (searchValue.indexOf(SCOPE_PREFIX) === 0) {
normalizedSearchValue = normalizedSearchValue.substr(SCOPE_PREFIX.length);
}
// Check for match and update visibility and group label
this.entries.forEach((entry: SymbolEntry) => {
// Clear all state first
entry.setGroupLabel(null);
entry.setShowBorder(false);
entry.setHighlights(null);
entry.setHidden(false);
// Filter by search
if (normalizedSearchValue) {
const highlights = filters.matchesFuzzy(normalizedSearchValue, entry.getLabel());
if (highlights) {
entry.setHighlights(highlights);
entry.setHidden(false);
} else if (!entry.isHidden()) {
entry.setHidden(true);
}
}
});
// Sort properly if actually searching
if (searchValue) {
if (searchValue.indexOf(SCOPE_PREFIX) === 0) {
this.entries.sort(this.sortScoped.bind(this, searchValue.toLowerCase()));
} else {
this.entries.sort(this.sortNormal.bind(this, searchValue.toLowerCase()));
}
}
// Otherwise restore order as appearing in outline
else {
this.entries.sort((a: SymbolEntry, b: SymbolEntry) => a.getIndex() - b.getIndex());
}
// Mark all type groups
const visibleResults = <SymbolEntry[]>this.getEntries(true);
if (visibleResults.length > 0 && searchValue.indexOf(SCOPE_PREFIX) === 0) {
let currentType: string = null;
let currentResult: SymbolEntry = null;
let typeCounter = 0;
for (let i = 0; i < visibleResults.length; i++) {
const result = visibleResults[i];
// Found new type
if (currentType !== result.getType()) {
// Update previous result with count
if (currentResult) {
currentResult.setGroupLabel(this.renderGroupLabel(currentType, typeCounter));
}
currentType = result.getType();
currentResult = result;
typeCounter = 1;
result.setShowBorder(i > 0);
}
// Existing type, keep counting
else {
typeCounter++;
}
}
// Update previous result with count
if (currentResult) {
currentResult.setGroupLabel(this.renderGroupLabel(currentType, typeCounter));
}
}
// Mark first entry as outline
else if (visibleResults.length > 0) {
visibleResults[0].setGroupLabel(nls.localize('symbols', "symbols ({0})", visibleResults.length));
}
}
private sortNormal(searchValue: string, elementA: SymbolEntry, elementB: SymbolEntry): number {
// Handle hidden elements
if (elementA.isHidden() && elementB.isHidden()) {
return 0;
} else if (elementA.isHidden()) {
return 1;
} else if (elementB.isHidden()) {
return -1;
}
const elementAName = elementA.getLabel().toLowerCase();
const elementBName = elementB.getLabel().toLowerCase();
// Compare by name
const r = elementAName.localeCompare(elementBName);
if (r !== 0) {
return r;
}
// If name identical sort by range instead
const elementARange = elementA.getRange();
const elementBRange = elementB.getRange();
return elementARange.startLineNumber - elementBRange.startLineNumber;
}
private sortScoped(searchValue: string, elementA: SymbolEntry, elementB: SymbolEntry): number {
// Handle hidden elements
if (elementA.isHidden() && elementB.isHidden()) {
return 0;
} else if (elementA.isHidden()) {
return 1;
} else if (elementB.isHidden()) {
return -1;
}
// Remove scope char
searchValue = searchValue.substr(SCOPE_PREFIX.length);
// Sort by type first if scoped search
const elementAType = elementA.getType();
const elementBType = elementB.getType();
let r = elementAType.localeCompare(elementBType);
if (r !== 0) {
return r;
}
// Special sort when searching in scoped mode
if (searchValue) {
const elementAName = elementA.getLabel().toLowerCase();
const elementBName = elementB.getLabel().toLowerCase();
// Compare by name
r = elementAName.localeCompare(elementBName);
if (r !== 0) {
return r;
}
}
// Default to sort by range
const elementARange = elementA.getRange();
const elementBRange = elementB.getRange();
return elementARange.startLineNumber - elementBRange.startLineNumber;
}
private renderGroupLabel(type: string, count: number): string {
const pattern = OutlineModel.getDefaultGroupLabelPatterns()[type];
if (pattern) {
return strings.format(pattern, count);
}
return type;
}
private static getDefaultGroupLabelPatterns(): { [type: string]: string } {
const result: { [type: string]: string } = Object.create(null);
result['method'] = nls.localize('method', "methods ({0})");
result['function'] = nls.localize('function', "functions ({0})");
result['constructor'] = <any>nls.localize('_constructor', "constructors ({0})");
result['variable'] = nls.localize('variable', "variables ({0})");
result['class'] = nls.localize('class', "classes ({0})");
result['interface'] = nls.localize('interface', "interfaces ({0})");
result['namespace'] = nls.localize('namespace', "namespaces ({0})");
result['package'] = nls.localize('package', "packages ({0})");
result['module'] = nls.localize('modules', "modules ({0})");
result['property'] = nls.localize('property', "properties ({0})");
result['enum'] = nls.localize('enum', "enumerations ({0})");
result['string'] = nls.localize('string', "strings ({0})");
result['rule'] = nls.localize('rule', "rules ({0})");
result['file'] = nls.localize('file', "files ({0})");
result['array'] = nls.localize('array', "arrays ({0})");
result['number'] = nls.localize('number', "numbers ({0})");
result['boolean'] = nls.localize('boolean', "booleans ({0})");
result['object'] = nls.localize('object', "objects ({0})");
result['key'] = nls.localize('key', "keys ({0})");
return result;
}
}
class SymbolEntry extends EditorQuickOpenEntryGroup {
private editorService: IEditorService;
private index: number;
private name: string;
private type: string;
private icon: string;
private description: string;
private range: IRange;
private revealRange: IRange;
private handler: GotoSymbolHandler;
constructor(index: number, name: string, type: string, description: string, icon: string, range: IRange, revealRange: IRange, highlights: IHighlight[], editorService: IEditorService, handler: GotoSymbolHandler) {
super();
this.index = index;
this.name = name;
this.type = type;
this.icon = icon;
this.description = description;
this.range = range;
this.revealRange = revealRange || range;
this.setHighlights(highlights);
this.editorService = editorService;
this.handler = handler;
}
getIndex(): number {
return this.index;
}
getLabel(): string {
return this.name;
}
getAriaLabel(): string {
return nls.localize('entryAriaLabel', "{0}, symbols", this.getLabel());
}
getIcon(): string {
return this.icon;
}
getDescription(): string {
return this.description;
}
getType(): string {
return this.type;
}
getRange(): IRange {
return this.range;
}
getInput(): IEditorInput {
return this.editorService.activeEditor;
}
getOptions(pinned?: boolean): ITextEditorOptions {
return {
selection: this.toSelection(),
pinned
};
}
run(mode: Mode, context: IEntryRunContext): boolean {
if (mode === Mode.OPEN) {
return this.runOpen(context);
}
return this.runPreview();
}
private runOpen(context: IEntryRunContext): boolean {
// Check for sideBySide use
const sideBySide = context.keymods.ctrlCmd;
if (sideBySide) {
this.editorService.openEditor(this.getInput(), this.getOptions(context.keymods.alt), SIDE_GROUP);
}
// Apply selection and focus
else {
const range = this.toSelection();
const activeTextEditorWidget = this.editorService.activeTextEditorWidget;
if (activeTextEditorWidget) {
activeTextEditorWidget.setSelection(range);
activeTextEditorWidget.revealRangeInCenter(range, ScrollType.Smooth);
}
}
return true;
}
private runPreview(): boolean {
// Select Outline Position
const range = this.toSelection();
const activeTextEditorWidget = this.editorService.activeTextEditorWidget;
if (activeTextEditorWidget) {
activeTextEditorWidget.revealRangeInCenter(range, ScrollType.Smooth);
// Decorate if possible
if (types.isFunction(activeTextEditorWidget.changeDecorations)) {
this.handler.decorateOutline(this.range, range, activeTextEditorWidget, this.editorService.activeControl.group);
}
}
return false;
}
private toSelection(): IRange {
return {
startLineNumber: this.revealRange.startLineNumber,
startColumn: this.revealRange.startColumn || 1,
endLineNumber: this.revealRange.startLineNumber,
endColumn: this.revealRange.startColumn || 1
};
}
}
interface IEditorLineDecoration {
groupId: GroupIdentifier;
rangeHighlightId: string;
lineDecorationId: string;
}
export class GotoSymbolHandler extends QuickOpenHandler {
static readonly ID = 'workbench.picker.filesymbols';
private outlineToModelCache: { [modelId: string]: OutlineModel; };
private rangeHighlightDecorationId: IEditorLineDecoration;
private lastKnownEditorViewState: IEditorViewState;
private activeOutlineRequest: TPromise<OutlineModel>;
constructor(
@IEditorService private editorService: IEditorService
) {
super();
this.outlineToModelCache = {};
}
getResults(searchValue: string): TPromise<QuickOpenModel> {
searchValue = searchValue.trim();
// Remember view state to be able to restore on cancel
if (!this.lastKnownEditorViewState) {
const activeTextEditorWidget = this.editorService.activeTextEditorWidget;
this.lastKnownEditorViewState = activeTextEditorWidget.saveViewState();
}
// Resolve Outline Model
return this.getActiveOutline().then(outline => {
// Filter by search
outline.applyFilter(searchValue);
return outline;
});
}
getEmptyLabel(searchString: string): string {
if (searchString.length > 0) {
return nls.localize('noSymbolsMatching', "No symbols matching");
}
return nls.localize('noSymbolsFound', "No symbols found");
}
getAriaLabel(): string {
return nls.localize('gotoSymbolHandlerAriaLabel', "Type to narrow down symbols of the currently active editor.");
}
canRun(): boolean | string {
let canRun = false;
const activeTextEditorWidget = this.editorService.activeTextEditorWidget;
if (activeTextEditorWidget) {
let model = activeTextEditorWidget.getModel();
if (model && (<IDiffEditorModel>model).modified && (<IDiffEditorModel>model).original) {
model = (<IDiffEditorModel>model).modified; // Support for diff editor models
}
if (model && types.isFunction((<ITextModel>model).getLanguageIdentifier)) {
canRun = DocumentSymbolProviderRegistry.has(<ITextModel>model);
}
}
return canRun ? true : activeTextEditorWidget !== null ? nls.localize('cannotRunGotoSymbolInFile', "No symbol information for the file") : nls.localize('cannotRunGotoSymbol', "Open a text file first to go to a symbol");
}
getAutoFocus(searchValue: string): IAutoFocus {
searchValue = searchValue.trim();
// Remove any type pattern (:) from search value as needed
if (searchValue.indexOf(SCOPE_PREFIX) === 0) {
searchValue = searchValue.substr(SCOPE_PREFIX.length);
}
return {
autoFocusPrefixMatch: searchValue,
autoFocusFirstEntry: !!searchValue
};
}
private toQuickOpenEntries(flattened: DocumentSymbol[]): SymbolEntry[] {
const results: SymbolEntry[] = [];
for (let i = 0; i < flattened.length; i++) {
const element = flattened[i];
const label = strings.trim(element.name);
// Show parent scope as description
const description: string = element.containerName;
const icon = symbolKindToCssClass(element.kind);
// Add
results.push(new SymbolEntry(i,
label, icon, description, `symbol-icon ${icon}`,
element.range, element.selectionRange, null, this.editorService, this
));
}
return results;
}
private getActiveOutline(): TPromise<OutlineModel> {
if (!this.activeOutlineRequest) {
this.activeOutlineRequest = this.doGetActiveOutline();
}
return this.activeOutlineRequest;
}
private doGetActiveOutline(): TPromise<OutlineModel> {
const activeTextEditorWidget = this.editorService.activeTextEditorWidget;
if (activeTextEditorWidget) {
let model = activeTextEditorWidget.getModel();
if (model && (<IDiffEditorModel>model).modified && (<IDiffEditorModel>model).original) {
model = (<IDiffEditorModel>model).modified; // Support for diff editor models
}
if (model && types.isFunction((<ITextModel>model).getLanguageIdentifier)) {
// Ask cache first
const modelId = (<ITextModel>model).id;
if (this.outlineToModelCache[modelId]) {
return TPromise.as(this.outlineToModelCache[modelId]);
}
return asWinJsPromise(token => getDocumentSymbols(<ITextModel>model, token)).then(entries => {
const model = new OutlineModel(this.toQuickOpenEntries(entries));
this.outlineToModelCache = {}; // Clear cache, only keep 1 outline
this.outlineToModelCache[modelId] = model;
return model;
});
}
}
return TPromise.wrap<OutlineModel>(null);
}
decorateOutline(fullRange: IRange, startRange: IRange, editor: IEditor, group: IEditorGroup): void {
editor.changeDecorations((changeAccessor: IModelDecorationsChangeAccessor) => {
const deleteDecorations: string[] = [];
if (this.rangeHighlightDecorationId) {
deleteDecorations.push(this.rangeHighlightDecorationId.lineDecorationId);
deleteDecorations.push(this.rangeHighlightDecorationId.rangeHighlightId);
this.rangeHighlightDecorationId = null;
}
const newDecorations: IModelDeltaDecoration[] = [
// rangeHighlight at index 0
{
range: fullRange,
options: {
className: 'rangeHighlight',
isWholeLine: true
}
},
// lineDecoration at index 1
{
range: startRange,
options: {
overviewRuler: {
color: themeColorFromId(overviewRulerRangeHighlight),
darkColor: themeColorFromId(overviewRulerRangeHighlight),
position: OverviewRulerLane.Full
}
}
}
];
const decorations = changeAccessor.deltaDecorations(deleteDecorations, newDecorations);
const rangeHighlightId = decorations[0];
const lineDecorationId = decorations[1];
this.rangeHighlightDecorationId = {
groupId: group.id,
rangeHighlightId: rangeHighlightId,
lineDecorationId: lineDecorationId,
};
});
}
clearDecorations(): void {
if (this.rangeHighlightDecorationId) {
this.editorService.visibleControls.forEach(editor => {
if (editor.group.id === this.rangeHighlightDecorationId.groupId) {
const editorControl = <IEditor>editor.getControl();
editorControl.changeDecorations((changeAccessor: IModelDecorationsChangeAccessor) => {
changeAccessor.deltaDecorations([
this.rangeHighlightDecorationId.lineDecorationId,
this.rangeHighlightDecorationId.rangeHighlightId
], []);
});
}
});
this.rangeHighlightDecorationId = null;
}
}
onClose(canceled: boolean): void {
// Clear Cache
this.outlineToModelCache = {};
// Clear Highlight Decorations if present
this.clearDecorations();
// Restore selection if canceled
if (canceled && this.lastKnownEditorViewState) {
const activeTextEditorWidget = this.editorService.activeTextEditorWidget;
if (activeTextEditorWidget) {
activeTextEditorWidget.restoreViewState(this.lastKnownEditorViewState);
}
}
this.lastKnownEditorViewState = null;
this.activeOutlineRequest = null;
}
}