Welcome to mirror list, hosted at ThFree Co, Russian Federation.

snippetController2.ts « browser « snippet « contrib « editor « vs « src - github.com/microsoft/vscode.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 43e72f6ce579115bcddbddfe2db8803707cf10ce (plain)
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
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorCommand, registerEditorCommand, registerEditorContribution } from 'vs/editor/browser/editorExtensions';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { ISelection } from 'vs/editor/common/core/selection';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { CompletionItem, CompletionItemKind, CompletionItemProvider } from 'vs/editor/common/languages';
import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry';
import { ITextModel } from 'vs/editor/common/model';
import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures';
import { Choice, SnippetParser } from 'vs/editor/contrib/snippet/browser/snippetParser';
import { showSimpleSuggestions } from 'vs/editor/contrib/suggest/browser/suggest';
import { OvertypingCapturer } from 'vs/editor/contrib/suggest/browser/suggestOvertypingCapturer';
import { localize } from 'vs/nls';
import { ContextKeyExpr, IContextKey, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { ILogService } from 'vs/platform/log/common/log';
import { SnippetSession } from './snippetSession';

export interface ISnippetInsertOptions {
	overwriteBefore: number;
	overwriteAfter: number;
	adjustWhitespace: boolean;
	undoStopBefore: boolean;
	undoStopAfter: boolean;
	clipboardText: string | undefined;
	overtypingCapturer: OvertypingCapturer | undefined;
}

const _defaultOptions: ISnippetInsertOptions = {
	overwriteBefore: 0,
	overwriteAfter: 0,
	undoStopBefore: true,
	undoStopAfter: true,
	adjustWhitespace: true,
	clipboardText: undefined,
	overtypingCapturer: undefined
};

export class SnippetController2 implements IEditorContribution {

	public static readonly ID = 'snippetController2';

	static get(editor: ICodeEditor): SnippetController2 | null {
		return editor.getContribution<SnippetController2>(SnippetController2.ID);
	}

	static readonly InSnippetMode = new RawContextKey('inSnippetMode', false, localize('inSnippetMode', "Whether the editor in current in snippet mode"));
	static readonly HasNextTabstop = new RawContextKey('hasNextTabstop', false, localize('hasNextTabstop', "Whether there is a next tab stop when in snippet mode"));
	static readonly HasPrevTabstop = new RawContextKey('hasPrevTabstop', false, localize('hasPrevTabstop', "Whether there is a previous tab stop when in snippet mode"));

	private readonly _inSnippet: IContextKey<boolean>;
	private readonly _hasNextTabstop: IContextKey<boolean>;
	private readonly _hasPrevTabstop: IContextKey<boolean>;

	private _session?: SnippetSession;
	private _snippetListener = new DisposableStore();
	private _modelVersionId: number = -1;
	private _currentChoice?: Choice;

	private _choiceCompletionItemProvider?: CompletionItemProvider;

	constructor(
		private readonly _editor: ICodeEditor,
		@ILogService private readonly _logService: ILogService,
		@ILanguageFeaturesService private readonly _languageFeaturesService: ILanguageFeaturesService,
		@IContextKeyService contextKeyService: IContextKeyService,
		@ILanguageConfigurationService private readonly _languageConfigurationService: ILanguageConfigurationService,
	) {
		this._inSnippet = SnippetController2.InSnippetMode.bindTo(contextKeyService);
		this._hasNextTabstop = SnippetController2.HasNextTabstop.bindTo(contextKeyService);
		this._hasPrevTabstop = SnippetController2.HasPrevTabstop.bindTo(contextKeyService);
	}

	dispose(): void {
		this._inSnippet.reset();
		this._hasPrevTabstop.reset();
		this._hasNextTabstop.reset();
		this._session?.dispose();
		this._snippetListener.dispose();
	}

	insert(
		template: string,
		opts?: Partial<ISnippetInsertOptions>
	): void {
		// this is here to find out more about the yet-not-understood
		// error that sometimes happens when we fail to inserted a nested
		// snippet
		try {
			this._doInsert(template, typeof opts === 'undefined' ? _defaultOptions : { ..._defaultOptions, ...opts });

		} catch (e) {
			this.cancel();
			this._logService.error(e);
			this._logService.error('snippet_error');
			this._logService.error('insert_template=', template);
			this._logService.error('existing_template=', this._session ? this._session._logInfo() : '<no_session>');
		}
	}

	private _doInsert(
		template: string,
		opts: ISnippetInsertOptions
	): void {
		if (!this._editor.hasModel()) {
			return;
		}

		// don't listen while inserting the snippet
		// as that is the inflight state causing cancelation
		this._snippetListener.clear();

		if (opts.undoStopBefore) {
			this._editor.getModel().pushStackElement();
		}

		if (!this._session) {
			this._modelVersionId = this._editor.getModel().getAlternativeVersionId();
			this._session = new SnippetSession(this._editor, template, opts, this._languageConfigurationService);
			this._session.insert();
		} else {
			this._session.merge(template, opts);
		}

		if (opts.undoStopAfter) {
			this._editor.getModel().pushStackElement();
		}

		// regster completion item provider when there is any choice element
		if (this._session?.hasChoice) {
			this._choiceCompletionItemProvider = {
				provideCompletionItems: (model: ITextModel, position: Position) => {
					if (!this._session || model !== this._editor.getModel() || !Position.equals(this._editor.getPosition(), position)) {
						return undefined;
					}
					const { activeChoice } = this._session;
					if (!activeChoice || activeChoice.choice.options.length === 0) {
						return undefined;
					}

					const word = model.getValueInRange(activeChoice.range);
					const isAnyOfOptions = Boolean(activeChoice.choice.options.find(o => o.value === word));
					const suggestions: CompletionItem[] = [];
					for (let i = 0; i < activeChoice.choice.options.length; i++) {
						const option = activeChoice.choice.options[i];
						suggestions.push({
							kind: CompletionItemKind.Value,
							label: option.value,
							insertText: option.value,
							sortText: 'a'.repeat(i + 1),
							range: activeChoice.range,
							filterText: isAnyOfOptions ? `${word}_${option.value}` : undefined,
							command: { id: 'jumpToNextSnippetPlaceholder', title: localize('next', 'Go to next placeholder...') }
						});
					}
					return { suggestions };
				}
			};

			const registration = this._languageFeaturesService.completionProvider.register({
				language: this._editor.getModel().getLanguageId(),
				pattern: this._editor.getModel().uri.fsPath,
				scheme: this._editor.getModel().uri.scheme
			}, this._choiceCompletionItemProvider);

			this._snippetListener.add(registration);
		}

		this._updateState();

		this._snippetListener.add(this._editor.onDidChangeModelContent(e => e.isFlush && this.cancel()));
		this._snippetListener.add(this._editor.onDidChangeModel(() => this.cancel()));
		this._snippetListener.add(this._editor.onDidChangeCursorSelection(() => this._updateState()));
	}

	private _updateState(): void {
		if (!this._session || !this._editor.hasModel()) {
			// canceled in the meanwhile
			return;
		}

		if (this._modelVersionId === this._editor.getModel().getAlternativeVersionId()) {
			// undo until the 'before' state happened
			// and makes use cancel snippet mode
			return this.cancel();
		}

		if (!this._session.hasPlaceholder) {
			// don't listen for selection changes and don't
			// update context keys when the snippet is plain text
			return this.cancel();
		}

		if (this._session.isAtLastPlaceholder || !this._session.isSelectionWithinPlaceholders()) {
			this._editor.getModel().pushStackElement();
			return this.cancel();
		}

		this._inSnippet.set(true);
		this._hasPrevTabstop.set(!this._session.isAtFirstPlaceholder);
		this._hasNextTabstop.set(!this._session.isAtLastPlaceholder);

		this._handleChoice();
	}

	private _handleChoice(): void {
		if (!this._session || !this._editor.hasModel()) {
			this._currentChoice = undefined;
			return;
		}

		const { activeChoice } = this._session;
		if (!activeChoice || !this._choiceCompletionItemProvider) {
			this._currentChoice = undefined;
			return;
		}

		if (this._currentChoice !== activeChoice.choice) {
			this._currentChoice = activeChoice.choice;

			// trigger suggest with the special choice completion provider
			queueMicrotask(() => {
				showSimpleSuggestions(this._editor, this._choiceCompletionItemProvider!);
			});
		}
	}

	finish(): void {
		while (this._inSnippet.get()) {
			this.next();
		}
	}

	cancel(resetSelection: boolean = false): void {
		this._inSnippet.reset();
		this._hasPrevTabstop.reset();
		this._hasNextTabstop.reset();
		this._snippetListener.clear();

		this._currentChoice = undefined;

		this._session?.dispose();
		this._session = undefined;
		this._modelVersionId = -1;
		if (resetSelection) {
			// reset selection to the primary cursor when being asked
			// for. this happens when explicitly cancelling snippet mode,
			// e.g. when pressing ESC
			this._editor.setSelections([this._editor.getSelection()!]);
		}
	}

	prev(): void {
		if (this._session) {
			this._session.prev();
		}
		this._updateState();
	}

	next(): void {
		if (this._session) {
			this._session.next();
		}
		this._updateState();
	}

	isInSnippet(): boolean {
		return Boolean(this._inSnippet.get());
	}

	getSessionEnclosingRange(): Range | undefined {
		if (this._session) {
			return this._session.getEnclosingRange();
		}
		return undefined;
	}
}


registerEditorContribution(SnippetController2.ID, SnippetController2);

const CommandCtor = EditorCommand.bindToContribution<SnippetController2>(SnippetController2.get);

registerEditorCommand(new CommandCtor({
	id: 'jumpToNextSnippetPlaceholder',
	precondition: ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasNextTabstop),
	handler: ctrl => ctrl.next(),
	kbOpts: {
		weight: KeybindingWeight.EditorContrib + 30,
		kbExpr: EditorContextKeys.editorTextFocus,
		primary: KeyCode.Tab
	}
}));
registerEditorCommand(new CommandCtor({
	id: 'jumpToPrevSnippetPlaceholder',
	precondition: ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasPrevTabstop),
	handler: ctrl => ctrl.prev(),
	kbOpts: {
		weight: KeybindingWeight.EditorContrib + 30,
		kbExpr: EditorContextKeys.editorTextFocus,
		primary: KeyMod.Shift | KeyCode.Tab
	}
}));
registerEditorCommand(new CommandCtor({
	id: 'leaveSnippet',
	precondition: SnippetController2.InSnippetMode,
	handler: ctrl => ctrl.cancel(true),
	kbOpts: {
		weight: KeybindingWeight.EditorContrib + 30,
		kbExpr: EditorContextKeys.editorTextFocus,
		primary: KeyCode.Escape,
		secondary: [KeyMod.Shift | KeyCode.Escape]
	}
}));

