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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { URI } from 'vs/base/common/uri';
import { ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { Position } from 'vs/editor/common/core/position';
import { IEditorContribution, IDiffEditorContribution } from 'vs/editor/common/editorCommon';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { MenuId, MenuRegistry, Action2 } from 'vs/platform/actions/common/actions';
import { CommandsRegistry, ICommandHandlerDescription } from 'vs/platform/commands/common/commands';
import { ContextKeyExpr, IContextKeyService, ContextKeyExpression } from 'vs/platform/contextkey/common/contextkey';
import { ServicesAccessor as InstantiationServicesAccessor, BrandedService, IInstantiationService, IConstructorSignature } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindings, KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { Registry } from 'vs/platform/registry/common/platform';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { withNullAsUndefined, assertType } from 'vs/base/common/types';
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
import { IDisposable } from 'vs/base/common/lifecycle';
import { KeyMod, KeyCode } from 'vs/base/common/keyCodes';
import { ILogService } from 'vs/platform/log/common/log';
export type ServicesAccessor = InstantiationServicesAccessor;
export type IEditorContributionCtor = IConstructorSignature<IEditorContribution, [ICodeEditor]>;
export type IDiffEditorContributionCtor = IConstructorSignature<IDiffEditorContribution, [IDiffEditor]>;
export interface IEditorContributionDescription {
id: string;
ctor: IEditorContributionCtor;
}
export interface IDiffEditorContributionDescription {
id: string;
ctor: IDiffEditorContributionCtor;
}
//#region Command
export interface ICommandKeybindingsOptions extends IKeybindings {
kbExpr?: ContextKeyExpression | null;
weight: number;
/**
* the default keybinding arguments
*/
args?: any;
}
export interface ICommandMenuOptions {
menuId: MenuId;
group: string;
order: number;
when?: ContextKeyExpression;
title: string;
icon?: ThemeIcon;
}
export interface ICommandOptions {
id: string;
precondition: ContextKeyExpression | undefined;
kbOpts?: ICommandKeybindingsOptions | ICommandKeybindingsOptions[];
description?: ICommandHandlerDescription;
menuOpts?: ICommandMenuOptions | ICommandMenuOptions[];
}
export abstract class Command {
public readonly id: string;
public readonly precondition: ContextKeyExpression | undefined;
private readonly _kbOpts: ICommandKeybindingsOptions | ICommandKeybindingsOptions[] | undefined;
private readonly _menuOpts: ICommandMenuOptions | ICommandMenuOptions[] | undefined;
private readonly _description: ICommandHandlerDescription | undefined;
constructor(opts: ICommandOptions) {
this.id = opts.id;
this.precondition = opts.precondition;
this._kbOpts = opts.kbOpts;
this._menuOpts = opts.menuOpts;
this._description = opts.description;
}
public register(): void {
if (Array.isArray(this._menuOpts)) {
this._menuOpts.forEach(this._registerMenuItem, this);
} else if (this._menuOpts) {
this._registerMenuItem(this._menuOpts);
}
if (this._kbOpts) {
const kbOptsArr = Array.isArray(this._kbOpts) ? this._kbOpts : [this._kbOpts];
for (const kbOpts of kbOptsArr) {
let kbWhen = kbOpts.kbExpr;
if (this.precondition) {
if (kbWhen) {
kbWhen = ContextKeyExpr.and(kbWhen, this.precondition);
} else {
kbWhen = this.precondition;
}
}
const desc = {
id: this.id,
weight: kbOpts.weight,
args: kbOpts.args,
when: kbWhen,
primary: kbOpts.primary,
secondary: kbOpts.secondary,
win: kbOpts.win,
linux: kbOpts.linux,
mac: kbOpts.mac,
};
KeybindingsRegistry.registerKeybindingRule(desc);
}
}
CommandsRegistry.registerCommand({
id: this.id,
handler: (accessor, args) => this.runCommand(accessor, args),
description: this._description
});
}
private _registerMenuItem(item: ICommandMenuOptions): void {
MenuRegistry.appendMenuItem(item.menuId, {
group: item.group,
command: {
id: this.id,
title: item.title,
icon: item.icon,
precondition: this.precondition
},
when: item.when,
order: item.order
});
}
public abstract runCommand(accessor: ServicesAccessor, args: any): void | Promise<void>;
}
//#endregion Command
//#region MultiplexingCommand
/**
* Potential override for a command.
*
* @return `true` if the command was successfully run. This stops other overrides from being executed.
*/
export type CommandImplementation = (accessor: ServicesAccessor, args: unknown) => boolean | Promise<void>;
interface ICommandImplementationRegistration {
priority: number;
name: string;
implementation: CommandImplementation;
}
export class MultiCommand extends Command {
private readonly _implementations: ICommandImplementationRegistration[] = [];
/**
* A higher priority gets to be looked at first
*/
public addImplementation(priority: number, name: string, implementation: CommandImplementation): IDisposable {
this._implementations.push({ priority, name, implementation });
this._implementations.sort((a, b) => b.priority - a.priority);
return {
dispose: () => {
for (let i = 0; i < this._implementations.length; i++) {
if (this._implementations[i].implementation === implementation) {
this._implementations.splice(i, 1);
return;
}
}
}
};
}
public runCommand(accessor: ServicesAccessor, args: any): void | Promise<void> {
const logService = accessor.get(ILogService);
logService.trace(`Executing Command '${this.id}' which has ${this._implementations.length} bound.`);
for (const impl of this._implementations) {
const result = impl.implementation(accessor, args);
if (result) {
logService.trace(`Command '${this.id}' was handled by '${impl.name}'.`);
if (typeof result === 'boolean') {
return;
}
return result;
}
}
logService.trace(`The Command '${this.id}' was not handled by any implementation.`);
}
}
//#endregion
/**
* A command that delegates to another command's implementation.
*
* This lets different commands be registered but share the same implementation
*/
export class ProxyCommand extends Command {
constructor(
private readonly command: Command,
opts: ICommandOptions
) {
super(opts);
}
public runCommand(accessor: ServicesAccessor, args: any): void | Promise<void> {
return this.command.runCommand(accessor, args);
}
}
//#region EditorCommand
export interface IContributionCommandOptions<T> extends ICommandOptions {
handler: (controller: T, args: any) => void;
}
export interface EditorControllerCommand<T extends IEditorContribution> {
new(opts: IContributionCommandOptions<T>): EditorCommand;
}
export abstract class EditorCommand extends Command {
/**
* Create a command class that is bound to a certain editor contribution.
*/
public static bindToContribution<T extends IEditorContribution>(controllerGetter: (editor: ICodeEditor) => T | null): EditorControllerCommand<T> {
return class EditorControllerCommandImpl extends EditorCommand {
private readonly _callback: (controller: T, args: any) => void;
constructor(opts: IContributionCommandOptions<T>) {
super(opts);
this._callback = opts.handler;
}
public runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor, args: any): void {
const controller = controllerGetter(editor);
if (controller) {
this._callback(controller, args);
}
}
};
}
public runCommand(accessor: ServicesAccessor, args: any): void | Promise<void> {
const codeEditorService = accessor.get(ICodeEditorService);
// Find the editor with text focus or active
const editor = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor();
if (!editor) {
// well, at least we tried...
return;
}
return editor.invokeWithinContext((editorAccessor) => {
const kbService = editorAccessor.get(IContextKeyService);
if (!kbService.contextMatchesRules(withNullAsUndefined(this.precondition))) {
// precondition does not hold
return;
}
return this.runEditorCommand(editorAccessor, editor!, args);
});
}
public abstract runEditorCommand(accessor: ServicesAccessor | null, editor: ICodeEditor, args: any): void | Promise<void>;
}
//#endregion EditorCommand
//#region EditorAction
export interface IEditorActionContextMenuOptions {
group: string;
order: number;
when?: ContextKeyExpression;
menuId?: MenuId;
}
export interface IActionOptions extends ICommandOptions {
label: string;
alias: string;
contextMenuOpts?: IEditorActionContextMenuOptions | IEditorActionContextMenuOptions[];
}
export abstract class EditorAction extends EditorCommand {
private static convertOptions(opts: IActionOptions): ICommandOptions {
let menuOpts: ICommandMenuOptions[];
if (Array.isArray(opts.menuOpts)) {
menuOpts = opts.menuOpts;
} else if (opts.menuOpts) {
menuOpts = [opts.menuOpts];
} else {
menuOpts = [];
}
function withDefaults(item: Partial<ICommandMenuOptions>): ICommandMenuOptions {
if (!item.menuId) {
item.menuId = MenuId.EditorContext;
}
if (!item.title) {
item.title = opts.label;
}
item.when = ContextKeyExpr.and(opts.precondition, item.when);
return <ICommandMenuOptions>item;
}
if (Array.isArray(opts.contextMenuOpts)) {
menuOpts.push(...opts.contextMenuOpts.map(withDefaults));
} else if (opts.contextMenuOpts) {
menuOpts.push(withDefaults(opts.contextMenuOpts));
}
opts.menuOpts = menuOpts;
return <ICommandOptions>opts;
}
public readonly label: string;
public readonly alias: string;
constructor(opts: IActionOptions) {
super(EditorAction.convertOptions(opts));
this.label = opts.label;
this.alias = opts.alias;
}
public runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor, args: any): void | Promise<void> {
this.reportTelemetry(accessor, editor);
return this.run(accessor, editor, args || {});
}
protected reportTelemetry(accessor: ServicesAccessor, editor: ICodeEditor) {
type EditorActionInvokedClassification = {
owner: 'alexdima';
comment: 'An editor action has been invoked.';
name: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The label of the action that was invoked.' };
id: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The identifier of the action that was invoked.' };
};
type EditorActionInvokedEvent = {
name: string;
id: string;
};
accessor.get(ITelemetryService).publicLog2<EditorActionInvokedEvent, EditorActionInvokedClassification>('editorActionInvoked', { name: this.label, id: this.id });
}
public abstract run(accessor: ServicesAccessor, editor: ICodeEditor, args: any): void | Promise<void>;
}
export type EditorActionImplementation = (accessor: ServicesAccessor, editor: ICodeEditor, args: any) => boolean | Promise<void>;
export class MultiEditorAction extends EditorAction {
private readonly _implementations: [number, EditorActionImplementation][] = [];
/**
* A higher priority gets to be looked at first
*/
public addImplementation(priority: number, implementation: EditorActionImplementation): IDisposable {
this._implementations.push([priority, implementation]);
this._implementations.sort((a, b) => b[0] - a[0]);
return {
dispose: () => {
for (let i = 0; i < this._implementations.length; i++) {
if (this._implementations[i][1] === implementation) {
this._implementations.splice(i, 1);
return;
}
}
}
};
}
public run(accessor: ServicesAccessor, editor: ICodeEditor, args: any): void | Promise<void> {
for (const impl of this._implementations) {
const result = impl[1](accessor, editor, args);
if (result) {
if (typeof result === 'boolean') {
return;
}
return result;
}
}
}
}
//#endregion EditorAction
//#region EditorAction2
export abstract class EditorAction2 extends Action2 {
run(accessor: ServicesAccessor, ...args: any[]) {
// Find the editor with text focus or active
const codeEditorService = accessor.get(ICodeEditorService);
const editor = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor();
if (!editor) {
// well, at least we tried...
return;
}
// precondition does hold
return editor.invokeWithinContext((editorAccessor) => {
const kbService = editorAccessor.get(IContextKeyService);
if (kbService.contextMatchesRules(withNullAsUndefined(this.desc.precondition))) {
return this.runEditorCommand(editorAccessor, editor!, args);
}
});
}
abstract runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor, ...args: any[]): any;
}
//#endregion
// --- Registration of commands and actions
export function registerModelAndPositionCommand(id: string, handler: (accessor: ServicesAccessor, model: ITextModel, position: Position, ...args: any[]) => any) {
CommandsRegistry.registerCommand(id, function (accessor, ...args) {
const instaService = accessor.get(IInstantiationService);
const [resource, position] = args;
assertType(URI.isUri(resource));
assertType(Position.isIPosition(position));
const model = accessor.get(IModelService).getModel(resource);
if (model) {
const editorPosition = Position.lift(position);
return instaService.invokeFunction(handler, model, editorPosition, ...args.slice(2));
}
return accessor.get(ITextModelService).createModelReference(resource).then(reference => {
return new Promise((resolve, reject) => {
try {
const result = instaService.invokeFunction(handler, reference.object.textEditorModel, Position.lift(position), args.slice(2));
resolve(result);
} catch (err) {
reject(err);
}
}).finally(() => {
reference.dispose();
});
});
});
}
export function registerEditorCommand<T extends EditorCommand>(editorCommand: T): T {
EditorContributionRegistry.INSTANCE.registerEditorCommand(editorCommand);
return editorCommand;
}
export function registerEditorAction<T extends EditorAction>(ctor: { new(): T }): T {
const action = new ctor();
EditorContributionRegistry.INSTANCE.registerEditorAction(action);
return action;
}
export function registerMultiEditorAction<T extends MultiEditorAction>(action: T): T {
EditorContributionRegistry.INSTANCE.registerEditorAction(action);
return action;
}
export function registerInstantiatedEditorAction(editorAction: EditorAction): void {
EditorContributionRegistry.INSTANCE.registerEditorAction(editorAction);
}
export function registerEditorContribution<Services extends BrandedService[]>(id: string, ctor: { new(editor: ICodeEditor, ...services: Services): IEditorContribution }): void {
EditorContributionRegistry.INSTANCE.registerEditorContribution(id, ctor);
}
export function registerDiffEditorContribution<Services extends BrandedService[]>(id: string, ctor: { new(editor: IDiffEditor, ...services: Services): IEditorContribution }): void {
EditorContributionRegistry.INSTANCE.registerDiffEditorContribution(id, ctor);
}
export namespace EditorExtensionsRegistry {
export function getEditorCommand(commandId: string): EditorCommand {
return EditorContributionRegistry.INSTANCE.getEditorCommand(commandId);
}
export function getEditorActions(): EditorAction[] {
return EditorContributionRegistry.INSTANCE.getEditorActions();
}
export function getEditorContributions(): IEditorContributionDescription[] {
return EditorContributionRegistry.INSTANCE.getEditorContributions();
}
export function getSomeEditorContributions(ids: string[]): IEditorContributionDescription[] {
return EditorContributionRegistry.INSTANCE.getEditorContributions().filter(c => ids.indexOf(c.id) >= 0);
}
export function getDiffEditorContributions(): IDiffEditorContributionDescription[] {
return EditorContributionRegistry.INSTANCE.getDiffEditorContributions();
}
}
// Editor extension points
const Extensions = {
EditorCommonContributions: 'editor.contributions'
};
class EditorContributionRegistry {
public static readonly INSTANCE = new EditorContributionRegistry();
private readonly editorContributions: IEditorContributionDescription[];
private readonly diffEditorContributions: IDiffEditorContributionDescription[];
private readonly editorActions: EditorAction[];
private readonly editorCommands: { [commandId: string]: EditorCommand };
constructor() {
this.editorContributions = [];
this.diffEditorContributions = [];
this.editorActions = [];
this.editorCommands = Object.create(null);
}
public registerEditorContribution<Services extends BrandedService[]>(id: string, ctor: { new(editor: ICodeEditor, ...services: Services): IEditorContribution }): void {
this.editorContributions.push({ id, ctor: ctor as IEditorContributionCtor });
}
public getEditorContributions(): IEditorContributionDescription[] {
return this.editorContributions.slice(0);
}
public registerDiffEditorContribution<Services extends BrandedService[]>(id: string, ctor: { new(editor: IDiffEditor, ...services: Services): IEditorContribution }): void {
this.diffEditorContributions.push({ id, ctor: ctor as IDiffEditorContributionCtor });
}
public getDiffEditorContributions(): IDiffEditorContributionDescription[] {
return this.diffEditorContributions.slice(0);
}
public registerEditorAction(action: EditorAction) {
action.register();
this.editorActions.push(action);
}
public getEditorActions(): EditorAction[] {
return this.editorActions.slice(0);
}
public registerEditorCommand(editorCommand: EditorCommand) {
editorCommand.register();
this.editorCommands[editorCommand.id] = editorCommand;
}
public getEditorCommand(commandId: string): EditorCommand {
return (this.editorCommands[commandId] || null);
}
}
Registry.add(Extensions.EditorCommonContributions, EditorContributionRegistry.INSTANCE);
function registerCommand<T extends Command>(command: T): T {
command.register();
return command;
}
export const UndoCommand = registerCommand(new MultiCommand({
id: 'undo',
precondition: undefined,
kbOpts: {
weight: KeybindingWeight.EditorCore,
primary: KeyMod.CtrlCmd | KeyCode.KeyZ
},
menuOpts: [{
menuId: MenuId.MenubarEditMenu,
group: '1_do',
title: nls.localize({ key: 'miUndo', comment: ['&& denotes a mnemonic'] }, "&&Undo"),
order: 1
}, {
menuId: MenuId.CommandPalette,
group: '',
title: nls.localize('undo', "Undo"),
order: 1
}]
}));
registerCommand(new ProxyCommand(UndoCommand, { id: 'default:undo', precondition: undefined }));
export const RedoCommand = registerCommand(new MultiCommand({
id: 'redo',
precondition: undefined,
kbOpts: {
weight: KeybindingWeight.EditorCore,
primary: KeyMod.CtrlCmd | KeyCode.KeyY,
secondary: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyZ],
mac: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyZ }
},
menuOpts: [{
menuId: MenuId.MenubarEditMenu,
group: '1_do',
title: nls.localize({ key: 'miRedo', comment: ['&& denotes a mnemonic'] }, "&&Redo"),
order: 2
}, {
menuId: MenuId.CommandPalette,
group: '',
title: nls.localize('redo', "Redo"),
order: 1
}]
}));
registerCommand(new ProxyCommand(RedoCommand, { id: 'default:redo', precondition: undefined }));
export const SelectAllCommand = registerCommand(new MultiCommand({
id: 'editor.action.selectAll',
precondition: undefined,
kbOpts: {
weight: KeybindingWeight.EditorCore,
kbExpr: null,
primary: KeyMod.CtrlCmd | KeyCode.KeyA
},
menuOpts: [{
menuId: MenuId.MenubarSelectionMenu,
group: '1_basic',
title: nls.localize({ key: 'miSelectAll', comment: ['&& denotes a mnemonic'] }, "&&Select All"),
order: 1
}, {
menuId: MenuId.CommandPalette,
group: '',
title: nls.localize('selectAll', "Select All"),
order: 1
}]
}));
|