-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathcompletion.ts
183 lines (159 loc) · 7.43 KB
/
completion.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
// *****************************************************************************
// Copyright (C) 2018 Red Hat, Inc. and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0.
//
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License v. 2.0 are satisfied: GNU General Public License, version 2
// with the GNU Classpath Exception which is available at
// https://www.gnu.org/software/classpath/license.html.
//
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
// *****************************************************************************
import { URI } from '@theia/core/shared/vscode-uri';
import * as theia from '@theia/plugin';
import { CompletionItemTag, CompletionList, Range, SnippetString } from '../types-impl';
import { DocumentsExtImpl } from '../documents';
import * as Converter from '../type-converters';
import { Position } from '../../common/plugin-api-rpc';
import { CompletionContext, CompletionResultDto, Completion, CompletionDto, CompletionItemInsertTextRule, ChainedCacheId } from '../../common/plugin-api-rpc-model';
import { CommandRegistryImpl } from '../command-registry';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
export class CompletionAdapter {
private cacheId = 0;
private readonly cache = new Map<number, theia.CompletionItem[]>();
private readonly disposables = new Map<number, DisposableCollection>();
constructor(
private readonly delegate: theia.CompletionItemProvider,
private readonly documents: DocumentsExtImpl,
private readonly commands: CommandRegistryImpl
) { }
provideCompletionItems(resource: URI, position: Position, context: CompletionContext, token: theia.CancellationToken): Promise<CompletionResultDto | undefined> {
const document = this.documents.getDocumentData(resource);
if (!document) {
return Promise.reject(new Error(`There are no document for ${resource}`));
}
const doc = document.document;
const pos = Converter.toPosition(position);
// The default insert/replace ranges. It's important to compute them
// before asynchronously asking the provider for its results. See
// https://github.com/microsoft/vscode/issues/83400#issuecomment-546851421
const replacing = doc.getWordRangeAtPosition(pos) || new Range(pos, pos);
const inserting = replacing.with({ end: pos });
return Promise.resolve(this.delegate.provideCompletionItems(doc, pos, token, context)).then(value => {
const id = this.cacheId++;
const toDispose = new DisposableCollection();
this.disposables.set(id, toDispose);
const result: CompletionResultDto = {
id,
completions: [],
defaultRange: {
insert: Converter.fromRange(inserting),
replace: Converter.fromRange(replacing)
}
};
let list: CompletionList;
if (!value) {
return undefined;
} else if (Array.isArray(value)) {
list = new CompletionList(value);
} else {
list = value;
result.incomplete = list.isIncomplete;
}
for (let i = 0; i < list.items.length; i++) {
const suggestion = this.convertCompletionItem(list.items[i], i, id, inserting, replacing);
if (suggestion) {
result.completions.push(suggestion);
}
}
this.cache.set(id, list.items);
return result;
});
}
async resolveCompletionItem(chainedId: ChainedCacheId, token: theia.CancellationToken): Promise<Completion | undefined> {
const [parentId, id] = chainedId;
if (typeof this.delegate.resolveCompletionItem !== 'function') {
return undefined;
}
const item = this.cache.get(parentId)?.[id];
if (!item) {
return undefined;
}
const resolvedItem = await this.delegate.resolveCompletionItem(item, token);
if (!resolvedItem) {
return undefined;
}
return this.convertCompletionItem(resolvedItem, id, parentId);
}
async releaseCompletionItems(id: number): Promise<void> {
this.cache.delete(id);
const toDispose = this.disposables.get(id);
if (toDispose) {
toDispose.dispose();
this.disposables.delete(id);
}
}
private convertCompletionItem(item: theia.CompletionItem, id: number, parentId: number,
defaultInserting?: theia.Range, defaultReplacing?: theia.Range): CompletionDto | undefined {
const itemLabel = typeof item.label === 'string' ? item.label : item.label.label;
if (itemLabel.length === 0) {
console.warn('Invalid Completion Item -> must have at least a label');
return undefined;
}
const toDispose = this.disposables.get(parentId);
if (!toDispose) {
throw Error('DisposableCollection is missing...');
}
let insertText = itemLabel;
let insertTextRules = item.keepWhitespace ? CompletionItemInsertTextRule.KeepWhitespace : 0;
if (item.textEdit) {
insertText = item.textEdit.newText;
} else if (typeof item.insertText === 'string') {
insertText = item.insertText;
} else if (item.insertText instanceof SnippetString) {
insertText = item.insertText.value;
insertTextRules |= CompletionItemInsertTextRule.InsertAsSnippet;
}
let range: Completion['range'] | undefined;
const itemRange = item.textEdit?.range || item.range;
if (Range.isRange(itemRange)) {
range = Converter.fromRange(itemRange);
} else if (itemRange && (!defaultInserting?.isEqual(itemRange.inserting) || !defaultReplacing?.isEqual(itemRange.replacing))) {
range = {
insert: Converter.fromRange(itemRange.inserting),
replace: Converter.fromRange(itemRange.replacing)
};
}
const tags = (!!item.tags?.length || item.deprecated === true)
? [CompletionItemTag.Deprecated]
: undefined;
const documentation = typeof item.documentation !== 'undefined'
? Converter.fromMarkdown(item.documentation)
: undefined;
return {
id,
parentId,
label: item.label,
kind: Converter.fromCompletionItemKind(item.kind),
detail: item.detail,
documentation,
filterText: item.filterText,
sortText: item.sortText,
preselect: item.preselect,
insertText,
insertTextRules,
range,
additionalTextEdits: item.additionalTextEdits && item.additionalTextEdits.map(Converter.fromTextEdit),
command: this.commands.converter.toSafeCommand(item.command, toDispose),
commitCharacters: item.commitCharacters,
tags
};
}
static hasResolveSupport(provider: theia.CompletionItemProvider): boolean {
return typeof provider.resolveCompletionItem === 'function';
}
}