robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
57.8 KiB1925 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3
4local t_lsp = require('test.functional.plugin.lsp.testutil')
5
6local describe, it, before_each, after_each, teardown =
7  t.describe, t.it, t.before_each, t.after_each, t.teardown
8local command = n.command
9local eq = t.eq
10local exec_lua = n.exec_lua
11local matches = t.matches
12local pcall_err = t.pcall_err
13local retry = t.retry
14local stop = n.stop
15local NIL = vim.NIL
16local api = n.api
17local skip = t.skip
18local is_os = t.is_os
19
20local clear_notrace = t_lsp.clear_notrace
21local create_server_definition = t_lsp.create_server_definition
22local fake_lsp_logfile = t_lsp.fake_lsp_logfile
23local test_rpc_server = t_lsp.test_rpc_server
24local test_root = vim.uv.cwd()
25
26-- TODO(justinmk): hangs on Windows https://github.com/neovim/neovim/pull/11837
27if skip(is_os('win')) then
28  return
29end
30
31describe('vim.lsp.buf', function()
32  local function exec_capture(cmd)
33    return exec_lua(function(cmd0)
34      return vim.api.nvim_exec2(cmd0, { output = true }).output
35    end, cmd)
36  end
37
38  before_each(function()
39    clear_notrace()
40    command('cd ' .. test_root)
41  end)
42
43  after_each(function()
44    stop()
45    exec_lua(function()
46      vim.iter(vim.lsp.get_clients({ _uninitialized = true })):each(function(client)
47        client:stop(true)
48      end)
49    end)
50    api.nvim_exec_autocmds('VimLeavePre', { modeline = false })
51  end)
52
53  teardown(function()
54    os.remove(fake_lsp_logfile)
55  end)
56
57  describe('vim.lsp.buf.outgoing_calls', function()
58    it('does nothing for an empty response', function()
59      local qflist_count = exec_lua(function()
60        require 'vim.lsp.handlers'['callHierarchy/outgoingCalls'](nil, nil, {}, nil)
61        return #vim.fn.getqflist()
62      end)
63      eq(0, qflist_count)
64    end)
65
66    it('opens the quickfix list with the right caller', function()
67      local qflist = exec_lua(function()
68        local rust_analyzer_response = {
69          {
70            fromRanges = {
71              {
72                ['end'] = {
73                  character = 7,
74                  line = 3,
75                },
76                start = {
77                  character = 4,
78                  line = 3,
79                },
80              },
81            },
82            to = {
83              detail = 'fn foo()',
84              kind = 12,
85              name = 'foo',
86              range = {
87                ['end'] = {
88                  character = 11,
89                  line = 0,
90                },
91                start = {
92                  character = 0,
93                  line = 0,
94                },
95              },
96              selectionRange = {
97                ['end'] = {
98                  character = 6,
99                  line = 0,
100                },
101                start = {
102                  character = 3,
103                  line = 0,
104                },
105              },
106              uri = 'file:///src/main.rs',
107            },
108          },
109        }
110        local handler = require 'vim.lsp.handlers'['callHierarchy/outgoingCalls']
111        local bufnr = vim.api.nvim_get_current_buf()
112        handler(nil, rust_analyzer_response, { bufnr = bufnr })
113        return vim.fn.getqflist()
114      end)
115
116      local expected = {
117        {
118          bufnr = 1,
119          col = 5,
120          end_col = 0,
121          lnum = 4,
122          end_lnum = 0,
123          module = '',
124          nr = 0,
125          pattern = '',
126          text = 'foo',
127          type = '',
128          valid = 1,
129          vcol = 0,
130        },
131      }
132
133      eq(expected, qflist)
134    end)
135  end)
136
137  describe('vim.lsp.buf.incoming_calls', function()
138    it('does nothing for an empty response', function()
139      local qflist_count = exec_lua(function()
140        require 'vim.lsp.handlers'['callHierarchy/incomingCalls'](nil, nil, {})
141        return #vim.fn.getqflist()
142      end)
143      eq(0, qflist_count)
144    end)
145
146    it('opens the quickfix list with the right callee', function()
147      local qflist = exec_lua(function()
148        local rust_analyzer_response = {
149          {
150            from = {
151              detail = 'fn main()',
152              kind = 12,
153              name = 'main',
154              range = {
155                ['end'] = {
156                  character = 1,
157                  line = 4,
158                },
159                start = {
160                  character = 0,
161                  line = 2,
162                },
163              },
164              selectionRange = {
165                ['end'] = {
166                  character = 7,
167                  line = 2,
168                },
169                start = {
170                  character = 3,
171                  line = 2,
172                },
173              },
174              uri = 'file:///src/main.rs',
175            },
176            fromRanges = {
177              {
178                ['end'] = {
179                  character = 7,
180                  line = 3,
181                },
182                start = {
183                  character = 4,
184                  line = 3,
185                },
186              },
187            },
188          },
189        }
190
191        local handler = require 'vim.lsp.handlers'['callHierarchy/incomingCalls']
192        handler(nil, rust_analyzer_response, {})
193        return vim.fn.getqflist()
194      end)
195
196      local expected = {
197        {
198          bufnr = 2,
199          col = 5,
200          end_col = 0,
201          lnum = 4,
202          end_lnum = 0,
203          module = '',
204          nr = 0,
205          pattern = '',
206          text = 'main',
207          type = '',
208          valid = 1,
209          vcol = 0,
210        },
211      }
212
213      eq(expected, qflist)
214    end)
215  end)
216
217  describe('vim.lsp.buf.typehierarchy subtypes', function()
218    it('does nothing for an empty response', function()
219      local qflist_count = exec_lua(function()
220        require 'vim.lsp.handlers'['typeHierarchy/subtypes'](nil, nil, {})
221        return #vim.fn.getqflist()
222      end)
223      eq(0, qflist_count)
224    end)
225
226    it('opens the quickfix list with the right subtypes', function()
227      exec_lua(create_server_definition)
228      local qflist = exec_lua(function()
229        local clangd_response = {
230          {
231            data = {
232              parents = {
233                {
234                  parents = {
235                    {
236                      parents = {
237                        {
238                          parents = {},
239                          symbolID = '62B3D268A01B9978',
240                        },
241                      },
242                      symbolID = 'DC9B0AD433B43BEC',
243                    },
244                  },
245                  symbolID = '06B5F6A19BA9F6A8',
246                },
247              },
248              symbolID = 'EDC336589C09ABB2',
249            },
250            kind = 5,
251            name = 'D2',
252            range = {
253              ['end'] = {
254                character = 8,
255                line = 3,
256              },
257              start = {
258                character = 6,
259                line = 3,
260              },
261            },
262            selectionRange = {
263              ['end'] = {
264                character = 8,
265                line = 3,
266              },
267              start = {
268                character = 6,
269                line = 3,
270              },
271            },
272            uri = 'file:///home/jiangyinzuo/hello.cpp',
273          },
274          {
275            data = {
276              parents = {
277                {
278                  parents = {
279                    {
280                      parents = {
281                        {
282                          parents = {},
283                          symbolID = '62B3D268A01B9978',
284                        },
285                      },
286                      symbolID = 'DC9B0AD433B43BEC',
287                    },
288                  },
289                  symbolID = '06B5F6A19BA9F6A8',
290                },
291              },
292              symbolID = 'AFFCAED15557EF08',
293            },
294            kind = 5,
295            name = 'D1',
296            range = {
297              ['end'] = {
298                character = 8,
299                line = 2,
300              },
301              start = {
302                character = 6,
303                line = 2,
304              },
305            },
306            selectionRange = {
307              ['end'] = {
308                character = 8,
309                line = 2,
310              },
311              start = {
312                character = 6,
313                line = 2,
314              },
315            },
316            uri = 'file:///home/jiangyinzuo/hello.cpp',
317          },
318        }
319
320        local server = _G._create_server({
321          capabilities = {
322            positionEncoding = 'utf-8',
323          },
324        })
325        local client_id = vim.lsp.start({ name = 'dummy', cmd = server.cmd })
326        local handler = require 'vim.lsp.handlers'['typeHierarchy/subtypes']
327        local bufnr = vim.api.nvim_get_current_buf()
328        vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, {
329          'class B : public A{};',
330          'class C : public B{};',
331          'class D1 : public C{};',
332          'class D2 : public C{};',
333          'class E : public D1, D2 {};',
334        })
335        handler(nil, clangd_response, { client_id = client_id, bufnr = bufnr })
336        return vim.fn.getqflist()
337      end)
338
339      local expected = {
340        {
341          bufnr = 2,
342          col = 7,
343          end_col = 0,
344          end_lnum = 0,
345          lnum = 4,
346          module = '',
347          nr = 0,
348          pattern = '',
349          text = 'D2',
350          type = '',
351          valid = 1,
352          vcol = 0,
353        },
354        {
355          bufnr = 2,
356          col = 7,
357          end_col = 0,
358          end_lnum = 0,
359          lnum = 3,
360          module = '',
361          nr = 0,
362          pattern = '',
363          text = 'D1',
364          type = '',
365          valid = 1,
366          vcol = 0,
367        },
368      }
369
370      eq(expected, qflist)
371    end)
372
373    it('opens the quickfix list with the right subtypes and details', function()
374      exec_lua(create_server_definition)
375      local qflist = exec_lua(function()
376        local jdtls_response = {
377          {
378            data = { element = '=hello-java_ed323c3c/_<{Main.java[Main[A' },
379            detail = '',
380            kind = 5,
381            name = 'A',
382            range = {
383              ['end'] = { character = 26, line = 3 },
384              start = { character = 1, line = 3 },
385            },
386            selectionRange = {
387              ['end'] = { character = 8, line = 3 },
388              start = { character = 7, line = 3 },
389            },
390            tags = {},
391            uri = 'file:///home/jiangyinzuo/hello-java/Main.java',
392          },
393          {
394            data = { element = '=hello-java_ed323c3c/_<mylist{MyList.java[MyList[Inner' },
395            detail = 'mylist',
396            kind = 5,
397            name = 'MyList$Inner',
398            range = {
399              ['end'] = { character = 37, line = 3 },
400              start = { character = 1, line = 3 },
401            },
402            selectionRange = {
403              ['end'] = { character = 19, line = 3 },
404              start = { character = 14, line = 3 },
405            },
406            tags = {},
407            uri = 'file:///home/jiangyinzuo/hello-java/mylist/MyList.java',
408          },
409        }
410
411        local server = _G._create_server({
412          capabilities = {
413            positionEncoding = 'utf-8',
414          },
415        })
416        local client_id = vim.lsp.start({ name = 'dummy', cmd = server.cmd })
417        local handler = require 'vim.lsp.handlers'['typeHierarchy/subtypes']
418        local bufnr = vim.api.nvim_get_current_buf()
419        vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, {
420          'package mylist;',
421          '',
422          'public class MyList {',
423          ' static class Inner extends MyList{}',
424          '~}',
425        })
426        handler(nil, jdtls_response, { client_id = client_id, bufnr = bufnr })
427        return vim.fn.getqflist()
428      end)
429
430      local expected = {
431        {
432          bufnr = 2,
433          col = 2,
434          end_col = 0,
435          end_lnum = 0,
436          lnum = 4,
437          module = '',
438          nr = 0,
439          pattern = '',
440          text = 'A',
441          type = '',
442          valid = 1,
443          vcol = 0,
444        },
445        {
446          bufnr = 3,
447          col = 2,
448          end_col = 0,
449          end_lnum = 0,
450          lnum = 4,
451          module = '',
452          nr = 0,
453          pattern = '',
454          text = 'MyList$Inner mylist',
455          type = '',
456          valid = 1,
457          vcol = 0,
458        },
459      }
460      eq(expected, qflist)
461    end)
462  end)
463
464  describe('vim.lsp.buf.typehierarchy supertypes', function()
465    it('does nothing for an empty response', function()
466      local qflist_count = exec_lua(function()
467        require 'vim.lsp.handlers'['typeHierarchy/supertypes'](nil, nil, {})
468        return #vim.fn.getqflist()
469      end)
470      eq(0, qflist_count)
471    end)
472
473    it('opens the quickfix list with the right supertypes', function()
474      exec_lua(create_server_definition)
475      local qflist = exec_lua(function()
476        local clangd_response = {
477          {
478            data = {
479              parents = {
480                {
481                  parents = {
482                    {
483                      parents = {
484                        {
485                          parents = {},
486                          symbolID = '62B3D268A01B9978',
487                        },
488                      },
489                      symbolID = 'DC9B0AD433B43BEC',
490                    },
491                  },
492                  symbolID = '06B5F6A19BA9F6A8',
493                },
494              },
495              symbolID = 'EDC336589C09ABB2',
496            },
497            kind = 5,
498            name = 'D2',
499            range = {
500              ['end'] = {
501                character = 8,
502                line = 3,
503              },
504              start = {
505                character = 6,
506                line = 3,
507              },
508            },
509            selectionRange = {
510              ['end'] = {
511                character = 8,
512                line = 3,
513              },
514              start = {
515                character = 6,
516                line = 3,
517              },
518            },
519            uri = 'file:///home/jiangyinzuo/hello.cpp',
520          },
521          {
522            data = {
523              parents = {
524                {
525                  parents = {
526                    {
527                      parents = {
528                        {
529                          parents = {},
530                          symbolID = '62B3D268A01B9978',
531                        },
532                      },
533                      symbolID = 'DC9B0AD433B43BEC',
534                    },
535                  },
536                  symbolID = '06B5F6A19BA9F6A8',
537                },
538              },
539              symbolID = 'AFFCAED15557EF08',
540            },
541            kind = 5,
542            name = 'D1',
543            range = {
544              ['end'] = {
545                character = 8,
546                line = 2,
547              },
548              start = {
549                character = 6,
550                line = 2,
551              },
552            },
553            selectionRange = {
554              ['end'] = {
555                character = 8,
556                line = 2,
557              },
558              start = {
559                character = 6,
560                line = 2,
561              },
562            },
563            uri = 'file:///home/jiangyinzuo/hello.cpp',
564          },
565        }
566
567        local server = _G._create_server({
568          capabilities = {
569            positionEncoding = 'utf-8',
570          },
571        })
572        local client_id = vim.lsp.start({ name = 'dummy', cmd = server.cmd })
573        local handler = require 'vim.lsp.handlers'['typeHierarchy/supertypes']
574        local bufnr = vim.api.nvim_get_current_buf()
575        vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, {
576          'class B : public A{};',
577          'class C : public B{};',
578          'class D1 : public C{};',
579          'class D2 : public C{};',
580          'class E : public D1, D2 {};',
581        })
582
583        handler(nil, clangd_response, { client_id = client_id, bufnr = bufnr })
584        return vim.fn.getqflist()
585      end)
586
587      local expected = {
588        {
589          bufnr = 2,
590          col = 7,
591          end_col = 0,
592          end_lnum = 0,
593          lnum = 4,
594          module = '',
595          nr = 0,
596          pattern = '',
597          text = 'D2',
598          type = '',
599          valid = 1,
600          vcol = 0,
601        },
602        {
603          bufnr = 2,
604          col = 7,
605          end_col = 0,
606          end_lnum = 0,
607          lnum = 3,
608          module = '',
609          nr = 0,
610          pattern = '',
611          text = 'D1',
612          type = '',
613          valid = 1,
614          vcol = 0,
615        },
616      }
617
618      eq(expected, qflist)
619    end)
620
621    it('opens the quickfix list with the right supertypes and details', function()
622      exec_lua(create_server_definition)
623      local qflist = exec_lua(function()
624        local jdtls_response = {
625          {
626            data = { element = '=hello-java_ed323c3c/_<{Main.java[Main[A' },
627            detail = '',
628            kind = 5,
629            name = 'A',
630            range = {
631              ['end'] = { character = 26, line = 3 },
632              start = { character = 1, line = 3 },
633            },
634            selectionRange = {
635              ['end'] = { character = 8, line = 3 },
636              start = { character = 7, line = 3 },
637            },
638            tags = {},
639            uri = 'file:///home/jiangyinzuo/hello-java/Main.java',
640          },
641          {
642            data = { element = '=hello-java_ed323c3c/_<mylist{MyList.java[MyList[Inner' },
643            detail = 'mylist',
644            kind = 5,
645            name = 'MyList$Inner',
646            range = {
647              ['end'] = { character = 37, line = 3 },
648              start = { character = 1, line = 3 },
649            },
650            selectionRange = {
651              ['end'] = { character = 19, line = 3 },
652              start = { character = 14, line = 3 },
653            },
654            tags = {},
655            uri = 'file:///home/jiangyinzuo/hello-java/mylist/MyList.java',
656          },
657        }
658
659        local server = _G._create_server({
660          capabilities = {
661            positionEncoding = 'utf-8',
662          },
663        })
664        local client_id = vim.lsp.start({ name = 'dummy', cmd = server.cmd })
665        local handler = require 'vim.lsp.handlers'['typeHierarchy/supertypes']
666        local bufnr = vim.api.nvim_get_current_buf()
667        vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, {
668          'package mylist;',
669          '',
670          'public class MyList {',
671          ' static class Inner extends MyList{}',
672          '~}',
673        })
674        handler(nil, jdtls_response, { client_id = client_id, bufnr = bufnr })
675        return vim.fn.getqflist()
676      end)
677
678      local expected = {
679        {
680          bufnr = 2,
681          col = 2,
682          end_col = 0,
683          end_lnum = 0,
684          lnum = 4,
685          module = '',
686          nr = 0,
687          pattern = '',
688          text = 'A',
689          type = '',
690          valid = 1,
691          vcol = 0,
692        },
693        {
694          bufnr = 3,
695          col = 2,
696          end_col = 0,
697          end_lnum = 0,
698          lnum = 4,
699          module = '',
700          nr = 0,
701          pattern = '',
702          text = 'MyList$Inner mylist',
703          type = '',
704          valid = 1,
705          vcol = 0,
706        },
707      }
708      eq(expected, qflist)
709    end)
710  end)
711
712  describe('vim.lsp.buf.rename', function()
713    for _, test in ipairs({
714      {
715        it = 'does not attempt to rename on nil response',
716        name = 'prepare_rename_nil',
717        expected_handlers = {
718          { NIL, {}, { method = 'shutdown', client_id = 1 } },
719          { NIL, {}, { method = 'start', client_id = 1 } },
720        },
721      },
722      {
723        it = 'handles prepareRename placeholder response',
724        name = 'prepare_rename_placeholder',
725        expected_handlers = {
726          { NIL, {}, { method = 'shutdown', client_id = 1 } },
727          { {}, NIL, { method = 'textDocument/rename', client_id = 1, request_id = 3, bufnr = 1 } },
728          { NIL, {}, { method = 'start', client_id = 1 } },
729        },
730        expected_text = 'placeholder', -- see fake lsp response
731      },
732      {
733        it = 'handles range response',
734        name = 'prepare_rename_range',
735        expected_handlers = {
736          { NIL, {}, { method = 'shutdown', client_id = 1 } },
737          { {}, NIL, { method = 'textDocument/rename', client_id = 1, request_id = 3, bufnr = 1 } },
738          { NIL, {}, { method = 'start', client_id = 1 } },
739        },
740        expected_text = 'line', -- see test case and fake lsp response
741      },
742      {
743        it = 'handles error',
744        name = 'prepare_rename_error',
745        expected_handlers = {
746          { NIL, {}, { method = 'shutdown', client_id = 1 } },
747          { NIL, {}, { method = 'start', client_id = 1 } },
748        },
749      },
750    }) do
751      it(test.it, function()
752        local client --- @type vim.lsp.Client
753        test_rpc_server {
754          test_name = test.name,
755          on_init = function(_client)
756            client = _client
757            eq(true, client.server_capabilities().renameProvider.prepareProvider)
758          end,
759          on_setup = function()
760            exec_lua(function()
761              local bufnr = vim.api.nvim_get_current_buf()
762              vim.lsp.buf_attach_client(bufnr, _G.TEST_RPC_CLIENT_ID)
763              vim.lsp._stubs = {}
764              --- @diagnostic disable-next-line:duplicate-set-field
765              vim.fn.input = function(opts, _)
766                vim.lsp._stubs.input_prompt = opts.prompt
767                vim.lsp._stubs.input_text = opts.default
768                return 'renameto' -- expect this value in fake lsp
769              end
770              vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, { '', 'this is line two' })
771              vim.fn.cursor(2, 13) -- the space between "line" and "two"
772            end)
773          end,
774          on_exit = function(code, signal)
775            eq(0, code, 'exit code')
776            eq(0, signal, 'exit signal')
777          end,
778          on_handler = function(err, result, ctx)
779            -- Don't compare & assert params and version, they're not relevant for the testcase
780            -- This allows us to be lazy and avoid declaring them
781            ctx.params = nil
782            ctx.version = nil
783
784            eq(table.remove(test.expected_handlers), { err, result, ctx }, 'expected handler')
785            if ctx.method == 'start' then
786              exec_lua(function()
787                vim.lsp.buf.rename()
788              end)
789            end
790            if ctx.method == 'shutdown' then
791              if test.expected_text then
792                eq(
793                  'New Name: ',
794                  exec_lua(function()
795                    return vim.lsp._stubs.input_prompt
796                  end)
797                )
798                eq(
799                  test.expected_text,
800                  exec_lua(function()
801                    return vim.lsp._stubs.input_text
802                  end)
803                )
804              end
805              client:stop()
806            end
807          end,
808        }
809      end)
810    end
811  end)
812
813  describe('vim.lsp.buf.code_action', function()
814    it('calls client side command if available', function()
815      local client --- @type vim.lsp.Client
816      local expected_handlers = {
817        { NIL, {}, { method = 'shutdown', client_id = 1 } },
818        { NIL, {}, { method = 'start', client_id = 1 } },
819      }
820      test_rpc_server {
821        test_name = 'code_action_with_resolve',
822        on_init = function(client_)
823          client = client_
824        end,
825        on_setup = function() end,
826        on_exit = function(code, signal)
827          eq(0, code, 'exit code')
828          eq(0, signal, 'exit signal')
829        end,
830        on_handler = function(err, result, ctx)
831          eq(table.remove(expected_handlers), { err, result, ctx })
832          if ctx.method == 'start' then
833            exec_lua(function()
834              vim.lsp.commands['dummy1'] = function(_)
835                vim.lsp.commands['dummy2'] = function() end
836              end
837              local bufnr = vim.api.nvim_get_current_buf()
838              vim.lsp.buf_attach_client(bufnr, _G.TEST_RPC_CLIENT_ID)
839              --- @diagnostic disable-next-line:duplicate-set-field
840              vim.fn.inputlist = function()
841                return 1
842              end
843              vim.lsp.buf.code_action()
844            end)
845          elseif ctx.method == 'shutdown' then
846            eq(
847              'function',
848              exec_lua(function()
849                return type(vim.lsp.commands['dummy2'])
850              end)
851            )
852            client:stop()
853          end
854        end,
855      }
856    end)
857
858    it('calls workspace/executeCommand if no client side command', function()
859      local client --- @type vim.lsp.Client
860      local expected_handlers = {
861        { NIL, {}, { method = 'shutdown', client_id = 1 } },
862        {
863          NIL,
864          { command = 'dummy1', title = 'Command 1' },
865          { bufnr = 1, method = 'workspace/executeCommand', request_id = 3, client_id = 1 },
866        },
867        { NIL, {}, { method = 'start', client_id = 1 } },
868      }
869      test_rpc_server({
870        test_name = 'code_action_server_side_command',
871        on_init = function(client_)
872          client = client_
873        end,
874        on_setup = function() end,
875        on_exit = function(code, signal)
876          eq(0, code, 'exit code', fake_lsp_logfile)
877          eq(0, signal, 'exit signal', fake_lsp_logfile)
878        end,
879        on_handler = function(err, result, ctx)
880          ctx.params = nil -- don't compare in assert
881          ctx.version = nil
882          eq(table.remove(expected_handlers), { err, result, ctx })
883          if ctx.method == 'start' then
884            exec_lua(function()
885              local bufnr = vim.api.nvim_get_current_buf()
886              vim.lsp.buf_attach_client(bufnr, _G.TEST_RPC_CLIENT_ID)
887              vim.fn.inputlist = function()
888                return 1
889              end
890              vim.lsp.buf.code_action()
891            end)
892          elseif ctx.method == 'shutdown' then
893            client:stop()
894          end
895        end,
896      })
897    end)
898
899    it('filters and automatically applies action if requested', function()
900      local client --- @type vim.lsp.Client
901      local expected_handlers = {
902        { NIL, {}, { method = 'shutdown', client_id = 1 } },
903        { NIL, {}, { method = 'start', client_id = 1 } },
904      }
905      test_rpc_server {
906        test_name = 'code_action_filter',
907        on_init = function(client_)
908          client = client_
909        end,
910        on_setup = function() end,
911        on_exit = function(code, signal)
912          eq(0, code, 'exit code')
913          eq(0, signal, 'exit signal')
914        end,
915        on_handler = function(err, result, ctx)
916          eq(table.remove(expected_handlers), { err, result, ctx })
917          if ctx.method == 'start' then
918            exec_lua(function()
919              vim.lsp.commands['preferred_command'] = function(_)
920                vim.lsp.commands['executed_preferred'] = function() end
921              end
922              vim.lsp.commands['type_annotate_command'] = function(_)
923                vim.lsp.commands['executed_type_annotate'] = function() end
924              end
925              local bufnr = vim.api.nvim_get_current_buf()
926              vim.lsp.buf_attach_client(bufnr, _G.TEST_RPC_CLIENT_ID)
927              vim.lsp.buf.code_action({
928                filter = function(a)
929                  return a.isPreferred
930                end,
931                apply = true,
932              })
933              vim.lsp.buf.code_action({
934                -- expect to be returned actions 'type-annotate' and 'type-annotate.foo'
935                context = { only = { 'type-annotate' } },
936                apply = true,
937                filter = function(a)
938                  if a.kind == 'type-annotate.foo' then
939                    vim.lsp.commands['filtered_type_annotate_foo'] = function() end
940                    return false
941                  elseif a.kind == 'type-annotate' then
942                    return true
943                  else
944                    assert(nil, 'unreachable')
945                  end
946                end,
947              })
948            end)
949          elseif ctx.method == 'shutdown' then
950            eq(
951              'function',
952              exec_lua(function()
953                return type(vim.lsp.commands['executed_preferred'])
954              end)
955            )
956            eq(
957              'function',
958              exec_lua(function()
959                return type(vim.lsp.commands['filtered_type_annotate_foo'])
960              end)
961            )
962            eq(
963              'function',
964              exec_lua(function()
965                return type(vim.lsp.commands['executed_type_annotate'])
966              end)
967            )
968            client:stop()
969          end
970        end,
971      }
972    end)
973
974    it('uses diagnostics at cursor position', function()
975      exec_lua(create_server_definition)
976      local severity = exec_lua(function()
977        return vim.diagnostic.severity.ERROR
978      end)
979      local messages = exec_lua(function(severity_)
980        local server = _G._create_server({
981          capabilities = {
982            codeActionProvider = true,
983          },
984          handlers = {
985            ['textDocument/codeAction'] = function(_, _, callback)
986              callback(nil, {})
987            end,
988          },
989        })
990
991        local bufnr = vim.api.nvim_get_current_buf()
992        vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, { 'local first, second = 1, 2' })
993
994        local client_id = assert(vim.lsp.start({
995          name = 'dummy',
996          cmd = server.cmd,
997        }))
998
999        local expected_messages = 2 -- initialize, initialized
1000        local function wait_for_messages()
1001          assert(
1002            vim.wait(200, function()
1003              return #server.messages == expected_messages
1004            end),
1005            'Timed out waiting for expected number of messages. Current messages seen so far: '
1006              .. vim.inspect(server.messages)
1007          )
1008        end
1009
1010        wait_for_messages()
1011
1012        vim.api.nvim_win_set_cursor(0, { 1, 15 })
1013
1014        local ns = vim.lsp.diagnostic.get_namespace(client_id)
1015        vim.diagnostic.set(ns, bufnr, {
1016          {
1017            lnum = 0,
1018            col = 6,
1019            end_lnum = 0,
1020            end_col = 11,
1021            message = 'first',
1022            severity = severity_,
1023            user_data = {
1024              lsp = {
1025                range = {
1026                  start = { line = 0, character = 6 },
1027                  ['end'] = { line = 0, character = 11 },
1028                },
1029                message = 'first',
1030                severity = severity_,
1031              },
1032            },
1033          },
1034          {
1035            lnum = 0,
1036            col = 13,
1037            end_lnum = 0,
1038            end_col = 19,
1039            message = 'second',
1040            severity = severity_,
1041            user_data = {
1042              lsp = {
1043                range = {
1044                  start = { line = 0, character = 13 },
1045                  ['end'] = { line = 0, character = 19 },
1046                },
1047                message = 'second',
1048                severity = severity_,
1049              },
1050            },
1051          },
1052        })
1053
1054        vim.lsp.buf.code_action()
1055
1056        expected_messages = expected_messages + 1
1057        wait_for_messages()
1058
1059        vim.lsp.get_client_by_id(client_id):stop()
1060
1061        return server.messages
1062      end, severity)
1063
1064      eq('textDocument/codeAction', messages[3].method)
1065      eq({
1066        {
1067          range = {
1068            start = { line = 0, character = 13 },
1069            ['end'] = { line = 0, character = 19 },
1070          },
1071          message = 'second',
1072          severity = severity,
1073        },
1074      }, messages[3].params.context.diagnostics)
1075    end)
1076
1077    it('fallback to command execution on resolve error', function()
1078      exec_lua(create_server_definition)
1079      local result = exec_lua(function()
1080        local server = _G._create_server({
1081          capabilities = {
1082            executeCommandProvider = {
1083              commands = { 'command:1' },
1084            },
1085            codeActionProvider = {
1086              resolveProvider = true,
1087            },
1088          },
1089          handlers = {
1090            ['textDocument/codeAction'] = function(_, _, callback)
1091              callback(nil, {
1092                {
1093                  title = 'Code Action 1',
1094                  command = {
1095                    title = 'Command 1',
1096                    command = 'command:1',
1097                  },
1098                },
1099              })
1100            end,
1101            ['codeAction/resolve'] = function(_, _, callback)
1102              callback(
1103                { code = vim.lsp.protocol.ErrorCodes.InternalError, message = 'resolve failed' },
1104                nil
1105              )
1106            end,
1107          },
1108        })
1109
1110        local client_id = assert(vim.lsp.start({
1111          name = 'dummy',
1112          cmd = server.cmd,
1113        }))
1114
1115        vim.lsp.buf.code_action({ apply = true })
1116        vim.lsp.get_client_by_id(client_id):stop()
1117        return server.messages
1118      end)
1119      eq('codeAction/resolve', result[4].method)
1120      eq('workspace/executeCommand', result[5].method)
1121      eq('command:1', result[5].params.command)
1122    end)
1123
1124    it('resolves command property', function()
1125      exec_lua(create_server_definition)
1126      local result = exec_lua(function()
1127        local server = _G._create_server({
1128          capabilities = {
1129            executeCommandProvider = {
1130              commands = { 'command:1' },
1131            },
1132            codeActionProvider = {
1133              resolveProvider = true,
1134            },
1135          },
1136          handlers = {
1137            ['textDocument/codeAction'] = function(_, _, callback)
1138              callback(nil, {
1139                { title = 'Code Action 1' },
1140              })
1141            end,
1142            ['codeAction/resolve'] = function(_, _, callback)
1143              callback(nil, {
1144                title = 'Code Action 1',
1145                command = {
1146                  title = 'Command 1',
1147                  command = 'command:1',
1148                },
1149              })
1150            end,
1151          },
1152        })
1153
1154        local client_id = assert(vim.lsp.start({
1155          name = 'dummy',
1156          cmd = server.cmd,
1157        }))
1158
1159        vim.lsp.buf.code_action({ apply = true })
1160        vim.lsp.get_client_by_id(client_id):stop()
1161        return server.messages
1162      end)
1163      eq('codeAction/resolve', result[4].method)
1164      eq('workspace/executeCommand', result[5].method)
1165      eq('command:1', result[5].params.command)
1166    end)
1167
1168    it('supports disabled actions', function()
1169      exec_lua(create_server_definition)
1170      local result = exec_lua(function()
1171        local server = _G._create_server({
1172          capabilities = {
1173            executeCommandProvider = {
1174              commands = { 'command:1' },
1175            },
1176            codeActionProvider = {
1177              resolveProvider = true,
1178            },
1179          },
1180          handlers = {
1181            ['textDocument/codeAction'] = function(_, _, callback)
1182              callback(nil, {
1183                {
1184                  title = 'Code Action 1',
1185                  disabled = {
1186                    reason = 'This action is disabled',
1187                  },
1188                },
1189              })
1190            end,
1191            ['codeAction/resolve'] = function(_, _, callback)
1192              callback(nil, {
1193                title = 'Code Action 1',
1194                command = {
1195                  title = 'Command 1',
1196                  command = 'command:1',
1197                },
1198              })
1199            end,
1200          },
1201        })
1202
1203        local client_id = assert(vim.lsp.start({
1204          name = 'dummy',
1205          cmd = server.cmd,
1206        }))
1207
1208        --- @diagnostic disable-next-line:duplicate-set-field
1209        vim.notify = function(message, code)
1210          server.messages[#server.messages + 1] = {
1211            params = {
1212              message = message,
1213              code = code,
1214            },
1215          }
1216        end
1217
1218        vim.lsp.buf.code_action({ apply = true })
1219        vim.lsp.get_client_by_id(client_id):stop()
1220        return server.messages
1221      end)
1222      eq(
1223        exec_lua(function()
1224          return { message = 'This action is disabled', code = vim.log.levels.ERROR }
1225        end),
1226        result[4].params
1227      )
1228      -- No command is resolved/applied after selecting a disabled code action
1229      eq('shutdown', result[5].method)
1230    end)
1231  end)
1232
1233  describe('vim.lsp.commands', function()
1234    it('accepts only string keys', function()
1235      matches(
1236        '.*The key for commands in `vim.lsp.commands` must be a string',
1237        pcall_err(exec_lua, 'vim.lsp.commands[1] = function() end')
1238      )
1239    end)
1240
1241    it('accepts only function values', function()
1242      matches(
1243        '.*Command added to `vim.lsp.commands` must be a function',
1244        pcall_err(exec_lua, 'vim.lsp.commands.dummy = 10')
1245      )
1246    end)
1247  end)
1248
1249  describe('vim.lsp.buf.format', function()
1250    it('aborts with notify if no client matches filter', function()
1251      local client --- @type vim.lsp.Client
1252      test_rpc_server {
1253        test_name = 'basic_init',
1254        on_init = function(c)
1255          client = c
1256        end,
1257        on_handler = function()
1258          local notify_msg = exec_lua(function()
1259            local bufnr = vim.api.nvim_get_current_buf()
1260            vim.lsp.buf_attach_client(bufnr, _G.TEST_RPC_CLIENT_ID)
1261            local notify_msg --- @type string?
1262            local notify = vim.notify
1263            vim.notify = function(msg, _)
1264              notify_msg = msg
1265            end
1266            vim.lsp.buf.format({ name = 'does-not-exist' })
1267            vim.notify = notify
1268            return notify_msg
1269          end)
1270          eq('[LSP] Format request failed, no matching language servers.', notify_msg)
1271          client:stop()
1272        end,
1273      }
1274    end)
1275
1276    it('sends textDocument/formatting request to format buffer', function()
1277      local expected_handlers = {
1278        { NIL, {}, { method = 'shutdown', client_id = 1 } },
1279        { NIL, {}, { method = 'start', client_id = 1 } },
1280      }
1281      local client --- @type vim.lsp.Client
1282      test_rpc_server {
1283        test_name = 'basic_formatting',
1284        on_init = function(c)
1285          client = c
1286        end,
1287        on_handler = function(_, _, ctx)
1288          table.remove(expected_handlers)
1289          if ctx.method == 'start' then
1290            local notify_msg = exec_lua(function()
1291              local bufnr = vim.api.nvim_get_current_buf()
1292              vim.lsp.buf_attach_client(bufnr, _G.TEST_RPC_CLIENT_ID)
1293              local notify_msg --- @type string?
1294              local notify = vim.notify
1295              vim.notify = function(msg, _)
1296                notify_msg = msg
1297              end
1298              vim.lsp.buf.format({ bufnr = bufnr })
1299              vim.notify = notify
1300              return notify_msg
1301            end)
1302            eq(nil, notify_msg)
1303          elseif ctx.method == 'shutdown' then
1304            client:stop()
1305          end
1306        end,
1307      }
1308    end)
1309
1310    it('sends textDocument/rangeFormatting request to format a range', function()
1311      local expected_handlers = {
1312        { NIL, {}, { method = 'shutdown', client_id = 1 } },
1313        { NIL, {}, { method = 'start', client_id = 1 } },
1314      }
1315      local client --- @type vim.lsp.Client
1316      test_rpc_server {
1317        test_name = 'range_formatting',
1318        on_init = function(c)
1319          client = c
1320        end,
1321        on_handler = function(_, _, ctx)
1322          table.remove(expected_handlers)
1323          if ctx.method == 'start' then
1324            local notify_msg = exec_lua(function()
1325              local bufnr = vim.api.nvim_get_current_buf()
1326              vim.api.nvim_buf_set_lines(bufnr, 0, -1, true, { 'foo', 'bar' })
1327              vim.lsp.buf_attach_client(bufnr, _G.TEST_RPC_CLIENT_ID)
1328              local notify_msg --- @type string?
1329              local notify = vim.notify
1330              vim.notify = function(msg, _)
1331                notify_msg = msg
1332              end
1333              vim.lsp.buf.format({
1334                bufnr = bufnr,
1335                range = {
1336                  start = { 1, 1 },
1337                  ['end'] = { 1, 1 },
1338                },
1339              })
1340              vim.notify = notify
1341              return notify_msg
1342            end)
1343            eq(nil, notify_msg)
1344          elseif ctx.method == 'shutdown' then
1345            client:stop()
1346          end
1347        end,
1348      }
1349    end)
1350
1351    it('formats range ending with -1 column', function()
1352      exec_lua(create_server_definition)
1353      local result = exec_lua(function()
1354        local server = _G._create_server({
1355          capabilities = {
1356            documentRangeFormattingProvider = true,
1357          },
1358          handlers = {
1359            ['textDocument/rangeFormatting'] = function(_, params, callback)
1360              callback(nil, {
1361                {
1362                  range = params.range,
1363                  newText = 'function fn(abc)\n  print("hello")',
1364                },
1365              })
1366            end,
1367          },
1368        })
1369        local bufnr = vim.api.nvim_get_current_buf()
1370        local client_id = assert(vim.lsp.start({ name = 'dummy', cmd = server.cmd }))
1371        vim.api.nvim_win_set_buf(0, bufnr)
1372        vim.api.nvim_buf_set_lines(bufnr, 0, -1, true, {
1373          'function fn(abc  )',
1374          '  print("hello" )',
1375          'end',
1376        })
1377        vim.lsp.buf.format({
1378          bufnr = bufnr,
1379          range = {
1380            start = { 1, 0 },
1381            ['end'] = { 2, -1 },
1382          },
1383        })
1384        vim.lsp.get_client_by_id(client_id):stop()
1385        return {
1386          lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, true),
1387          range = server.messages[3].params.range,
1388        }
1389      end)
1390      eq({
1391        start = { line = 0, character = 0 },
1392        ['end'] = { line = 1, character = 17 },
1393      }, result.range)
1394      eq({ 'function fn(abc)', '  print("hello")', 'end' }, result.lines)
1395    end)
1396
1397    it('sends textDocument/rangesFormatting request to format multiple ranges', function()
1398      local expected_handlers = {
1399        { NIL, {}, { method = 'shutdown', client_id = 1 } },
1400        { NIL, {}, { method = 'start', client_id = 1 } },
1401      }
1402      local client --- @type vim.lsp.Client
1403      test_rpc_server {
1404        test_name = 'ranges_formatting',
1405        on_init = function(c)
1406          client = c
1407        end,
1408        on_handler = function(_, _, ctx)
1409          table.remove(expected_handlers)
1410          if ctx.method == 'start' then
1411            local notify_msg = exec_lua(function()
1412              local bufnr = vim.api.nvim_get_current_buf()
1413              vim.api.nvim_buf_set_lines(bufnr, 0, -1, true, { 'foo', 'bar', 'baz' })
1414              vim.lsp.buf_attach_client(bufnr, _G.TEST_RPC_CLIENT_ID)
1415              local notify_msg --- @type string?
1416              local notify = vim.notify
1417              vim.notify = function(msg, _)
1418                notify_msg = msg
1419              end
1420              vim.lsp.buf.format({
1421                bufnr = bufnr,
1422                range = {
1423                  {
1424                    start = { 1, 1 },
1425                    ['end'] = { 1, 1 },
1426                  },
1427                  {
1428                    start = { 2, 2 },
1429                    ['end'] = { 2, 2 },
1430                  },
1431                },
1432              })
1433              vim.notify = notify
1434              return notify_msg
1435            end)
1436            eq(nil, notify_msg)
1437          elseif ctx.method == 'shutdown' then
1438            client:stop()
1439          end
1440        end,
1441      }
1442    end)
1443
1444    it('can format async with an optional timeout', function()
1445      exec_lua(create_server_definition)
1446      exec_lua(function()
1447        _G.edits = {
1448          {
1449            range = {
1450              start = { line = 0, character = 0 },
1451              ['end'] = { line = 0, character = 0 },
1452            },
1453            newText = 'formatted',
1454          },
1455        }
1456        local opts = {
1457          capabilities = { documentFormattingProvider = true },
1458          handlers = {
1459            ['textDocument/formatting'] = function(_, _, callback)
1460              table.insert(_G.callbacks, callback)
1461              if #_G.callbacks == 2 then
1462                callback(nil, _G.edits)
1463              end
1464            end,
1465          },
1466        }
1467        _G.server = _G._create_server(opts)
1468        _G.server2 = _G._create_server(opts)
1469        vim.lsp.start({ name = 'dummy', cmd = _G.server.cmd })
1470        vim.lsp.start({ name = 'dummy2', cmd = _G.server2.cmd })
1471      end)
1472
1473      for _, timeout_ms in ipairs({ false, 20 }) do
1474        eq(
1475          1,
1476          exec_lua(function()
1477            _G.callbacks = {}
1478            vim.api.nvim_buf_set_lines(0, 0, -1, true, { '' })
1479            vim.lsp.buf.format({ async = true, timeout_ms = timeout_ms or nil })
1480            return #_G.callbacks
1481          end)
1482        )
1483        if not timeout_ms then
1484          exec_lua('_G.callbacks[1](nil, _G.edits)')
1485        end
1486        local expected = { timeout_ms and 'formatted' or 'formattedformatted' }
1487        retry(nil, 1000, function()
1488          eq(expected, api.nvim_buf_get_lines(0, 0, -1, true))
1489        end)
1490        if timeout_ms then
1491          eq(
1492            { method = '$/cancelRequest', params = { id = 4 } },
1493            exec_lua('return _G.server.messages[5] or _G.server2.messages[5]')
1494          )
1495          exec_lua('_G.callbacks[1](nil, _G.edits)')
1496          eq(expected, api.nvim_buf_get_lines(0, 0, -1, true))
1497        end
1498        eq(2, exec_lua('return #_G.callbacks'))
1499      end
1500    end)
1501
1502    it('format formats range in visual mode', function()
1503      exec_lua(create_server_definition)
1504      local result = exec_lua(function()
1505        local server = _G._create_server({
1506          capabilities = {
1507            documentFormattingProvider = true,
1508            documentRangeFormattingProvider = true,
1509          },
1510        })
1511        local bufnr = vim.api.nvim_get_current_buf()
1512        local client_id = assert(vim.lsp.start({ name = 'dummy', cmd = server.cmd }))
1513        vim.api.nvim_win_set_buf(0, bufnr)
1514        vim.api.nvim_buf_set_lines(bufnr, 0, -1, true, { 'foo', 'bar' })
1515        vim.api.nvim_win_set_cursor(0, { 1, 0 })
1516        vim.cmd.normal('v')
1517        vim.api.nvim_win_set_cursor(0, { 2, 3 })
1518        vim.lsp.buf.format({ bufnr = bufnr, false })
1519        vim.lsp.get_client_by_id(client_id):stop()
1520        return server.messages
1521      end)
1522      eq('textDocument/rangeFormatting', result[3].method)
1523      local expected_range = {
1524        start = { line = 0, character = 0 },
1525        ['end'] = { line = 2, character = 0 },
1526      }
1527      eq(expected_range, result[3].params.range)
1528    end)
1529
1530    it('format formats range in visual line mode', function()
1531      exec_lua(create_server_definition)
1532      local result = exec_lua(function()
1533        local server = _G._create_server({
1534          capabilities = {
1535            documentFormattingProvider = true,
1536            documentRangeFormattingProvider = true,
1537          },
1538        })
1539        local bufnr = vim.api.nvim_get_current_buf()
1540        local client_id = assert(vim.lsp.start({ name = 'dummy', cmd = server.cmd }))
1541        vim.api.nvim_win_set_buf(0, bufnr)
1542        vim.api.nvim_buf_set_lines(bufnr, 0, -1, true, { 'foo', 'bar baz' })
1543        vim.api.nvim_win_set_cursor(0, { 1, 2 })
1544        vim.cmd.normal('V')
1545        vim.api.nvim_win_set_cursor(0, { 2, 1 })
1546        vim.lsp.buf.format({ bufnr = bufnr, false })
1547
1548        -- Format again with visual lines going from bottom to top
1549        -- Must result in same formatting
1550        vim.cmd.normal('<ESC>')
1551        vim.api.nvim_win_set_cursor(0, { 2, 1 })
1552        vim.cmd.normal('V')
1553        vim.api.nvim_win_set_cursor(0, { 1, 2 })
1554        vim.lsp.buf.format({ bufnr = bufnr, false })
1555
1556        vim.lsp.get_client_by_id(client_id):stop()
1557        return server.messages
1558      end)
1559      local expected_methods = {
1560        'initialize',
1561        'initialized',
1562        'textDocument/rangeFormatting',
1563        '$/cancelRequest',
1564        'textDocument/rangeFormatting',
1565        '$/cancelRequest',
1566        'shutdown',
1567        'exit',
1568      }
1569      eq(
1570        expected_methods,
1571        vim.tbl_map(function(x)
1572          return x.method
1573        end, result)
1574      )
1575      -- uses first column of start line and last column of end line
1576      local expected_range = {
1577        start = { line = 0, character = 0 },
1578        ['end'] = { line = 1, character = 7 },
1579      }
1580      eq(expected_range, result[3].params.range)
1581      eq(expected_range, result[5].params.range)
1582    end)
1583
1584    it('aborts with notify if no clients support requested method', function()
1585      exec_lua(create_server_definition)
1586      exec_lua(function()
1587        vim.notify = function(msg, _)
1588          _G.notify_msg = msg
1589        end
1590      end)
1591      local fail_msg = '[LSP] Format request failed, no matching language servers.'
1592      --- @param name string
1593      --- @param formatting boolean
1594      --- @param range_formatting boolean
1595      local function check_notify(name, formatting, range_formatting)
1596        local timeout_msg = '[LSP][' .. name .. '] timeout'
1597        exec_lua(function()
1598          local server = _G._create_server({
1599            capabilities = {
1600              documentFormattingProvider = formatting,
1601              documentRangeFormattingProvider = range_formatting,
1602            },
1603          })
1604          vim.lsp.start({ name = name, cmd = server.cmd })
1605          _G.notify_msg = nil
1606          vim.lsp.buf.format({ name = name, timeout_ms = 1 })
1607        end)
1608        eq(
1609          formatting and timeout_msg or fail_msg,
1610          exec_lua(function()
1611            return _G.notify_msg
1612          end)
1613        )
1614        exec_lua(function()
1615          _G.notify_msg = nil
1616          vim.lsp.buf.format({
1617            name = name,
1618            timeout_ms = 1,
1619            range = {
1620              start = { 1, 0 },
1621              ['end'] = {
1622                1,
1623                0,
1624              },
1625            },
1626          })
1627        end)
1628        eq(
1629          range_formatting and timeout_msg or fail_msg,
1630          exec_lua(function()
1631            return _G.notify_msg
1632          end)
1633        )
1634      end
1635      check_notify('none', false, false)
1636      check_notify('formatting', true, false)
1637      check_notify('rangeFormatting', false, true)
1638      check_notify('both', true, true)
1639    end)
1640  end)
1641
1642  describe('vim.lsp.buf.definition', function()
1643    it('jumps to single location and can reuse win', function()
1644      exec_lua(create_server_definition)
1645      local result = exec_lua(function()
1646        local bufnr = vim.api.nvim_get_current_buf()
1647        local server = _G._create_server({
1648          capabilities = {
1649            definitionProvider = true,
1650          },
1651          handlers = {
1652            ['textDocument/definition'] = function(_, _, callback)
1653              local location = {
1654                range = {
1655                  start = { line = 0, character = 0 },
1656                  ['end'] = { line = 0, character = 0 },
1657                },
1658                uri = vim.uri_from_bufnr(bufnr),
1659              }
1660              callback(nil, location)
1661            end,
1662          },
1663        })
1664        local win = vim.api.nvim_get_current_win()
1665        vim.api.nvim_buf_set_lines(bufnr, 0, -1, true, { 'local x = 10', '', 'print(x)' })
1666        vim.api.nvim_win_set_cursor(win, { 3, 6 })
1667        local client_id = assert(vim.lsp.start({ name = 'dummy', cmd = server.cmd }))
1668        vim.lsp.buf.definition()
1669        return {
1670          win = win,
1671          bufnr = bufnr,
1672          client_id = client_id,
1673          cursor = vim.api.nvim_win_get_cursor(win),
1674          messages = server.messages,
1675          tagstack = vim.fn.gettagstack(win),
1676        }
1677      end)
1678      eq('textDocument/definition', result.messages[3].method)
1679      eq({ 1, 0 }, result.cursor)
1680      eq(1, #result.tagstack.items)
1681      eq('x', result.tagstack.items[1].tagname)
1682      eq(3, result.tagstack.items[1].from[2])
1683      eq(7, result.tagstack.items[1].from[3])
1684
1685      local result_bufnr = api.nvim_get_current_buf()
1686      n.feed(':tabe<CR>')
1687      api.nvim_win_set_buf(0, result_bufnr)
1688      local displayed_result_win = api.nvim_get_current_win()
1689      n.feed(':vnew<CR>')
1690      api.nvim_win_set_buf(0, result.bufnr)
1691      api.nvim_win_set_cursor(0, { 3, 6 })
1692      n.feed(':set switchbuf=usetab<CR>')
1693      n.feed(':=vim.lsp.buf.definition()<CR>')
1694      eq(displayed_result_win, api.nvim_get_current_win())
1695      exec_lua(function()
1696        vim.lsp.get_client_by_id(result.client_id):stop()
1697      end)
1698    end)
1699    it('merges results from multiple servers', function()
1700      exec_lua(create_server_definition)
1701      local result = exec_lua(function()
1702        local bufnr = vim.api.nvim_get_current_buf()
1703        local function serveropts(character)
1704          return {
1705            capabilities = {
1706              definitionProvider = true,
1707            },
1708            handlers = {
1709              ['textDocument/definition'] = function(_, _, callback)
1710                local location = {
1711                  range = {
1712                    start = { line = 0, character = character },
1713                    ['end'] = { line = 0, character = character },
1714                  },
1715                  uri = vim.uri_from_bufnr(bufnr),
1716                }
1717                callback(nil, location)
1718              end,
1719            },
1720          }
1721        end
1722        local server1 = _G._create_server(serveropts(0))
1723        local server2 = _G._create_server(serveropts(7))
1724        local win = vim.api.nvim_get_current_win()
1725        vim.api.nvim_buf_set_lines(bufnr, 0, -1, true, { 'local x = 10', '', 'print(x)' })
1726        vim.api.nvim_win_set_cursor(win, { 3, 6 })
1727        local client_id1 = assert(vim.lsp.start({ name = 'dummy1', cmd = server1.cmd }))
1728        local client_id2 = assert(vim.lsp.start({ name = 'dummy2', cmd = server2.cmd }))
1729        local response
1730        vim.lsp.buf.definition({
1731          on_list = function(r)
1732            response = r
1733          end,
1734        })
1735        vim.lsp.get_client_by_id(client_id1):stop()
1736        vim.lsp.get_client_by_id(client_id2):stop()
1737        return response
1738      end)
1739      eq(2, #result.items)
1740    end)
1741  end)
1742
1743  describe('vim.lsp.buf.workspace_diagnostics()', function()
1744    local fake_uri = 'file:///fake/uri'
1745
1746    --- @param kind lsp.DocumentDiagnosticReportKind
1747    --- @param msg string
1748    --- @param pos integer
1749    --- @return lsp.WorkspaceDocumentDiagnosticReport
1750    local function make_report(kind, msg, pos)
1751      return {
1752        kind = kind,
1753        uri = fake_uri,
1754        items = {
1755          {
1756            range = {
1757              start = { line = pos, character = pos },
1758              ['end'] = { line = pos, character = pos },
1759            },
1760            message = msg,
1761            severity = 1,
1762          },
1763        },
1764      }
1765    end
1766
1767    --- @param items lsp.WorkspaceDocumentDiagnosticReport[]
1768    --- @return integer
1769    local function setup_server(items)
1770      exec_lua(create_server_definition)
1771      return exec_lua(function()
1772        _G.server = _G._create_server({
1773          capabilities = {
1774            diagnosticProvider = {
1775              documentSelector = vim.NIL,
1776              interFileDependencies = false,
1777              workspaceDiagnostics = true,
1778            },
1779          },
1780          handlers = {
1781            ['workspace/diagnostic'] = function(_, _, callback)
1782              callback(nil, { items = items })
1783            end,
1784          },
1785        })
1786        local client_id = assert(vim.lsp.start({ name = 'dummy', cmd = _G.server.cmd }))
1787        vim.lsp.buf.workspace_diagnostics()
1788        return client_id
1789      end, { items })
1790    end
1791
1792    it('updates diagnostics obtained with vim.diagnostic.get()', function()
1793      setup_server({ make_report('full', 'Error here', 1) })
1794
1795      retry(nil, nil, function()
1796        eq(
1797          1,
1798          exec_lua(function()
1799            return #vim.diagnostic.get()
1800          end)
1801        )
1802      end)
1803
1804      eq(
1805        'Error here',
1806        exec_lua(function()
1807          return vim.diagnostic.get()[1].message
1808        end)
1809      )
1810    end)
1811
1812    it('ignores unchanged diagnostic reports', function()
1813      setup_server({ make_report('unchanged', '', 1) })
1814
1815      eq(
1816        0,
1817        exec_lua(function()
1818          -- Wait for diagnostics to be processed.
1819          vim.uv.sleep(50)
1820
1821          return #vim.diagnostic.get()
1822        end)
1823      )
1824    end)
1825
1826    it('favors document diagnostics over workspace diagnostics', function()
1827      local client_id = setup_server({ make_report('full', 'Workspace error', 1) })
1828      local diagnostic_bufnr = exec_lua(function()
1829        return vim.uri_to_bufnr(fake_uri)
1830      end)
1831
1832      exec_lua(function()
1833        vim.lsp.diagnostic.on_diagnostic(nil, {
1834          kind = 'full',
1835          items = {
1836            {
1837              range = {
1838                start = { line = 2, character = 2 },
1839                ['end'] = { line = 2, character = 2 },
1840              },
1841              message = 'Document error',
1842              severity = 1,
1843            },
1844          },
1845        }, {
1846          method = 'textDocument/diagnostic',
1847          params = {
1848            textDocument = { uri = fake_uri },
1849          },
1850          client_id = client_id,
1851          bufnr = diagnostic_bufnr,
1852        })
1853      end)
1854
1855      eq(
1856        1,
1857        exec_lua(function()
1858          return #vim.diagnostic.get(diagnostic_bufnr)
1859        end)
1860      )
1861
1862      eq(
1863        'Document error',
1864        exec_lua(function()
1865          return vim.diagnostic.get(vim.uri_to_bufnr(fake_uri))[1].message
1866        end)
1867      )
1868    end)
1869  end)
1870
1871  describe('vim.lsp.buf.hover()', function()
1872    it('handles empty contents', function()
1873      exec_lua(create_server_definition)
1874      exec_lua(function()
1875        local server = _G._create_server({
1876          capabilities = {
1877            hoverProvider = true,
1878          },
1879          handlers = {
1880            ['textDocument/hover'] = function(_, _, callback)
1881              local res = {
1882                contents = {
1883                  kind = 'markdown',
1884                  value = '',
1885                },
1886              }
1887              callback(nil, res)
1888            end,
1889          },
1890        })
1891        vim.lsp.start({ name = 'dummy', cmd = server.cmd })
1892      end)
1893
1894      eq('Empty hover response', exec_capture('lua vim.lsp.buf.hover()'))
1895    end)
1896
1897    it('treats markedstring array as not empty', function()
1898      exec_lua(create_server_definition)
1899      exec_lua(function()
1900        local server = _G._create_server({
1901          capabilities = {
1902            hoverProvider = true,
1903          },
1904          handlers = {
1905            ['textDocument/hover'] = function(_, _, callback)
1906              local res = {
1907                contents = {
1908                  {
1909                    language = 'java',
1910                    value = 'Example',
1911                  },
1912                  'doc comment',
1913                },
1914              }
1915              callback(nil, res)
1916            end,
1917          },
1918        })
1919        vim.lsp.start({ name = 'dummy', cmd = server.cmd })
1920      end)
1921
1922      eq('', exec_capture('lua vim.lsp.buf.hover()'))
1923    end)
1924  end)
1925end)