-
Notifications
You must be signed in to change notification settings - Fork 27.9k
/
ghostTextController.ts
439 lines (379 loc) · 17.2 KB
/
ghostTextController.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter } from 'vs/base/common/event';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { firstNonWhitespaceIndex } from 'vs/base/common/strings';
import { IActiveCodeEditor, ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorAction, ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { EditorOption } from 'vs/editor/common/config/editorOptions';
import { CursorColumns } from 'vs/editor/common/core/cursorColumns';
import { Range } from 'vs/editor/common/core/range';
import { CursorChangeReason } from 'vs/editor/common/cursorEvents';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { inlineSuggestCommitId, showNextInlineSuggestionActionId, showPreviousInlineSuggestionActionId } from 'vs/editor/contrib/inlineCompletions/browser/consts';
import { GhostTextModel } from 'vs/editor/contrib/inlineCompletions/browser/ghostTextModel';
import { GhostTextWidget } from 'vs/editor/contrib/inlineCompletions/browser/ghostTextWidget';
import { InlineSuggestionHintsWidget } from 'vs/editor/contrib/inlineCompletions/browser/inlineSuggestionHintsWidget';
import * as nls from 'vs/nls';
import { Action2, MenuId } from 'vs/platform/actions/common/actions';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
export class GhostTextController extends Disposable {
public static readonly inlineSuggestionVisible = new RawContextKey<boolean>('inlineSuggestionVisible', false, nls.localize('inlineSuggestionVisible', "Whether an inline suggestion is visible"));
public static readonly inlineSuggestionHasIndentation = new RawContextKey<boolean>('inlineSuggestionHasIndentation', false, nls.localize('inlineSuggestionHasIndentation', "Whether the inline suggestion starts with whitespace"));
public static readonly inlineSuggestionHasIndentationLessThanTabSize = new RawContextKey<boolean>('inlineSuggestionHasIndentationLessThanTabSize', true, nls.localize('inlineSuggestionHasIndentationLessThanTabSize', "Whether the inline suggestion starts with whitespace that is less than what would be inserted by tab"));
/**
* Enables to use Ctrl+Left to undo partially accepted inline completions.
*/
public static readonly canUndoInlineSuggestion = new RawContextKey<boolean>('canUndoInlineSuggestion', false, nls.localize('canUndoInlineSuggestion', "Whether undo would undo an inline suggestion"));
public static readonly alwaysShowInlineSuggestionToolbar = new RawContextKey<boolean>('alwaysShowInlineSuggestionToolbar', false, nls.localize('alwaysShowInlineSuggestionToolbar', "Whether the inline suggestion toolbar should always be visible"));
static ID = 'editor.contrib.ghostTextController';
public static get(editor: ICodeEditor): GhostTextController | null {
return editor.getContribution<GhostTextController>(GhostTextController.ID);
}
private triggeredExplicitly = false;
protected readonly activeController = this._register(new MutableDisposable<ActiveGhostTextController>());
public get activeModel(): GhostTextModel | undefined {
return this.activeController.value?.model;
}
private readonly activeModelDidChangeEmitter = this._register(new Emitter<void>());
public readonly onActiveModelDidChange = this.activeModelDidChangeEmitter.event;
/**
* Tracks the first alternative version id until which only partial inline suggestions can be undone.
* Any other content change will invalidate this.
* This field is used to set the corresponding context key.
*/
private firstUndoableVersionId: number | undefined = undefined;
public readonly alwaysShowInlineSuggestionToolbar = GhostTextController.alwaysShowInlineSuggestionToolbar.bindTo(this.contextKeyService);
constructor(
public readonly editor: ICodeEditor,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
) {
super();
this._register(this.editor.onDidChangeModelContent((e) => {
if (!e.isUndoing || this.firstUndoableVersionId && this.editor.getModel()!.getAlternativeVersionId() < this.firstUndoableVersionId) {
this.activeController.value?.contextKeys.canUndoInlineSuggestion.reset();
this.firstUndoableVersionId = undefined; // Will be set again if this change was caused by an inline suggestion.
}
}));
this._register(this.editor.onDidChangeCursorPosition((e) => {
if (e.reason === CursorChangeReason.Explicit) {
this.activeController.value?.contextKeys.canUndoInlineSuggestion.reset();
this.firstUndoableVersionId = undefined;
}
}));
this._register(this.editor.onDidChangeModel(() => {
this.update();
}));
this._register(this.editor.onDidChangeConfiguration((e) => {
if (e.hasChanged(EditorOption.suggest) || e.hasChanged(EditorOption.inlineSuggest)) {
this.update();
}
}));
this.update();
}
// Don't call this method when not necessary. It will recreate the activeController.
private update(): void {
const suggestOptions = this.editor.getOption(EditorOption.suggest);
const inlineSuggestOptions = this.editor.getOption(EditorOption.inlineSuggest);
this.alwaysShowInlineSuggestionToolbar.set(inlineSuggestOptions.showToolbar === 'always');
const shouldCreate = this.editor.hasModel() && (suggestOptions.preview || inlineSuggestOptions.enabled || this.triggeredExplicitly);
if (shouldCreate !== !!this.activeController.value) {
this.activeController.value = undefined;
// ActiveGhostTextController is only created if one of those settings is set or if the inline completions are triggered explicitly.
this.activeController.value =
shouldCreate ? this.instantiationService.createInstance(
ActiveGhostTextController,
this.editor as IActiveCodeEditor
)
: undefined;
this.activeModelDidChangeEmitter.fire();
}
}
public shouldShowHoverAt(hoverRange: Range): boolean {
return this.activeModel?.shouldShowHoverAt(hoverRange) || false;
}
public shouldShowHoverAtViewZone(viewZoneId: string): boolean {
return this.activeController.value?.widget?.shouldShowHoverAtViewZone(viewZoneId) || false;
}
public trigger(): void {
this.triggeredExplicitly = true;
if (!this.activeController.value) {
this.update();
}
this.activeModel?.triggerInlineCompletion();
}
public commitPartially(): void {
const nextVersion = this.firstUndoableVersionId; // Read this before committing, as it will be reset.
this.activeModel?.commitInlineCompletionPartially();
this.activeController?.value?.contextKeys.canUndoInlineSuggestion.set(true);
// Don't override this field if the previous command already accepted some inline suggestion.
this.firstUndoableVersionId = nextVersion ?? this.editor.getModel()!.getAlternativeVersionId();
}
public commit(): void {
this.activeModel?.commitInlineCompletion();
}
public hide(): void {
this.activeModel?.hideInlineCompletion();
}
public showNextInlineCompletion(): void {
this.activeModel?.showNextInlineCompletion();
}
public showPreviousInlineCompletion(): void {
this.activeModel?.showPreviousInlineCompletion();
}
public async getInlineCompletionsCount(): Promise<number> {
const result = await this.activeModel?.getInlineCompletionsCount();
return result ?? 0;
}
}
class GhostTextContextKeys {
public readonly inlineCompletionVisible = GhostTextController.inlineSuggestionVisible.bindTo(this.contextKeyService);
public readonly inlineCompletionSuggestsIndentation = GhostTextController.inlineSuggestionHasIndentation.bindTo(this.contextKeyService);
public readonly inlineCompletionSuggestsIndentationLessThanTabSize = GhostTextController.inlineSuggestionHasIndentationLessThanTabSize.bindTo(this.contextKeyService);
public readonly canUndoInlineSuggestion = GhostTextController.canUndoInlineSuggestion.bindTo(this.contextKeyService);
constructor(private readonly contextKeyService: IContextKeyService) {
}
}
/**
* The controller for a text editor with an initialized text model.
* Must be disposed as soon as the model detaches from the editor.
*/
export class ActiveGhostTextController extends Disposable {
public readonly contextKeys = new GhostTextContextKeys(this.contextKeyService);
public readonly model = this._register(this.instantiationService.createInstance(GhostTextModel, this.editor));
public readonly widget = this._register(this.instantiationService.createInstance(GhostTextWidget, this.editor, this.model));
public readonly hintsWidget = this._register(this.instantiationService.createInstance(InlineSuggestionHintsWidget, this.editor, this.model.inlineCompletionsModel));
constructor(
private readonly editor: IActiveCodeEditor,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
) {
super();
this._register(toDisposable(() => {
this.contextKeys.inlineCompletionVisible.set(false);
this.contextKeys.inlineCompletionSuggestsIndentation.set(false);
this.contextKeys.inlineCompletionSuggestsIndentationLessThanTabSize.set(true);
}));
this._register(this.model.onDidChange(() => {
this.updateContextKeys();
}));
this.updateContextKeys();
}
private updateContextKeys(): void {
this.contextKeys.inlineCompletionVisible.set(
this.model.activeInlineCompletionsModel?.ghostText !== undefined
);
let startsWithIndentation = false;
let startsWithIndentationLessThanTabSize = true;
const ghostText = this.model.inlineCompletionsModel.ghostText;
if (!!this.model.activeInlineCompletionsModel && ghostText && ghostText.parts.length > 0) {
const { column, lines } = ghostText.parts[0];
const firstLine = lines[0];
const indentationEndColumn = this.editor.getModel().getLineIndentColumn(ghostText.lineNumber);
const inIndentation = column <= indentationEndColumn;
if (inIndentation) {
let firstNonWsIdx = firstNonWhitespaceIndex(firstLine);
if (firstNonWsIdx === -1) {
firstNonWsIdx = firstLine.length - 1;
}
startsWithIndentation = firstNonWsIdx > 0;
const tabSize = this.editor.getModel().getOptions().tabSize;
const visibleColumnIndentation = CursorColumns.visibleColumnFromColumn(firstLine, firstNonWsIdx + 1, tabSize);
startsWithIndentationLessThanTabSize = visibleColumnIndentation < tabSize;
}
}
this.contextKeys.inlineCompletionSuggestsIndentation.set(startsWithIndentation);
this.contextKeys.inlineCompletionSuggestsIndentationLessThanTabSize.set(startsWithIndentationLessThanTabSize);
}
}
export class ShowNextInlineSuggestionAction extends EditorAction {
public static ID = showNextInlineSuggestionActionId;
constructor() {
super({
id: ShowNextInlineSuggestionAction.ID,
label: nls.localize('action.inlineSuggest.showNext', "Show Next Inline Suggestion"),
alias: 'Show Next Inline Suggestion',
precondition: ContextKeyExpr.and(EditorContextKeys.writable, GhostTextController.inlineSuggestionVisible),
kbOpts: {
weight: 100,
primary: KeyMod.Alt | KeyCode.BracketRight,
},
});
}
public async run(accessor: ServicesAccessor | undefined, editor: ICodeEditor): Promise<void> {
const controller = GhostTextController.get(editor);
if (controller) {
controller.showNextInlineCompletion();
editor.focus();
}
}
}
export class ShowPreviousInlineSuggestionAction extends EditorAction {
public static ID = showPreviousInlineSuggestionActionId;
constructor() {
super({
id: ShowPreviousInlineSuggestionAction.ID,
label: nls.localize('action.inlineSuggest.showPrevious', "Show Previous Inline Suggestion"),
alias: 'Show Previous Inline Suggestion',
precondition: ContextKeyExpr.and(EditorContextKeys.writable, GhostTextController.inlineSuggestionVisible),
kbOpts: {
weight: 100,
primary: KeyMod.Alt | KeyCode.BracketLeft,
},
});
}
public async run(accessor: ServicesAccessor | undefined, editor: ICodeEditor): Promise<void> {
const controller = GhostTextController.get(editor);
if (controller) {
controller.showPreviousInlineCompletion();
editor.focus();
}
}
}
export class TriggerInlineSuggestionAction extends EditorAction {
constructor() {
super({
id: 'editor.action.inlineSuggest.trigger',
label: nls.localize('action.inlineSuggest.trigger', "Trigger Inline Suggestion"),
alias: 'Trigger Inline Suggestion',
precondition: EditorContextKeys.writable
});
}
public async run(accessor: ServicesAccessor | undefined, editor: ICodeEditor): Promise<void> {
const controller = GhostTextController.get(editor);
controller?.trigger();
}
}
export class AcceptNextWordOfInlineCompletion extends EditorAction {
constructor() {
super({
id: 'editor.action.inlineSuggest.acceptNextWord',
label: nls.localize('action.inlineSuggest.acceptNextWord', "Accept Next Word Of Inline Suggestion"),
alias: 'Accept Next Word Of Inline Suggestion',
precondition: ContextKeyExpr.and(EditorContextKeys.writable, GhostTextController.inlineSuggestionVisible),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 1,
primary: KeyMod.CtrlCmd | KeyCode.RightArrow,
},
menuOpts: [{
menuId: MenuId.InlineSuggestionToolbar,
title: nls.localize('acceptWord', 'Accept Word'),
group: 'primary',
order: 2,
}],
});
}
public async run(accessor: ServicesAccessor | undefined, editor: ICodeEditor): Promise<void> {
const controller = GhostTextController.get(editor);
if (controller) {
controller.commitPartially();
}
}
}
export class AcceptInlineCompletion extends EditorAction {
constructor() {
super({
id: inlineSuggestCommitId,
label: nls.localize('action.inlineSuggest.accept', "Accept Inline Suggestion"),
alias: 'Accept Inline Suggestion',
precondition: GhostTextController.inlineSuggestionVisible,
menuOpts: [{
menuId: MenuId.InlineSuggestionToolbar,
title: nls.localize('accept', "Accept"),
group: 'primary',
order: 1,
}],
kbOpts: {
primary: KeyCode.Tab,
weight: 200,
kbExpr: ContextKeyExpr.and(
GhostTextController.inlineSuggestionVisible,
EditorContextKeys.tabMovesFocus.toNegated(),
GhostTextController.inlineSuggestionHasIndentationLessThanTabSize
),
}
});
}
public async run(accessor: ServicesAccessor | undefined, editor: ICodeEditor): Promise<void> {
const controller = GhostTextController.get(editor);
if (controller) {
controller.commit();
controller.editor.focus();
}
}
}
export class HideInlineCompletion extends EditorAction {
public static ID = 'editor.action.inlineSuggest.hide';
constructor() {
super({
id: HideInlineCompletion.ID,
label: nls.localize('action.inlineSuggest.hide', "Hide Inline Suggestion"),
alias: 'Hide Inline Suggestion',
precondition: GhostTextController.inlineSuggestionVisible,
kbOpts: {
weight: 100,
primary: KeyCode.Escape,
}
});
}
public async run(accessor: ServicesAccessor | undefined, editor: ICodeEditor): Promise<void> {
const controller = GhostTextController.get(editor);
if (controller) {
controller.hide();
}
}
}
export class ToggleAlwaysShowInlineSuggestionToolbar extends Action2 {
public static ID = 'editor.action.inlineSuggest.toggleAlwaysShowToolbar';
constructor() {
super({
id: ToggleAlwaysShowInlineSuggestionToolbar.ID,
title: nls.localize('action.inlineSuggest.alwaysShowToolbar', "Always Show Toolbar"),
f1: false,
precondition: undefined,
menu: [{
id: MenuId.InlineSuggestionToolbar,
group: 'secondary',
order: 10,
}],
toggled: GhostTextController.alwaysShowInlineSuggestionToolbar,
});
}
public async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> {
const configService = accessor.get(IConfigurationService);
const currentValue = configService.getValue<'always' | 'onHover'>('editor.inlineSuggest.showToolbar');
const newValue = currentValue === 'always' ? 'onHover' : 'always';
configService.updateValue('editor.inlineSuggest.showToolbar', newValue);
}
}
export class UndoAcceptPart extends EditorAction {
constructor() {
super({
id: 'editor.action.inlineSuggest.undo',
label: nls.localize('action.inlineSuggest.undo', "Undo Accept Word"),
alias: 'Undo Accept Word',
precondition: ContextKeyExpr.and(EditorContextKeys.writable, GhostTextController.canUndoInlineSuggestion),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 1,
primary: KeyMod.CtrlCmd | KeyCode.LeftArrow,
kbExpr: ContextKeyExpr.and(EditorContextKeys.writable, GhostTextController.canUndoInlineSuggestion),
},
menuOpts: [{
menuId: MenuId.InlineSuggestionToolbar,
title: nls.localize('undoAcceptWord', 'Undo Accept Word'),
group: 'secondary',
order: 3,
}],
});
}
public async run(accessor: ServicesAccessor | undefined, editor: ICodeEditor): Promise<void> {
editor.getModel()?.undo();
}
}