/
autoCompleteProvider.ts
306 lines (268 loc) · 8.88 KB
/
autoCompleteProvider.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
// more: https://github.com/atom-community/autocomplete-plus/wiki/Provider-API
import * as Atom from "atom"
import * as ACP from "atom/autocomplete-plus"
import * as fuzzaldrin from "fuzzaldrin"
import {GetClientFunction, TSClient} from "../../client"
import {FileLocationQuery, inits, spanToRange, typeScriptScopes} from "./utils"
type SuggestionWithDetails = ACP.TextSuggestion & {
details?: protocol.CompletionEntryDetails
replacementRange?: Atom.Range
}
export class AutocompleteProvider implements ACP.AutocompleteProvider {
public selector = typeScriptScopes()
.map(x => (x.includes(".") ? `.${x}` : x))
.join(", ")
public disableForSelector = ".comment"
public inclusionPriority = 3
public suggestionPriority = atom.config.get("atom-typescript").autocompletionSuggestionPriority
public excludeLowerPriority = false
private lastSuggestions?: {
// Client used to get the suggestions
client: TSClient
// File and position for the suggestions
location: FileLocationQuery
// Prefix used
prefix: string
// The completions that were returned for the position
suggestions: SuggestionWithDetails[]
}
constructor(private getClient: GetClientFunction) {}
public async getSuggestions(opts: ACP.SuggestionsRequestedEvent): Promise<ACP.AnySuggestion[]> {
const location = getLocationQuery(opts)
const {prefix} = opts
if (!location) {
return []
}
// Don't show autocomplete if the previous character was a non word character except "."
const lastChar = getLastNonWhitespaceChar(opts.editor.getBuffer(), opts.bufferPosition)
if (lastChar !== undefined && !opts.activatedManually) {
if (/\W/i.test(lastChar) && lastChar !== ".") {
return []
}
}
// Don't show autocomplete if we're in a string.template and not in a template expression
if (
containsScope(opts.scopeDescriptor.getScopesArray(), "string.template.") &&
!containsScope(opts.scopeDescriptor.getScopesArray(), "template.expression.")
) {
return []
}
try {
let suggestions = await this.getSuggestionsWithCache(prefix, location, opts.activatedManually)
const alphaPrefix = prefix.replace(/\W/g, "")
if (alphaPrefix !== "") {
suggestions = fuzzaldrin.filter(suggestions, alphaPrefix, {
key: "text",
})
}
// Get additional details for the first few suggestions
await this.getAdditionalDetails(suggestions.slice(0, 10), location)
return suggestions.map(suggestion => ({
replacementPrefix: suggestion.replacementRange
? opts.editor.getTextInBufferRange(suggestion.replacementRange)
: getReplacementPrefix(opts, suggestion.text!),
...addCallableParens(suggestion),
}))
} catch (error) {
return []
}
}
private async getAdditionalDetails(
suggestions: SuggestionWithDetails[],
location: FileLocationQuery,
) {
if (suggestions.some(s => !s.details) && this.lastSuggestions) {
const details = await this.lastSuggestions.client.execute("completionEntryDetails", {
entryNames: suggestions.map(s => s.displayText!),
...location,
})
details.body!.forEach((detail, i) => {
const suggestion = suggestions[i]
suggestion.details = detail
let parts = detail.displayParts
if (
parts.length >= 3 &&
parts[0].text === "(" &&
parts[1].text === suggestion.leftLabel &&
parts[2].text === ")"
) {
parts = parts.slice(3)
}
suggestion.rightLabel = parts.map(d => d.text).join("")
suggestion.description =
detail.documentation && detail.documentation.map(d => d.text).join(" ")
})
}
}
// Try to reuse the last completions we got from tsserver if they're for the same position.
private async getSuggestionsWithCache(
prefix: string,
location: FileLocationQuery,
activatedManually: boolean,
): Promise<SuggestionWithDetails[]> {
if (this.lastSuggestions && !activatedManually) {
const lastLoc = this.lastSuggestions.location
const lastCol = getNormalizedCol(this.lastSuggestions.prefix, lastLoc.offset)
const thisCol = getNormalizedCol(prefix, location.offset)
if (lastLoc.file === location.file && lastLoc.line === location.line && lastCol === thisCol) {
if (this.lastSuggestions.suggestions.length !== 0) {
return this.lastSuggestions.suggestions
}
}
}
const client = await this.getClient(location.file)
const suggestions = await getSuggestionsInternal(client, location, prefix)
this.lastSuggestions = {
client,
location,
prefix,
suggestions,
}
return suggestions
}
}
async function getSuggestionsInternal(
client: TSClient,
location: FileLocationQuery,
prefix: string,
) {
if (parseInt(client.version.split(".")[0], 10) >= 3) {
// use completionInfo
const completions = await client.execute("completionInfo", {
prefix,
includeExternalModuleExports: false,
includeInsertTextCompletions: true,
...location,
})
return completions.body!.entries.map(completionEntryToSuggestion)
} else {
// use deprecated completions
const completions = await client.execute("completions", {
prefix,
includeExternalModuleExports: false,
includeInsertTextCompletions: true,
...location,
})
return completions.body!.map(completionEntryToSuggestion)
}
}
// Decide what needs to be replaced in the editor buffer when inserting the completion
function getReplacementPrefix(opts: ACP.SuggestionsRequestedEvent, replacement: string): string {
const prefix = opts.editor
.getBuffer()
.getTextInRange([[opts.bufferPosition.row, 0], opts.bufferPosition])
for (const i of inits(replacement.toLowerCase(), 1)) {
if (prefix.toLowerCase().endsWith(i)) {
return prefix.slice(-i.length)
}
}
return ""
}
// When the user types each character in ".hello", we want to normalize the column such that it's
// the same for every invocation of the getSuggestions. In this case, it would be right after "."
function getNormalizedCol(prefix: string, col: number): number {
const length = prefix === "." ? 0 : prefix.length
return col - length
}
function getLocationQuery(opts: ACP.SuggestionsRequestedEvent): FileLocationQuery | undefined {
const path = opts.editor.getPath()
if (path === undefined) {
return undefined
}
return {
file: path,
line: opts.bufferPosition.row + 1,
offset: opts.bufferPosition.column + 1,
}
}
function getLastNonWhitespaceChar(buffer: Atom.TextBuffer, pos: Atom.Point): string | undefined {
let lastChar: string | undefined
const range = new Atom.Range([0, 0], pos)
buffer.backwardsScanInRange(
/\S/,
range,
({matchText, stop}: {matchText: string; stop: () => void}) => {
lastChar = matchText
stop()
},
)
return lastChar
}
function containsScope(scopes: ReadonlyArray<string>, matchScope: string): boolean {
for (const scope of scopes) {
if (scope.includes(matchScope)) {
return true
}
}
return false
}
function completionEntryToSuggestion(entry: protocol.CompletionEntry): SuggestionWithDetails {
return {
displayText: entry.name,
text: entry.insertText !== undefined ? entry.insertText : entry.name,
leftLabel: entry.kind,
replacementRange: entry.replacementSpan ? spanToRange(entry.replacementSpan) : undefined,
type: kindMap[entry.kind],
}
}
function addCallableParens(s: SuggestionWithDetails): ACP.TextSuggestion | ACP.SnippetSuggestion {
if (
atom.config.get("atom-typescript.autocompleteParens") &&
["function", "method"].includes(s.leftLabel!)
) {
return {...s, snippet: `${s.text}($1)`, text: undefined}
} else return s
}
/** From :
* https://github.com/atom-community/autocomplete-plus/pull/334#issuecomment-85697409
*/
type ACPCompletionType =
| "variable"
| "constant"
| "property"
| "value"
| "method"
| "function"
| "class"
| "type"
| "keyword"
| "tag"
| "import"
| "require"
| "snippet"
const kindMap: {[key in protocol.ScriptElementKind]: ACPCompletionType | undefined} = {
directory: "require",
module: "import",
"external module name": "import",
class: "class",
"local class": "class",
method: "method",
property: "property",
getter: "property",
setter: "property",
"JSX attribute": "property",
constructor: "method",
enum: "type",
interface: "type",
type: "type",
"type parameter": "type",
"primitive type": "type",
function: "function",
"local function": "function",
label: "variable",
alias: "import",
var: "variable",
let: "variable",
"local var": "variable",
parameter: "variable",
"enum member": "constant",
const: "constant",
string: "value",
keyword: "keyword",
"": undefined,
warning: undefined,
script: undefined,
call: undefined,
index: undefined,
construct: undefined,
}