registerEditorCommand(new CommandCtor({
	id: 'acceptSnippet',
	precondition: SnippetController2.InSnippetMode,
	handler: ctrl => ctrl.finish(),
	// kbOpts: {
	// 	weight: KeybindingWeight.EditorContrib + 30,
	// 	kbExpr: EditorContextKeys.textFocus,
	// 	primary: KeyCode.Enter,
	// }
}));


// ---

export function performSnippetEdit(editor: ICodeEditor, snippet: string, selections: ISelection[]): boolean {
	const controller = SnippetController2.get(editor);
	if (!controller) {
		return false;
	}
	editor.focus();
	editor.setSelections(selections ?? []);
	controller.insert(snippet);
	return controller.isInSnippet();
}


export type ISnippetEdit = {
	range: Range;
	snippet: string;
};

// ---

export function performSnippetEdits(editor: ICodeEditor, edits: ISnippetEdit[]) {

	if (!editor.hasModel()) {
		return false;
	}
	if (edits.length === 0) {
		return false;
	}

	const model = editor.getModel();
	let newText = '';
	let last: ISnippetEdit | undefined;
	edits.sort((a, b) => Range.compareRangesUsingStarts(a.range, b.range));

	for (const item of edits) {
		if (last) {
			const between = Range.fromPositions(last.range.getEndPosition(), item.range.getStartPosition());
			const text = model.getValueInRange(between);
			newText += SnippetParser.escape(text);
		}
		newText += item.snippet;
		last = item;
	}

	const controller = SnippetController2.get(editor);
	if (!controller) {
		return false;
	}
	model.pushStackElement();
	const range = Range.plusRange(edits[0].range, edits[edits.length - 1].range);
	editor.setSelection(range);
	controller.insert(newText, { undoStopBefore: false });
	return controller.isInSnippet();
}