robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
59.5 KiB2025 linesraw
1---@diagnostic disable: no-unknown
2local t = require('test.testutil')
3local t_lsp = require('test.functional.plugin.lsp.testutil')
4local n = require('test.functional.testnvim')()
5
6local describe, it, before_each, after_each = t.describe, t.it, t.before_each, t.after_each
7local clear = n.clear
8local eq = t.eq
9local neq = t.neq
10local exec_lua = n.exec_lua
11local feed = n.feed
12local retry = t.retry
13local Screen = require('test.functional.ui.screen')
14
15local create_server_definition = t_lsp.create_server_definition
16
17--- Extract only abbr/word from a list of completion items for assertion
18---@param items table
19---@return table
20local function extract_word_abbr(items)
21  return vim.tbl_map(function(x)
22    return { abbr = x.abbr, word = x.word }
23  end, items)
24end
25
26--- Convert completion results.
27---
28---@param line string line contents. Mark cursor position with `|`
29---@param candidates lsp.CompletionList|lsp.CompletionItem[]
30---@param lnum? integer 0-based, defaults to 0
31---@return {items: table[], server_start_boundary: integer?}
32local function complete(line, candidates, lnum, server_boundary)
33  lnum = lnum or 0
34  -- nvim_win_get_cursor returns 0 based column, line:find returns 1 based
35  local cursor_col = line:find('|') - 1
36  line = line:gsub('|', '')
37  return exec_lua(function(result)
38    local line_to_cursor = line:sub(1, cursor_col)
39    local client_start_boundary = vim.fn.match(line_to_cursor, '\\k*$')
40    local items, new_server_boundary = require('vim.lsp.completion')._convert_results(
41      line,
42      lnum,
43      cursor_col,
44      1,
45      client_start_boundary,
46      server_boundary,
47      result,
48      'utf-16'
49    )
50    return {
51      items = items,
52      server_start_boundary = new_server_boundary,
53    }
54  end, candidates)
55end
56
57--- Wait for pumvisible() to equal `visible` (default 1)
58---@param visible? integer 1 to wait for pum shown, 0 to wait for pum hidden
59local function wait_for_pum(visible)
60  visible = visible == nil and 1 or visible
61  retry(nil, nil, function()
62    eq(
63      visible,
64      exec_lua(function()
65        return vim.fn.pumvisible()
66      end)
67    )
68  end)
69end
70
71--- Detach client and assert the pum no longer appears.
72---@param client_id integer
73local function assert_cleanup_after_detach(client_id)
74  feed('<Esc>o')
75  exec_lua(function()
76    vim.lsp.completion.get()
77  end)
78  wait_for_pum(1)
79  feed('<C-e>')
80
81  -- Detach then re-trigger under identical conditions.
82  exec_lua(function()
83    vim.lsp.buf_detach_client(0, client_id)
84  end)
85  exec_lua(function()
86    vim.lsp.completion.get()
87  end)
88  wait_for_pum(0)
89  feed('<Esc>')
90end
91
92describe('vim.lsp.completion: item conversion', function()
93  before_each(n.clear)
94
95  -- https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion
96  it('prefers textEdit over label as word', function()
97    local range0 = {
98      start = { line = 0, character = 0 },
99      ['end'] = { line = 0, character = 0 },
100    }
101    local completion_list = {
102      -- resolves into label
103      { label = 'foobar', sortText = 'a', documentation = 'documentation' },
104      {
105        label = 'foobar',
106        sortText = 'b',
107        documentation = { value = 'documentation' },
108      },
109      -- resolves into insertText
110      { label = 'foocar', sortText = 'c', insertText = 'foobar' },
111      { label = 'foocar', sortText = 'd', insertText = 'foobar' },
112      -- resolves into textEdit.newText
113      {
114        label = 'foocar',
115        sortText = 'e',
116        insertText = 'foodar',
117        textEdit = { newText = 'foobar', range = range0 },
118      },
119      { label = 'foocar', sortText = 'f', textEdit = { newText = 'foobar', range = range0 } },
120      -- plain text
121      {
122        label = 'foocar',
123        sortText = 'g',
124        insertText = 'foodar(${1:var1})',
125        insertTextFormat = 1,
126      },
127      {
128        label = '•INT16_C(c)',
129        insertText = 'INT16_C(${1:c})',
130        insertTextFormat = 2,
131        filterText = 'INT16_C',
132        sortText = 'h',
133        textEdit = {
134          newText = 'INT16_C(${1:c})',
135          range = range0,
136        },
137      },
138      -- "" is unset
139      {
140        label = 'zoocar_long',
141        sortText = '',
142        insertText = '',
143        insertTextFormat = 2,
144        textEdit = { newText = 'foobar($1)', range = range0 },
145      },
146    }
147    local expected = {
148      { abbr = 'foobar', word = 'foobar' },
149      { abbr = 'foobar', word = 'foobar' },
150      { abbr = 'foocar', word = 'foobar' },
151      { abbr = 'foocar', word = 'foobar' },
152      { abbr = 'foocar', word = 'foobar' },
153      { abbr = 'foocar', word = 'foobar' },
154      { abbr = 'foocar', word = 'foodar(${1:var1})' }, -- marked as PlainText, text is used as is
155      { abbr = '•INT16_C(c)', word = 'INT16_C' },
156      { abbr = 'zoocar_long', word = 'foobar' },
157    }
158    local result = complete('|', completion_list)
159    eq(expected, extract_word_abbr(result.items))
160  end)
161
162  local word_sorter = function(a, b)
163    return a.word > b.word
164  end
165
166  it('does not filter if there is a textEdit', function()
167    local range0 = {
168      start = { line = 0, character = 0 },
169      ['end'] = { line = 0, character = 0 },
170    }
171    local completion_list = {
172      { label = 'foo', textEdit = { newText = 'foo', range = range0 } },
173      { label = 'bar', textEdit = { newText = 'bar', range = range0 } },
174    }
175    local result = complete('fo|', completion_list)
176    local expected = {
177      { abbr = 'foo', word = 'foo' },
178    }
179    local got = extract_word_abbr(result.items)
180    table.sort(expected, word_sorter)
181    table.sort(got, word_sorter)
182    eq(expected, got)
183  end)
184
185  it('generate "■" symbol with highlight group for CompletionItemKind.Color', function()
186    local completion_list = {
187      { label = 'text-red-300', kind = 16, documentation = 'color: rgb(252, 165, 165)' },
188    }
189    local result = complete('|', completion_list)
190    result = vim.tbl_map(function(x)
191      return {
192        word = x.word,
193        kind_hlgroup = x.kind_hlgroup,
194        kind = x.kind,
195      }
196    end, result.items)
197    eq({ { word = 'text-red-300', kind_hlgroup = '@lsp.color.fca5a5', kind = '■' } }, result)
198  end)
199
200  it('uses labelDetails for abbr and menu', function()
201    local completion_list = {
202      {
203        label = 'printf',
204        kind = 3,
205        detail = 'int',
206        sortText = '1',
207        labelDetails = { detail = '(const char *restrict, ...)', description = 'stdio.h' },
208      },
209      {
210        label = ' flush',
211        kind = 2,
212        insertText = 'flush()',
213        insertTextFormat = 2,
214        filterText = 'flush',
215        sortText = '2',
216        labelDetails = { detail = '()' },
217      },
218    }
219    local result = complete('|', completion_list)
220    eq('printf(const char *restrict, ...)', result.items[1].abbr)
221    eq('stdio.h', result.items[1].menu)
222    eq('flush', result.items[2].word)
223  end)
224
225  ---@param prefix string
226  ---@param items lsp.CompletionItem[]
227  ---@param expected table[]
228  local assert_completion_matches = function(prefix, items, expected)
229    local got = extract_word_abbr(complete(prefix .. '|', items).items)
230    table.sort(expected, word_sorter)
231    table.sort(got, word_sorter)
232    eq(expected, got)
233  end
234
235  it('uses filterText as word if label/newText would not match', function()
236    local items = {
237      {
238        filterText = '<module',
239        insertTextFormat = 2,
240        kind = 10,
241        label = 'module',
242        sortText = 'module',
243        textEdit = {
244          newText = '<module>$1</module>$0',
245          range = {
246            start = { character = 0, line = 0 },
247            ['end'] = { character = 0, line = 0 },
248          },
249        },
250      },
251      {
252        filterText = 'atto',
253        insertTextFormat = 1,
254        kind = 7,
255        label = '•std::atto',
256        sortText = 'atto',
257        textEdit = {
258          newText = 'std::atto',
259          range = {
260            start = { character = 0, line = 0 },
261            ['end'] = { character = 0, line = 0 },
262          },
263        },
264      },
265      {
266        filterText = 'adopt_lock_t',
267        insertTextFormat = 1,
268        kind = 7,
269        label = '•std::adopt_lock_t',
270        sortText = 'adopt_lock_t',
271        insertText = 'std::adopt_lock_t',
272      },
273    }
274    assert_completion_matches('<mo', items, {
275      { abbr = 'module', word = '<module' },
276    })
277    assert_completion_matches('a', items, {
278      { abbr = '•std::atto', word = 'atto' },
279      { abbr = '•std::adopt_lock_t', word = 'adopt_lock_t' },
280    })
281    assert_completion_matches('', items, {
282      { abbr = 'module', word = 'module' },
283      { abbr = '•std::atto', word = 'std::atto' },
284      { abbr = '•std::adopt_lock_t', word = 'std::adopt_lock_t' },
285    })
286  end)
287
288  describe('when completeopt has fuzzy matching enabled', function()
289    before_each(function()
290      exec_lua(function()
291        vim.opt.completeopt:append('fuzzy')
292      end)
293    end)
294    after_each(function()
295      exec_lua(function()
296        vim.opt.completeopt:remove('fuzzy')
297      end)
298    end)
299
300    it('fuzzy matches on filterText', function()
301      assert_completion_matches('fo', {
302        { label = '?.foo', filterText = 'foo' },
303        { label = 'faz other', filterText = 'faz other' },
304        { label = 'bar', filterText = 'bar' },
305      }, {
306        { abbr = 'faz other', word = 'faz other' },
307        { abbr = '?.foo', word = '?.foo' },
308      })
309    end)
310
311    it('fuzzy matches on label when filterText is missing or empty', function()
312      assert_completion_matches('fo', {
313        { label = 'foo', filterText = '' },
314        { label = 'faz other' },
315        { label = 'bar' },
316      }, {
317        { abbr = 'faz other', word = 'faz other' },
318        { abbr = 'foo', word = 'foo' },
319      })
320    end)
321  end)
322
323  describe('when smartcase is enabled', function()
324    before_each(function()
325      exec_lua(function()
326        vim.opt.smartcase = true
327      end)
328    end)
329    after_each(function()
330      exec_lua(function()
331        vim.opt.smartcase = false
332      end)
333    end)
334
335    it('matches filterText case sensitively', function()
336      assert_completion_matches('Fo', {
337        { label = 'foo', filterText = 'foo' },
338        { label = '?.Foo', filterText = 'Foo' },
339        { label = 'Faz other', filterText = 'Faz other' },
340        { label = 'faz other', filterText = 'faz other' },
341        { label = 'bar', filterText = 'bar' },
342      }, {
343        { abbr = '?.Foo', word = '?.Foo' },
344      })
345    end)
346
347    it('matches label case sensitively when filterText is missing', function()
348      assert_completion_matches('Fo', {
349        { label = 'foo' },
350        { label = 'Foo' },
351        { label = 'Faz other' },
352        { label = 'faz other' },
353        { label = 'bar' },
354      }, {
355        { abbr = 'Foo', word = 'Foo' },
356      })
357    end)
358
359    describe('when ignorecase is enabled', function()
360      before_each(function()
361        exec_lua(function()
362          vim.opt.ignorecase = true
363        end)
364      end)
365      after_each(function()
366        exec_lua(function()
367          vim.opt.ignorecase = false
368        end)
369      end)
370
371      it('matches filterText case insensitively if prefix is lowercase', function()
372        assert_completion_matches('fo', {
373          { label = '?.foo', filterText = 'foo' },
374          { label = '?.Foo', filterText = 'Foo' },
375          { label = 'Faz other', filterText = 'Faz other' },
376          { label = 'faz other', filterText = 'faz other' },
377          { label = 'bar', filterText = 'bar' },
378        }, {
379          { abbr = '?.Foo', word = '?.Foo' },
380          { abbr = '?.foo', word = '?.foo' },
381        })
382      end)
383
384      it(
385        'matches label case insensitively if prefix is lowercase and filterText is missing',
386        function()
387          assert_completion_matches('fo', {
388            { label = 'foo' },
389            { label = 'Foo' },
390            { label = 'Faz other' },
391            { label = 'faz other' },
392            { label = 'bar' },
393          }, {
394            { abbr = 'Foo', word = 'Foo' },
395            { abbr = 'foo', word = 'foo' },
396          })
397        end
398      )
399
400      it('matches filterText case sensitively if prefix has uppercase letters', function()
401        assert_completion_matches('Fo', {
402          { label = 'foo', filterText = 'foo' },
403          { label = '?.Foo', filterText = 'Foo' },
404          { label = 'Faz other', filterText = 'Faz other' },
405          { label = 'faz other', filterText = 'faz other' },
406          { label = 'bar', filterText = 'bar' },
407        }, {
408          { abbr = '?.Foo', word = '?.Foo' },
409        })
410      end)
411
412      it(
413        'matches label case sensitively if prefix has uppercase letters and filterText is missing',
414        function()
415          assert_completion_matches('Fo', {
416            { label = 'foo' },
417            { label = 'Foo' },
418            { label = 'Faz other' },
419            { label = 'faz other' },
420            { label = 'bar' },
421          }, {
422            { abbr = 'Foo', word = 'Foo' },
423          })
424        end
425      )
426    end)
427  end)
428
429  describe('when ignorecase is enabled', function()
430    before_each(function()
431      exec_lua(function()
432        vim.opt.ignorecase = true
433      end)
434    end)
435    after_each(function()
436      exec_lua(function()
437        vim.opt.ignorecase = false
438      end)
439    end)
440
441    it('matches filterText case insensitively', function()
442      assert_completion_matches('Fo', {
443        { label = '?.foo', filterText = 'foo' },
444        { label = '?.Foo', filterText = 'Foo' },
445        { label = 'Faz other', filterText = 'Faz other' },
446        { label = 'faz other', filterText = 'faz other' },
447        { label = 'bar', filterText = 'bar' },
448      }, {
449        { abbr = '?.Foo', word = '?.Foo' },
450        { abbr = '?.foo', word = '?.foo' },
451      })
452    end)
453
454    it('matches label case insensitively when filterText is missing', function()
455      assert_completion_matches('Fo', {
456        { label = 'foo' },
457        { label = 'Foo' },
458        { label = 'Faz other' },
459        { label = 'faz other' },
460        { label = 'bar' },
461      }, {
462        { abbr = 'Foo', word = 'Foo' },
463        { abbr = 'foo', word = 'foo' },
464      })
465    end)
466  end)
467
468  it('works on non word prefix', function()
469    local completion_list = {
470      { label = ' foo', insertText = '->foo', sortText = '1' },
471      { label = ' bar', insertText = '->bar', filterText = 'bar', sortText = '2' },
472    }
473    local result = complete('wp.|', completion_list, 0, 2)
474    eq({
475      { abbr = ' foo', word = '->foo' },
476      { abbr = ' bar', word = '->bar' },
477    }, extract_word_abbr(result.items))
478  end)
479
480  it('trims trailing newline or tab from textEdit and insertText', function()
481    local range0 = {
482      start = { line = 0, character = 0 },
483      ['end'] = { line = 0, character = 0 },
484    }
485    local items = {
486      {
487        detail = 'ansible.builtin',
488        filterText = 'lineinfile ansible.builtin.lineinfile builtin ansible',
489        kind = 7,
490        label = 'ansible.builtin.lineinfile',
491        sortText = '2_ansible.builtin.lineinfile',
492        textEdit = {
493          newText = 'ansible.builtin.lineinfile:\n	',
494          range = range0,
495        },
496      },
497      {
498        kind = 7,
499        label = 'ansible.builtin.copy',
500        sortText = '3_ansible.builtin.copy',
501        insertText = 'ansible.builtin.copy:\n	',
502      },
503    }
504    eq({
505      { abbr = 'ansible.builtin.lineinfile', word = 'ansible.builtin.lineinfile:' },
506      { abbr = 'ansible.builtin.copy', word = 'ansible.builtin.copy:' },
507    }, extract_word_abbr(complete('|', items).items))
508  end)
509
510  it('handles multiword textEdits', function()
511    local range0 = {
512      start = { line = 0, character = 0 },
513      ['end'] = { line = 0, character = 0 },
514    }
515    local items = {
516      {
517        detail = 'abc',
518        filterText = 'abc',
519        kind = 7,
520        label = 'abc',
521        sortText = 'abc',
522        textEdit = {
523          newText = 'abc: Abc',
524          range = range0,
525        },
526      },
527    }
528    eq({ { abbr = 'abc', word = 'abc: Abc' } }, extract_word_abbr(complete('|', items).items))
529  end)
530
531  it('prefers wordlike components for snippets', function()
532    -- There are two goals here:
533    --
534    -- 1. The `word` should match what the user started typing, so that vim.fn.complete() doesn't
535    --    filter it away, preventing snippet expansion
536    --
537    -- For example, if they type `items@ins`, luals returns `table.insert(items, $0)` as
538    -- textEdit.newText and `insert` as label.
539    -- There would be no prefix match if textEdit.newText is used as `word`
540    --
541    -- 2. If users do not expand a snippet, but continue typing, they should see a somewhat reasonable
542    --    `word` getting inserted.
543    --
544    -- For example in:
545    --
546    --  insertText: "testSuites ${1:Env}"
547    --  label: "testSuites"
548    --
549    -- "testSuites" should have priority as `word`, as long as the full snippet gets expanded on accept (<c-y>)
550    local range0 = {
551      start = { line = 0, character = 0 },
552      ['end'] = { line = 0, character = 0 },
553    }
554    local completion_list = {
555      -- luals postfix snippet (typed text: items@ins|)
556      {
557        label = 'insert',
558        insertTextFormat = 2,
559        textEdit = {
560          newText = 'table.insert(items, $0)',
561          range = range0,
562        },
563      },
564      -- eclipse.jdt.ls `new` snippet
565      {
566        label = 'new',
567        insertTextFormat = 2,
568        textEdit = {
569          newText = '${1:Object} ${2:foo} = new ${1}(${3});\n${0}',
570          range = range0,
571        },
572        textEditText = '${1:Object} ${2:foo} = new ${1}(${3});\n${0}',
573      },
574      -- eclipse.jdt.ls `List.copyO` function call completion
575      {
576        label = 'copyOf(Collection<? extends E> coll) : List<E>',
577        insertTextFormat = 2,
578        insertText = 'copyOf',
579        textEdit = {
580          newText = 'copyOf(${1:coll})',
581          range = range0,
582        },
583      },
584      -- luals for snippet
585      {
586        insertText = 'for ${1:index}, ${2:value} in ipairs(${3:t}) do\n\t$0\nend',
587        insertTextFormat = 2,
588        kind = 15,
589        label = 'for .. ipairs',
590      },
591    }
592    local expected = {
593      { abbr = 'copyOf(Collection<? extends E> coll) : List<E>', word = 'copyOf' },
594      { abbr = 'for .. ipairs', word = 'for .. ipairs' },
595      { abbr = 'insert', word = 'insert' },
596      { abbr = 'new', word = 'new' },
597    }
598    eq(expected, extract_word_abbr(complete('|', completion_list).items))
599  end)
600
601  it('uses correct start boundary', function()
602    local completion_list = {
603      isIncomplete = false,
604      items = {
605        {
606          filterText = 'this_thread',
607          insertText = 'this_thread',
608          insertTextFormat = 1,
609          kind = 9,
610          label = ' this_thread',
611          score = 1.3205767869949,
612          sortText = '4056f757this_thread',
613          textEdit = {
614            newText = 'this_thread',
615            range = {
616              start = { line = 0, character = 7 },
617              ['end'] = { line = 0, character = 11 },
618            },
619          },
620        },
621      },
622    }
623    local expected = {
624      {
625        abbr = ' this_thread',
626        dup = 1,
627        empty = 1,
628        icase = 1,
629        info = '',
630        kind = 'Module',
631        menu = '',
632        abbr_hlgroup = '',
633        word = 'this_thread',
634      },
635    }
636    local result = complete('  std::this|', completion_list)
637    eq(7, result.server_start_boundary)
638    for _, item in ipairs(result.items) do
639      item.user_data = nil
640    end
641    eq(expected, result.items)
642  end)
643
644  it('should search from start boundary to cursor position', function()
645    local completion_list = {
646      isIncomplete = false,
647      items = {
648        {
649          filterText = 'this_thread',
650          insertText = 'this_thread',
651          insertTextFormat = 1,
652          kind = 9,
653          label = ' this_thread',
654          score = 1.3205767869949,
655          sortText = '4056f757this_thread',
656          textEdit = {
657            newText = 'this_thread',
658            range = {
659              start = { line = 0, character = 7 },
660              ['end'] = { line = 0, character = 11 },
661            },
662          },
663        },
664        {
665          filterText = 'no_match',
666          insertText = 'notthis_thread',
667          insertTextFormat = 1,
668          kind = 9,
669          label = ' notthis_thread',
670          score = 1.3205767869949,
671          sortText = '4056f757this_thread',
672          textEdit = {
673            newText = 'notthis_thread',
674            range = {
675              start = { line = 0, character = 7 },
676              ['end'] = { line = 0, character = 11 },
677            },
678          },
679        },
680      },
681    }
682    local expected = {
683      abbr = ' this_thread',
684      dup = 1,
685      empty = 1,
686      icase = 1,
687      info = '',
688      kind = 'Module',
689      menu = '',
690      abbr_hlgroup = '',
691      word = 'this_thread',
692    }
693    local result = complete('  std::this|is', completion_list)
694    eq(1, #result.items)
695    local item = result.items[1]
696    item.user_data = nil
697    eq(expected, item)
698  end)
699
700  it('uses defaults from itemDefaults', function()
701    --- @type lsp.CompletionList
702    local completion_list = {
703      isIncomplete = false,
704      itemDefaults = {
705        editRange = {
706          start = { line = 1, character = 1 },
707          ['end'] = { line = 1, character = 4 },
708        },
709        insertTextFormat = 2,
710        data = 'foobar',
711      },
712      items = {
713        {
714          label = 'hello',
715          data = 'item-property-has-priority',
716          textEditText = 'hello',
717        },
718      },
719    }
720    local result = complete('|', completion_list)
721    eq(1, #result.items)
722    local item = result.items[1].user_data.nvim.lsp.completion_item --- @type lsp.CompletionItem
723    eq(2, item.insertTextFormat)
724    eq('item-property-has-priority', item.data)
725    eq({ line = 1, character = 1 }, item.textEdit.range.start)
726  end)
727
728  it(
729    'uses insertText as textEdit.newText if there are editRange defaults but no textEditText',
730    function()
731      --- @type lsp.CompletionList
732      local completion_list = {
733        isIncomplete = false,
734        itemDefaults = {
735          editRange = {
736            start = { line = 1, character = 1 },
737            ['end'] = { line = 1, character = 4 },
738          },
739          insertTextFormat = 2,
740          data = 'foobar',
741        },
742        items = {
743          {
744            insertText = 'the-insertText',
745            label = 'hello',
746            data = 'item-property-has-priority',
747          },
748        },
749      }
750      local result = complete('|', completion_list)
751      eq(1, #result.items)
752      eq('the-insertText', result.items[1].user_data.nvim.lsp.completion_item.textEdit.newText)
753    end
754  )
755
756  it(
757    'defaults to label as textEdit.newText if insertText or textEditText are not present',
758    function()
759      local completion_list = {
760        isIncomplete = false,
761        itemDefaults = {
762          editRange = {
763            start = { line = 1, character = 1 },
764            ['end'] = { line = 1, character = 4 },
765          },
766          insertTextFormat = 2,
767          data = 'foobar',
768        },
769        items = {
770          {
771            label = 'hello',
772            data = 'item-property-has-priority',
773            insertText = '',
774          },
775        },
776      }
777      local result = complete('|', completion_list)
778      eq(1, #result.items)
779      eq('hello', result.items[1].user_data.nvim.lsp.completion_item.textEdit.newText)
780    end
781  )
782
783  it('uses the start boundary from an insertReplace response', function()
784    local completion_list = {
785      isIncomplete = false,
786      items = {
787        {
788          data = { cacheId = 1 },
789          kind = 2,
790          label = 'foobar',
791          sortText = '11',
792          textEdit = {
793            insert = {
794              start = { character = 4, line = 4 },
795              ['end'] = { character = 8, line = 4 },
796            },
797            newText = 'foobar',
798            replace = {
799              start = { character = 4, line = 4 },
800              ['end'] = { character = 8, line = 4 },
801            },
802          },
803        },
804        {
805          data = { cacheId = 2 },
806          kind = 2,
807          label = 'bazqux',
808          sortText = '11',
809          textEdit = {
810            insert = {
811              start = { character = 4, line = 4 },
812              ['end'] = { character = 5, line = 4 },
813            },
814            newText = 'bazqux',
815            replace = {
816              start = { character = 4, line = 4 },
817              ['end'] = { character = 5, line = 4 },
818            },
819          },
820        },
821      },
822    }
823
824    local result = complete('foo.f|', completion_list)
825    eq(1, #result.items)
826    eq('foobar', result.items[1].user_data.nvim.lsp.completion_item.textEdit.newText)
827  end)
828
829  --- @param candidates lsp.CompletionList
830  --- @return table<string, lsp.CompletionItem>
831  local function convert(candidates)
832    local items = {} --- @type table<string, lsp.CompletionItem>
833    for _, match in ipairs(complete('|', candidates).items) do
834      local item = match.user_data.nvim.lsp.completion_item
835      items[item.label] = item
836    end
837    return items
838  end
839
840  it('itemDefaults are replaced by the item by default', function()
841    local items = convert({
842      isIncomplete = false,
843      itemDefaults = { commitCharacters = { '.', ';' }, data = { a = 1 } },
844      items = {
845        { label = 'own', commitCharacters = { '(' }, data = { b = 2 } },
846        { label = 'absent' },
847        { label = 'empty', commitCharacters = {}, data = false },
848      },
849    })
850    eq({ '(' }, items.own.commitCharacters)
851    eq({ b = 2 }, items.own.data)
852    eq({ '.', ';' }, items.absent.commitCharacters)
853    eq({ a = 1 }, items.absent.data)
854    eq({}, items.empty.commitCharacters)
855    eq(false, items.empty.data)
856  end)
857
858  it('applyKind=Merge merges the item with itemDefaults', function()
859    local Merge = 2
860    local items = convert({
861      isIncomplete = false,
862      applyKind = { commitCharacters = Merge, data = Merge },
863      itemDefaults = { commitCharacters = { '.', ';' }, data = { a = 1, nested = { x = 1 } } },
864      items = {
865        { label = 'own', commitCharacters = { '(' }, data = { a = 9, nested = { y = 2 } } },
866        { label = 'absent' },
867      },
868    })
869    eq({ '(', '.', ';' }, items.own.commitCharacters)
870    eq({ a = 9, nested = { y = 2 } }, items.own.data)
871    eq({ '.', ';' }, items.absent.commitCharacters)
872    eq({ a = 1, nested = { x = 1 } }, items.absent.data)
873  end)
874end)
875
876--- @param name string
877--- @param completion_result vim.lsp.CompletionResult
878--- @param opts? {trigger_chars?: string[], resolve_result?: lsp.CompletionItem|lsp.CompletionItem[], delay?: integer, cmp?: string}
879--- @return integer
880local function create_server(name, completion_result, opts)
881  opts = opts or {}
882  return exec_lua(function()
883    local server = _G._create_server({
884      capabilities = {
885        completionProvider = {
886          triggerCharacters = opts.trigger_chars or { '.' },
887          resolveProvider = opts.resolve_result ~= nil,
888        },
889      },
890      handlers = {
891        ['textDocument/completion'] = function(_, _, callback)
892          if opts.delay then
893            -- simulate delay in completion request, needed for some of these tests
894            vim.defer_fn(function()
895              callback(nil, completion_result)
896            end, opts.delay)
897          else
898            callback(nil, completion_result)
899          end
900        end,
901        ['completionItem/resolve'] = function(_, request_item, callback)
902          if type(opts.resolve_result) == 'table' and not opts.resolve_result.label then
903            local selected = vim.fn.complete_info({ 'selected' }).selected
904            callback(nil, opts.resolve_result[selected + 1] or request_item)
905          else
906            callback(nil, opts.resolve_result)
907          end
908        end,
909      },
910    })
911
912    local bufnr = vim.api.nvim_get_current_buf()
913    vim.api.nvim_win_set_buf(0, bufnr)
914    local cmp_fn
915    if opts.cmp then
916      cmp_fn = assert(loadstring(opts.cmp))
917    end
918    return vim.lsp.start({
919      name = name,
920      cmd = server.cmd,
921      on_attach = function(client, bufnr0)
922        vim.lsp.completion.enable(true, client.id, bufnr0, {
923          autotrigger = opts.trigger_chars ~= nil,
924          convert = function(item)
925            return { abbr = item.label:gsub('%b()', '') }
926          end,
927          cmp = cmp_fn,
928        })
929      end,
930    })
931  end)
932end
933
934describe('vim.lsp.completion: protocol', function()
935  before_each(function()
936    clear()
937    exec_lua(create_server_definition)
938    exec_lua(function()
939      _G.capture = {}
940      --- @diagnostic disable-next-line:duplicate-set-field
941      vim.fn.complete = function(col, matches)
942        _G.capture.col = col
943        _G.capture.matches = matches
944      end
945    end)
946  end)
947
948  local function assert_matches(fn)
949    retry(nil, nil, function()
950      fn(exec_lua('return _G.capture.matches'))
951    end)
952  end
953
954  --- @param pos [integer, integer]
955  local function trigger_at_pos(pos)
956    exec_lua(function()
957      local win = vim.api.nvim_get_current_win()
958      vim.api.nvim_win_set_cursor(win, pos)
959      vim.lsp.completion.get()
960    end)
961
962    retry(nil, nil, function()
963      neq(nil, exec_lua('return _G.capture.col'))
964    end)
965  end
966
967  it('does not error on :checktime after client restart', function()
968    local fname = 'Xtest-lsp-completion-reload'
969    t.write_file(fname, 'foo')
970    t.finally(function()
971      os.remove(fname)
972    end)
973    local mtime = os.time() - 10
974    vim.uv.fs_utime(fname, mtime, mtime)
975    n.command('edit ' .. fname)
976    n.command('set autoread')
977
978    local client_id = create_server('dummy', { isIncomplete = false, items = {} })
979    exec_lua(function()
980      vim.lsp.get_client_by_id(client_id):stop(true)
981      vim.wait(1000, function()
982        return vim.lsp.get_client_by_id(client_id) == nil
983      end)
984    end)
985    create_server('dummy', { isIncomplete = false, items = {} })
986
987    t.write_file(fname, 'bar')
988    n.command('checktime')
989    eq({ 'bar' }, n.api.nvim_buf_get_lines(0, 0, -1, true))
990  end)
991
992  it('fetches completions and shows them using complete on trigger', function()
993    create_server('dummy', {
994      isIncomplete = false,
995      items = {
996        { label = 'hello' },
997        { label = 'hercules', tags = { 1 } }, -- 1 represents Deprecated tag
998        { label = 'hero', deprecated = true },
999      },
1000    })
1001
1002    feed('ih')
1003    trigger_at_pos({ 1, 1 })
1004
1005    assert_matches(function(matches)
1006      eq({
1007        {
1008          abbr = 'hello',
1009          dup = 1,
1010          empty = 1,
1011          icase = 1,
1012          info = '',
1013          kind = 'Unknown',
1014          menu = '',
1015          abbr_hlgroup = '',
1016          user_data = {
1017            nvim = {
1018              lsp = {
1019                client_id = 1,
1020                completion_item = { label = 'hello' },
1021                info_kind = 'markdown',
1022                completion_item_needs_resolving = false,
1023              },
1024            },
1025          },
1026          word = 'hello',
1027        },
1028        {
1029          abbr = 'hercules',
1030          dup = 1,
1031          empty = 1,
1032          icase = 1,
1033          info = '',
1034          kind = 'Unknown',
1035          menu = '',
1036          abbr_hlgroup = 'DiagnosticDeprecated',
1037          user_data = {
1038            nvim = {
1039              lsp = {
1040                client_id = 1,
1041                completion_item = { label = 'hercules', tags = { 1 } },
1042                info_kind = 'markdown',
1043                completion_item_needs_resolving = false,
1044              },
1045            },
1046          },
1047          word = 'hercules',
1048        },
1049        {
1050          abbr = 'hero',
1051          dup = 1,
1052          empty = 1,
1053          icase = 1,
1054          info = '',
1055          kind = 'Unknown',
1056          menu = '',
1057          abbr_hlgroup = 'DiagnosticDeprecated',
1058          user_data = {
1059            nvim = {
1060              lsp = {
1061                client_id = 1,
1062                completion_item = { label = 'hero', deprecated = true },
1063                info_kind = 'markdown',
1064                completion_item_needs_resolving = false,
1065              },
1066            },
1067          },
1068          word = 'hero',
1069        },
1070      }, matches)
1071    end)
1072  end)
1073
1074  it('merges results from multiple clients', function()
1075    create_server('dummy1', { isIncomplete = false, items = { { label = 'hello' } } })
1076    create_server('dummy2', { isIncomplete = false, items = { { label = 'hallo' } } })
1077    create_server('dummy3', { { label = 'hallo' } })
1078
1079    feed('ih')
1080    trigger_at_pos({ 1, 1 })
1081
1082    assert_matches(function(matches)
1083      eq(3, #matches)
1084      eq('hello', matches[1].word)
1085      eq('hallo', matches[2].word)
1086      eq('hallo', matches[3].word)
1087    end)
1088  end)
1089
1090  it('insert char triggers clients matching trigger characters', function()
1091    create_server('dummy1', {
1092      isIncomplete = false,
1093      items = { { label = 'hello' } },
1094    }, { trigger_chars = { 'e' } })
1095    create_server('dummy2', {
1096      isIncomplete = false,
1097      items = { { label = 'hallo' } },
1098    }, { trigger_chars = { 'h' } })
1099
1100    feed('h')
1101    exec_lua(function()
1102      vim.v.char = 'h'
1103      vim.cmd.startinsert()
1104      vim.api.nvim_exec_autocmds('InsertCharPre', {})
1105    end)
1106
1107    assert_matches(function(matches)
1108      eq(1, #matches)
1109      eq('hallo', matches[1].word)
1110    end)
1111  end)
1112
1113  it('reads completionProvider from a dynamic registration', function()
1114    exec_lua(function()
1115      local server = _G._create_server({
1116        capabilities = {},
1117        handlers = {
1118          ['textDocument/completion'] = function(_, _, callback)
1119            callback(nil, { isIncomplete = false, items = { { label = 'hello' } } })
1120          end,
1121        },
1122      })
1123      local client_id = assert(vim.lsp.start({
1124        name = 'dummy',
1125        cmd = server.cmd,
1126        capabilities = {
1127          textDocument = { completion = { dynamicRegistration = true } },
1128        },
1129      }))
1130      assert(vim.lsp.get_client_by_id(client_id)):_register({
1131        {
1132          id = 'nvim.test.completion',
1133          method = 'textDocument/completion',
1134          registerOptions = {
1135            triggerCharacters = { '.' },
1136            resolveProvider = true,
1137            allCommitCharacters = { ';' },
1138          },
1139        },
1140      })
1141      vim.lsp.completion.enable(true, client_id, 0, { autotrigger = true })
1142    end)
1143
1144    feed('i.')
1145
1146    assert_matches(function(matches)
1147      eq(1, #matches)
1148      eq('hello', matches[1].word)
1149      eq(';', matches[1].commit_chars)
1150      eq(true, matches[1].user_data.nvim.lsp.completion_item_needs_resolving)
1151    end)
1152  end)
1153
1154  it('treats 2-triggers-at-once as "last char wins"', function()
1155    create_server('dummy1', {
1156      isIncomplete = false,
1157      items = { { label = 'first' } },
1158    }, { trigger_chars = { '-' } })
1159    create_server('dummy2', {
1160      isIncomplete = false,
1161      items = { { label = 'second' } },
1162    }, { trigger_chars = { '>' } })
1163
1164    feed('i->')
1165
1166    assert_matches(function(matches)
1167      eq(1, #matches)
1168      eq('second', matches[1].word)
1169    end)
1170  end)
1171
1172  it('executes commands', function()
1173    local completion_list = {
1174      isIncomplete = false,
1175      items = {
1176        {
1177          label = 'hello',
1178          command = { arguments = { '1', '0' }, command = 'dummy', title = '' },
1179        },
1180      },
1181    }
1182    local client_id = create_server('dummy', completion_list)
1183
1184    exec_lua(function()
1185      _G.called = false
1186      local client = assert(vim.lsp.get_client_by_id(client_id))
1187      client.commands.dummy = function()
1188        _G.called = true
1189      end
1190    end)
1191
1192    feed('ih')
1193    trigger_at_pos({ 1, 1 })
1194
1195    local item = completion_list.items[1]
1196    exec_lua(function()
1197      vim.v.completed_item = {
1198        user_data = {
1199          nvim = {
1200            lsp = { client_id = client_id, completion_item = item },
1201          },
1202        },
1203      }
1204    end)
1205
1206    feed('<C-x><C-o><C-y>')
1207
1208    assert_matches(function(matches)
1209      eq(1, #matches)
1210      eq('hello', matches[1].word)
1211      eq(true, exec_lua('return _G.called'))
1212    end)
1213  end)
1214
1215  it('resolves and executes commands', function()
1216    local completion_list = {
1217      isIncomplete = false,
1218      items = { { label = 'hello' } },
1219    }
1220    local client_id = create_server('dummy', completion_list, {
1221      resolve_result = {
1222        label = 'hello',
1223        command = { arguments = { '1', '0' }, command = 'dummy', title = '' },
1224      },
1225    })
1226    exec_lua(function()
1227      _G.called = false
1228      local client = assert(vim.lsp.get_client_by_id(client_id))
1229      client.commands.dummy = function()
1230        _G.called = true
1231      end
1232    end)
1233
1234    feed('ih')
1235    trigger_at_pos({ 1, 1 })
1236
1237    local item = completion_list.items[1]
1238    exec_lua(function()
1239      vim.v.completed_item = {
1240        user_data = {
1241          nvim = {
1242            lsp = { client_id = client_id, completion_item = item },
1243          },
1244        },
1245      }
1246    end)
1247
1248    feed('<C-x><C-o><C-y>')
1249
1250    assert_matches(function(matches)
1251      eq(1, #matches)
1252      eq('hello', matches[1].word)
1253      eq(true, exec_lua('return _G.called'))
1254    end)
1255  end)
1256
1257  it('enable(…,{convert=fn}) custom word/abbr format', function()
1258    create_server('dummy', {
1259      isIncomplete = false,
1260      items = { { label = 'foo(bar)' } },
1261    })
1262
1263    feed('ifo')
1264    trigger_at_pos({ 1, 1 })
1265    assert_matches(function(matches)
1266      eq('foo', matches[1].abbr)
1267    end)
1268  end)
1269
1270  it('enable(…,{cmp=fn}) custom sort order', function()
1271    create_server('dummy', {
1272      isIncomplete = false,
1273      items = {
1274        { label = 'zzz', sortText = 'a' },
1275        { label = 'aaa', sortText = 'z' },
1276        { label = 'mmm', sortText = 'm' },
1277      },
1278    }, {
1279      cmp = string.dump(function(a, b)
1280        return a.abbr < b.abbr
1281      end),
1282    })
1283    feed('i')
1284    trigger_at_pos({ 1, 0 })
1285    assert_matches(function(matches)
1286      eq(3, #matches)
1287      eq('aaa', matches[1].abbr)
1288      eq('mmm', matches[2].abbr)
1289      eq('zzz', matches[3].abbr)
1290    end)
1291  end)
1292
1293  it('sends completion context when invoked', function()
1294    local params = exec_lua(function()
1295      local params
1296      local server = _G._create_server({
1297        capabilities = { completionProvider = {} },
1298        handlers = {
1299          ['textDocument/completion'] = function(_, params0, callback)
1300            params = params0
1301            callback(nil, nil)
1302          end,
1303        },
1304      })
1305
1306      local bufnr = vim.api.nvim_get_current_buf()
1307      vim.api.nvim_win_set_buf(0, bufnr)
1308      vim.lsp.start({
1309        name = 'dummy',
1310        cmd = server.cmd,
1311        on_attach = function(client, bufnr0)
1312          vim.lsp.completion.enable(true, client.id, bufnr0)
1313        end,
1314      })
1315
1316      vim.lsp.completion.get()
1317
1318      return params
1319    end)
1320
1321    eq({ triggerKind = 1 }, params.context)
1322  end)
1323
1324  it('sends completion context with trigger characters', function()
1325    exec_lua(function()
1326      local server = _G._create_server({
1327        capabilities = {
1328          completionProvider = { triggerCharacters = { 'h' } },
1329        },
1330        handlers = {
1331          ['textDocument/completion'] = function(_, params, callback)
1332            _G.params = params
1333            callback(nil, { isIncomplete = false, items = { label = 'hello' } })
1334          end,
1335        },
1336      })
1337
1338      local bufnr = vim.api.nvim_get_current_buf()
1339      vim.api.nvim_win_set_buf(0, bufnr)
1340      vim.lsp.start({
1341        name = 'dummy',
1342        cmd = server.cmd,
1343        on_attach = function(client, bufnr0)
1344          vim.lsp.completion.enable(true, client.id, bufnr0, { autotrigger = true })
1345        end,
1346      })
1347    end)
1348
1349    feed('ih')
1350
1351    retry(100, nil, function()
1352      eq({ triggerKind = 2, triggerCharacter = 'h' }, exec_lua('return _G.params.context'))
1353    end)
1354  end)
1355
1356  it('errors on invalid items=null in completion response #39400', function()
1357    create_server('dummy', {
1358      isIncomplete = false,
1359      items = vim.NIL,
1360    })
1361    feed('ih')
1362    local err = t.pcall_err(function()
1363      exec_lua(function()
1364        vim.api.nvim_win_set_cursor(0, { 1, 1 })
1365        vim.lsp.completion.get()
1366        vim.wait(1000, function()
1367          return false
1368        end)
1369      end)
1370    end)
1371    t.matches('items=null', err)
1372  end)
1373
1374  it('keeps requerying while the completion list is incomplete #40096', function()
1375    exec_lua(function()
1376      _G.contexts = {}
1377      local server = _G._create_server({
1378        capabilities = {
1379          completionProvider = { triggerCharacters = { 'h' } },
1380        },
1381        handlers = {
1382          ['textDocument/completion'] = function(_, params, callback)
1383            _G.contexts[#_G.contexts + 1] = params.context
1384            callback(nil, { isIncomplete = true, items = { { label = 'hello' } } })
1385          end,
1386        },
1387      })
1388      local bufnr = vim.api.nvim_get_current_buf()
1389      vim.api.nvim_win_set_buf(0, bufnr)
1390      vim.lsp.start({
1391        name = 'dummy',
1392        cmd = server.cmd,
1393        on_attach = function(client, bufnr0)
1394          vim.lsp.completion.enable(true, client.id, bufnr0, { autotrigger = true })
1395        end,
1396      })
1397    end)
1398    feed('ih')
1399    assert_matches(function(matches)
1400      eq('hello', matches[1].word)
1401    end)
1402    eq({ triggerKind = 2, triggerCharacter = 'h' }, exec_lua('return _G.contexts[1]'))
1403
1404    exec_lua('_G.capture = {}')
1405    feed('e')
1406    assert_matches(function(matches)
1407      eq('hello', matches[1].word)
1408    end)
1409    eq({ triggerKind = 3 }, exec_lua('return _G.contexts[2]'))
1410  end)
1411end)
1412
1413describe('vim.lsp.completion: integration', function()
1414  before_each(function()
1415    clear()
1416    exec_lua(create_server_definition)
1417    exec_lua(function()
1418      vim.fn.complete = vim.schedule_wrap(vim.fn.complete)
1419    end)
1420  end)
1421
1422  it('puts cursor at the end of completed word', function()
1423    local completion_list = {
1424      isIncomplete = false,
1425      items = {
1426        {
1427          label = 'hello',
1428          insertText = '${1:hello} friends',
1429          insertTextFormat = 2,
1430        },
1431      },
1432    }
1433    exec_lua(function()
1434      vim.o.completeopt = 'menuone,noselect'
1435    end)
1436    local client_id = create_server('dummy', completion_list)
1437    feed('i world<esc>0ih<c-x><c-o>')
1438    wait_for_pum()
1439    feed('<C-n><C-y>')
1440    eq(
1441      { true, { 'hello friends world' } },
1442      exec_lua(function()
1443        return {
1444          vim.snippet.active({ direction = 1 }),
1445          vim.api.nvim_buf_get_lines(0, 0, -1, true),
1446        }
1447      end)
1448    )
1449    exec_lua(function()
1450      vim.snippet.jump(1)
1451    end)
1452    eq(
1453      #'hello friends',
1454      exec_lua(function()
1455        return vim.api.nvim_win_get_cursor(0)[2]
1456      end)
1457    )
1458    assert_cleanup_after_detach(client_id)
1459  end)
1460
1461  it('expands a snippet before a slow resolve answers', function()
1462    exec_lua(function()
1463      vim.o.completeopt = 'menuone,noselect'
1464      local server = _G._create_server({
1465        capabilities = { completionProvider = { resolveProvider = true } },
1466        handlers = {
1467          ['textDocument/completion'] = function(_, _, callback)
1468            callback(nil, {
1469              isIncomplete = false,
1470              items = { { label = 'hello', insertText = 'hello($0)', insertTextFormat = 2 } },
1471            })
1472          end,
1473          ['completionItem/resolve'] = function(_, item, callback)
1474            vim.defer_fn(function()
1475              callback(nil, item)
1476            end, 100)
1477          end,
1478        },
1479      })
1480      local client_id = assert(vim.lsp.start({ name = 'dummy', cmd = server.cmd }))
1481      vim.lsp.completion.enable(true, client_id, 0)
1482    end)
1483    feed('S<C-x><C-o>')
1484    wait_for_pum()
1485    feed('<C-n><C-y>x')
1486    eq({ 'hello(x)' }, n.api.nvim_buf_get_lines(0, 0, -1, true))
1487  end)
1488
1489  it('clear multiple-lines word', function()
1490    local completion_list = {
1491      isIncomplete = false,
1492      items = {
1493        {
1494          label = 'then...end',
1495          sortText = '0001',
1496          insertText = 'then\n\t$0\nend',
1497          kind = 15,
1498          insertTextFormat = 2,
1499        },
1500      },
1501    }
1502    exec_lua(function()
1503      vim.o.completeopt = 'menuone,noselect'
1504    end)
1505    local client_id = create_server('dummy', completion_list)
1506    feed('Sif true <C-X><C-O>')
1507    wait_for_pum()
1508    feed('<C-n><C-y>')
1509    eq(
1510      { false, { 'if true then', '\t', 'end' } },
1511      exec_lua(function()
1512        return {
1513          vim.snippet.active({ direction = 1 }),
1514          vim.api.nvim_buf_get_lines(0, 0, -1, true),
1515        }
1516      end)
1517    )
1518    assert_cleanup_after_detach(client_id)
1519  end)
1520
1521  it('prepends prefix for items with different start positions', function()
1522    local completion_list = {
1523      isIncomplete = false,
1524      items = {
1525        {
1526          label = 'div.foo',
1527          insertTextFormat = 2,
1528          textEdit = {
1529            newText = '<div class="foo">$0</div>',
1530            range = { start = { line = 0, character = 0 }, ['end'] = { line = 0, character = 7 } },
1531          },
1532        },
1533        {
1534          label = 'foobar',
1535          insertTextFormat = 1,
1536        },
1537      },
1538    }
1539    exec_lua(function()
1540      vim.o.completeopt = 'menu,menuone,noinsert'
1541    end)
1542    local client_id = create_server('dummy', completion_list)
1543    feed('Adiv.foo<C-x><C-O>')
1544    wait_for_pum()
1545    feed('<C-Y>')
1546    eq('<div class="foo"></div>', n.api.nvim_get_current_line())
1547    eq({ 1, 17 }, n.api.nvim_win_get_cursor(0))
1548
1549    feed('<Esc>ccdiv.foo<C-x><C-O>')
1550    wait_for_pum()
1551    feed('<C-N><C-Y>')
1552    eq('div.foobar', n.api.nvim_get_current_line())
1553
1554    assert_cleanup_after_detach(client_id)
1555  end)
1556
1557  it('does not empty server start boundary', function()
1558    local completion_list = {
1559      isIncomplete = false,
1560      items = {
1561        {
1562          label = 'div.foo',
1563          insertTextFormat = 2,
1564          textEdit = {
1565            newText = '<div class="foo">$0</div>',
1566            range = {
1567              start = { line = 0, character = 0 },
1568              ['end'] = { line = 0, character = 7 },
1569            },
1570          },
1571        },
1572      },
1573    }
1574    local completion_list2 = {
1575      isIncomplete = false,
1576      items = { { insertTextFormat = 1, label = 'foo' } },
1577    }
1578    exec_lua(function()
1579      vim.o.completeopt = 'menu,menuone,noinsert'
1580    end)
1581    create_server('dummy', completion_list)
1582    create_server('dummy2', completion_list2)
1583    create_server('dummy3', { isIncomplete = false, items = {} })
1584    feed('Adiv.foo<C-x><C-O>')
1585    wait_for_pum()
1586    feed('<C-Y>')
1587    eq('<div class="foo"></div>', n.api.nvim_get_current_line())
1588    eq({ 1, 17 }, n.api.nvim_win_get_cursor(0))
1589  end)
1590
1591  it('sorts items when fuzzy is enabled and prefix not empty #33610', function()
1592    local completion_list = {
1593      isIncomplete = false,
1594      items = {
1595        {
1596          kind = 21,
1597          label = '-row-end-1',
1598          sortText = '0327',
1599          textEdit = {
1600            newText = '-row-end-1',
1601            range = {
1602              ['end'] = { character = 1, line = 0 },
1603              start = { character = 0, line = 0 },
1604            },
1605          },
1606        },
1607        {
1608          kind = 21,
1609          label = 'w-1/2',
1610          sortText = '3052',
1611          textEdit = {
1612            newText = 'w-1/2',
1613            range = {
1614              ['end'] = { character = 1, line = 0 },
1615              start = { character = 0, line = 0 },
1616            },
1617          },
1618        },
1619      },
1620    }
1621    exec_lua(function()
1622      vim.o.completeopt = 'menuone,fuzzy'
1623    end)
1624    create_server('dummy', completion_list, { trigger_chars = { '-' } })
1625    feed('Sw-')
1626    wait_for_pum()
1627    feed('<C-y>')
1628    eq('w-1/2', n.api.nvim_get_current_line())
1629  end)
1630
1631  describe('selecting an item triggers (snippet) preview', function()
1632    ---@type lsp.CompletionItem[]
1633    local incomplete_items = {
1634      {
1635        -- detail populated but not documentation
1636        detail = '(method) nvim__id_array_1(arr: any[]): any[]',
1637        insertText = 'nvim__id_array_1',
1638        insertTextFormat = 1,
1639        kind = 3,
1640        label = 'nvim__id_array_1(arr)',
1641        sortText = '0001',
1642      },
1643      {
1644        -- documentation populated but not detail
1645        documentation = {
1646          kind = 'markdown',
1647          value = [[```lua\nfunction vim.api.nvim__id_array_2(arr: any[])\n  -> any[]\n```]],
1648        },
1649        insertText = 'nvim__id_array_2',
1650        insertTextFormat = 1,
1651        kind = 3,
1652        label = 'nvim__id_array_2(arr)',
1653        sortText = '0002',
1654      },
1655      {
1656        insertText = 'for ${1:i} = ${2:1}, ${3:10, 1} do\n\t$0\nend',
1657        insertTextFormat = 2,
1658        kind = 15,
1659        label = 'for i = ..',
1660        sortText = '0003',
1661      },
1662      {
1663        textEdit = {
1664          newText = 'for ${1:j} = ${2:1}, ${3:10, 1} do\n\t$0\nend',
1665          range = {
1666            start = { character = 0, line = 0 },
1667            ['end'] = { character = 0, line = 0 },
1668          },
1669        },
1670        insertTextFormat = 2,
1671        kind = 15,
1672        label = 'for j = ..',
1673        sortText = '0004',
1674      },
1675      {
1676        insertText = '_assert_integer(${1:x}, ${2:base?})',
1677        insertTextFormat = 2,
1678        kind = 3,
1679        label = '_assert_integer(x, base)',
1680        sortText = '0005',
1681      },
1682    }
1683    ---@type lsp.CompletionItem[]
1684    local complete_items = {
1685      {
1686        -- detail not in documentation, should be prepended as code block
1687        detail = '(method) nvim__id_array_1(arr: any[]): any[]',
1688        documentation = {
1689          kind = 'markdown',
1690          value = [[```lua\nfunction vim.api.nvim__id_array_1(arr: any[])\n  -> any[]\n```]],
1691        },
1692        insertText = 'nvim__id_array_1',
1693        insertTextFormat = 1,
1694        kind = 3,
1695        label = 'nvim__id_array_1(arr)',
1696        sortText = '0001',
1697      },
1698      {
1699        -- detail not in documentation, should be prepended as code block
1700        detail = '(method) nvim__id_array_2(arr: any[]): any[]',
1701        documentation = {
1702          kind = 'markdown',
1703          value = [[```lua\nfunction vim.api.nvim__id_array_2(arr: any[])\n  -> any[]\n```]],
1704        },
1705        insertText = 'nvim__id_array_2',
1706        insertTextFormat = 1,
1707        kind = 3,
1708        label = 'nvim__id_array_2(arr)',
1709        sortText = '0002',
1710      },
1711      {
1712        -- snippet populated in insertText
1713        insertText = 'for ${1:i} = ${2:1}, ${3:10, 1} do\n\t$0\nend',
1714        insertTextFormat = 2,
1715        kind = 15,
1716        label = 'for i = ..',
1717        sortText = '0003',
1718      },
1719      {
1720        -- snippet populated in textEdit.newText
1721        textEdit = {
1722          newText = 'for ${1:j} = ${2:1}, ${3:10, 1} do\n\t$0\nend',
1723          range = {
1724            start = { character = 0, line = 0 },
1725            ['end'] = { character = 0, line = 0 },
1726          },
1727        },
1728        insertTextFormat = 2,
1729        kind = 15,
1730        label = 'for j = ..',
1731        sortText = '0004',
1732      },
1733      {
1734        -- detail is in documentation, should not be duplicated
1735        detail = '_assert_integer',
1736        documentation = {
1737          kind = 'markdown',
1738          value = [[```lua\nmore doc for vim._assert_integer\n```]],
1739        },
1740        insertText = '_assert_integer(${1:x}, ${2:base?})',
1741        insertTextFormat = 2,
1742        kind = 3,
1743        label = '_assert_integer(x, base)',
1744        sortText = '0005',
1745      },
1746    }
1747
1748    ---@param opts {items:lsp.CompletionItem[], resolved_items:lsp.CompletionItem[]}
1749    local function run_test(opts)
1750      local screen = Screen.new(50, 20)
1751      screen:add_extra_attr_ids({
1752        [100] = { background = Screen.colors.Plum1, foreground = Screen.colors.Blue },
1753      })
1754      local completion_list = {
1755        isIncomplete = false,
1756        items = opts.items,
1757      }
1758      exec_lua(function()
1759        vim.o.completeopt = 'menuone,popup'
1760      end)
1761      create_server('dummy', completion_list, {
1762        resolve_result = opts.resolved_items,
1763      })
1764
1765      feed('S<C-X><C-O>')
1766      retry(nil, nil, function()
1767        local info = exec_lua(function()
1768          local data = vim.fn.complete_info({ 'selected' })
1769          if
1770            not data.preview_winid
1771            or not vim.api.nvim_win_is_valid(data.preview_winid)
1772            or not data.preview_bufnr
1773            or not vim.api.nvim_buf_is_valid(data.preview_bufnr)
1774          then
1775            error('preview not ready')
1776          end
1777          return table.concat(vim.api.nvim_buf_get_lines(data.preview_bufnr, 0, -1, false), '\n')
1778        end)
1779        -- item 1: detail is not in documentation, should be prepended
1780        neq(nil, info:find('(method) nvim__id_array_1(arr: any[]): any[]', 1, true))
1781        neq(nil, info:find('function vim.api.nvim__id_array_1', 1, true))
1782      end)
1783      screen:expect([[
1784        nvim__id_array_1^                                  |
1785        {12:nvim__id_array_1 Function }{100:(method) nvim__id_array}{1: }|
1786        {4:nvim__id_array_2 Function }{100:_1(arr: any[]): any[]}{4:  }{1: }|
1787        {4:for i = ..       Snippet  }{100:lua\nfunction vim.ap}{4:   }{1: }|
1788        {4:for j = ..       Snippet  }{100:i.nvim__id_array_1(arr:}{1: }|
1789        {4:_assert_integer  Function }{100: any[])\n  -> any[]\n}{4:  }{1: }|
1790        {1:~                         }{4:                       }{1: }|
1791        {1:~                                                 }|*12
1792        {5:-- INSERT --}                                      |
1793      ]])
1794      feed('<C-N>')
1795      screen:expect([[
1796        nvim__id_array_2^                                  |
1797        {4:nvim__id_array_1 Function }{100:(method) nvim__id_array}{1: }|
1798        {12:nvim__id_array_2 Function }{100:_2(arr: any[]): any[]}{4:  }{1: }|
1799        {4:for i = ..       Snippet  }{100:lua\nfunction vim.ap}{4:   }{1: }|
1800        {4:for j = ..       Snippet  }{100:i.nvim__id_array_2(arr:}{1: }|
1801        {4:_assert_integer  Function }{100: any[])\n  -> any[]\n}{4:  }{1: }|
1802        {1:~                         }{4:                       }{1: }|
1803        {1:~                                                 }|*12
1804        {5:-- INSERT --}                                      |
1805      ]])
1806      feed('<C-N>')
1807      screen:expect([[
1808        for i = ..^                                        |
1809        {4:nvim__id_array_1 Function }{100:for i = 1, 10, 1 do}{1:     }|
1810        {4:nvim__id_array_2 Function }{100:        }{4:           }{1:     }|
1811        {12:for i = ..       Snippet  }{100:end}{4:                }{1:     }|
1812        {4:for j = ..       Snippet  }{1:                        }|
1813        {4:_assert_integer  Function }{1:                        }|
1814        {1:~                                                 }|*13
1815        {5:-- INSERT --}                                      |
1816      ]])
1817      feed('<C-N>')
1818      screen:expect([[
1819        for j = ..^                                        |
1820        {4:nvim__id_array_1 Function }{100:for j = 1, 10, 1 do}{1:     }|
1821        {4:nvim__id_array_2 Function }{100:        }{4:           }{1:     }|
1822        {4:for i = ..       Snippet  }{100:end}{4:                }{1:     }|
1823        {12:for j = ..       Snippet  }{1:                        }|
1824        {4:_assert_integer  Function }{1:                        }|
1825        {1:~                                                 }|*13
1826        {5:-- INSERT --}                                      |
1827      ]])
1828      feed('<C-N>')
1829      retry(nil, nil, function()
1830        local info = exec_lua(function()
1831          local data = vim.fn.complete_info({ 'selected' })
1832          if not data.preview_bufnr or not vim.api.nvim_buf_is_valid(data.preview_bufnr) then
1833            error('preview not ready')
1834          end
1835          return table.concat(vim.api.nvim_buf_get_lines(data.preview_bufnr, 0, -1, false), '\n')
1836        end)
1837        neq(nil, info:find('more doc for vim._assert_integer', 1, true))
1838        local _, count = info:gsub('_assert_integer', '')
1839        -- item 3: detail '_assert_integer' is in documentation, should not be duplicated
1840        eq(1, count)
1841      end)
1842      screen:expect([[
1843        _assert_integer(x, base)^                          |
1844        {4:nvim__id_array_1 Function }{100:lua\nmore doc for vi}{4:   }{1: }|
1845        {4:nvim__id_array_2 Function }{100:m._assert_integer\n}{4:    }{1: }|
1846        {4:for i = ..       Snippet  }{1:                        }|
1847        {4:for j = ..       Snippet  }{1:                        }|
1848        {12:_assert_integer  Function }{1:                        }|
1849        {1:~                                                 }|*13
1850        {5:-- INSERT --}                                      |
1851      ]])
1852    end
1853
1854    it('when server supports completionItem/resolve', function()
1855      run_test({ items = incomplete_items, resolved_items = complete_items })
1856    end)
1857
1858    it('when server does not support completionItem/resolve', function()
1859      run_test({ items = complete_items })
1860    end)
1861  end)
1862
1863  it('omnifunc works without enable() #38252', function()
1864    local completion_list = {
1865      isIncomplete = false,
1866      items = {
1867        { label = 'hello' },
1868        { label = 'hallo' },
1869      },
1870    }
1871    exec_lua(function()
1872      local server = _G._create_server({
1873        capabilities = {
1874          completionProvider = {
1875            triggerCharacters = { '.' },
1876          },
1877        },
1878        handlers = {
1879          ['textDocument/completion'] = function(_, _, callback)
1880            callback(nil, completion_list)
1881          end,
1882        },
1883      })
1884      local bufnr = vim.api.nvim_get_current_buf()
1885      local id = vim.lsp.start({
1886        name = 'dummy',
1887        cmd = server.cmd,
1888      })
1889      if id then
1890        vim.lsp.buf_attach_client(bufnr, id)
1891        vim.bo[bufnr].omnifunc = 'v:lua.vim.lsp.omnifunc'
1892      end
1893    end)
1894    feed('ih<C-x><C-o>')
1895    wait_for_pum()
1896    feed('<C-y>')
1897    eq('hallo', n.api.nvim_get_current_line())
1898  end)
1899
1900  it('CompletionItem.preselect', function()
1901    local completion_list = {
1902      isIncomplete = false,
1903      items = {
1904        { label = 'aaa' },
1905        { label = 'zzz', preselect = true },
1906        { label = 'mmm' },
1907      },
1908    }
1909    exec_lua(function()
1910      vim.o.completeopt = 'menuone,noselect,preselect'
1911    end)
1912    create_server('dummy', completion_list)
1913    feed('i<C-x><C-o>')
1914    wait_for_pum()
1915    eq(
1916      2,
1917      exec_lua(function()
1918        return vim.fn.complete_info({ 'selected' }).selected
1919      end)
1920    )
1921  end)
1922
1923  it('support commitCharacters', function()
1924    n.command('set completeopt=menuone,menu,noinsert')
1925    -- from typescript-language-server
1926    local completion_list = {
1927      isIncomplete = false,
1928      items = {
1929        {
1930          -- Only whole characters are kept: '\0' and '\169x' are dropped, '=>' becomes '='.
1931          commitCharacters = { '.', ',', ';', '\0', '(', '=>', '\169x' },
1932          data = {
1933            cacheId = 1,
1934          },
1935          filterText = '.bar',
1936          kind = 2,
1937          label = 'bar',
1938          sortText = '11',
1939          textEdit = {
1940            newText = '.bar',
1941            range = {
1942              ['end'] = {
1943                character = 2,
1944                line = 0,
1945              },
1946              start = {
1947                character = 1,
1948                line = 0,
1949              },
1950            },
1951          },
1952        },
1953      },
1954    }
1955    create_server('dummy', completion_list, { trigger_chars = { '.' } })
1956    feed('Sf.')
1957    wait_for_pum()
1958    feed('(')
1959    eq('f.bar(', n.api.nvim_get_current_line())
1960
1961    n.command('set completeopt+=noselect')
1962    feed('<ESC>Sf.')
1963    wait_for_pum()
1964    feed('(')
1965    eq('f.(', n.api.nvim_get_current_line())
1966
1967    -- Test that a dropped fragment did not leak: 'x' must not commit, '=' must.
1968    n.command('set completeopt=menuone,menu,noinsert')
1969    feed('<ESC>Sf.')
1970    wait_for_pum()
1971    feed('x')
1972    eq('f.x', n.api.nvim_get_current_line())
1973
1974    feed('<ESC>Sf.')
1975    wait_for_pum()
1976    feed('=')
1977    eq('f.bar=', n.api.nvim_get_current_line())
1978  end)
1979end)
1980
1981describe("vim.lsp.completion: omnifunc + 'autocomplete'", function()
1982  before_each(function()
1983    clear()
1984    exec_lua(create_server_definition)
1985    exec_lua(function()
1986      -- enable buffer and omnifunc autocompletion
1987      -- omnifunc will be the lsp omnifunc
1988      vim.o.complete = '.,o'
1989      vim.o.autocomplete = true
1990    end)
1991
1992    local completion_list = {
1993      isIncomplete = false,
1994      items = {
1995        { label = 'hello' },
1996        { label = 'hallo' },
1997      },
1998    }
1999    create_server('dummy', completion_list, { delay = 50 })
2000  end)
2001
2002  local function assert_matches(expected)
2003    retry(nil, nil, function()
2004      local matches = vim.tbl_map(function(m)
2005        return m.word
2006      end, exec_lua('return vim.fn.complete_info({ "items" })').items)
2007      eq(expected, matches)
2008    end)
2009  end
2010
2011  it('merges with other completions', function()
2012    feed('ihillo<cr><esc>ih')
2013    assert_matches({ 'hillo', 'hallo', 'hello' })
2014  end)
2015
2016  it('fuzzy matches without duplication', function()
2017    -- wait for one completion request to start and then request another before
2018    -- the first one finishes, then wait for both to finish
2019    feed('ihillo<cr>h')
2020    vim.uv.sleep(1)
2021    feed('e')
2022
2023    assert_matches({ 'hello' })
2024  end)
2025end)