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
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { MarkdownString } from 'vs/base/common/htmlContent';
import { compare, compareSubstring } from 'vs/base/common/strings';
import { Position } from 'vs/editor/common/core/position';
import { IRange, Range } from 'vs/editor/common/core/range';
import { ITextModel } from 'vs/editor/common/model';
import { CompletionItem, CompletionItemKind, CompletionItemProvider, CompletionList, CompletionItemInsertTextRule, CompletionContext, CompletionTriggerKind, CompletionItemLabel } from 'vs/editor/common/languages';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { SnippetParser } from 'vs/editor/contrib/snippet/browser/snippetParser';
import { localize } from 'vs/nls';
import { ISnippetsService } from 'vs/workbench/contrib/snippets/browser/snippets.contribution';
import { Snippet, SnippetSource } from 'vs/workbench/contrib/snippets/browser/snippetsFile';
import { isPatternInWord } from 'vs/base/common/filters';
import { StopWatch } from 'vs/base/common/stopwatch';
import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry';
import { getWordAtText } from 'vs/editor/common/core/wordHelper';
export class SnippetCompletion implements CompletionItem {
label: CompletionItemLabel;
detail: string;
insertText: string;
documentation?: MarkdownString;
range: IRange | { insert: IRange; replace: IRange };
sortText: string;
kind: CompletionItemKind;
insertTextRules: CompletionItemInsertTextRule;
constructor(
readonly snippet: Snippet,
range: IRange | { insert: IRange; replace: IRange }
) {
this.label = { label: snippet.prefix, description: snippet.name };
this.detail = localize('detail.snippet', "{0} ({1})", snippet.description || snippet.name, snippet.source);
this.insertText = snippet.codeSnippet;
this.range = range;
this.sortText = `${snippet.snippetSource === SnippetSource.Extension ? 'z' : 'a'}-${snippet.prefix}`;
this.kind = CompletionItemKind.Snippet;
this.insertTextRules = CompletionItemInsertTextRule.InsertAsSnippet;
}
resolve(): this {
this.documentation = new MarkdownString().appendCodeblock('', new SnippetParser().text(this.snippet.codeSnippet));
return this;
}
static compareByLabel(a: SnippetCompletion, b: SnippetCompletion): number {
return compare(a.label.label, b.label.label);
}
}
export class SnippetCompletionProvider implements CompletionItemProvider {
readonly _debugDisplayName = 'snippetCompletions';
constructor(
@ILanguageService private readonly _languageService: ILanguageService,
@ISnippetsService private readonly _snippets: ISnippetsService,
@ILanguageConfigurationService private readonly _languageConfigurationService: ILanguageConfigurationService
) {
//
}
async provideCompletionItems(model: ITextModel, position: Position, context: CompletionContext): Promise<CompletionList> {
const sw = new StopWatch(true);
const languageId = this._getLanguageIdAtPosition(model, position);
const languageConfig = this._languageConfigurationService.getLanguageConfiguration(languageId);
const snippets = new Set(await this._snippets.getSnippets(languageId));
const lineContentLow = model.getLineContent(position.lineNumber).toLowerCase();
const wordUntil = model.getWordUntilPosition(position).word.toLowerCase();
const suggestions: SnippetCompletion[] = [];
const columnOffset = position.column - 1;
const triggerCharacterLow = context.triggerCharacter?.toLowerCase() ?? '';
snippet: for (const snippet of snippets) {
if (context.triggerKind === CompletionTriggerKind.TriggerCharacter && !snippet.prefixLow.startsWith(triggerCharacterLow)) {
// strict -> when having trigger characters they must prefix-match
continue snippet;
}
const word = getWordAtText(1, languageConfig.getWordDefinition(), snippet.prefixLow, 0);
if (wordUntil && word && !isPatternInWord(wordUntil, 0, wordUntil.length, snippet.prefixLow, 0, snippet.prefixLow.length)) {
// when at a word the snippet prefix must match
continue snippet;
}
column: for (let pos = Math.max(0, columnOffset - snippet.prefixLow.length); pos < lineContentLow.length; pos++) {
if (!isPatternInWord(lineContentLow, pos, columnOffset, snippet.prefixLow, 0, snippet.prefixLow.length)) {
continue column;
}
const prefixRestLen = snippet.prefixLow.length - (columnOffset - pos);
const endsWithPrefixRest = compareSubstring(lineContentLow, snippet.prefixLow, columnOffset, columnOffset + prefixRestLen, columnOffset - pos);
const startPosition = position.with(undefined, pos + 1);
if (wordUntil && position.equals(startPosition)) {
// at word-end but no overlap
continue snippet;
}
let endColumn = endsWithPrefixRest === 0 ? position.column + prefixRestLen : position.column;
// First check if there is anything to the right of the cursor
if (columnOffset < lineContentLow.length) {
const autoClosingPairs = languageConfig.getAutoClosingPairs();
const standardAutoClosingPairConditionals = autoClosingPairs.autoClosingPairsCloseSingleChar.get(lineContentLow[columnOffset]);
// If the character to the right of the cursor is a closing character of an autoclosing pair
if (standardAutoClosingPairConditionals?.some(p =>
// and the start position is the opening character of an autoclosing pair
p.open === lineContentLow[startPosition.column - 1] &&
// and the snippet prefix contains the opening and closing pair at its edges
snippet.prefix.startsWith(p.open) &&
snippet.prefix[snippet.prefix.length - 1] === p.close)
) {
// Eat the character that was likely inserted because of auto-closing pairs
endColumn++;
}
}
const replace = Range.fromPositions(startPosition, { lineNumber: position.lineNumber, column: endColumn });
const insert = replace.setEndPosition(position.lineNumber, position.column);
suggestions.push(new SnippetCompletion(snippet, { replace, insert }));
snippets.delete(snippet);
break;
}
}
// add remaing snippets when the current prefix ends in whitespace or when line is empty
// and when not having a trigger character
if (!triggerCharacterLow) {
const endsInWhitespace = /\s/.test(lineContentLow[position.column - 2]);
if (endsInWhitespace || !lineContentLow /*empty line*/) {
for (let snippet of snippets) {
const insert = Range.fromPositions(position);
const replace = lineContentLow.indexOf(snippet.prefixLow, columnOffset) === columnOffset ? insert.setEndPosition(position.lineNumber, position.column + snippet.prefixLow.length) : insert;
suggestions.push(new SnippetCompletion(snippet, { replace, insert }));
}
}
}
// dismbiguate suggestions with same labels
suggestions.sort(SnippetCompletion.compareByLabel);
for (let i = 0; i < suggestions.length; i++) {
let item = suggestions[i];
let to = i + 1;
for (; to < suggestions.length && item.label === suggestions[to].label; to++) {
suggestions[to].label.label = localize('snippetSuggest.longLabel', "{0}, {1}", suggestions[to].label.label, suggestions[to].snippet.name);
}
if (to > i + 1) {
suggestions[i].label.label = localize('snippetSuggest.longLabel', "{0}, {1}", suggestions[i].label.label, suggestions[i].snippet.name);
i = to;
}
}
return {
suggestions,
duration: sw.elapsed()
};
}
resolveCompletionItem(item: CompletionItem): CompletionItem {
return (item instanceof SnippetCompletion) ? item.resolve() : item;
}
private _getLanguageIdAtPosition(model: ITextModel, position: Position): string {
// validate the `languageId` to ensure this is a user
// facing language with a name and the chance to have
// snippets, else fall back to the outer language
model.tokenizeIfCheap(position.lineNumber);
let languageId = model.getLanguageIdAtPosition(position.lineNumber, position.column);
if (!this._languageService.getLanguageName(languageId)) {
languageId = model.getLanguageId();
}
return languageId;
}
}
|