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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
|
local M = {}
local api = vim.api
local lsp = vim.lsp
local protocol = lsp.protocol
local ms = protocol.Methods
local rtt_ms = 50
local ns_to_ms = 0.000001
--- @alias vim.lsp.CompletionResult lsp.CompletionList | lsp.CompletionItem[]
-- TODO(mariasolos): Remove this declaration once we figure out a better way to handle
-- literal/anonymous types (see https://github.com/neovim/neovim/pull/27542/files#r1495259331).
--- @nodoc
--- @class lsp.ItemDefaults
--- @field editRange lsp.Range | { insert: lsp.Range, replace: lsp.Range } | nil
--- @field insertTextFormat lsp.InsertTextFormat?
--- @field insertTextMode lsp.InsertTextMode?
--- @field data any
--- @nodoc
--- @class vim.lsp.completion.BufHandle
--- @field clients table<integer, vim.lsp.Client>
--- @field triggers table<string, vim.lsp.Client[]>
--- @field convert? fun(item: lsp.CompletionItem): table
--- @type table<integer, vim.lsp.completion.BufHandle>
local buf_handles = {}
--- @nodoc
--- @class vim.lsp.completion.Context
local Context = {
cursor = nil, --- @type [integer, integer]?
last_request_time = nil, --- @type integer?
pending_requests = {}, --- @type function[]
isIncomplete = false,
}
--- @nodoc
function Context:cancel_pending()
for _, cancel in ipairs(self.pending_requests) do
cancel()
end
self.pending_requests = {}
end
--- @nodoc
function Context:reset()
-- Note that the cursor isn't reset here, it needs to survive a `CompleteDone` event.
self.isIncomplete = false
self.last_request_time = nil
self:cancel_pending()
end
--- @type uv.uv_timer_t?
local completion_timer = nil
--- @return uv.uv_timer_t
local function new_timer()
return assert(vim.uv.new_timer())
end
local function reset_timer()
if completion_timer then
completion_timer:stop()
completion_timer:close()
end
completion_timer = nil
end
--- @param window integer
--- @param warmup integer
--- @return fun(sample: number): number
local function exp_avg(window, warmup)
local count = 0
local sum = 0
local value = 0
return function(sample)
if count < warmup then
count = count + 1
sum = sum + sample
value = sum / count
else
local factor = 2.0 / (window + 1)
value = value * (1 - factor) + sample * factor
end
return value
end
end
local compute_new_average = exp_avg(10, 10)
--- @return number
local function next_debounce()
if not Context.last_request_time then
return rtt_ms
end
local ms_since_request = (vim.uv.hrtime() - Context.last_request_time) * ns_to_ms
return math.max((ms_since_request - rtt_ms) * -1, 0)
end
--- @param input string Unparsed snippet
--- @return string # Parsed snippet if successful, else returns its input
local function parse_snippet(input)
local ok, parsed = pcall(function()
return lsp._snippet_grammar.parse(input)
end)
return ok and tostring(parsed) or input
end
--- @param item lsp.CompletionItem
local function apply_snippet(item)
if item.textEdit then
vim.snippet.expand(item.textEdit.newText)
elseif item.insertText then
vim.snippet.expand(item.insertText)
end
end
--- Returns text that should be inserted when a selecting completion item. The
--- precedence is as follows: textEdit.newText > insertText > label
---
--- See https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion
---
--- @param item lsp.CompletionItem
--- @param prefix string
--- @param match fun(text: string, prefix: string):boolean
--- @return string
local function get_completion_word(item, prefix, match)
if item.insertTextFormat == protocol.InsertTextFormat.Snippet then
if item.textEdit then
-- Use label instead of text if text has different starting characters.
-- label is used as abbr (=displayed), but word is used for filtering
-- This is required for things like postfix completion.
-- E.g. in lua:
--
-- local f = {}
-- f@|
-- ▲
-- └─ cursor
--
-- item.textEdit.newText: table.insert(f, $0)
-- label: insert
--
-- Typing `i` would remove the candidate because newText starts with `t`.
local text = parse_snippet(item.insertText or item.textEdit.newText)
local word = #text < #item.label and vim.fn.matchstr(text, '\\k*') or item.label
if item.filterText and not match(word, prefix) then
return item.filterText
else
return word
end
elseif item.insertText and item.insertText ~= '' then
return parse_snippet(item.insertText)
else
return item.label
end
elseif item.textEdit then
local word = item.textEdit.newText
return word:match('^(%S*)') or word
elseif item.insertText and item.insertText ~= '' then
return item.insertText
end
return item.label
end
--- Applies the given defaults to the completion item, modifying it in place.
---
--- @param item lsp.CompletionItem
--- @param defaults lsp.ItemDefaults?
local function apply_defaults(item, defaults)
if not defaults then
return
end
item.insertTextFormat = item.insertTextFormat or defaults.insertTextFormat
item.insertTextMode = item.insertTextMode or defaults.insertTextMode
item.data = item.data or defaults.data
if defaults.editRange then
local textEdit = item.textEdit or {}
item.textEdit = textEdit
textEdit.newText = textEdit.newText or item.textEditText or item.insertText or item.label
if defaults.editRange.start then
textEdit.range = textEdit.range or defaults.editRange
elseif defaults.editRange.insert then
textEdit.insert = defaults.editRange.insert
textEdit.replace = defaults.editRange.replace
end
end
end
--- @param result vim.lsp.CompletionResult
--- @return lsp.CompletionItem[]
local function get_items(result)
if result.items then
-- When we have a list, apply the defaults and return an array of items.
for _, item in ipairs(result.items) do
---@diagnostic disable-next-line: param-type-mismatch
apply_defaults(item, result.itemDefaults)
end
return result.items
else
-- Else just return the items as they are.
return result
end
end
---@param item lsp.CompletionItem
---@return string
local function get_doc(item)
local doc = item.documentation
if not doc then
return ''
end
if type(doc) == 'string' then
return doc
end
if type(doc) == 'table' and type(doc.value) == 'string' then
return doc.value
end
vim.notify('invalid documentation value: ' .. vim.inspect(doc), vim.log.levels.WARN)
return ''
end
---@param value string
---@param prefix string
---@return boolean
local function match_item_by_value(value, prefix)
if prefix == '' then
return true
end
if vim.o.completeopt:find('fuzzy') ~= nil then
return next(vim.fn.matchfuzzy({ value }, prefix)) ~= nil
end
if vim.o.ignorecase and (not vim.o.smartcase or not prefix:find('%u')) then
return vim.startswith(value:lower(), prefix:lower())
end
return vim.startswith(value, prefix)
end
--- Turns the result of a `textDocument/completion` request into vim-compatible
--- |complete-items|.
---
--- @private
--- @param result vim.lsp.CompletionResult Result of `textDocument/completion`
--- @param prefix string prefix to filter the completion items
--- @param client_id integer? Client ID
--- @return table[]
--- @see complete-items
function M._lsp_to_complete_items(result, prefix, client_id)
local items = get_items(result)
if vim.tbl_isempty(items) then
return {}
end
---@type fun(item: lsp.CompletionItem):boolean
local matches
if not prefix:find('%w') then
matches = function(_)
return true
end
else
---@param item lsp.CompletionItem
matches = function(item)
if item.filterText then
return match_item_by_value(item.filterText, prefix)
end
if item.textEdit then
-- server took care of filtering
return true
end
return match_item_by_value(item.label, prefix)
end
end
local candidates = {}
local bufnr = api.nvim_get_current_buf()
local user_convert = vim.tbl_get(buf_handles, bufnr, 'convert')
for _, item in ipairs(items) do
if matches(item) then
local word = get_completion_word(item, prefix, match_item_by_value)
local hl_group = ''
if
item.deprecated
or vim.list_contains((item.tags or {}), protocol.CompletionTag.Deprecated)
then
hl_group = 'DiagnosticDeprecated'
end
local completion_item = {
word = word,
abbr = item.label,
kind = protocol.CompletionItemKind[item.kind] or 'Unknown',
menu = item.detail or '',
info = get_doc(item),
icase = 1,
dup = 1,
empty = 1,
abbr_hlgroup = hl_group,
user_data = {
nvim = {
lsp = {
completion_item = item,
client_id = client_id,
},
},
},
}
if user_convert then
completion_item = vim.tbl_extend('keep', user_convert(item), completion_item)
end
table.insert(candidates, completion_item)
end
end
---@diagnostic disable-next-line: no-unknown
table.sort(candidates, function(a, b)
---@type lsp.CompletionItem
local itema = a.user_data.nvim.lsp.completion_item
---@type lsp.CompletionItem
local itemb = b.user_data.nvim.lsp.completion_item
return (itema.sortText or itema.label) < (itemb.sortText or itemb.label)
end)
return candidates
end
--- @param lnum integer 0-indexed
--- @param line string
--- @param items lsp.CompletionItem[]
--- @param encoding string
--- @return integer?
local function adjust_start_col(lnum, line, items, encoding)
local min_start_char = nil
for _, item in pairs(items) do
if item.textEdit and item.textEdit.range.start.line == lnum then
if min_start_char and min_start_char ~= item.textEdit.range.
|