robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
173.1 KiB5380 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, setup, teardown, pending =
7  t.describe, t.it, t.before_each, t.after_each, t.setup, t.teardown, t.pending
8local buf_lines = n.buf_lines
9local command = n.command
10local dedent = t.dedent
11local exec_lua = n.exec_lua
12local feed = n.feed
13local eq = t.eq
14local eval = n.eval
15local matches = t.matches
16local pcall_err = t.pcall_err
17local pesc = vim.pesc
18local insert = n.insert
19local fn = n.fn
20local retry = t.retry
21local stop = n.stop
22local NIL = vim.NIL
23local read_file = t.read_file
24local write_file = t.write_file
25local is_ci = t.is_ci
26local api = n.api
27local is_os = t.is_os
28local skip = t.skip
29local mkdir = t.mkdir
30local tmpname = t.tmpname
31
32local clear_notrace = t_lsp.clear_notrace
33local create_server_definition = t_lsp.create_server_definition
34local fake_lsp_code = t_lsp.fake_lsp_code
35local fake_lsp_logfile = t_lsp.fake_lsp_logfile
36local test_rpc_server = t_lsp.test_rpc_server
37local create_tcp_echo_server = t_lsp.create_tcp_echo_server
38
39local function get_buf_option(name, bufnr)
40  return exec_lua(function()
41    bufnr = bufnr or _G.BUFFER
42    return vim.api.nvim_get_option_value(name, { buf = bufnr })
43  end)
44end
45
46--- True if buf-local option (func option like 'tagfunc') holds `vim.lsp[name]`.
47local function buf_option_is_lsp(name, bufnr)
48  return exec_lua(function()
49    bufnr = bufnr or _G.BUFFER
50    return vim.api.nvim_get_option_value(name, { buf = bufnr }) == vim.lsp[name]
51  end)
52end
53
54local function make_edit(y_0, x_0, y_1, x_1, text)
55  return {
56    range = {
57      start = { line = y_0, character = x_0 },
58      ['end'] = { line = y_1, character = x_1 },
59    },
60    newText = type(text) == 'table' and table.concat(text, '\n') or (text or ''),
61  }
62end
63
64--- @param edits [integer, integer, integer, integer, string|string[]][]
65--- @param encoding? string
66local function apply_text_edits(edits, encoding)
67  local edits1 = vim.tbl_map(
68    --- @param edit [integer, integer, integer, integer, string|string[]]
69    function(edit)
70      return make_edit(unpack(edit))
71    end,
72    edits
73  )
74  exec_lua(function()
75    vim.lsp.util.apply_text_edits(edits1, 1, encoding or 'utf-16')
76  end)
77end
78
79--- @param notification_cb fun(method: 'body' | 'error', args: any)
80local function verify_single_notification(notification_cb)
81  local called = false
82  n.run(nil, function(method, args)
83    notification_cb(method, args)
84    stop()
85    called = true
86  end, nil, 1000)
87  eq(true, called)
88end
89
90-- TODO(justinmk): hangs on Windows https://github.com/neovim/neovim/pull/11837
91if skip(is_os('win')) then
92  return
93end
94
95describe('LSP', function()
96  before_each(function()
97    clear_notrace()
98  end)
99
100  after_each(function()
101    stop()
102    exec_lua(function()
103      vim.iter(vim.lsp.get_clients({ _uninitialized = true })):each(function(client)
104        client:stop(true)
105      end)
106    end)
107    api.nvim_exec_autocmds('VimLeavePre', { modeline = false })
108  end)
109
110  teardown(function()
111    os.remove(fake_lsp_logfile)
112  end)
113
114  describe('server_name specified', function()
115    before_each(function()
116      -- Run an instance of nvim on the file which contains our "scripts".
117      -- Pass TEST_NAME to pick the script.
118      local test_name = 'basic_init'
119      exec_lua(function()
120        _G.lsp = require('vim.lsp')
121        function _G.test__start_client()
122          return vim.lsp.start({
123            cmd_env = {
124              NVIM_LOG_FILE = fake_lsp_logfile,
125              NVIM_APPNAME = 'nvim_lsp_test',
126            },
127            cmd = {
128              vim.v.progpath,
129              '-l',
130              fake_lsp_code,
131              test_name,
132            },
133            workspace_folders = {
134              {
135                uri = 'file://' .. vim.uv.cwd(),
136                name = 'test_folder',
137              },
138            },
139          }, { attach = false })
140        end
141        _G.TEST_CLIENT1 = _G.test__start_client()
142      end)
143    end)
144
145    it('start_client(), Client:stop()', function()
146      retry(nil, 4000, function()
147        eq(
148          1,
149          exec_lua(function()
150            return #vim.lsp.get_clients()
151          end)
152        )
153      end)
154      eq(
155        2,
156        exec_lua(function()
157          _G.TEST_CLIENT2 = _G.test__start_client()
158          return _G.TEST_CLIENT2
159        end)
160      )
161      eq(
162        3,
163        exec_lua(function()
164          _G.TEST_CLIENT3 = _G.test__start_client()
165          return _G.TEST_CLIENT3
166        end)
167      )
168      retry(nil, 4000, function()
169        eq(
170          3,
171          exec_lua(function()
172            return #vim.lsp.get_clients()
173          end)
174        )
175      end)
176
177      eq(
178        false,
179        exec_lua(function()
180          return vim.lsp.get_client_by_id(_G.TEST_CLIENT1) == nil
181        end)
182      )
183      eq(
184        false,
185        exec_lua(function()
186          return vim.lsp.get_client_by_id(_G.TEST_CLIENT1).is_stopped()
187        end)
188      )
189      exec_lua(function()
190        return vim.lsp.get_client_by_id(_G.TEST_CLIENT1).stop()
191      end)
192      retry(nil, 4000, function()
193        eq(
194          2,
195          exec_lua(function()
196            return #vim.lsp.get_clients()
197          end)
198        )
199      end)
200      eq(
201        true,
202        exec_lua(function()
203          return vim.lsp.get_client_by_id(_G.TEST_CLIENT1) == nil
204        end)
205      )
206
207      exec_lua(function()
208        vim.lsp.get_client_by_id(_G.TEST_CLIENT2):stop()
209        vim.lsp.get_client_by_id(_G.TEST_CLIENT3):stop()
210      end)
211      retry(nil, 4000, function()
212        eq(
213          0,
214          exec_lua(function()
215            return #vim.lsp.get_clients()
216          end)
217        )
218      end)
219    end)
220
221    it('does not reuse an already-stopping client #33616', function()
222      -- we immediately try to start a second client with the same name/root
223      -- before the first one has finished shutting down; we must get a new id.
224      local clients = exec_lua(function()
225        local client1 = assert(vim.lsp.start({
226          name = 'dup-test',
227          cmd = { vim.v.progpath, '-l', fake_lsp_code, 'basic_init' },
228        }, { attach = false }))
229        vim.lsp.get_client_by_id(client1):stop()
230        local client2 = assert(vim.lsp.start({
231          name = 'dup-test',
232          cmd = { vim.v.progpath, '-l', fake_lsp_code, 'basic_init' },
233        }, { attach = false }))
234        return { client1, client2 }
235      end)
236      local c1, c2 = clients[1], clients[2]
237      eq(false, c1 == c2, 'Expected a fresh client while the old one is stopping')
238    end)
239  end)
240
241  describe('basic_init test', function()
242    it('should run correctly', function()
243      local expected_handlers = {
244        { NIL, {}, { method = 'test', client_id = 1 } },
245      }
246      test_rpc_server {
247        test_name = 'basic_init',
248        on_init = function(client, _)
249          -- client is a dummy object which will queue up commands to be run
250          -- once the server initializes. It can't accept lua callbacks or
251          -- other types that may be unserializable for now.
252          client:stop()
253        end,
254        -- If the program timed out, then code will be nil.
255        on_exit = function(code, signal)
256          eq(0, code, 'exit code')
257          eq(0, signal, 'exit signal')
258        end,
259        -- Note that NIL must be used here.
260        -- on_handler(err, method, result, client_id)
261        on_handler = function(...)
262          eq(table.remove(expected_handlers), { ... })
263        end,
264      }
265    end)
266
267    it('should fail', function()
268      local expected_handlers = {
269        { NIL, {}, { method = 'test', client_id = 1 } },
270      }
271      test_rpc_server {
272        test_name = 'basic_init',
273        on_init = function(client)
274          client:notify('test')
275          client:stop()
276        end,
277        on_exit = function(code, signal)
278          eq(101, code, 'exit code') -- See fake-lsp-server.lua
279          eq(0, signal, 'exit signal')
280          t.assert_log(
281            pesc([[assert_eq failed: left == "\"shutdown\"", right == "\"test\""]]),
282            fake_lsp_logfile
283          )
284        end,
285        on_handler = function(...)
286          eq(table.remove(expected_handlers), { ... }, 'expected handler')
287        end,
288      }
289    end)
290
291    it('should send didChangeConfiguration after initialize if there are settings', function()
292      test_rpc_server({
293        test_name = 'basic_init_did_change_configuration',
294        on_init = function(client, _)
295          client:stop()
296        end,
297        on_exit = function(code, signal)
298          eq(0, code, 'exit code')
299          eq(0, signal, 'exit signal')
300        end,
301        settings = {
302          dummy = 1,
303        },
304      })
305    end)
306
307    it(
308      "should set the client's offset_encoding when positionEncoding capability is supported",
309      function()
310        exec_lua(create_server_definition)
311        local result = exec_lua(function()
312          local server = _G._create_server({
313            capabilities = {
314              positionEncoding = 'utf-8',
315            },
316          })
317
318          local client_id = vim.lsp.start({
319            name = 'dummy',
320            cmd = server.cmd,
321          })
322
323          if not client_id then
324            return 'vim.lsp.start did not return client_id'
325          end
326
327          local client = vim.lsp.get_client_by_id(client_id)
328          if not client then
329            return 'No client found with id ' .. client_id
330          end
331          return client.offset_encoding
332        end)
333        eq('utf-8', result)
334      end
335    )
336
337    it('should succeed with manual shutdown', function()
338      local expected_handlers = {
339        { NIL, {}, { method = 'shutdown', bufnr = 1, client_id = 1, request_id = 2, version = 0 } },
340        { NIL, {}, { method = 'test', client_id = 1 } },
341      }
342      test_rpc_server {
343        test_name = 'basic_init',
344        on_init = function(client)
345          eq(0, client.server_capabilities().textDocumentSync.change)
346          client:request('shutdown')
347          client:notify('exit')
348          client:stop()
349        end,
350        on_exit = function(code, signal)
351          eq(0, code, 'exit code')
352          eq(0, signal, 'exit signal')
353        end,
354        on_handler = function(...)
355          eq(table.remove(expected_handlers), { ... }, 'expected handler')
356        end,
357      }
358    end)
359
360    it('should detach buffer in response to nvim_buf_detach', function()
361      local expected_handlers = {
362        { NIL, {}, { method = 'shutdown', client_id = 1 } },
363        { NIL, {}, { method = 'finish', client_id = 1 } },
364      }
365      local client --- @type vim.lsp.Client
366      test_rpc_server {
367        test_name = 'basic_finish',
368        on_setup = function()
369          exec_lua(function()
370            _G.BUFFER = vim.api.nvim_create_buf(false, true)
371          end)
372          eq(
373            true,
374            exec_lua(function()
375              return vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID)
376            end)
377          )
378          eq(
379            true,
380            exec_lua(function()
381              return vim.lsp.buf_is_attached(_G.BUFFER, _G.TEST_RPC_CLIENT_ID)
382            end)
383          )
384          exec_lua(function()
385            vim.cmd(_G.BUFFER .. 'bwipeout')
386          end)
387        end,
388        on_init = function(_client)
389          client = _client
390          client:notify('finish')
391        end,
392        on_exit = function(code, signal)
393          eq(0, code, 'exit code')
394          eq(0, signal, 'exit signal')
395        end,
396        on_handler = function(err, result, ctx)
397          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
398          if ctx.method == 'finish' then
399            exec_lua(function()
400              return vim.lsp.buf_detach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID)
401            end)
402            eq(
403              false,
404              exec_lua(function()
405                return vim.lsp.buf_is_attached(_G.BUFFER, _G.TEST_RPC_CLIENT_ID)
406              end)
407            )
408            client:stop()
409          end
410        end,
411      }
412    end)
413
414    it('should fire autocommands on attach and detach', function()
415      local client --- @type vim.lsp.Client
416      test_rpc_server {
417        test_name = 'basic_init',
418        on_setup = function()
419          exec_lua(function()
420            _G.BUFFER = vim.api.nvim_create_buf(false, true)
421            vim.api.nvim_create_autocmd('LspAttach', {
422              callback = function(ev)
423                local client0 = assert(vim.lsp.get_client_by_id(ev.data.client_id))
424                vim.g.lsp_attached = client0.name
425              end,
426            })
427            vim.api.nvim_create_autocmd('LspDetach', {
428              callback = function(ev)
429                local client0 = assert(vim.lsp.get_client_by_id(ev.data.client_id))
430                vim.g.lsp_detached = client0.name
431              end,
432            })
433          end)
434        end,
435        on_init = function(_client)
436          client = _client
437          eq(
438            true,
439            exec_lua(function()
440              return vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID)
441            end)
442          )
443          client:notify('finish')
444        end,
445        on_handler = function(_, _, ctx)
446          if ctx.method == 'finish' then
447            eq('basic_init', api.nvim_get_var('lsp_attached'))
448            exec_lua(function()
449              return vim.lsp.buf_detach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID)
450            end)
451            eq('basic_init', api.nvim_get_var('lsp_detached'))
452            client:stop()
453          end
454        end,
455      }
456    end)
457
458    it('should set default options on attach', function()
459      local client --- @type vim.lsp.Client
460      test_rpc_server {
461        test_name = 'set_defaults_all_capabilities',
462        on_init = function(_client)
463          client = _client
464          exec_lua(function()
465            _G.BUFFER = vim.api.nvim_create_buf(false, true)
466            vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID)
467          end)
468        end,
469        on_handler = function(_, _, ctx)
470          if ctx.method == 'test' then
471            eq(true, buf_option_is_lsp('tagfunc'))
472            eq(true, buf_option_is_lsp('omnifunc'))
473            eq('v:lua.vim.lsp.formatexpr()', get_buf_option('formatexpr'))
474            eq('', get_buf_option('keywordprg'))
475            eq(
476              true,
477              exec_lua(function()
478                local keymap --- @type table<string,any>
479                local called = false
480                local origin = vim.lsp.buf.hover
481                vim.lsp.buf.hover = function()
482                  called = true
483                end
484                vim._with({ buf = _G.BUFFER }, function()
485                  keymap = vim.fn.maparg('K', 'n', false, true)
486                end)
487                keymap.callback()
488                vim.lsp.buf.hover = origin
489                return called
490              end)
491            )
492            client:stop()
493          end
494        end,
495        on_exit = function(_, _)
496          eq('', get_buf_option('tagfunc'))
497          eq('', get_buf_option('omnifunc'))
498          eq('', get_buf_option('formatexpr'))
499          eq(
500            true,
501            exec_lua(function()
502              local keymap --- @type string
503              vim._with({ buf = _G.BUFFER }, function()
504                keymap = vim.fn.maparg('K', 'n', false, false)
505              end)
506              return keymap:match('<Lua %d+: .*runtime/lua/vim/lsp%.lua:%d+>') ~= nil
507            end)
508          )
509        end,
510      }
511    end)
512
513    it('should overwrite options set by ftplugins', function()
514      local client --- @type vim.lsp.Client
515      local BUFFER_1 --- @type integer
516      local BUFFER_2 --- @type integer
517      test_rpc_server {
518        test_name = 'set_defaults_all_capabilities',
519        on_init = function(_client)
520          client = _client
521          exec_lua(function()
522            vim.api.nvim_command('filetype plugin on')
523            BUFFER_1 = vim.api.nvim_create_buf(false, true)
524            BUFFER_2 = vim.api.nvim_create_buf(false, true)
525            vim.api.nvim_set_option_value('filetype', 'man', { buf = BUFFER_1 })
526            vim.api.nvim_set_option_value('filetype', 'xml', { buf = BUFFER_2 })
527          end)
528
529          -- Sanity check to ensure that some values are set after setting filetype.
530          eq("v:lua.require'man'.goto_tag", get_buf_option('tagfunc', BUFFER_1))
531          eq('xmlcomplete#CompleteTags', get_buf_option('omnifunc', BUFFER_2))
532          eq('xmlformat#Format()', get_buf_option('formatexpr', BUFFER_2))
533
534          exec_lua(function()
535            vim.lsp.buf_attach_client(BUFFER_1, _G.TEST_RPC_CLIENT_ID)
536            vim.lsp.buf_attach_client(BUFFER_2, _G.TEST_RPC_CLIENT_ID)
537          end)
538        end,
539        on_handler = function(_, _, ctx)
540          if ctx.method == 'test' then
541            eq(true, buf_option_is_lsp('tagfunc', BUFFER_1))
542            eq(true, buf_option_is_lsp('omnifunc', BUFFER_2))
543            eq('v:lua.vim.lsp.formatexpr()', get_buf_option('formatexpr', BUFFER_2))
544            client:stop()
545          end
546        end,
547        on_exit = function(_, _)
548          eq('', get_buf_option('tagfunc', BUFFER_1))
549          eq('', get_buf_option('omnifunc', BUFFER_2))
550          eq('', get_buf_option('formatexpr', BUFFER_2))
551        end,
552      }
553    end)
554
555    it('should not overwrite user-defined options', function()
556      local client --- @type vim.lsp.Client
557      test_rpc_server {
558        test_name = 'set_defaults_all_capabilities',
559        on_init = function(_client)
560          client = _client
561          exec_lua(function()
562            _G.BUFFER = vim.api.nvim_create_buf(false, true)
563            vim.api.nvim_set_option_value('tagfunc', 'tfu', { buf = _G.BUFFER })
564            vim.api.nvim_set_option_value('omnifunc', 'ofu', { buf = _G.BUFFER })
565            vim.api.nvim_set_option_value('formatexpr', 'fex', { buf = _G.BUFFER })
566            vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID)
567          end)
568        end,
569        on_handler = function(_, _, ctx)
570          if ctx.method == 'test' then
571            eq('tfu', get_buf_option('tagfunc'))
572            eq('ofu', get_buf_option('omnifunc'))
573            eq('fex', get_buf_option('formatexpr'))
574            client:stop()
575          end
576        end,
577        on_exit = function(_, _)
578          eq('tfu', get_buf_option('tagfunc'))
579          eq('ofu', get_buf_option('omnifunc'))
580          eq('fex', get_buf_option('formatexpr'))
581        end,
582      }
583    end)
584
585    it('should detach buffer on bufwipe', function()
586      exec_lua(create_server_definition)
587      local result = exec_lua(function()
588        local server = _G._create_server()
589        local bufnr1 = vim.api.nvim_create_buf(false, true)
590        local bufnr2 = vim.api.nvim_create_buf(false, true)
591        local detach_called1 = false
592        local detach_called2 = false
593        vim.api.nvim_create_autocmd('LspDetach', {
594          buf = bufnr1,
595          callback = function()
596            detach_called1 = true
597          end,
598        })
599        vim.api.nvim_create_autocmd('LspDetach', {
600          buf = bufnr2,
601          callback = function()
602            detach_called2 = true
603          end,
604        })
605        vim.api.nvim_set_current_buf(bufnr1)
606        local client_id = assert(vim.lsp.start({ name = 'detach-dummy', cmd = server.cmd }))
607        local client = assert(vim.lsp.get_client_by_id(client_id))
608        vim.api.nvim_set_current_buf(bufnr2)
609        vim.lsp.start({ name = 'detach-dummy', cmd = server.cmd })
610        assert(vim.tbl_count(client.attached_buffers) == 2)
611        vim.api.nvim_buf_delete(bufnr1, { force = true })
612        assert(vim.tbl_count(client.attached_buffers) == 1)
613        vim.api.nvim_buf_delete(bufnr2, { force = true })
614        assert(vim.tbl_count(client.attached_buffers) == 0)
615        return detach_called1 and detach_called2
616      end)
617      eq(true, result)
618    end)
619
620    it('should not re-attach buffer if it was deleted in on_init #28575', function()
621      exec_lua(create_server_definition)
622      exec_lua(function()
623        local server = _G._create_server({
624          handlers = {
625            initialize = function(_, _, callback)
626              vim.schedule(function()
627                callback(nil, { capabilities = {} })
628              end)
629            end,
630          },
631        })
632        local bufnr = vim.api.nvim_create_buf(false, true)
633        local on_init_called = false
634        local client_id = assert(vim.lsp.start({
635          name = 'detach-dummy',
636          cmd = server.cmd,
637          on_init = function()
638            vim.api.nvim_buf_delete(bufnr, {})
639            on_init_called = true
640          end,
641        }))
642        vim.lsp.buf_attach_client(bufnr, client_id)
643        local ok = vim.wait(1000, function()
644          return on_init_called
645        end)
646        assert(ok, 'on_init was not called')
647      end)
648    end)
649
650    it('should allow on_lines + nvim_buf_delete during LSP initialization #28575', function()
651      exec_lua(create_server_definition)
652      exec_lua(function()
653        local initialized = false
654        local server = _G._create_server({
655          handlers = {
656            initialize = function(_, _, callback)
657              vim.schedule(function()
658                callback(nil, { capabilities = {} })
659                initialized = true
660              end)
661            end,
662          },
663        })
664        local bufnr = vim.api.nvim_create_buf(false, true)
665        vim.api.nvim_set_current_buf(bufnr)
666        vim.lsp.start({
667          name = 'detach-dummy',
668          cmd = server.cmd,
669        })
670        vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, { 'hello' })
671        vim.api.nvim_buf_delete(bufnr, {})
672        local ok = vim.wait(1000, function()
673          return initialized
674        end)
675        assert(ok, 'lsp did not initialize')
676      end)
677    end)
678
679    it('client should return settings via workspace/configuration handler', function()
680      local expected_handlers = {
681        { NIL, {}, { method = 'shutdown', client_id = 1 } },
682        {
683          NIL,
684          {
685            items = {
686              { section = 'testSetting1' },
687              { section = 'testSetting2' },
688              { section = 'test.Setting3' },
689              { section = 'test.Setting4' },
690              {},
691              { section = '' },
692            },
693          },
694          { method = 'workspace/configuration', client_id = 1 },
695        },
696        { NIL, {}, { method = 'start', client_id = 1 } },
697      }
698      local client --- @type vim.lsp.Client
699      test_rpc_server {
700        test_name = 'check_workspace_configuration',
701        on_init = function(_client)
702          client = _client
703        end,
704        on_exit = function(code, signal)
705          eq(0, code, 'exit code')
706          eq(0, signal, 'exit signal')
707        end,
708        on_handler = function(err, result, ctx)
709          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
710          if ctx.method == 'start' then
711            exec_lua(function()
712              local client0 = vim.lsp.get_client_by_id(_G.TEST_RPC_CLIENT_ID)
713              client0.settings = {
714                testSetting1 = true,
715                testSetting2 = false,
716                test = { Setting3 = 'nested' },
717              }
718            end)
719          end
720          if ctx.method == 'workspace/configuration' then
721            local server_result = exec_lua(
722              [[
723              local method, params = ...
724              return require 'vim.lsp.handlers'['workspace/configuration'](
725                err,
726                params,
727                { method = method, client_id = _G.TEST_RPC_CLIENT_ID }
728              )
729              ]],
730              ctx.method,
731              result
732            )
733            client:notify('workspace/configuration', server_result)
734          end
735          if ctx.method == 'shutdown' then
736            client:stop()
737          end
738        end,
739      }
740    end)
741
742    it(
743      'workspace/configuration returns NIL per section if client was started without config.settings',
744      function()
745        local result = nil
746        test_rpc_server {
747          test_name = 'basic_init',
748          on_init = function(c)
749            c.stop()
750          end,
751          on_setup = function()
752            result = exec_lua(function()
753              local result0 = {
754                items = {
755                  { section = 'foo' },
756                  { section = 'bar' },
757                },
758              }
759              return vim.lsp.handlers['workspace/configuration'](
760                nil,
761                result0,
762                { client_id = _G.TEST_RPC_CLIENT_ID }
763              )
764            end)
765          end,
766        }
767        eq({ NIL, NIL }, result)
768      end
769    )
770
771    it('should verify capabilities sent', function()
772      local expected_handlers = {
773        { NIL, {}, { method = 'shutdown', client_id = 1 } },
774      }
775      test_rpc_server {
776        test_name = 'basic_check_capabilities',
777        on_init = function(client)
778          client:stop()
779          local full_kind = exec_lua(function()
780            return require 'vim.lsp.protocol'.TextDocumentSyncKind.Full
781          end)
782          eq(full_kind, client.server_capabilities().textDocumentSync.change)
783          eq({ includeText = false }, client.server_capabilities().textDocumentSync.save)
784          eq(false, client.server_capabilities().codeLensProvider)
785        end,
786        on_exit = function(code, signal)
787          eq(0, code, 'exit code')
788          eq(0, signal, 'exit signal')
789        end,
790        on_handler = function(...)
791          eq(table.remove(expected_handlers), { ... }, 'expected handler')
792        end,
793      }
794    end)
795
796    it('BufWritePost sends didSave with bool textDocumentSync.save', function()
797      local expected_handlers = {
798        { NIL, {}, { method = 'shutdown', client_id = 1 } },
799        { NIL, {}, { method = 'start', client_id = 1 } },
800      }
801      local client --- @type vim.lsp.Client
802      test_rpc_server {
803        test_name = 'text_document_sync_save_bool',
804        on_init = function(c)
805          client = c
806        end,
807        on_exit = function(code, signal)
808          eq(0, code, 'exit code')
809          eq(0, signal, 'exit signal')
810        end,
811        on_handler = function(err, result, ctx)
812          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
813          if ctx.method == 'start' then
814            exec_lua(function()
815              _G.BUFFER = vim.api.nvim_get_current_buf()
816              vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID)
817              vim.api.nvim_exec_autocmds('BufWritePost', { buf = _G.BUFFER, modeline = false })
818            end)
819          else
820            client:stop()
821          end
822        end,
823      }
824    end)
825
826    it('saveas sends didOpen to all attached servers only, if filename changed', function()
827      local tmpfile_new = tmpname(false)
828      exec_lua(create_server_definition)
829      local messages = exec_lua(function()
830        local server1 = _G._create_server()
831        local server2 = _G._create_server()
832        local server3 = _G._create_server()
833        local client1_id = assert(vim.lsp.start({ name = 'dummy1', cmd = server1.cmd }))
834        local client2_id = assert(vim.lsp.start({ name = 'dummy2', cmd = server2.cmd }))
835        -- Attached to another buffer, so it must not be notified about this one.
836        local other_buf = vim.api.nvim_create_buf(true, false)
837        local client3_id =
838          assert(vim.lsp.start({ name = 'dummy3', cmd = server3.cmd }, { bufnr = other_buf }))
839
840        vim.cmd('saveas ' .. tmpfile_new)
841
842        vim.lsp.get_client_by_id(client1_id):stop()
843        vim.lsp.get_client_by_id(client2_id):stop()
844        vim.lsp.get_client_by_id(client3_id):stop()
845
846        return {
847          server1 = server1.messages,
848          server2 = server2.messages,
849          server3 = vim.tbl_map(function(m)
850            return m.method
851          end, server3.messages),
852        }
853      end)
854      eq('textDocument/didClose', messages.server1[3].method)
855      eq('textDocument/didOpen', messages.server1[4].method)
856      eq('textDocument/didSave', messages.server1[5].method)
857
858      eq('textDocument/didClose', messages.server2[3].method)
859      eq('textDocument/didOpen', messages.server2[4].method)
860      eq('textDocument/didSave', messages.server2[5].method)
861
862      eq({ 'initialize', 'initialized', 'shutdown', 'exit' }, messages.server3)
863    end)
864
865    it('BufWritePre does not send notifications if server lacks willSave capabilities', function()
866      exec_lua(create_server_definition)
867      local messages = exec_lua(function()
868        local server = _G._create_server({
869          capabilities = {
870            textDocumentSync = {
871              willSave = false,
872              willSaveWaitUntil = false,
873            },
874          },
875        })
876        local client_id = assert(vim.lsp.start({ name = 'dummy', cmd = server.cmd }))
877        local buf = vim.api.nvim_get_current_buf()
878        vim.api.nvim_exec_autocmds('BufWritePre', { buf = buf, modeline = false })
879        vim.lsp.get_client_by_id(client_id):stop()
880        return server.messages
881      end)
882      eq(4, #messages)
883      eq('initialize', messages[1].method)
884      eq('initialized', messages[2].method)
885      eq('shutdown', messages[3].method)
886      eq('exit', messages[4].method)
887    end)
888
889    it('BufWritePre sends willSave / willSaveWaitUntil, applies textEdits', function()
890      exec_lua(create_server_definition)
891      local result = exec_lua(function()
892        local server = _G._create_server({
893          capabilities = {
894            textDocumentSync = {
895              willSave = true,
896              willSaveWaitUntil = true,
897            },
898          },
899          handlers = {
900            ['textDocument/willSaveWaitUntil'] = function(_, _, callback)
901              local text_edit = {
902                range = {
903                  start = { line = 0, character = 0 },
904                  ['end'] = { line = 0, character = 0 },
905                },
906                newText = 'Hello',
907              }
908              callback(nil, { text_edit })
909            end,
910          },
911        })
912        local buf = vim.api.nvim_get_current_buf()
913        local client_id = assert(vim.lsp.start({ name = 'dummy', cmd = server.cmd }))
914        vim.api.nvim_exec_autocmds('BufWritePre', { buf = buf, modeline = false })
915        vim.lsp.get_client_by_id(client_id):stop()
916        return {
917          messages = server.messages,
918          lines = vim.api.nvim_buf_get_lines(buf, 0, -1, true),
919        }
920      end)
921      local messages = result.messages
922      eq('textDocument/willSave', messages[3].method)
923      eq('textDocument/willSaveWaitUntil', messages[4].method)
924      eq({ 'Hello' }, result.lines)
925    end)
926
927    it('saveas sends didOpen if filename changed', function()
928      local expected_handlers = {
929        { NIL, {}, { method = 'shutdown', client_id = 1 } },
930        { NIL, {}, { method = 'start', client_id = 1 } },
931      }
932      local client --- @type vim.lsp.Client
933      test_rpc_server({
934        test_name = 'text_document_save_did_open',
935        on_init = function(c)
936          client = c
937        end,
938        on_exit = function(code, signal)
939          eq(0, code, 'exit code')
940          eq(0, signal, 'exit signal')
941        end,
942        on_handler = function(err, result, ctx)
943          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
944          if ctx.method == 'start' then
945            local tmpfile_old = tmpname()
946            local tmpfile_new = tmpname(false)
947            exec_lua(function()
948              _G.BUFFER = vim.api.nvim_get_current_buf()
949              vim.api.nvim_buf_set_name(_G.BUFFER, tmpfile_old)
950              vim.api.nvim_buf_set_lines(_G.BUFFER, 0, -1, true, { 'help me' })
951              vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID)
952              vim._with({ buf = _G.BUFFER }, function()
953                vim.cmd('saveas ' .. tmpfile_new)
954              end)
955            end)
956          else
957            client:stop()
958          end
959        end,
960      })
961    end)
962
963    it('BufWritePost sends didSave including text if server capability is set', function()
964      local expected_handlers = {
965        { NIL, {}, { method = 'shutdown', client_id = 1 } },
966        { NIL, {}, { method = 'start', client_id = 1 } },
967      }
968      local client --- @type vim.lsp.Client
969      test_rpc_server {
970        test_name = 'text_document_sync_save_includeText',
971        on_init = function(c)
972          client = c
973        end,
974        on_exit = function(code, signal)
975          eq(0, code, 'exit code')
976          eq(0, signal, 'exit signal')
977        end,
978        on_handler = function(err, result, ctx)
979          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
980          if ctx.method == 'start' then
981            exec_lua(function()
982              _G.BUFFER = vim.api.nvim_get_current_buf()
983              vim.api.nvim_buf_set_lines(_G.BUFFER, 0, -1, true, { 'help me' })
984              vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID)
985              vim.api.nvim_exec_autocmds('BufWritePost', { buf = _G.BUFFER, modeline = false })
986            end)
987          else
988            client:stop()
989          end
990        end,
991      }
992    end)
993
994    it('client:supports_methods() should validate capabilities', function()
995      local expected_handlers = {
996        { NIL, {}, { method = 'shutdown', client_id = 1 } },
997      }
998      test_rpc_server {
999        test_name = 'capabilities_for_client_supports_method',
1000        on_init = function(client)
1001          client:stop()
1002          local expected_sync_capabilities = {
1003            change = 1,
1004            openClose = true,
1005            save = { includeText = false },
1006            willSave = false,
1007            willSaveWaitUntil = false,
1008          }
1009          eq(expected_sync_capabilities, client.server_capabilities().textDocumentSync)
1010          eq(true, client.server_capabilities().completionProvider)
1011          eq(true, client.server_capabilities().hoverProvider)
1012          eq(false, client.server_capabilities().definitionProvider)
1013          eq(false, client.server_capabilities().renameProvider)
1014          eq(true, client.server_capabilities().codeLensProvider.resolveProvider)
1015
1016          -- known methods for resolved capabilities
1017          eq(true, client:supports_method('textDocument/hover'))
1018          eq(false, client:supports_method('textDocument/definition'))
1019
1020          eq(false, client:supports_method('workspace/didCreateFiles'))
1021
1022          -- Self-mapped methods do not have a related server capability and should be assumed
1023          -- to be supported.
1024          eq(true, client:supports_method('shutdown'))
1025
1026          -- unknown methods are assumed to be supported.
1027          eq(true, client:supports_method('unknown-method'))
1028        end,
1029        on_exit = function(code, signal)
1030          eq(0, code, 'exit code')
1031          eq(0, signal, 'exit signal')
1032        end,
1033        on_handler = function(...)
1034          eq(table.remove(expected_handlers), { ... }, 'expected handler')
1035        end,
1036      }
1037    end)
1038
1039    it('should not call unsupported_method when trying to call an unsupported method', function()
1040      local expected_handlers = {
1041        { NIL, {}, { method = 'shutdown', client_id = 1 } },
1042      }
1043      test_rpc_server {
1044        test_name = 'capabilities_for_client_supports_method',
1045        on_setup = function()
1046          exec_lua(function()
1047            _G.BUFFER = vim.api.nvim_get_current_buf()
1048            vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID)
1049            vim.lsp.handlers['textDocument/typeDefinition'] = function() end
1050            vim.cmd(_G.BUFFER .. 'bwipeout')
1051          end)
1052        end,
1053        on_init = function(client)
1054          client:stop()
1055          exec_lua(function()
1056            vim.lsp.buf.type_definition()
1057          end)
1058        end,
1059        on_exit = function(code, signal)
1060          eq(0, code, 'exit code')
1061          eq(0, signal, 'exit signal')
1062        end,
1063        on_handler = function(...)
1064          eq(table.remove(expected_handlers), { ... }, 'expected handler')
1065        end,
1066      }
1067    end)
1068
1069    it(
1070      'should not call unsupported_method when no client and trying to call an unsupported method',
1071      function()
1072        local expected_handlers = {
1073          { NIL, {}, { method = 'shutdown', client_id = 1 } },
1074        }
1075        test_rpc_server {
1076          test_name = 'capabilities_for_client_supports_method',
1077          on_setup = function()
1078            exec_lua(function()
1079              vim.lsp.handlers['textDocument/typeDefinition'] = function() end
1080            end)
1081          end,
1082          on_init = function(client)
1083            client:stop()
1084            exec_lua(function()
1085              vim.lsp.buf.type_definition()
1086            end)
1087          end,
1088          on_exit = function(code, signal)
1089            eq(0, code, 'exit code')
1090            eq(0, signal, 'exit signal')
1091          end,
1092          on_handler = function(...)
1093            eq(table.remove(expected_handlers), { ... }, 'expected handler')
1094          end,
1095        }
1096      end
1097    )
1098
1099    it('should not forward RequestCancelled to callback', function()
1100      local expected_handlers = {
1101        { NIL, {}, { method = 'finish', client_id = 1 } },
1102      }
1103      local client --- @type vim.lsp.Client
1104      test_rpc_server {
1105        test_name = 'check_forward_request_cancelled',
1106        on_init = function(_client)
1107          _client:request('error_code_test')
1108          client = _client
1109        end,
1110        on_exit = function(code, signal)
1111          eq(0, code, 'exit code')
1112          eq(0, signal, 'exit signal')
1113          eq(0, #expected_handlers, 'did not call expected handler')
1114        end,
1115        on_handler = function(err, _, ctx)
1116          eq(table.remove(expected_handlers), { err, {}, ctx }, 'expected handler')
1117          if ctx.method == 'finish' then
1118            client:stop()
1119          end
1120        end,
1121      }
1122    end)
1123
1124    it('should forward ServerCancelled to callback', function()
1125      local expected_handlers = {
1126        { NIL, {}, { method = 'finish', client_id = 1 } },
1127        {
1128          { code = -32802 },
1129          NIL,
1130          { method = 'error_code_test', bufnr = 1, client_id = 1, request_id = 2, version = 0 },
1131        },
1132      }
1133      local client --- @type vim.lsp.Client
1134      test_rpc_server {
1135        test_name = 'check_forward_server_cancelled',
1136        on_init = function(_client)
1137          _client:request('error_code_test')
1138          client = _client
1139        end,
1140        on_exit = function(code, signal)
1141          eq(0, code, 'exit code')
1142          eq(0, signal, 'exit signal')
1143          eq(0, #expected_handlers, 'did not call expected handler')
1144        end,
1145        on_handler = function(err, _, ctx)
1146          eq(table.remove(expected_handlers), { err, _, ctx }, 'expected handler')
1147          if ctx.method ~= 'finish' then
1148            client:notify('finish')
1149          end
1150          if ctx.method == 'finish' then
1151            client:stop()
1152          end
1153        end,
1154      }
1155    end)
1156
1157    it('should forward ContentModified to callback', function()
1158      local expected_handlers = {
1159        { NIL, {}, { method = 'finish', client_id = 1 } },
1160        {
1161          { code = -32801 },
1162          NIL,
1163          { method = 'error_code_test', bufnr = 1, client_id = 1, request_id = 2, version = 0 },
1164        },
1165      }
1166      local client --- @type vim.lsp.Client
1167      test_rpc_server {
1168        test_name = 'check_forward_content_modified',
1169        on_init = function(_client)
1170          _client:request('error_code_test')
1171          client = _client
1172        end,
1173        on_exit = function(code, signal)
1174          eq(0, code, 'exit code')
1175          eq(0, signal, 'exit signal')
1176          eq(0, #expected_handlers, 'did not call expected handler')
1177        end,
1178        on_handler = function(err, _, ctx)
1179          eq(table.remove(expected_handlers), { err, _, ctx }, 'expected handler')
1180          if ctx.method ~= 'finish' then
1181            client:notify('finish')
1182          end
1183          if ctx.method == 'finish' then
1184            client:stop()
1185          end
1186        end,
1187      }
1188    end)
1189
1190    it('should track pending requests to the language server', function()
1191      local expected_handlers = {
1192        { NIL, {}, { method = 'finish', client_id = 1 } },
1193        {
1194          NIL,
1195          {},
1196          { method = 'slow_request', bufnr = 1, client_id = 1, request_id = 2, version = 0 },
1197        },
1198      }
1199      local client --- @type vim.lsp.Client
1200      test_rpc_server {
1201        test_name = 'check_pending_request_tracked',
1202        on_init = function(_client)
1203          client = _client
1204          client:request('slow_request')
1205          local request = exec_lua(function()
1206            return _G.TEST_RPC_CLIENT.requests[2]
1207          end)
1208          eq('slow_request', request.method)
1209          eq('pending', request.type)
1210          client:notify('release')
1211        end,
1212        on_exit = function(code, signal)
1213          eq(0, code, 'exit code')
1214          eq(0, signal, 'exit signal')
1215          eq(0, #expected_handlers, 'did not call expected handler')
1216        end,
1217        on_handler = function(err, _, ctx)
1218          eq(table.remove(expected_handlers), { err, {}, ctx }, 'expected handler')
1219          if ctx.method == 'slow_request' then
1220            local request = exec_lua(function()
1221              return _G.TEST_RPC_CLIENT.requests[2]
1222            end)
1223            eq(nil, request)
1224            client:notify('finish')
1225          end
1226          if ctx.method == 'finish' then
1227            client:stop()
1228          end
1229        end,
1230      }
1231    end)
1232
1233    it('should track cancel requests to the language server', function()
1234      local expected_handlers = {
1235        { NIL, {}, { method = 'finish', client_id = 1 } },
1236      }
1237      local client --- @type vim.lsp.Client
1238      test_rpc_server {
1239        test_name = 'check_cancel_request_tracked',
1240        on_init = function(_client)
1241          client = _client
1242          client:request('slow_request')
1243          client:cancel_request(2)
1244          local request = exec_lua(function()
1245            return _G.TEST_RPC_CLIENT.requests[2]
1246          end)
1247          eq('slow_request', request.method)
1248          eq('cancel', request.type)
1249          client:notify('release')
1250        end,
1251        on_exit = function(code, signal)
1252          eq(0, code, 'exit code')
1253          eq(0, signal, 'exit signal')
1254          eq(0, #expected_handlers, 'did not call expected handler')
1255        end,
1256        on_handler = function(err, _, ctx)
1257          eq(table.remove(expected_handlers), { err, {}, ctx }, 'expected handler')
1258          local request = exec_lua(function()
1259            return _G.TEST_RPC_CLIENT.requests[2]
1260          end)
1261          eq(nil, request)
1262          if ctx.method == 'finish' then
1263            client:stop()
1264          end
1265        end,
1266      }
1267    end)
1268
1269    it('should clear pending and cancel requests on reply', function()
1270      local expected_handlers = {
1271        { NIL, {}, { method = 'finish', client_id = 1 } },
1272        {
1273          NIL,
1274          {},
1275          { method = 'slow_request', bufnr = 1, client_id = 1, request_id = 2, version = 0 },
1276        },
1277      }
1278      local client --- @type vim.lsp.Client
1279      test_rpc_server {
1280        test_name = 'check_tracked_requests_cleared',
1281        on_init = function(_client)
1282          client = _client
1283          client:request('slow_request')
1284          local request = exec_lua(function()
1285            return _G.TEST_RPC_CLIENT.requests[2]
1286          end)
1287          eq('slow_request', request.method)
1288          eq('pending', request.type)
1289          client:cancel_request(2)
1290          request = exec_lua(function()
1291            return _G.TEST_RPC_CLIENT.requests[2]
1292          end)
1293          eq('slow_request', request.method)
1294          eq('cancel', request.type)
1295          client:notify('release')
1296        end,
1297        on_exit = function(code, signal)
1298          eq(0, code, 'exit code')
1299          eq(0, signal, 'exit signal')
1300          eq(0, #expected_handlers, 'did not call expected handler')
1301        end,
1302        on_handler = function(err, _, ctx)
1303          eq(table.remove(expected_handlers), { err, {}, ctx }, 'expected handler')
1304          if ctx.method == 'slow_request' then
1305            local request = exec_lua(function()
1306              return _G.TEST_RPC_CLIENT.requests[2]
1307            end)
1308            eq(nil, request)
1309            client:notify('finish')
1310          end
1311          if ctx.method == 'finish' then
1312            client:stop()
1313          end
1314        end,
1315      }
1316    end)
1317
1318    it('request should not be pending for sync responses (in-process LS)', function()
1319      --- @type boolean
1320      local pending_request = exec_lua(function()
1321        local function server(dispatchers)
1322          local closing = false
1323          local srv = {}
1324          local request_id = 0
1325
1326          function srv.request(method, _params, callback, notify_reply_callback)
1327            if method == 'textDocument/formatting' then
1328              callback(nil, {})
1329            elseif method == 'initialize' then
1330              callback(nil, {
1331                capabilities = {
1332                  textDocument = {
1333                    formatting = true,
1334                  },
1335                },
1336              })
1337            elseif method == 'shutdown' then
1338              callback(nil, nil)
1339            end
1340            request_id = request_id + 1
1341            if notify_reply_callback then
1342              notify_reply_callback(request_id)
1343            end
1344            return true, request_id
1345          end
1346
1347          function srv.notify(method)
1348            if method == 'exit' then
1349              dispatchers.on_exit(0, 15)
1350            end
1351          end
1352          function srv.is_closing()
1353            return closing
1354          end
1355          function srv.terminate()
1356            closing = true
1357          end
1358
1359          return srv
1360        end
1361
1362        local client_id = assert(vim.lsp.start({ cmd = server }))
1363        local client = assert(vim.lsp.get_client_by_id(client_id))
1364
1365        local ok, request_id = client:request('textDocument/formatting', {})
1366        assert(ok)
1367
1368        local has_pending = client.requests[request_id] ~= nil
1369        vim.lsp.get_client_by_id(client_id):stop()
1370
1371        return has_pending
1372      end)
1373
1374      eq(false, pending_request, 'expected no pending requests')
1375    end)
1376
1377    it('should trigger LspRequest autocmd when requests table changes', function()
1378      local expected_handlers = {
1379        { NIL, {}, { method = 'finish', client_id = 1 } },
1380        {
1381          NIL,
1382          {},
1383          { method = 'slow_request', bufnr = 1, client_id = 1, request_id = 2, version = 0 },
1384        },
1385      }
1386      local client --- @type vim.lsp.Client
1387      test_rpc_server {
1388        test_name = 'check_tracked_requests_cleared',
1389        on_init = function(_client)
1390          command('let g:requests = 0')
1391          command('autocmd LspRequest * let g:requests+=1')
1392          client = _client
1393          client:request('slow_request')
1394          eq(1, eval('g:requests'))
1395          client:cancel_request(2)
1396          eq(2, eval('g:requests'))
1397          client:notify('release')
1398        end,
1399        on_exit = function(code, signal)
1400          eq(0, code, 'exit code')
1401          eq(0, signal, 'exit signal')
1402          eq(0, #expected_handlers, 'did not call expected handler')
1403          eq(3, eval('g:requests'))
1404        end,
1405        on_handler = function(err, _, ctx)
1406          eq(table.remove(expected_handlers), { err, {}, ctx }, 'expected handler')
1407          if ctx.method == 'slow_request' then
1408            client:notify('finish')
1409          end
1410          if ctx.method == 'finish' then
1411            client:stop()
1412          end
1413        end,
1414      }
1415    end)
1416
1417    it('should not send didOpen if the buffer closes before init', function()
1418      local expected_handlers = {
1419        { NIL, {}, { method = 'shutdown', client_id = 1 } },
1420        { NIL, {}, { method = 'finish', client_id = 1 } },
1421      }
1422      local client --- @type vim.lsp.Client
1423      test_rpc_server {
1424        test_name = 'basic_finish',
1425        on_setup = function()
1426          exec_lua(function()
1427            _G.BUFFER = vim.api.nvim_create_buf(false, true)
1428            vim.api.nvim_buf_set_lines(_G.BUFFER, 0, -1, false, {
1429              'testing',
1430              '123',
1431            })
1432            assert(_G.TEST_RPC_CLIENT_ID == 1)
1433            assert(vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID))
1434            assert(vim.lsp.buf_is_attached(_G.BUFFER, _G.TEST_RPC_CLIENT_ID))
1435            vim.cmd(_G.BUFFER .. 'bwipeout')
1436          end)
1437        end,
1438        on_init = function(_client)
1439          client = _client
1440          local full_kind = exec_lua(function()
1441            return require 'vim.lsp.protocol'.TextDocumentSyncKind.Full
1442          end)
1443          eq(full_kind, client.server_capabilities().textDocumentSync.change)
1444          eq(true, client.server_capabilities().textDocumentSync.openClose)
1445          client:notify('finish')
1446        end,
1447        on_exit = function(code, signal)
1448          eq(0, code, 'exit code')
1449          eq(0, signal, 'exit signal')
1450        end,
1451        on_handler = function(err, result, ctx)
1452          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
1453          if ctx.method == 'finish' then
1454            client:stop()
1455          end
1456        end,
1457      }
1458    end)
1459
1460    it('should check the body sent attaching before init', function()
1461      local expected_handlers = {
1462        { NIL, {}, { method = 'shutdown', client_id = 1 } },
1463        { NIL, {}, { method = 'finish', client_id = 1 } },
1464        { NIL, {}, { method = 'start', client_id = 1 } },
1465      }
1466      local client --- @type vim.lsp.Client
1467      test_rpc_server {
1468        test_name = 'basic_check_buffer_open',
1469        on_setup = function()
1470          exec_lua(function()
1471            _G.BUFFER = vim.api.nvim_create_buf(false, true)
1472            vim.api.nvim_buf_set_lines(_G.BUFFER, 0, -1, false, {
1473              'testing',
1474              '123',
1475            })
1476          end)
1477          exec_lua(function()
1478            assert(vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID))
1479          end)
1480        end,
1481        on_init = function(_client)
1482          client = _client
1483          local full_kind = exec_lua(function()
1484            return require 'vim.lsp.protocol'.TextDocumentSyncKind.Full
1485          end)
1486          eq(full_kind, client.server_capabilities().textDocumentSync.change)
1487          eq(true, client.server_capabilities().textDocumentSync.openClose)
1488          exec_lua(function()
1489            assert(
1490              vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID),
1491              'Already attached, returns true'
1492            )
1493          end)
1494        end,
1495        on_exit = function(code, signal)
1496          eq(0, code, 'exit code')
1497          eq(0, signal, 'exit signal')
1498        end,
1499        on_handler = function(err, result, ctx)
1500          if ctx.method == 'start' then
1501            client:notify('finish')
1502          end
1503          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
1504          if ctx.method == 'finish' then
1505            client:stop()
1506          end
1507        end,
1508      }
1509    end)
1510
1511    it('should check the body sent attaching after init', function()
1512      local expected_handlers = {
1513        { NIL, {}, { method = 'shutdown', client_id = 1 } },
1514        { NIL, {}, { method = 'finish', client_id = 1 } },
1515        { NIL, {}, { method = 'start', client_id = 1 } },
1516      }
1517      local client --- @type vim.lsp.Client
1518      test_rpc_server {
1519        test_name = 'basic_check_buffer_open',
1520        on_setup = function()
1521          exec_lua(function()
1522            _G.BUFFER = vim.api.nvim_create_buf(false, true)
1523            vim.api.nvim_buf_set_lines(_G.BUFFER, 0, -1, false, {
1524              'testing',
1525              '123',
1526            })
1527          end)
1528        end,
1529        on_init = function(_client)
1530          client = _client
1531          local full_kind = exec_lua(function()
1532            return require 'vim.lsp.protocol'.TextDocumentSyncKind.Full
1533          end)
1534          eq(full_kind, client.server_capabilities().textDocumentSync.change)
1535          eq(true, client.server_capabilities().textDocumentSync.openClose)
1536          exec_lua(function()
1537            assert(vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID))
1538          end)
1539        end,
1540        on_exit = function(code, signal)
1541          eq(0, code, 'exit code')
1542          eq(0, signal, 'exit signal')
1543        end,
1544        on_handler = function(err, result, ctx)
1545          if ctx.method == 'start' then
1546            client:notify('finish')
1547          end
1548          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
1549          if ctx.method == 'finish' then
1550            client:stop()
1551          end
1552        end,
1553      }
1554    end)
1555
1556    it('should check the body and didChange full', function()
1557      local expected_handlers = {
1558        { NIL, {}, { method = 'shutdown', client_id = 1 } },
1559        { NIL, {}, { method = 'finish', client_id = 1 } },
1560        { NIL, {}, { method = 'start', client_id = 1 } },
1561      }
1562      local client --- @type vim.lsp.Client
1563      test_rpc_server {
1564        test_name = 'basic_check_buffer_open_and_change',
1565        on_setup = function()
1566          exec_lua(function()
1567            _G.BUFFER = vim.api.nvim_create_buf(false, true)
1568            vim.api.nvim_buf_set_lines(_G.BUFFER, 0, -1, false, {
1569              'testing',
1570              '123',
1571            })
1572          end)
1573        end,
1574        on_init = function(_client)
1575          client = _client
1576          local full_kind = exec_lua(function()
1577            return require 'vim.lsp.protocol'.TextDocumentSyncKind.Full
1578          end)
1579          eq(full_kind, client.server_capabilities().textDocumentSync.change)
1580          eq(true, client.server_capabilities().textDocumentSync.openClose)
1581          exec_lua(function()
1582            assert(vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID))
1583          end)
1584        end,
1585        on_exit = function(code, signal)
1586          eq(0, code, 'exit code')
1587          eq(0, signal, 'exit signal')
1588        end,
1589        on_handler = function(err, result, ctx)
1590          if ctx.method == 'start' then
1591            exec_lua(function()
1592              vim.api.nvim_buf_set_lines(_G.BUFFER, 1, 2, false, {
1593                'boop',
1594              })
1595            end)
1596            client:notify('finish')
1597          end
1598          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
1599          if ctx.method == 'finish' then
1600            client:stop()
1601          end
1602        end,
1603      }
1604    end)
1605
1606    it('should check the body and didChange full with noeol', function()
1607      local expected_handlers = {
1608        { NIL, {}, { method = 'shutdown', client_id = 1 } },
1609        { NIL, {}, { method = 'finish', client_id = 1 } },
1610        { NIL, {}, { method = 'start', client_id = 1 } },
1611      }
1612      local client --- @type vim.lsp.Client
1613      test_rpc_server {
1614        test_name = 'basic_check_buffer_open_and_change_noeol',
1615        on_setup = function()
1616          exec_lua(function()
1617            _G.BUFFER = vim.api.nvim_create_buf(false, true)
1618            vim.api.nvim_buf_set_lines(_G.BUFFER, 0, -1, false, {
1619              'testing',
1620              '123',
1621            })
1622            vim.bo[_G.BUFFER].eol = false
1623          end)
1624        end,
1625        on_init = function(_client)
1626          client = _client
1627          local full_kind = exec_lua(function()
1628            return require 'vim.lsp.protocol'.TextDocumentSyncKind.Full
1629          end)
1630          eq(full_kind, client.server_capabilities().textDocumentSync.change)
1631          eq(true, client.server_capabilities().textDocumentSync.openClose)
1632          exec_lua(function()
1633            assert(vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID))
1634          end)
1635        end,
1636        on_exit = function(code, signal)
1637          eq(0, code, 'exit code')
1638          eq(0, signal, 'exit signal')
1639        end,
1640        on_handler = function(err, result, ctx)
1641          if ctx.method == 'start' then
1642            exec_lua(function()
1643              vim.api.nvim_buf_set_lines(_G.BUFFER, 1, 2, false, {
1644                'boop',
1645              })
1646            end)
1647            client:notify('finish')
1648          end
1649          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
1650          if ctx.method == 'finish' then
1651            client:stop()
1652          end
1653        end,
1654      }
1655    end)
1656
1657    it('should send correct range for inlay hints with noeol', function()
1658      local expected_handlers = {
1659        { NIL, {}, { method = 'shutdown', client_id = 1 } },
1660        { NIL, {}, { method = 'finish', client_id = 1 } },
1661        {
1662          NIL,
1663          {},
1664          {
1665            method = 'textDocument/inlayHint',
1666            params = {
1667              textDocument = {
1668                uri = 'file://',
1669              },
1670              range = {
1671                start = { line = 0, character = 0 },
1672                ['end'] = { line = 1, character = 3 },
1673              },
1674            },
1675            bufnr = 2,
1676            client_id = 1,
1677            request_id = 2,
1678            version = 0,
1679          },
1680        },
1681        { NIL, {}, { method = 'start', client_id = 1 } },
1682      }
1683      local client --- @type vim.lsp.Client
1684      test_rpc_server {
1685        test_name = 'inlay_hint',
1686        on_setup = function()
1687          exec_lua(function()
1688            _G.BUFFER = vim.api.nvim_create_buf(false, true)
1689            vim.api.nvim_buf_set_lines(_G.BUFFER, 0, -1, false, {
1690              'testing',
1691              '123',
1692            })
1693            vim.bo[_G.BUFFER].eol = false
1694          end)
1695        end,
1696        on_init = function(_client)
1697          client = _client
1698          eq(true, client:supports_method('textDocument/inlayHint'))
1699          exec_lua(function()
1700            assert(vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID))
1701          end)
1702        end,
1703        on_exit = function(code, signal)
1704          eq(0, code, 'exit code')
1705          eq(0, signal, 'exit signal')
1706        end,
1707        on_handler = function(err, result, ctx)
1708          if ctx.method == 'start' then
1709            exec_lua(function()
1710              vim.lsp.inlay_hint.enable(true, { bufnr = _G.BUFFER })
1711            end)
1712          end
1713          if ctx.method == 'textDocument/inlayHint' then
1714            client:notify('finish')
1715          end
1716          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
1717          if ctx.method == 'finish' then
1718            client:stop()
1719          end
1720        end,
1721      }
1722    end)
1723
1724    it('should check the body and didChange incremental', function()
1725      local expected_handlers = {
1726        { NIL, {}, { method = 'shutdown', client_id = 1 } },
1727        { NIL, {}, { method = 'finish', client_id = 1 } },
1728        { NIL, {}, { method = 'start', client_id = 1 } },
1729      }
1730      local client --- @type vim.lsp.Client
1731      test_rpc_server {
1732        test_name = 'basic_check_buffer_open_and_change_incremental',
1733        options = {
1734          allow_incremental_sync = true,
1735        },
1736        on_setup = function()
1737          exec_lua(function()
1738            _G.BUFFER = vim.api.nvim_create_buf(false, true)
1739            vim.api.nvim_buf_set_lines(_G.BUFFER, 0, -1, false, {
1740              'testing',
1741              '123',
1742            })
1743          end)
1744        end,
1745        on_init = function(_client)
1746          client = _client
1747          local sync_kind = exec_lua(function()
1748            return require 'vim.lsp.protocol'.TextDocumentSyncKind.Incremental
1749          end)
1750          eq(sync_kind, client.server_capabilities().textDocumentSync.change)
1751          eq(true, client.server_capabilities().textDocumentSync.openClose)
1752          exec_lua(function()
1753            assert(vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID))
1754          end)
1755        end,
1756        on_exit = function(code, signal)
1757          eq(0, code, 'exit code')
1758          eq(0, signal, 'exit signal')
1759        end,
1760        on_handler = function(err, result, ctx)
1761          if ctx.method == 'start' then
1762            exec_lua(function()
1763              vim.api.nvim_buf_set_lines(_G.BUFFER, 1, 2, false, {
1764                '123boop',
1765              })
1766            end)
1767            client:notify('finish')
1768          end
1769          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
1770          if ctx.method == 'finish' then
1771            client:stop()
1772          end
1773        end,
1774      }
1775    end)
1776
1777    it('should check the body and didChange incremental with debounce', function()
1778      local expected_handlers = {
1779        { NIL, {}, { method = 'shutdown', client_id = 1 } },
1780        { NIL, {}, { method = 'finish', client_id = 1 } },
1781        { NIL, {}, { method = 'start', client_id = 1 } },
1782      }
1783      local client --- @type vim.lsp.Client
1784      test_rpc_server {
1785        test_name = 'basic_check_buffer_open_and_change_incremental',
1786        options = {
1787          allow_incremental_sync = true,
1788          debounce_text_changes = 5,
1789        },
1790        on_setup = function()
1791          exec_lua(function()
1792            _G.BUFFER = vim.api.nvim_create_buf(false, true)
1793            vim.api.nvim_buf_set_lines(_G.BUFFER, 0, -1, false, {
1794              'testing',
1795              '123',
1796            })
1797          end)
1798        end,
1799        on_init = function(_client)
1800          client = _client
1801          local sync_kind = exec_lua(function()
1802            return require 'vim.lsp.protocol'.TextDocumentSyncKind.Incremental
1803          end)
1804          eq(sync_kind, client.server_capabilities().textDocumentSync.change)
1805          eq(true, client.server_capabilities().textDocumentSync.openClose)
1806          exec_lua(function()
1807            assert(vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID))
1808          end)
1809        end,
1810        on_exit = function(code, signal)
1811          eq(0, code, 'exit code')
1812          eq(0, signal, 'exit signal')
1813        end,
1814        on_handler = function(err, result, ctx)
1815          if ctx.method == 'start' then
1816            exec_lua(function()
1817              vim.api.nvim_buf_set_lines(_G.BUFFER, 1, 2, false, {
1818                '123boop',
1819              })
1820            end)
1821            client:notify('finish')
1822          end
1823          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
1824          if ctx.method == 'finish' then
1825            client:stop()
1826          end
1827        end,
1828      }
1829    end)
1830
1831    -- TODO(askhan) we don't support full for now, so we can disable these tests.
1832    pending('should check the body and didChange incremental normal mode editing', function()
1833      local expected_handlers = {
1834        { NIL, {}, { method = 'shutdown', bufnr = 1, client_id = 1 } },
1835        { NIL, {}, { method = 'finish', client_id = 1 } },
1836        { NIL, {}, { method = 'start', client_id = 1 } },
1837      }
1838      local client --- @type vim.lsp.Client
1839      test_rpc_server {
1840        test_name = 'basic_check_buffer_open_and_change_incremental_editing',
1841        on_setup = function()
1842          exec_lua(function()
1843            _G.BUFFER = vim.api.nvim_create_buf(false, true)
1844            vim.api.nvim_buf_set_lines(_G.BUFFER, 0, -1, false, {
1845              'testing',
1846              '123',
1847            })
1848          end)
1849        end,
1850        on_init = function(_client)
1851          client = _client
1852          local sync_kind = exec_lua(function()
1853            return require 'vim.lsp.protocol'.TextDocumentSyncKind.Incremental
1854          end)
1855          eq(sync_kind, client.server_capabilities().textDocumentSync.change)
1856          eq(true, client.server_capabilities().textDocumentSync.openClose)
1857          exec_lua(function()
1858            assert(vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID))
1859          end)
1860        end,
1861        on_exit = function(code, signal)
1862          eq(0, code, 'exit code')
1863          eq(0, signal, 'exit signal')
1864        end,
1865        on_handler = function(err, result, ctx)
1866          if ctx.method == 'start' then
1867            n.command('normal! 1Go')
1868            client:notify('finish')
1869          end
1870          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
1871          if ctx.method == 'finish' then
1872            client:stop()
1873          end
1874        end,
1875      }
1876    end)
1877
1878    it('should check the body and didChange full with 2 changes', function()
1879      local expected_handlers = {
1880        { NIL, {}, { method = 'shutdown', client_id = 1 } },
1881        { NIL, {}, { method = 'finish', client_id = 1 } },
1882        { NIL, {}, { method = 'start', client_id = 1 } },
1883      }
1884      local client --- @type vim.lsp.Client
1885      test_rpc_server {
1886        test_name = 'basic_check_buffer_open_and_change_multi',
1887        on_setup = function()
1888          exec_lua(function()
1889            _G.BUFFER = vim.api.nvim_create_buf(false, true)
1890            vim.api.nvim_buf_set_lines(_G.BUFFER, 0, -1, false, {
1891              'testing',
1892              '123',
1893            })
1894          end)
1895        end,
1896        on_init = function(_client)
1897          client = _client
1898          local sync_kind = exec_lua(function()
1899            return require 'vim.lsp.protocol'.TextDocumentSyncKind.Full
1900          end)
1901          eq(sync_kind, client.server_capabilities().textDocumentSync.change)
1902          eq(true, client.server_capabilities().textDocumentSync.openClose)
1903          exec_lua(function()
1904            assert(vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID))
1905          end)
1906        end,
1907        on_exit = function(code, signal)
1908          eq(0, code, 'exit code')
1909          eq(0, signal, 'exit signal')
1910        end,
1911        on_handler = function(err, result, ctx)
1912          if ctx.method == 'start' then
1913            exec_lua(function()
1914              vim.api.nvim_buf_set_lines(_G.BUFFER, 1, 2, false, {
1915                '321',
1916              })
1917              vim.api.nvim_buf_set_lines(_G.BUFFER, 1, 2, false, {
1918                'boop',
1919              })
1920            end)
1921            client:notify('finish')
1922          end
1923          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
1924          if ctx.method == 'finish' then
1925            client:stop()
1926          end
1927        end,
1928      }
1929    end)
1930
1931    it('should check the body and didChange full lifecycle', function()
1932      local expected_handlers = {
1933        { NIL, {}, { method = 'shutdown', client_id = 1 } },
1934        { NIL, {}, { method = 'finish', client_id = 1 } },
1935        { NIL, {}, { method = 'start', client_id = 1 } },
1936      }
1937      local client --- @type vim.lsp.Client
1938      test_rpc_server {
1939        test_name = 'basic_check_buffer_open_and_change_multi_and_close',
1940        on_setup = function()
1941          exec_lua(function()
1942            _G.BUFFER = vim.api.nvim_create_buf(false, true)
1943            vim.api.nvim_buf_set_lines(_G.BUFFER, 0, -1, false, {
1944              'testing',
1945              '123',
1946            })
1947          end)
1948        end,
1949        on_init = function(_client)
1950          client = _client
1951          local sync_kind = exec_lua(function()
1952            return require 'vim.lsp.protocol'.TextDocumentSyncKind.Full
1953          end)
1954          eq(sync_kind, client.server_capabilities().textDocumentSync.change)
1955          eq(true, client.server_capabilities().textDocumentSync.openClose)
1956          exec_lua(function()
1957            assert(vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID))
1958          end)
1959        end,
1960        on_exit = function(code, signal)
1961          eq(0, code, 'exit code')
1962          eq(0, signal, 'exit signal')
1963        end,
1964        on_handler = function(err, result, ctx)
1965          if ctx.method == 'start' then
1966            exec_lua(function()
1967              vim.api.nvim_buf_set_lines(_G.BUFFER, 1, 2, false, {
1968                '321',
1969              })
1970              vim.api.nvim_buf_set_lines(_G.BUFFER, 1, 2, false, {
1971                'boop',
1972              })
1973              vim.api.nvim_command(_G.BUFFER .. 'bwipeout')
1974            end)
1975            client:notify('finish')
1976          end
1977          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
1978          if ctx.method == 'finish' then
1979            client:stop()
1980          end
1981        end,
1982      }
1983    end)
1984
1985    it('vim.lsp.start when existing client has no workspace_folders', function()
1986      exec_lua(create_server_definition)
1987      eq(
1988        { 2, 'foo', 'foo' },
1989        exec_lua(function()
1990          local server = _G._create_server()
1991          vim.lsp.start { cmd = server.cmd, name = 'foo' }
1992          vim.lsp.start { cmd = server.cmd, name = 'foo', root_dir = 'bar' }
1993          local foos = vim.lsp.get_clients()
1994          return { #foos, foos[1].name, foos[2].name }
1995        end)
1996      )
1997    end)
1998  end)
1999
2000  describe('parsing tests', function()
2001    local body = '{"jsonrpc":"2.0","id": 1,"method":"demo"}'
2002
2003    before_each(function()
2004      exec_lua(create_tcp_echo_server)
2005    end)
2006
2007    it('should catch error while parsing invalid header', function()
2008      -- No whitespace is allowed between the header field-name and colon.
2009      -- See https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.4
2010      local field = 'Content-Length : 10 \r\n'
2011      exec_lua(function()
2012        _G._send_msg_to_server(field .. '\r\n')
2013      end)
2014      verify_single_notification(function(method, args) ---@param args [string, number]
2015        eq('error', method)
2016        eq(1, args[2])
2017        matches(vim.pesc('Content-Length not found in header: ' .. field) .. '$', args[1])
2018      end)
2019    end)
2020
2021    it('value of Content-Length shoud be number', function()
2022      local value = '123 foo'
2023      exec_lua(function()
2024        _G._send_msg_to_server('Content-Length: ' .. value .. '\r\n\r\n')
2025      end)
2026      verify_single_notification(function(method, args) ---@param args [string, number]
2027        eq('error', method)
2028        eq(1, args[2])
2029        matches('value of Content%-Length is not number: ' .. value .. '$', args[1])
2030      end)
2031    end)
2032
2033    it('field name is case-insensitive', function()
2034      exec_lua(function()
2035        _G._send_msg_to_server('CONTENT-Length: ' .. #body .. ' \r\n\r\n' .. body)
2036      end)
2037      verify_single_notification(function(method, args) ---@param args [string]
2038        eq('body', method)
2039        eq(body, args[1])
2040      end)
2041    end)
2042
2043    it("ignore some lines ending with LF that don't contain content-length", function()
2044      exec_lua(function()
2045        _G._send_msg_to_server(
2046          'foo \n bar\nWARN: no common words.\nContent-Length: ' .. #body .. ' \r\n\r\n' .. body
2047        )
2048      end)
2049      verify_single_notification(function(method, args) ---@param args [string]
2050        eq('body', method)
2051        eq(body, args[1])
2052      end)
2053    end)
2054
2055    it('ignores blank lines before content-length', function()
2056      exec_lua(function()
2057        _G._send_msg_to_server(
2058          'Info: Parsed 35 declarations\n\nContent-Length: ' .. #body .. ' \r\n\r\n' .. body
2059        )
2060      end)
2061      verify_single_notification(function(method, args) ---@param args [string]
2062        eq('body', method)
2063        eq(body, args[1])
2064      end)
2065    end)
2066
2067    it('skips partial match of "content-length"', function()
2068      exec_lua(function()
2069        _G._send_msg_to_server('Cont\nContent-Length: ' .. #body .. ' \r\n\r\n' .. body)
2070      end)
2071      verify_single_notification(function(method, args) ---@param args [string]
2072        eq('body', method)
2073        eq(body, args[1])
2074      end)
2075    end)
2076
2077    it('should not trim vim.NIL from the end of a list', function()
2078      local expected_handlers = {
2079        { NIL, {}, { method = 'shutdown', client_id = 1 } },
2080        { NIL, {}, { method = 'finish', client_id = 1 } },
2081        {
2082          NIL,
2083          {
2084            arguments = { 'EXTRACT_METHOD', { metadata = { field = vim.NIL } }, 3, 0, 6123, NIL },
2085            command = 'refactor.perform',
2086            title = 'EXTRACT_METHOD',
2087          },
2088          { method = 'workspace/executeCommand', client_id = 1 },
2089        },
2090        { NIL, {}, { method = 'start', client_id = 1 } },
2091      }
2092      local client --- @type vim.lsp.Client
2093      test_rpc_server {
2094        test_name = 'decode_nil',
2095        on_setup = function()
2096          exec_lua(function()
2097            _G.BUFFER = vim.api.nvim_create_buf(false, true)
2098            vim.api.nvim_buf_set_lines(_G.BUFFER, 0, -1, false, {
2099              'testing',
2100              '123',
2101            })
2102          end)
2103        end,
2104        on_init = function(_client)
2105          client = _client
2106          exec_lua(function()
2107            assert(vim.lsp.buf_attach_client(_G.BUFFER, _G.TEST_RPC_CLIENT_ID))
2108          end)
2109        end,
2110        on_exit = function(code, signal)
2111          eq(0, code, 'exit code')
2112          eq(0, signal, 'exit signal')
2113        end,
2114        on_handler = function(err, result, ctx)
2115          eq(table.remove(expected_handlers), { err, result, ctx }, 'expected handler')
2116          if ctx.method == 'finish' then
2117            client:stop()
2118          end
2119        end,
2120      }
2121    end)
2122  end)
2123
2124  describe('apply vscode text_edits', function()
2125    it('single replace', function()
2126      insert('012345678901234567890123456789')
2127      apply_text_edits({
2128        { 0, 3, 0, 6, { 'Hello' } },
2129      })
2130      eq({ '012Hello678901234567890123456789' }, buf_lines(1))
2131    end)
2132
2133    it('two replaces', function()
2134      insert('012345678901234567890123456789')
2135      apply_text_edits({
2136        { 0, 3, 0, 6, { 'Hello' } },
2137        { 0, 6, 0, 9, { 'World' } },
2138      })
2139      eq({ '012HelloWorld901234567890123456789' }, buf_lines(1))
2140    end)
2141
2142    it('same start pos insert are kept in order', function()
2143      insert('012345678901234567890123456789')
2144      apply_text_edits({
2145        { 0, 3, 0, 3, { 'World' } },
2146        { 0, 3, 0, 3, { 'Hello' } },
2147      })
2148      eq({ '012WorldHello345678901234567890123456789' }, buf_lines(1))
2149    end)
2150
2151    it('same start pos insert and replace are kept in order', function()
2152      insert('012345678901234567890123456789')
2153      apply_text_edits({
2154        { 0, 3, 0, 3, { 'World' } },
2155        { 0, 3, 0, 3, { 'Hello' } },
2156        { 0, 3, 0, 8, { 'No' } },
2157      })
2158      eq({ '012WorldHelloNo8901234567890123456789' }, buf_lines(1))
2159    end)
2160
2161    it('multiline', function()
2162      exec_lua(function()
2163        vim.api.nvim_buf_set_lines(1, 0, 0, true, { '  {', '    "foo": "bar"', '  }' })
2164      end)
2165      eq({ '  {', '    "foo": "bar"', '  }', '' }, buf_lines(1))
2166      apply_text_edits({
2167        { 0, 0, 3, 0, { '' } },
2168        { 3, 0, 3, 0, { '{\n' } },
2169        { 3, 0, 3, 0, { '  "foo": "bar"\n' } },
2170        { 3, 0, 3, 0, { '}\n' } },
2171      })
2172      eq({ '{', '  "foo": "bar"', '}', '' }, buf_lines(1))
2173    end)
2174  end)
2175
2176  describe('apply_text_edits', function()
2177    local buffer_text = {
2178      'First line of text',
2179      'Second line of text',
2180      'Third line of text',
2181      'Fourth line of text',
2182      'å å ɧ 汉语 ↥ 🤦 🦄',
2183    }
2184
2185    before_each(function()
2186      insert(dedent(table.concat(buffer_text, '\n')))
2187    end)
2188
2189    it('applies simple edits', function()
2190      apply_text_edits({
2191        { 0, 0, 0, 0, { '123' } },
2192        { 1, 0, 1, 1, { '2' } },
2193        { 2, 0, 2, 2, { '3' } },
2194        { 3, 2, 3, 4, { '' } },
2195      })
2196      eq({
2197        '123First line of text',
2198        '2econd line of text',
2199        '3ird line of text',
2200        'Foth line of text',
2201        'å å ɧ 汉语 ↥ 🤦 🦄',
2202      }, buf_lines(1))
2203    end)
2204
2205    it('applies complex edits', function()
2206      apply_text_edits({
2207        { 0, 0, 0, 0, { '', '12' } },
2208        { 0, 0, 0, 0, { '3', 'foo' } },
2209        { 0, 1, 0, 1, { 'bar', '123' } },
2210        { 0, #'First ', 0, #'First line of text', { 'guy' } },
2211        { 1, 0, 1, #'Second', { 'baz' } },
2212        { 2, #'Th', 2, #'Third', { 'e next' } },
2213        { 3, #'', 3, #'Fourth', { 'another line of text', 'before this' } },
2214        { 3, #'Fourth', 3, #'Fourth line of text', { '!' } },
2215      })
2216      eq({
2217        '',
2218        '123',
2219        'fooFbar',
2220        '123irst guy',
2221        'baz line of text',
2222        'The next line of text',
2223        'another line of text',
2224        'before this!',
2225        'å å ɧ 汉语 ↥ 🤦 🦄',
2226      }, buf_lines(1))
2227    end)
2228
2229    it('applies complex edits (reversed range)', function()
2230      apply_text_edits({
2231        { 0, 0, 0, 0, { '', '12' } },
2232        { 0, 0, 0, 0, { '3', 'foo' } },
2233        { 0, 1, 0, 1, { 'bar', '123' } },
2234        { 0, #'First line of text', 0, #'First ', { 'guy' } },
2235        { 1, #'Second', 1, 0, { 'baz' } },
2236        { 2, #'Third', 2, #'Th', { 'e next' } },
2237        { 3, #'Fourth', 3, #'', { 'another line of text', 'before this' } },
2238        { 3, #'Fourth line of text', 3, #'Fourth', { '!' } },
2239      })
2240      eq({
2241        '',
2242        '123',
2243        'fooFbar',
2244        '123irst guy',
2245        'baz line of text',
2246        'The next line of text',
2247        'another line of text',
2248        'before this!',
2249        'å å ɧ 汉语 ↥ 🤦 🦄',
2250      }, buf_lines(1))
2251    end)
2252
2253    it('applies non-ASCII characters edits', function()
2254      apply_text_edits({
2255        { 4, 3, 4, 4, { 'ä' } },
2256      })
2257      eq({
2258        'First line of text',
2259        'Second line of text',
2260        'Third line of text',
2261        'Fourth line of text',
2262        'å ä ɧ 汉语 ↥ 🤦 🦄',
2263      }, buf_lines(1))
2264    end)
2265
2266    it('applies text edits at the end of the document', function()
2267      apply_text_edits({
2268        { 5, 0, 5, 0, 'foobar' },
2269      })
2270      eq({
2271        'First line of text',
2272        'Second line of text',
2273        'Third line of text',
2274        'Fourth line of text',
2275        'å å ɧ 汉语 ↥ 🤦 🦄',
2276        'foobar',
2277      }, buf_lines(1))
2278    end)
2279
2280    it('applies multiple text edits at the end of the document', function()
2281      apply_text_edits({
2282        { 4, 0, 5, 0, '' },
2283        { 5, 0, 5, 0, 'foobar' },
2284      })
2285      eq({
2286        'First line of text',
2287        'Second line of text',
2288        'Third line of text',
2289        'Fourth line of text',
2290        'foobar',
2291      }, buf_lines(1))
2292    end)
2293
2294    it('applies newline-terminated text edits at the end of the document', function()
2295      apply_text_edits({
2296        { 5, 0, 5, 0, 'foobar\n' },
2297      })
2298      eq({
2299        'First line of text',
2300        'Second line of text',
2301        'Third line of text',
2302        'Fourth line of text',
2303        'å å ɧ 汉语 ↥ 🤦 🦄',
2304        'foobar',
2305      }, buf_lines(1))
2306    end)
2307
2308    it('it restores marks', function()
2309      eq(true, api.nvim_buf_set_mark(1, 'a', 2, 1, {}))
2310      apply_text_edits({
2311        { 1, 0, 2, 5, 'foobar' },
2312        { 4, 0, 5, 0, 'barfoo' },
2313      })
2314      eq({
2315        'First line of text',
2316        'foobar line of text',
2317        'Fourth line of text',
2318        'barfoo',
2319      }, buf_lines(1))
2320      eq({ 2, 1 }, api.nvim_buf_get_mark(1, 'a'))
2321    end)
2322
2323    it('it restores marks to last valid col', function()
2324      eq(true, api.nvim_buf_set_mark(1, 'a', 2, 10, {}))
2325      apply_text_edits({
2326        { 1, 0, 2, 15, 'foobar' },
2327        { 4, 0, 5, 0, 'barfoo' },
2328      })
2329      eq({
2330        'First line of text',
2331        'foobarext',
2332        'Fourth line of text',
2333        'barfoo',
2334      }, buf_lines(1))
2335      eq({ 2, 9 }, api.nvim_buf_get_mark(1, 'a'))
2336    end)
2337
2338    it('it restores marks to last valid line', function()
2339      eq(true, api.nvim_buf_set_mark(1, 'a', 4, 1, {}))
2340      apply_text_edits({
2341        { 1, 0, 4, 5, 'foobar' },
2342        { 4, 0, 5, 0, 'barfoo' },
2343      })
2344      eq({
2345        'First line of text',
2346        'foobaro',
2347      }, buf_lines(1))
2348      eq({ 2, 1 }, api.nvim_buf_get_mark(1, 'a'))
2349    end)
2350
2351    it('applies edit based on confirmation response', function()
2352      --- @type lsp.AnnotatedTextEdit
2353      local edit = make_edit(0, 0, 5, 0, 'foo')
2354      edit.annotationId = 'annotation-id'
2355
2356      local function test(response)
2357        exec_lua(function()
2358          ---@diagnostic disable-next-line: duplicate-set-field
2359          vim.fn.confirm = function()
2360            return response
2361          end
2362
2363          vim.lsp.util.apply_text_edits(
2364            { edit },
2365            1,
2366            'utf-16',
2367            { ['annotation-id'] = { label = 'Insert "foo"', needsConfirmation = true } }
2368          )
2369        end, { response })
2370      end
2371
2372      test(2) -- 2 = No
2373      eq(buffer_text, buf_lines(1))
2374
2375      test(1) -- 1 = Yes
2376      eq({ 'foo' }, buf_lines(1))
2377    end)
2378
2379    describe('cursor position', function()
2380      it("don't fix the cursor if the range contains the cursor", function()
2381        api.nvim_win_set_cursor(0, { 2, 6 })
2382        apply_text_edits({
2383          { 1, 0, 1, 19, 'Second line of text' },
2384        })
2385        eq({
2386          'First line of text',
2387          'Second line of text',
2388          'Third line of text',
2389          'Fourth line of text',
2390          'å å ɧ 汉语 ↥ 🤦 🦄',
2391        }, buf_lines(1))
2392        eq({ 2, 6 }, api.nvim_win_get_cursor(0))
2393      end)
2394
2395      it('fix the cursor to the valid col if the content was removed', function()
2396        api.nvim_win_set_cursor(0, { 2, 6 })
2397        apply_text_edits({
2398          { 1, 0, 1, 6, '' },
2399          { 1, 6, 1, 19, '' },
2400        })
2401        eq({
2402          'First line of text',
2403          '',
2404          'Third line of text',
2405          'Fourth line of text',
2406          'å å ɧ 汉语 ↥ 🤦 🦄',
2407        }, buf_lines(1))
2408        eq({ 2, 0 }, api.nvim_win_get_cursor(0))
2409      end)
2410
2411      it('fix the cursor to the valid row if the content was removed', function()
2412        api.nvim_win_set_cursor(0, { 2, 6 })
2413        apply_text_edits({
2414          { 1, 0, 1, 6, '' },
2415          { 0, 18, 5, 0, '' },
2416        })
2417        eq({
2418          'First line of text',
2419        }, buf_lines(1))
2420        eq({ 1, 17 }, api.nvim_win_get_cursor(0))
2421      end)
2422
2423      it('fix the cursor row', function()
2424        api.nvim_win_set_cursor(0, { 3, 0 })
2425        apply_text_edits({
2426          { 1, 0, 2, 0, '' },
2427        })
2428        eq({
2429          'First line of text',
2430          'Third line of text',
2431          'Fourth line of text',
2432          'å å ɧ 汉语 ↥ 🤦 🦄',
2433        }, buf_lines(1))
2434        eq({ 2, 0 }, api.nvim_win_get_cursor(0))
2435      end)
2436
2437      it('fix the cursor col', function()
2438        -- append empty last line. See #22636
2439        api.nvim_buf_set_lines(1, -1, -1, true, { '' })
2440
2441        api.nvim_win_set_cursor(0, { 2, 11 })
2442        apply_text_edits({
2443          { 1, 7, 1, 11, '' },
2444        })
2445        eq({
2446          'First line of text',
2447          'Second  of text',
2448          'Third line of text',
2449          'Fourth line of text',
2450          'å å ɧ 汉语 ↥ 🤦 🦄',
2451          '',
2452        }, buf_lines(1))
2453        eq({ 2, 7 }, api.nvim_win_get_cursor(0))
2454      end)
2455
2456      it('fix the cursor row and col', function()
2457        api.nvim_win_set_cursor(0, { 2, 12 })
2458        apply_text_edits({
2459          { 0, 11, 1, 12, '' },
2460        })
2461        eq({
2462          'First line of text',
2463          'Third line of text',
2464          'Fourth line of text',
2465          'å å ɧ 汉语 ↥ 🤦 🦄',
2466        }, buf_lines(1))
2467        eq({ 1, 11 }, api.nvim_win_get_cursor(0))
2468      end)
2469    end)
2470
2471    describe('with LSP end line after what Vim considers to be the end line', function()
2472      it('applies edits when the last linebreak is considered a new line', function()
2473        apply_text_edits({
2474          { 0, 0, 5, 0, { 'All replaced' } },
2475        })
2476        eq({ 'All replaced' }, buf_lines(1))
2477      end)
2478
2479      it("applies edits when the end line is 2 larger than vim's", function()
2480        apply_text_edits({
2481          { 0, 0, 6, 0, { 'All replaced' } },
2482        })
2483        eq({ 'All replaced' }, buf_lines(1))
2484      end)
2485
2486      it('applies edits with a column offset', function()
2487        apply_text_edits({
2488          { 0, 0, 5, 2, { 'All replaced' } },
2489        })
2490        eq({ 'All replaced' }, buf_lines(1))
2491      end)
2492    end)
2493  end)
2494
2495  describe('apply_text_edits regression tests for #20116', function()
2496    before_each(function()
2497      insert(dedent([[
2498      Test line one
2499      Test line two 21 char]]))
2500    end)
2501
2502    describe('with LSP end column out of bounds and start column at 0', function()
2503      it('applies edits at the end of the buffer', function()
2504        apply_text_edits({
2505          { 0, 0, 1, 22, { '#include "whatever.h"\r\n#include <algorithm>\r' } },
2506        }, 'utf-8')
2507        eq({ '#include "whatever.h"', '#include <algorithm>' }, buf_lines(1))
2508      end)
2509
2510      it('applies edits in the middle of the buffer', function()
2511        apply_text_edits({
2512          { 0, 0, 0, 22, { '#include "whatever.h"\r\n#include <algorithm>\r' } },
2513        }, 'utf-8')
2514        eq(
2515          { '#include "whatever.h"', '#include <algorithm>', 'Test line two 21 char' },
2516          buf_lines(1)
2517        )
2518      end)
2519    end)
2520
2521    describe('with LSP end column out of bounds and start column NOT at 0', function()
2522      it('applies edits at the end of the buffer', function()
2523        apply_text_edits({
2524          { 0, 2, 1, 22, { '#include "whatever.h"\r\n#include <algorithm>\r' } },
2525        }, 'utf-8')
2526        eq({ 'Te#include "whatever.h"', '#include <algorithm>' }, buf_lines(1))
2527      end)
2528
2529      it('applies edits in the middle of the buffer', function()
2530        apply_text_edits({
2531          { 0, 2, 0, 22, { '#include "whatever.h"\r\n#include <algorithm>\r' } },
2532        }, 'utf-8')
2533        eq(
2534          { 'Te#include "whatever.h"', '#include <algorithm>', 'Test line two 21 char' },
2535          buf_lines(1)
2536        )
2537      end)
2538    end)
2539  end)
2540
2541  describe('apply_text_document_edit', function()
2542    local target_bufnr --- @type integer
2543
2544    local text_document_edit = function(editVersion)
2545      return {
2546        edits = {
2547          make_edit(0, 0, 0, 3, 'First ↥ 🤦 🦄'),
2548        },
2549        textDocument = {
2550          uri = 'file:///fake/uri',
2551          version = editVersion,
2552        },
2553      }
2554    end
2555
2556    before_each(function()
2557      target_bufnr = exec_lua(function()
2558        local bufnr = vim.uri_to_bufnr('file:///fake/uri')
2559        local lines = { '1st line of text', '2nd line of 语text' }
2560        vim.api.nvim_buf_set_lines(bufnr, 0, 1, false, lines)
2561        return bufnr
2562      end)
2563    end)
2564
2565    it('correctly goes ahead with the edit if all is normal', function()
2566      exec_lua(function(text_edit)
2567        vim.lsp.util.apply_text_document_edit(text_edit, nil, 'utf-16')
2568      end, text_document_edit(5))
2569      eq({
2570        'First ↥ 🤦 🦄 line of text',
2571        '2nd line of 语text',
2572      }, buf_lines(target_bufnr))
2573    end)
2574
2575    it('always accepts edit with version = 0', function()
2576      exec_lua(function(text_edit)
2577        vim.lsp.util.buf_versions[target_bufnr] = 10
2578        vim.lsp.util.apply_text_document_edit(text_edit, nil, 'utf-16')
2579      end, text_document_edit(0))
2580      eq({
2581        'First ↥ 🤦 🦄 line of text',
2582        '2nd line of 语text',
2583      }, buf_lines(target_bufnr))
2584    end)
2585
2586    it('skips the edit if the version of the edit is behind the local buffer ', function()
2587      local apply_edit_mocking_current_version = function(edit, versionedBuf)
2588        exec_lua(function()
2589          vim.lsp.util.buf_versions[versionedBuf.bufnr] = versionedBuf.currentVersion
2590          vim.lsp.util.apply_text_document_edit(edit, nil, 'utf-16')
2591        end)
2592      end
2593
2594      local baseText = {
2595        '1st line of text',
2596        '2nd line of 语text',
2597      }
2598
2599      eq(baseText, buf_lines(target_bufnr))
2600
2601      -- Apply an edit for an old version, should skip
2602      apply_edit_mocking_current_version(
2603        text_document_edit(2),
2604        { currentVersion = 7, bufnr = target_bufnr }
2605      )
2606      eq(baseText, buf_lines(target_bufnr)) -- no change
2607
2608      -- Sanity check that next version to current does apply change
2609      apply_edit_mocking_current_version(
2610        text_document_edit(8),
2611        { currentVersion = 7, bufnr = target_bufnr }
2612      )
2613      eq({
2614        'First ↥ 🤦 🦄 line of text',
2615        '2nd line of 语text',
2616      }, buf_lines(target_bufnr))
2617    end)
2618  end)
2619
2620  describe('workspace_apply_edit', function()
2621    it('workspace/applyEdit returns ApplyWorkspaceEditResponse', function()
2622      local expected_handlers = {
2623        { NIL, {}, { method = 'test', client_id = 1 } },
2624      }
2625      test_rpc_server {
2626        test_name = 'basic_init',
2627        on_init = function(client, _)
2628          client:stop()
2629        end,
2630        -- If the program timed out, then code will be nil.
2631        on_exit = function(code, signal)
2632          eq(0, code, 'exit code')
2633          eq(0, signal, 'exit signal')
2634        end,
2635        -- Note that NIL must be used here.
2636        -- on_handler(err, method, result, client_id)
2637        on_handler = function(...)
2638          local expected = {
2639            applied = true,
2640            failureReason = nil,
2641          }
2642          eq(
2643            expected,
2644            exec_lua(function()
2645              local apply_edit = {
2646                label = nil,
2647                edit = {},
2648              }
2649              return vim.lsp.handlers['workspace/applyEdit'](
2650                nil,
2651                apply_edit,
2652                { client_id = _G.TEST_RPC_CLIENT_ID }
2653              )
2654            end)
2655          )
2656          eq(table.remove(expected_handlers), { ... })
2657        end,
2658      }
2659    end)
2660  end)
2661
2662  describe('apply_workspace_edit', function()
2663    local replace_line_edit = function(row, new_line, editVersion)
2664      return {
2665        edits = {
2666          -- NOTE: This is a hack if you have a line longer than 1000 it won't replace it
2667          make_edit(row, 0, row, 1000, new_line),
2668        },
2669        textDocument = {
2670          uri = 'file:///fake/uri',
2671          version = editVersion,
2672        },
2673      }
2674    end
2675
2676    -- Some servers send all the edits separately, but with the same version.
2677    -- We should not stop applying the edits
2678    local make_workspace_edit = function(changes)
2679      return {
2680        documentChanges = changes,
2681      }
2682    end
2683
2684    local target_bufnr --- @type integer
2685    local changedtick --- @type integer
2686
2687    before_each(function()
2688      exec_lua(function()
2689        target_bufnr = vim.uri_to_bufnr('file:///fake/uri')
2690        local lines = {
2691          'Original Line #1',
2692          'Original Line #2',
2693        }
2694
2695        vim.api.nvim_buf_set_lines(target_bufnr, 0, -1, false, lines)
2696
2697        local function update_changed_tick()
2698          vim.lsp.util.buf_versions[target_bufnr] = vim.b[target_bufnr].changedtick
2699        end
2700
2701        update_changed_tick()
2702        vim.api.nvim_buf_attach(target_bufnr, false, {
2703          on_changedtick = update_changed_tick,
2704        })
2705
2706        changedtick = vim.b[target_bufnr].changedtick
2707      end)
2708    end)
2709
2710    it('apply_workspace_edit applies a single edit', function()
2711      local new_lines = {
2712        'First Line',
2713      }
2714
2715      local edits = {}
2716      for row, line in ipairs(new_lines) do
2717        table.insert(edits, replace_line_edit(row - 1, line, changedtick))
2718      end
2719
2720      eq(
2721        {
2722          'First Line',
2723          'Original Line #2',
2724        },
2725        exec_lua(function(workspace_edits)
2726          vim.lsp.util.apply_workspace_edit(workspace_edits, 'utf-16')
2727
2728          return vim.api.nvim_buf_get_lines(target_bufnr, 0, -1, false)
2729        end, make_workspace_edit(edits))
2730      )
2731      eq(true, api.nvim_get_option_value('buflisted', { buf = target_bufnr }))
2732    end)
2733
2734    it('apply_workspace_edit applies multiple edits', function()
2735      local new_lines = {
2736        'First Line',
2737        'Second Line',
2738      }
2739
2740      local edits = {}
2741      for row, line in ipairs(new_lines) do
2742        table.insert(edits, replace_line_edit(row - 1, line, changedtick))
2743      end
2744
2745      eq(
2746        new_lines,
2747        exec_lua(function(workspace_edits)
2748          vim.lsp.util.apply_workspace_edit(workspace_edits, 'utf-16')
2749          return vim.api.nvim_buf_get_lines(target_bufnr, 0, -1, false)
2750        end, make_workspace_edit(edits))
2751      )
2752    end)
2753
2754    it('supports file creation with CreateFile payload', function()
2755      local tmpfile = tmpname(false)
2756      local uri = exec_lua('return vim.uri_from_fname(...)', tmpfile)
2757      local edit = {
2758        documentChanges = {
2759          {
2760            kind = 'create',
2761            uri = uri,
2762          },
2763        },
2764      }
2765      exec_lua(function()
2766        vim.lsp.util.apply_workspace_edit(edit, 'utf-16')
2767      end)
2768      eq(true, vim.uv.fs_stat(tmpfile) ~= nil)
2769    end)
2770
2771    it(
2772      'supports file creation in folder that needs to be created with CreateFile payload',
2773      function()
2774        local tmpfile = tmpname(false) .. '/dummy/x/'
2775        local uri = exec_lua('return vim.uri_from_fname(...)', tmpfile)
2776        local edit = {
2777          documentChanges = {
2778            {
2779              kind = 'create',
2780              uri = uri,
2781            },
2782          },
2783        }
2784        exec_lua(function()
2785          vim.lsp.util.apply_workspace_edit(edit, 'utf-16')
2786        end)
2787        eq(true, vim.uv.fs_stat(tmpfile) ~= nil)
2788      end
2789    )
2790
2791    it('createFile does not touch file if it exists and ignoreIfExists is set', function()
2792      local tmpfile = tmpname()
2793      write_file(tmpfile, 'Dummy content')
2794      local uri = exec_lua('return vim.uri_from_fname(...)', tmpfile)
2795      local edit = {
2796        documentChanges = {
2797          {
2798            kind = 'create',
2799            uri = uri,
2800            options = {
2801              ignoreIfExists = true,
2802            },
2803          },
2804        },
2805      }
2806      exec_lua('vim.lsp.util.apply_workspace_edit(...)', edit, 'utf-16')
2807      eq(true, vim.uv.fs_stat(tmpfile) ~= nil)
2808      eq('Dummy content', read_file(tmpfile))
2809    end)
2810
2811    it('createFile overrides file if overwrite is set', function()
2812      local tmpfile = tmpname()
2813      write_file(tmpfile, 'Dummy content')
2814      local uri = exec_lua('return vim.uri_from_fname(...)', tmpfile)
2815      local edit = {
2816        documentChanges = {
2817          {
2818            kind = 'create',
2819            uri = uri,
2820            options = {
2821              overwrite = true,
2822              ignoreIfExists = true, -- overwrite must win over ignoreIfExists
2823            },
2824          },
2825        },
2826      }
2827      exec_lua('vim.lsp.util.apply_workspace_edit(...)', edit, 'utf-16')
2828      eq(true, vim.uv.fs_stat(tmpfile) ~= nil)
2829      eq('', read_file(tmpfile))
2830    end)
2831
2832    it('DeleteFile delete file and buffer', function()
2833      local tmpfile = tmpname()
2834      write_file(tmpfile, 'Be gone')
2835      local uri = exec_lua(function()
2836        local bufnr = vim.fn.bufadd(tmpfile)
2837        vim.fn.bufload(bufnr)
2838        return vim.uri_from_fname(tmpfile)
2839      end)
2840      local edit = {
2841        documentChanges = {
2842          {
2843            kind = 'delete',
2844            uri = uri,
2845          },
2846        },
2847      }
2848      eq(true, pcall(exec_lua, 'vim.lsp.util.apply_workspace_edit(...)', edit, 'utf-16'))
2849      eq(false, vim.uv.fs_stat(tmpfile) ~= nil)
2850      eq(false, api.nvim_buf_is_loaded(fn.bufadd(tmpfile)))
2851    end)
2852
2853    it('DeleteFile fails if file does not exist and ignoreIfNotExists is false', function()
2854      local tmpfile = tmpname(false)
2855      local uri = exec_lua('return vim.uri_from_fname(...)', tmpfile)
2856      local edit = {
2857        documentChanges = {
2858          {
2859            kind = 'delete',
2860            uri = uri,
2861            options = {
2862              ignoreIfNotExists = false,
2863            },
2864          },
2865        },
2866      }
2867      eq(false, pcall(exec_lua, 'vim.lsp.util.apply_workspace_edit(...)', edit, 'utf-16'))
2868      eq(false, vim.uv.fs_stat(tmpfile) ~= nil)
2869    end)
2870  end)
2871
2872  describe('vim.lsp.formatexpr', function()
2873    ---@return string[]
2874    local function nvim_buf_get_all_lines()
2875      return exec_lua(function()
2876        return vim.api.nvim_buf_get_lines(0, 0, -1, true)
2877      end)
2878    end
2879
2880    before_each(function()
2881      exec_lua(create_server_definition)
2882      exec_lua(function()
2883        vim.bo.formatexpr = 'v:lua.vim.lsp.formatexpr()'
2884
2885        ---@class test.functional.plugin.lsp_spec.formatexpr.start_server.Opts
2886        ---@field range_formatting_handler? fun(params: lsp.DocumentRangeFormattingParams): lsp.TextEdit[]?
2887        ---@field formatting_handler? fun(params: lsp.DocumentFormattingParams): lsp.TextEdit[]?
2888
2889        local server_number = 1
2890        ---Starts a server which can support textDocument/rangeFormatting and
2891        ---textDocument/formatting. Providing a handler for either method enables the corresponding
2892        ---capability.
2893        ---@param opts test.functional.plugin.lsp_spec.formatexpr.start_server.Opts?
2894        function _G.start_server(opts)
2895          opts = opts or {}
2896          local server = _G._create_server({
2897            capabilities = {
2898              documentRangeFormattingProvider = opts.range_formatting_handler ~= nil,
2899              documentFormattingProvider = opts.formatting_handler ~= nil,
2900            },
2901            handlers = {
2902              ---@param params lsp.DocumentRangeFormattingParams
2903              ['textDocument/rangeFormatting'] = function(_, params, callback)
2904                local text_edits = opts.range_formatting_handler(params)
2905                callback(nil, text_edits)
2906              end,
2907              ---@param params lsp.DocumentFormattingParams
2908              ['textDocument/formatting'] = function(_, params, callback)
2909                local text_edits = opts.formatting_handler(params)
2910                callback(nil, text_edits)
2911              end,
2912            },
2913          })
2914          vim.lsp.start({ name = string.format('server %d', server_number), cmd = server.cmd })
2915          server_number = server_number + 1
2916        end
2917      end)
2918    end)
2919
2920    it('formats range of lines with textDocument/rangeFormatting', function()
2921      local lines = { 'line 1', 'line 2', 'line 3', 'line 4' }
2922      exec_lua(function()
2923        vim.api.nvim_buf_set_lines(0, 0, -1, true, lines)
2924        -- This server formats a range starting on line n and ending on line m by replacing the
2925        -- whole range with the lines "formatted line $i" where $i goes from n to m. This enables us
2926        -- to verify that the correct range is requested for formatting (starts at first character
2927        -- of first line and ends on last character of last line).
2928        start_server({
2929          range_formatting_handler = function(params)
2930            local lines = {} ---@type string[]
2931            for i = params.range.start.line + 1, params.range['end'].line + 1 do
2932              table.insert(lines, string.format('formatted line %d', i))
2933            end
2934            return { { range = params.range, newText = table.concat(lines, '\n') } }
2935          end,
2936        })
2937      end)
2938
2939      feed('2G') -- Move to line 2
2940      feed('gqj') -- Format lines 2 and 3
2941
2942      local expected_lines = vim.deepcopy(lines)
2943      expected_lines[2] = 'formatted line 2'
2944      expected_lines[3] = 'formatted line 3'
2945      eq(expected_lines, nvim_buf_get_all_lines())
2946    end)
2947
2948    it(
2949      'formats whole buffer with textDocument/rangeFormatting when client supports textDocument/rangeFormatting and textDocument/formatting',
2950      function()
2951        local range_formatting_new_text = 'range formatting result'
2952        local formatting_new_text = 'formatting result'
2953        exec_lua(function()
2954          -- This server formats a range and a whole document by inserting "range formatting result"
2955          -- and "formatting result" respectively at the start of the buffer.
2956          local first_char = { line = 0, character = 0 }
2957          start_server({
2958            range_formatting_handler = function()
2959              return {
2960                {
2961                  range = { start = first_char, ['end'] = first_char },
2962                  newText = range_formatting_new_text,
2963                },
2964              }
2965            end,
2966            formatting_handler = function()
2967              return {
2968                {
2969                  range = { start = first_char, ['end'] = first_char },
2970                  newText = formatting_new_text,
2971                },
2972              }
2973            end,
2974          })
2975        end)
2976
2977        feed('gqal') -- Format whole buffer
2978
2979        eq({ range_formatting_new_text }, nvim_buf_get_all_lines())
2980      end
2981    )
2982
2983    it(
2984      'formats whole buffer with textDocument/formatting when client supports textDocument/formatting but not textDocument/rangeFormatting',
2985      function()
2986        local new_text = 'formatting result'
2987        exec_lua(function()
2988          -- This server formats a whole document by inserting "formatting result" at the start of
2989          -- the buffer.
2990          start_server({
2991            formatting_handler = function()
2992              local first_char = { line = 0, character = 0 }
2993              return {
2994                {
2995                  range = { start = first_char, ['end'] = first_char },
2996                  newText = new_text,
2997                },
2998              }
2999            end,
3000          })
3001        end)
3002
3003        feed('gqal') -- Format whole buffer
3004
3005        eq({ new_text }, nvim_buf_get_all_lines())
3006      end
3007    )
3008
3009    it(
3010      'does nothing when range is not whole buffer and client supports textDocument/formatting but not textDocument/rangeFormatting',
3011      function()
3012        local lines = { 'a b', 'c d' }
3013        local new_text = 'formatting result'
3014        exec_lua(function()
3015          vim.api.nvim_buf_set_lines(0, 0, -1, true, lines)
3016          -- Set small textwidth to verify that gq doesn't perform internal formatting (wrap
3017          -- lines) on the buffer.
3018          vim.bo.textwidth = 1
3019          -- This server formats a whole document by inserting "formatting result" at the start of
3020          -- the buffer.
3021          start_server({
3022            formatting_handler = function()
3023              local first_char = { line = 0, character = 0 }
3024              return {
3025                {
3026                  range = { start = first_char, ['end'] = first_char },
3027                  newText = new_text,
3028                },
3029              }
3030            end,
3031          })
3032        end)
3033
3034        feed('2G') -- Move to line 2
3035        feed('Vgq') -- Format line 2
3036
3037        eq(lines, nvim_buf_get_all_lines())
3038      end
3039    )
3040
3041    it('applies only one formatting result when multiple clients support formatting', function()
3042      local new_text = 'formatting result'
3043      exec_lua(function()
3044        -- These servers format a range by inserting "formatting result" at the start of the buffer.
3045        -- This enables us to verify that only one client was used, since if both were used then
3046        -- both results would have been inserted at the start of the buffer.
3047        for _ = 1, 2 do
3048          start_server({
3049            range_formatting_handler = function()
3050              local first_char = { line = 0, character = 0 }
3051              return {
3052                {
3053                  range = { start = first_char, ['end'] = first_char },
3054                  newText = new_text,
3055                },
3056              }
3057            end,
3058          })
3059        end
3060      end)
3061
3062      feed('gqal') -- Format whole buffer
3063
3064      eq({ new_text }, nvim_buf_get_all_lines())
3065    end)
3066
3067    it(
3068      'applies first non-null formatting result when multiple clients support formatting',
3069      function()
3070        local new_text = 'formatting result'
3071        exec_lua(function()
3072          -- These servers format a range by returning null if neither of them have been called
3073          -- before and inserting "formatting result" otherwise. This decouples the test from the
3074          -- (undefined) order that clients are called in.
3075          for _ = 1, 2 do
3076            start_server({
3077              range_formatting_handler = function()
3078                if not range_formatting_called then
3079                  _G.range_formatting_called = true
3080                  return nil
3081                else
3082                  local first_char = { line = 0, character = 0 }
3083                  return {
3084                    {
3085                      range = { start = first_char, ['end'] = first_char },
3086                      newText = new_text,
3087                    },
3088                  }
3089                end
3090              end,
3091            })
3092          end
3093        end)
3094
3095        feed('gqal') -- Format whole buffer
3096
3097        eq({ new_text }, nvim_buf_get_all_lines())
3098      end
3099    )
3100
3101    describe('does nothing when', function()
3102      ---@type table<string, function>
3103      local test_case_setups = {
3104        ['no clients are attached'] = function() end,
3105        ['all servers return null formatting result'] = function()
3106          start_server({
3107            range_formatting_handler = function()
3108              return nil
3109            end,
3110          })
3111        end,
3112        ['no servers support textDocument/rangeFormatting or textDocument/formatting'] = function()
3113          start_server()
3114        end,
3115      }
3116
3117      for test_case, setup in pairs(test_case_setups) do
3118        it(test_case, function()
3119          local lines = { 'a b' }
3120          exec_lua(function()
3121            vim.api.nvim_buf_set_lines(0, 0, -1, true, lines)
3122            -- Set small textwidth to verify that gq doesn't perform internal formatting (wrap
3123            -- lines) on the buffer.
3124            vim.bo.textwidth = 1
3125            start_server({
3126              range_formatting_handler = function()
3127                return nil
3128              end,
3129            })
3130          end)
3131          exec_lua(setup)
3132
3133          feed('gqal') -- Format whole buffer
3134
3135          eq(lines, nvim_buf_get_all_lines())
3136        end)
3137      end
3138    end)
3139
3140    describe('falls back to internal formatting', function()
3141      for _, mode in ipairs({ 'i', 'R' }) do
3142        it(string.format('in %q mode', mode), function()
3143          exec_lua(function()
3144            vim.bo.textwidth = 1
3145            -- This server formats a range by inserting "formatting result" at the start of the
3146            -- buffer.
3147            start_server({
3148              range_formatting_handler = function()
3149                local first_char = { line = 0, character = 0 }
3150                return {
3151                  {
3152                    range = { start = first_char, ['end'] = first_char },
3153                    newText = 'formatting result',
3154                  },
3155                }
3156              end,
3157            })
3158          end)
3159
3160          feed(mode)
3161          feed('a b')
3162
3163          eq({ 'a', 'b' }, nvim_buf_get_all_lines())
3164        end)
3165      end
3166    end)
3167  end)
3168
3169  describe('vim.lsp.tagfunc', function()
3170    before_each(function()
3171      ---@type lsp.Location[]
3172      local mock_locations = {
3173        {
3174          range = {
3175            ['start'] = { line = 5, character = 23 },
3176            ['end'] = { line = 10, character = 0 },
3177          },
3178          uri = 'test://buf',
3179        },
3180        {
3181          range = {
3182            ['start'] = { line = 42, character = 10 },
3183            ['end'] = { line = 44, character = 0 },
3184          },
3185          uri = 'test://another-file',
3186        },
3187      }
3188      exec_lua(create_server_definition)
3189      exec_lua(function()
3190        _G.mock_locations = mock_locations
3191        _G.server = _G._create_server({
3192          capabilities = {
3193            definitionProvider = true,
3194            workspaceSymbolProvider = true,
3195          },
3196          handlers = {
3197            ['textDocument/definition'] = function(_, _, callback)
3198              callback(nil, { _G.mock_locations[1] })
3199            end,
3200            ['workspace/symbol'] = function(_, request, callback)
3201              assert(request.query == 'foobar')
3202              callback(nil, {
3203                {
3204                  name = 'foobar',
3205                  kind = 13, ---@type lsp.SymbolKind
3206                  location = _G.mock_locations[1],
3207                },
3208                {
3209                  name = 'vim.foobar',
3210                  kind = 12, ---@type lsp.SymbolKind
3211                  location = _G.mock_locations[2],
3212                },
3213              })
3214            end,
3215          },
3216        })
3217        _G.client_id = vim.lsp.start({ name = 'dummy', cmd = _G.server.cmd })
3218      end)
3219    end)
3220
3221    after_each(function()
3222      exec_lua(function()
3223        vim.lsp.get_client_by_id(_G.client_id):stop()
3224      end)
3225    end)
3226
3227    it('with flags=c, returns matching tags using textDocument/definition', function()
3228      local result = exec_lua(function()
3229        return vim.lsp.tagfunc('foobar', 'c')
3230      end)
3231      eq({
3232        {
3233          cmd = '/\\%6l\\%1c/', -- for location (5, 23)
3234          filename = 'test://buf',
3235          name = 'foobar',
3236        },
3237      }, result)
3238    end)
3239
3240    it('without flags=c, returns all matching tags using workspace/symbol', function()
3241      local result = exec_lua(function()
3242        return vim.lsp.tagfunc('foobar', '')
3243      end)
3244      eq({
3245        {
3246          cmd = '/\\%6l\\%1c/', -- for location (5, 23)
3247          filename = 'test://buf',
3248          kind = 'Variable',
3249          name = 'foobar',
3250        },
3251        {
3252          cmd = '/\\%43l\\%1c/', -- for location (42, 10)
3253          filename = 'test://another-file',
3254          kind = 'Function',
3255          name = 'vim.foobar',
3256        },
3257      }, result)
3258    end)
3259
3260    it('with flags including i, returns NIL', function()
3261      exec_lua(function()
3262        local result = vim.lsp.tagfunc('foobar', 'cir')
3263        assert(result == vim.NIL, 'should not issue LSP requests')
3264        return {}
3265      end)
3266    end)
3267  end)
3268
3269  describe('cmd', function()
3270    it('cmd string[] CWD', function()
3271      local root_dir = tmpname(false)
3272      local cmd_cwd = tmpname(false)
3273      mkdir(root_dir)
3274      mkdir(cmd_cwd)
3275
3276      local cwd = exec_lua(function()
3277        return assert(vim.uv.cwd())
3278      end)
3279
3280      local cases = {
3281        {
3282          desc = 'cmd_cwd takes precedence',
3283          config = { name = 'cwd-test-cmd-cwd', root_dir = root_dir, cmd_cwd = cmd_cwd },
3284          expected_cwd = cmd_cwd,
3285        },
3286        {
3287          desc = 'root_dir is used when cmd_cwd is unset',
3288          config = { name = 'cwd-test-root-dir', root_dir = root_dir },
3289          expected_cwd = root_dir,
3290        },
3291        {
3292          desc = 'current cwd is used when cmd_cwd and root_dir are unset',
3293          config = { name = 'cwd-test-current-cwd' },
3294          expected_cwd = cwd,
3295        },
3296      }
3297
3298      for _, case in ipairs(cases) do
3299        local outfile = tmpname(false)
3300        local config = vim.tbl_extend('force', {
3301          cmd = {
3302            n.nvim_prog,
3303            '--clean',
3304            '--headless',
3305            ('+call writefile([getcwd()], %q)'):format(outfile),
3306            '+qa!',
3307          },
3308        }, case.config)
3309        exec_lua(function(conf)
3310          assert(vim.lsp.start(conf, { attach = false }))
3311        end, config)
3312        t.assert_log(vim.pesc(case.expected_cwd), outfile)
3313      end
3314    end)
3315
3316    it('connects to lsp server via rpc.connect using ip address', function()
3317      exec_lua(create_tcp_echo_server)
3318      exec_lua(function()
3319        local port = _G._create_tcp_server('127.0.0.1')
3320        vim.lsp.start({ name = 'dummy', cmd = vim.lsp.rpc.connect('127.0.0.1', port) })
3321      end)
3322      verify_single_notification(function(method, args) ---@param args [string]
3323        eq('body', method)
3324        eq('initialize', vim.json.decode(args[1]).method)
3325      end)
3326    end)
3327
3328    it('connects to lsp server via rpc.connect using hostname', function()
3329      skip(is_os('bsd'), 'issue with host resolution in ci')
3330      skip(t.is_arch('s390x'), 'issue with host resolution in ci')
3331      exec_lua(create_tcp_echo_server)
3332      exec_lua(function()
3333        local port = _G._create_tcp_server('::1')
3334        vim.lsp.start({ name = 'dummy', cmd = vim.lsp.rpc.connect('localhost', port) })
3335      end)
3336      verify_single_notification(function(method, args) ---@param args [string]
3337        eq('body', method)
3338        eq('initialize', vim.json.decode(args[1]).method)
3339      end)
3340    end)
3341
3342    it('can connect to lsp server via pipe or domain_socket', function()
3343      local tmpfile = is_os('win') and '\\\\.\\\\pipe\\pipe.test' or tmpname(false)
3344      local result = exec_lua(function()
3345        local uv = vim.uv
3346        local server = assert(uv.new_pipe(false))
3347        server:bind(tmpfile)
3348        local init = nil
3349
3350        server:listen(127, function(err)
3351          assert(not err, err)
3352          local client = assert(vim.uv.new_pipe())
3353          server:accept(client)
3354          client:read_start(require('vim.lsp.rpc').create_read_loop(function(body)
3355            init = body
3356            client:close()
3357          end))
3358        end)
3359        vim.lsp.start({ name = 'dummy', cmd = vim.lsp.rpc.connect(tmpfile) })
3360        vim.wait(1000, function()
3361          return init ~= nil
3362        end)
3363        assert(init, 'server must receive `initialize` request')
3364        server:close()
3365        server:shutdown()
3366        return vim.json.decode(init)
3367      end)
3368      eq('initialize', result.method)
3369    end)
3370
3371    it('clean up failed lsp client when rpc.connect fails', function()
3372      exec_lua(function()
3373        local server = assert(vim.uv.new_tcp())
3374        server:bind('127.0.0.1', 0)
3375        local port = server:getsockname().port
3376        server:close()
3377        local exited = false
3378        vim.lsp.start({
3379          name = 'dummy',
3380          cmd = vim.lsp.rpc.connect('127.0.0.1', port),
3381          on_exit = function()
3382            exited = true
3383          end,
3384        })
3385        assert(
3386          vim.wait(1000, function()
3387            return #vim.lsp.get_clients({ name = 'dummy', _uninitialized = true }) == 0
3388          end),
3389          'Timed out waiting for errored client to be cleaned up'
3390        )
3391        assert(exited)
3392      end)
3393    end)
3394  end)
3395
3396  describe('handlers', function()
3397    it('handler can return false as response', function()
3398      local result = exec_lua(function()
3399        local server = assert(vim.uv.new_tcp())
3400        local messages = {}
3401        local responses = {}
3402        server:bind('127.0.0.1', 0)
3403        server:listen(127, function(err)
3404          assert(not err, err)
3405          local socket = assert(vim.uv.new_tcp())
3406          server:accept(socket)
3407          socket:read_start(require('vim.lsp.rpc').create_read_loop(function(body)
3408            local payload = vim.json.decode(body)
3409            if payload.method then
3410              table.insert(messages, payload.method)
3411              if payload.method == 'initialize' then
3412                local msg = vim.json.encode({
3413                  id = payload.id,
3414                  jsonrpc = '2.0',
3415                  result = {
3416                    capabilities = {},
3417                  },
3418                })
3419                socket:write(table.concat({ 'Content-Length: ', tostring(#msg), '\r\n\r\n', msg }))
3420              elseif payload.method == 'initialized' then
3421                local msg = vim.json.encode({
3422                  id = 10,
3423                  jsonrpc = '2.0',
3424                  method = 'dummy',
3425                  params = {},
3426                })
3427                socket:write(table.concat({ 'Content-Length: ', tostring(#msg), '\r\n\r\n', msg }))
3428              end
3429            else
3430              table.insert(responses, payload)
3431              socket:close()
3432            end
3433          end))
3434        end)
3435        local port = server:getsockname().port
3436        local handler_called = false
3437        vim.lsp.handlers['dummy'] = function(_, _)
3438          handler_called = true
3439          return false
3440        end
3441        local client_id =
3442          assert(vim.lsp.start({ name = 'dummy', cmd = vim.lsp.rpc.connect('127.0.0.1', port) }))
3443        vim.lsp.get_client_by_id(client_id)
3444        vim.wait(1000, function()
3445          return #messages == 2 and handler_called and #responses == 1
3446        end)
3447        server:close()
3448        server:shutdown()
3449        return {
3450          messages = messages,
3451          handler_called = handler_called,
3452          responses = responses,
3453        }
3454      end)
3455      local expected = {
3456        messages = { 'initialize', 'initialized' },
3457        handler_called = true,
3458        responses = {
3459          {
3460            id = 10,
3461            jsonrpc = '2.0',
3462            result = false,
3463          },
3464        },
3465      }
3466      eq(expected, result)
3467    end)
3468
3469    --- Starts a TCP server that completes initialization, then sends `null_id_payload` after the
3470    --- "initialized" notification.
3471    ---
3472    --- @param null_id_payload string JSON
3473    --- @return { on_error_called: table, notification_received: boolean, messages: boolean }.
3474    local function test_null_id_response(null_id_payload)
3475      return exec_lua(function()
3476        local server = assert(vim.uv.new_tcp())
3477        local accepted
3478        local messages = {}
3479        server:bind('127.0.0.1', 0)
3480        server:listen(127, function(err)
3481          assert(not err, err)
3482          accepted = assert(vim.uv.new_tcp())
3483          server:accept(accepted)
3484          accepted:read_start(require('vim.lsp.rpc').create_read_loop(function(body)
3485            local payload = vim.json.decode(body)
3486            if payload.method then
3487              table.insert(messages, payload.method)
3488              if payload.method == 'initialize' then
3489                -- Send a valid initialize response first
3490                local msg = vim.json.encode({
3491                  id = payload.id,
3492                  jsonrpc = '2.0',
3493                  result = {
3494                    capabilities = {},
3495                  },
3496                })
3497                accepted:write(
3498                  table.concat({ 'Content-Length: ', tostring(#msg), '\r\n\r\n', msg })
3499                )
3500              elseif payload.method == 'initialized' then
3501                accepted:write(table.concat({
3502                  'Content-Length: ',
3503                  tostring(#null_id_payload),
3504                  '\r\n\r\n',
3505                  null_id_payload,
3506                }))
3507              end
3508            end
3509          end, function()
3510            if accepted and not accepted:is_closing() then
3511              accepted:close()
3512            end
3513          end, function()
3514            if accepted and not accepted:is_closing() then
3515              accepted:close()
3516            end
3517          end))
3518        end)
3519        local port = server:getsockname().port
3520        local on_error_called = false
3521        local notification_received = false
3522        local client_id = assert(vim.lsp.start({
3523          name = 'null-id-test',
3524          cmd = function(dispatchers)
3525            local notification = dispatchers.notification
3526            dispatchers.notification = function(method, params)
3527              notification_received = true
3528              if notification then
3529                notification(method, params)
3530              end
3531            end
3532            return vim.lsp.rpc.connect('127.0.0.1', port)(dispatchers)
3533          end,
3534          on_error = function(_code, _err)
3535            on_error_called = true
3536          end,
3537        }))
3538        vim.lsp.get_client_by_id(client_id)
3539        vim.wait(1000, function()
3540          return #messages >= 2 and (on_error_called or notification_received)
3541        end)
3542        if accepted and not accepted:is_closing() then
3543          accepted:close()
3544        end
3545        server:shutdown()
3546        server:close()
3547        return {
3548          messages = messages,
3549          on_error_called = on_error_called,
3550          notification_received = notification_received,
3551        }
3552      end)
3553    end
3554
3555    it('null-id in response (JSON-RPC 2.0 parse error) is handled, emits error', function()
3556      local result = test_null_id_response(
3557        '{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"},"id":null}'
3558      )
3559      eq(true, result.on_error_called)
3560      eq(true, #result.messages >= 2)
3561    end)
3562
3563    it('null-id in response does not misclassify as a notification', function()
3564      -- Sanity check: a real notification (no id) dispatches the handler.
3565      local valid = test_null_id_response(
3566        '{"jsonrpc":"2.0","method":"workspace/configuration","params":{"items":[]}}'
3567      )
3568      eq(true, valid.notification_received)
3569
3570      local result = test_null_id_response(
3571        -- Error response with null id (parse error per JSON-RPC 2.0 §5)
3572        '{"jsonrpc":"2.0","method":"workspace/configuration","params":{"items":[]},"id":null}'
3573      )
3574      -- Null id must be dispatched as a request, not as a notification.
3575      eq(false, result.notification_received)
3576    end)
3577  end)
3578
3579  describe('#dynamic vim.lsp._dynamic', function()
3580    it('supports dynamic registration', function()
3581      local root_dir = tmpname(false)
3582      mkdir(root_dir)
3583      local tmpfile = root_dir .. '/dynamic.foo'
3584      local file = io.open(tmpfile, 'w')
3585      if file then
3586        file:close()
3587      end
3588
3589      exec_lua(create_server_definition)
3590      local result = exec_lua(function()
3591        local server = _G._create_server()
3592        local client_id = assert(vim.lsp.start({
3593          name = 'dynamic-test',
3594          cmd = server.cmd,
3595          root_dir = root_dir,
3596          get_language_id = function()
3597            return 'dummy-lang'
3598          end,
3599          capabilities = {
3600            textDocument = {
3601              formatting = {
3602                dynamicRegistration = true,
3603              },
3604              rangeFormatting = {
3605                dynamicRegistration = true,
3606              },
3607            },
3608            workspace = {
3609              didChangeWatchedFiles = {
3610                dynamicRegistration = true,
3611              },
3612              didChangeConfiguration = {
3613                dynamicRegistration = true,
3614              },
3615              fileOperations = {
3616                didCreate = {
3617                  dynamicRegistration = true,
3618                },
3619              },
3620              textDocumentContent = {
3621                dynamicRegistration = true,
3622              },
3623            },
3624          },
3625        }))
3626
3627        vim.lsp.handlers['client/registerCapability'](nil, {
3628          registrations = {
3629            {
3630              id = 'formatting',
3631              method = 'textDocument/formatting',
3632              registerOptions = {
3633                documentSelector = {
3634                  {
3635                    pattern = root_dir .. '/*.foo',
3636                  },
3637                  { pattern = '**/**.foo' },
3638                },
3639              },
3640            },
3641          },
3642        }, { client_id = client_id })
3643
3644        vim.lsp.handlers['client/registerCapability'](nil, {
3645          registrations = {
3646            {
3647              id = 'range-formatting',
3648              method = 'textDocument/rangeFormatting',
3649              registerOptions = {
3650                documentSelector = {
3651                  {
3652                    language = 'dummy-lang',
3653                  },
3654                },
3655              },
3656            },
3657          },
3658        }, { client_id = client_id })
3659
3660        vim.lsp.handlers['client/registerCapability'](nil, {
3661          registrations = {
3662            {
3663              id = 'completion',
3664              method = 'textDocument/completion',
3665            },
3666          },
3667        }, { client_id = client_id })
3668
3669        local result = {}
3670        local function check(method, fname, ...)
3671          local bufnr = fname and vim.fn.bufadd(fname) or nil
3672          local client = assert(vim.lsp.get_client_by_id(client_id))
3673          local keys = { ... }
3674          local caps = {}
3675          if #keys > 0 then
3676            client:_provider_foreach(method, function(cap)
3677              table.insert(caps, vim.tbl_get(cap, unpack(keys)) or vim.NIL)
3678            end)
3679          end
3680          result[#result + 1] = {
3681            method = method,
3682            fname = fname,
3683            supported = client:supports_method(method, bufnr),
3684            cap = #keys > 0 and caps or nil,
3685          }
3686        end
3687
3688        check('textDocument/formatting')
3689        check('textDocument/formatting', tmpfile)
3690        check('textDocument/rangeFormatting')
3691        check('textDocument/rangeFormatting', tmpfile)
3692        check('textDocument/completion')
3693
3694        check('workspace/didChangeWatchedFiles')
3695        check('workspace/didChangeWatchedFiles', tmpfile)
3696
3697        vim.lsp.handlers['client/registerCapability'](nil, {
3698          registrations = {
3699            {
3700              id = 'didChangeWatched',
3701              method = 'workspace/didChangeWatchedFiles',
3702              registerOptions = {
3703                watchers = {
3704                  {
3705                    globPattern = 'something',
3706                    kind = 4,
3707                  },
3708                },
3709              },
3710            },
3711          },
3712        }, { client_id = client_id })
3713
3714        check('workspace/didChangeWatchedFiles')
3715        check('workspace/didChangeWatchedFiles', tmpfile)
3716
3717        -- Initial support false
3718        check('workspace/diagnostic')
3719
3720        vim.lsp.handlers['client/registerCapability'](nil, {
3721          registrations = {
3722            {
3723              id = 'diag1',
3724              method = 'textDocument/diagnostic',
3725              registerOptions = {
3726                identifier = 'diag-ident-1',
3727                -- workspaceDiagnostics field omitted
3728              },
3729            },
3730          },
3731        }, { client_id = client_id })
3732
3733        -- Checks after registering without workspaceDiagnostics support
3734        -- Returns false
3735        check('workspace/diagnostic', nil, 'identifier')
3736
3737        vim.lsp.handlers['client/registerCapability'](nil, {
3738          registrations = {
3739            {
3740              id = 'diag2',
3741              method = 'textDocument/diagnostic',
3742              registerOptions = {
3743                identifier = 'diag-ident-2',
3744                workspaceDiagnostics = true,
3745              },
3746            },
3747          },
3748        }, { client_id = client_id })
3749
3750        -- Check after second registration with support
3751        -- Returns true
3752        check('workspace/diagnostic', nil, 'identifier')
3753
3754        vim.lsp.handlers['client/unregisterCapability'](nil, {
3755          unregisterations = {
3756            { id = 'diag2', method = 'textDocument/diagnostic' },
3757          },
3758        }, { client_id = client_id })
3759
3760        -- Check after unregistering
3761        -- Returns false
3762        check('workspace/diagnostic', nil, 'identifier')
3763
3764        check('textDocument/codeAction')
3765        check('codeAction/resolve')
3766
3767        vim.lsp.handlers['client/registerCapability'](nil, {
3768          registrations = {
3769            {
3770              id = 'codeAction',
3771              method = 'textDocument/codeAction',
3772              registerOptions = {
3773                resolveProvider = true,
3774              },
3775            },
3776          },
3777        }, { client_id = client_id })
3778
3779        check('textDocument/codeAction')
3780        check('codeAction/resolve')
3781
3782        check('workspace/didChangeWorkspaceFolders')
3783        vim.lsp.handlers['client/registerCapability'](nil, {
3784          registrations = {
3785            {
3786              id = 'didChangeWorkspaceFolders-id',
3787              method = 'workspace/didChangeWorkspaceFolders',
3788            },
3789          },
3790        }, { client_id = client_id })
3791        check('workspace/didChangeWorkspaceFolders')
3792
3793        check('workspace/didChangeConfiguration')
3794        vim.lsp.handlers['client/registerCapability'](nil, {
3795          registrations = {
3796            {
3797              id = 'didChangeConfiguration-id',
3798              method = 'workspace/didChangeConfiguration',
3799              registerOptions = {
3800                section = 'dummy-section',
3801              },
3802            },
3803          },
3804        }, { client_id = client_id })
3805        check('workspace/didChangeConfiguration', nil, 'section')
3806
3807        check('workspace/didCreateFiles')
3808        vim.lsp.handlers['client/registerCapability'](nil, {
3809          registrations = {
3810            {
3811              id = 'didCreateFiles-id',
3812              method = 'workspace/didCreateFiles',
3813              registerOptions = {
3814                label = 'did-create-files',
3815                filters = {
3816                  {
3817                    scheme = 'file',
3818                    pattern = {
3819                      glob = '**/*.foo',
3820                    },
3821                  },
3822                },
3823              },
3824            },
3825          },
3826        }, { client_id = client_id })
3827        check('workspace/didCreateFiles', nil, 'label')
3828
3829        check('workspace/textDocumentContent')
3830        vim.lsp.handlers['client/registerCapability'](nil, {
3831          registrations = {
3832            {
3833              id = 'textDocumentContent-id',
3834              method = 'workspace/textDocumentContent',
3835              registerOptions = {
3836                schemes = { 'git', 'untitled' },
3837              },
3838            },
3839          },
3840        }, { client_id = client_id })
3841        check('workspace/textDocumentContent', nil, 'schemes')
3842
3843        vim.lsp.handlers['client/registerCapability'](nil, {
3844          registrations = {
3845            {
3846              id = 'unknown-method-id',
3847              method = 'unknown-method',
3848              registerOptions = {
3849                some_opt = 'unknown-dummy-opt',
3850              },
3851            },
3852          },
3853        }, { client_id = client_id })
3854        check('unknown-method', nil, 'some_opt')
3855
3856        check('unknown-method-2')
3857        vim.lsp.handlers['client/registerCapability'](nil, {
3858          registrations = {
3859            {
3860              id = 'unknown-method-2-id',
3861              method = 'unknown-method-2',
3862              registerOptions = {
3863                documentSelector = {
3864                  {
3865                    pattern = root_dir .. '/*.foo',
3866                  },
3867                },
3868              },
3869            },
3870          },
3871        }, { client_id = client_id })
3872        check('unknown-method-2')
3873        check('unknown-method-2', tmpfile)
3874
3875        return result
3876      end)
3877
3878      eq(29, #result)
3879      eq({ method = 'textDocument/formatting', supported = false }, result[1])
3880      eq({ method = 'textDocument/formatting', supported = true, fname = tmpfile }, result[2])
3881      eq({ method = 'textDocument/rangeFormatting', supported = true }, result[3])
3882      eq({ method = 'textDocument/rangeFormatting', supported = true, fname = tmpfile }, result[4])
3883      eq({ method = 'textDocument/completion', supported = false }, result[5])
3884      eq({ method = 'workspace/didChangeWatchedFiles', supported = false }, result[6])
3885      eq(
3886        { method = 'workspace/didChangeWatchedFiles', supported = false, fname = tmpfile },
3887        result[7]
3888      )
3889      eq({ method = 'workspace/didChangeWatchedFiles', supported = true }, result[8])
3890      eq(
3891        { method = 'workspace/didChangeWatchedFiles', supported = true, fname = tmpfile },
3892        result[9]
3893      )
3894      eq({ method = 'workspace/diagnostic', supported = false }, result[10])
3895      eq({ method = 'workspace/diagnostic', supported = false, cap = {} }, result[11])
3896      eq({
3897        method = 'workspace/diagnostic',
3898        supported = true,
3899        cap = { 'diag-ident-2' },
3900      }, result[12])
3901      eq({ method = 'workspace/diagnostic', supported = false, cap = {} }, result[13])
3902      eq({ method = 'textDocument/codeAction', supported = false }, result[14])
3903      eq({ method = 'codeAction/resolve', supported = false }, result[15])
3904      eq({ method = 'textDocument/codeAction', supported = true }, result[16])
3905      eq({ method = 'codeAction/resolve', supported = true }, result[17])
3906      eq({ method = 'workspace/didChangeWorkspaceFolders', supported = false }, result[18])
3907      eq({ method = 'workspace/didChangeWorkspaceFolders', supported = true }, result[19])
3908      eq({ method = 'workspace/didChangeConfiguration', supported = false }, result[20])
3909      eq(
3910        { method = 'workspace/didChangeConfiguration', supported = true, cap = { 'dummy-section' } },
3911        result[21]
3912      )
3913      eq({ method = 'workspace/didCreateFiles', supported = false }, result[22])
3914      eq(
3915        { method = 'workspace/didCreateFiles', supported = true, cap = { 'did-create-files' } },
3916        result[23]
3917      )
3918      eq({ method = 'workspace/textDocumentContent', supported = false }, result[24])
3919      eq({
3920        method = 'workspace/textDocumentContent',
3921        supported = true,
3922        cap = { { 'git', 'untitled' } },
3923      }, result[25])
3924      eq({
3925        method = 'unknown-method',
3926        supported = true,
3927        cap = { 'unknown-dummy-opt' },
3928      }, result[26])
3929      eq({ method = 'unknown-method-2', supported = true }, result[27])
3930      eq({ method = 'unknown-method-2', supported = false }, result[28])
3931      eq({ method = 'unknown-method-2', supported = true, fname = tmpfile }, result[29])
3932    end)
3933
3934    it('identifies client dynamic registration capability', function()
3935      exec_lua(create_server_definition)
3936      local result = exec_lua(function()
3937        local server = _G._create_server()
3938        local client_id = assert(vim.lsp.start({
3939          name = 'dynamic-test',
3940          cmd = server.cmd,
3941          capabilities = {
3942            textDocument = {
3943              formatting = {
3944                dynamicRegistration = true,
3945              },
3946              synchronization = {
3947                dynamicRegistration = true,
3948              },
3949              diagnostic = {
3950                dynamicRegistration = true,
3951              },
3952            },
3953          },
3954        }))
3955
3956        local result = {}
3957        local function check(method)
3958          local client = assert(vim.lsp.get_client_by_id(client_id))
3959          result[#result + 1] = {
3960            method = method,
3961            supports_reg = client:_supports_registration(method),
3962          }
3963        end
3964
3965        check('textDocument/formatting')
3966        check('textDocument/didSave')
3967        check('textDocument/didOpen')
3968        check('textDocument/codeLens')
3969        check('textDocument/diagnostic')
3970        check('workspace/diagnostic')
3971
3972        return result
3973      end)
3974
3975      eq(6, #result)
3976      eq({ method = 'textDocument/formatting', supports_reg = true }, result[1])
3977      eq({ method = 'textDocument/didSave', supports_reg = true }, result[2])
3978      eq({ method = 'textDocument/didOpen', supports_reg = true }, result[3])
3979      eq({ method = 'textDocument/codeLens', supports_reg = false }, result[4])
3980      eq({ method = 'textDocument/diagnostic', supports_reg = true }, result[5])
3981      eq({ method = 'workspace/diagnostic', supports_reg = true }, result[6])
3982    end)
3983
3984    it('supports static registration', function()
3985      exec_lua(create_server_definition)
3986
3987      local client_id = exec_lua(function()
3988        local server = _G._create_server({
3989          capabilities = {
3990            colorProvider = { id = 'color-registration' },
3991            diagnosticProvider = {
3992              documentSelector = vim.NIL,
3993              interFileDependencies = false,
3994              id = 'diag-registration',
3995              identifier = 'diag-ident-static',
3996              workspaceDiagnostics = true,
3997            },
3998            workspace = {
3999              textDocumentContent = {
4000                id = 'text-document-content-registration',
4001                schemes = { 'git', 'untitled' },
4002              },
4003            },
4004          },
4005        })
4006
4007        return assert(vim.lsp.start({ name = 'dynamic-test', cmd = server.cmd }))
4008      end)
4009
4010      local function sort_method(tbl)
4011        local result_t = vim.deepcopy(tbl)
4012        table.sort(result_t, function(a, b)
4013          return (a.method or '') < (b.method or '')
4014        end)
4015        return result_t
4016      end
4017
4018      eq(
4019        {
4020          {
4021            id = 'color-registration',
4022            method = 'textDocument/colorPresentation',
4023            registerOptions = { id = 'color-registration' },
4024          },
4025          {
4026            id = 'color-registration',
4027            method = 'textDocument/documentColor',
4028            registerOptions = { id = 'color-registration' },
4029          },
4030        },
4031        sort_method(exec_lua(function()
4032          local client = assert(vim.lsp.get_client_by_id(client_id))
4033          return client.dynamic_capabilities:get('colorProvider')
4034        end))
4035      )
4036
4037      eq(
4038        {
4039          {
4040            id = 'diag-registration',
4041            method = 'textDocument/diagnostic',
4042            registerOptions = {
4043              documentSelector = vim.NIL,
4044              interFileDependencies = false,
4045              id = 'diag-registration',
4046              identifier = 'diag-ident-static',
4047              workspaceDiagnostics = true,
4048            },
4049          },
4050        },
4051        sort_method(exec_lua(function()
4052          local client = assert(vim.lsp.get_client_by_id(client_id))
4053          return client.dynamic_capabilities:get('diagnosticProvider')
4054        end))
4055      )
4056
4057      eq(
4058        { 'diag-ident-static' },
4059        exec_lua(function()
4060          local client = assert(vim.lsp.get_client_by_id(client_id))
4061          local result = {}
4062          client:_provider_foreach('textDocument/diagnostic', function(cap)
4063            table.insert(result, cap.identifier)
4064          end)
4065          return result
4066        end)
4067      )
4068
4069      eq(
4070        {
4071          {
4072            id = 'text-document-content-registration',
4073            method = 'workspace/textDocumentContent',
4074            registerOptions = {
4075              id = 'text-document-content-registration',
4076              schemes = { 'git', 'untitled' },
4077            },
4078          },
4079        },
4080        sort_method(exec_lua(function()
4081          local client = assert(vim.lsp.get_client_by_id(client_id))
4082          return client.dynamic_capabilities:get('workspace.textDocumentContent')
4083        end))
4084      )
4085
4086      eq(
4087        { { 'git', 'untitled' } },
4088        exec_lua(function()
4089          local client = assert(vim.lsp.get_client_by_id(client_id))
4090          local result = {}
4091          client:_provider_foreach('workspace/textDocumentContent', function(cap)
4092            table.insert(result, cap.schemes)
4093          end)
4094          return result
4095        end)
4096      )
4097    end)
4098  end)
4099
4100  describe('vim.lsp._watchfiles', function()
4101    --- @type integer, integer, integer
4102    local created, changed, deleted
4103
4104    setup(function()
4105      n.clear()
4106      created = exec_lua([[return vim.lsp.protocol.FileChangeType.Created]])
4107      changed = exec_lua([[return vim.lsp.protocol.FileChangeType.Changed]])
4108      deleted = exec_lua([[return vim.lsp.protocol.FileChangeType.Deleted]])
4109    end)
4110
4111    before_each(function()
4112      exec_lua(create_server_definition)
4113      exec_lua(function()
4114        _G.start_watchfiles_client = function(root_dir)
4115          local server = _G._create_server()
4116          local client_id = assert(vim.lsp.start({
4117            name = 'watchfiles-test',
4118            cmd = server.cmd,
4119            root_dir = root_dir,
4120            capabilities = {
4121              workspace = { didChangeWatchedFiles = { dynamicRegistration = true } },
4122            },
4123          }))
4124
4125          local function wait_for_messages(count)
4126            assert(
4127              vim.wait(2500, function()
4128                return #server.messages == count
4129              end),
4130              'Timed out waiting for messages: ' .. vim.inspect(server.messages)
4131            )
4132          end
4133
4134          wait_for_messages(2) -- initialize, initialized
4135          return assert(vim.lsp.get_client_by_id(client_id)), server, wait_for_messages
4136        end
4137
4138        -- Mock the process so glob compilation, sharing, and event delivery still run.
4139        _G.mock_watch = function()
4140          local watchers = {}
4141          vim.lsp._watchfiles._watchfunc = vim._watch.inotify
4142          vim.system = function(_, opts)
4143            watchers[#watchers + 1] = opts
4144            return {
4145              kill = function()
4146                assert(not opts.stopped, 'watcher cancelled twice')
4147                opts.stopped = true
4148              end,
4149            }
4150          end
4151
4152          local function send_event(path, change_type)
4153            local event = ({ 'CREATE', 'MODIFY', 'DELETE' })[change_type]
4154            for _, opts in ipairs(watchers) do
4155              if not opts.stopped then
4156                opts.stdout(
4157                  nil,
4158                  vim.fs.dirname(path) .. ' ' .. event .. ' ' .. vim.fs.basename(path)
4159                )
4160              end
4161            end
4162          end
4163
4164          return watchers, send_event
4165        end
4166      end)
4167    end)
4168
4169    local function test_filechanges(watchfunc, root_change)
4170      it(
4171        string.format(
4172          'sends notifications when files change (watchfunc=%s)%s',
4173          watchfunc,
4174          root_change and (' after root is ' .. root_change) or ''
4175        ),
4176        function()
4177          if watchfunc == 'inotify' then
4178            skip(is_os('win'), 'not supported on windows')
4179            skip(is_os('mac'), 'flaky test on mac')
4180            skip(
4181              not is_ci() and fn.executable('inotifywait') == 0,
4182              'inotify-tools not installed and not on CI'
4183            )
4184            skip(t.is_arch('s390x'), 'inotifywait not available on s390x CI')
4185          end
4186
4187          if watchfunc == 'watch' then
4188            skip(is_os('mac'), 'flaky test on mac')
4189            skip(
4190              is_os('bsd'),
4191              'Stopped working on bsd after 3ca967387c49c754561c3b11a574797504d40f38'
4192            )
4193          else
4194            skip(
4195              is_os('bsd'),
4196              'kqueue only reports events on watched folder itself, not contained files #26110'
4197            )
4198          end
4199
4200          local root_dir = tmpname(false)
4201          if root_change ~= 'created' then
4202            mkdir(root_dir)
4203          end
4204
4205          local result = exec_lua(function()
4206            local logfile = vim.lsp.log.get_filename()
4207            vim.lsp.log.set_level('info')
4208            vim.fn.writefile({ '' }, logfile)
4209            local notifications = {}
4210            vim.notify = function(message, level)
4211              notifications[#notifications + 1] = { message, level }
4212            end
4213            local client, server, wait_for_messages = _G.start_watchfiles_client(root_dir)
4214
4215            vim.lsp._watchfiles._watchfunc = vim._watch[watchfunc]
4216
4217            vim.lsp.handlers['client/registerCapability'](nil, {
4218              registrations = {
4219                {
4220                  id = 'watchfiles-test-0',
4221                  method = 'workspace/didChangeWatchedFiles',
4222                  registerOptions = {
4223                    watchers = {
4224                      {
4225                        globPattern = 'a/**b',
4226                        kind = 7,
4227                      },
4228                      {
4229                        globPattern = {
4230                          baseUri = vim.uri_from_fname(root_dir),
4231                          pattern = '{foo}',
4232                        },
4233                        kind = 7,
4234                      },
4235                      {
4236                        globPattern = '**/watch',
4237                        kind = 7,
4238                      },
4239                    },
4240                  },
4241                },
4242              },
4243            }, { client_id = client.id })
4244
4245            if root_change then
4246              local method = 'workspace/didChangeWatchedFiles'
4247              local reg = vim.deepcopy(client.registrations[method][1])
4248              if root_change == 'replaced' then
4249                -- Allocate a different inode before deleting the original directory.
4250                vim.fn.mkdir(root_dir .. '-replacement')
4251                assert(vim.uv.fs_rmdir(root_dir))
4252                assert(vim.uv.fs_rename(root_dir .. '-replacement', root_dir))
4253              else
4254                reg.id = 'watchfiles-test-missing'
4255                client:_register({ reg })
4256                client:_unregister({ { id = reg.id, method = method } })
4257                vim.fn.mkdir(root_dir)
4258              end
4259              reg.id = 'watchfiles-test-1'
4260              client:_register({ reg })
4261              client:_unregister({ { id = 'watchfiles-test-0', method = method } })
4262            end
4263
4264            if watchfunc ~= 'watch' then
4265              vim.wait(100)
4266            end
4267
4268            local path = root_dir .. '/watch'
4269            local tmp = vim.fn.tempname()
4270            io.open(tmp, 'w'):close()
4271            vim.uv.fs_rename(tmp, path)
4272
4273            wait_for_messages(3)
4274
4275            os.remove(path)
4276
4277            wait_for_messages(4)
4278
4279            client:stop()
4280
4281            return { logfile = logfile, messages = server.messages, notifications = notifications }
4282          end)
4283
4284          local uri = vim.uri_from_fname(root_dir .. '/watch')
4285          local messages = result.messages
4286
4287          eq(6, #messages)
4288
4289          eq({
4290            method = 'workspace/didChangeWatchedFiles',
4291            params = {
4292              changes = {
4293                {
4294                  type = created,
4295                  uri = uri,
4296                },
4297              },
4298            },
4299          }, messages[3])
4300
4301          eq({
4302            method = 'workspace/didChangeWatchedFiles',
4303            params = {
4304              changes = {
4305                {
4306                  type = deleted,
4307                  uri = uri,
4308                },
4309              },
4310            },
4311          }, messages[4])
4312
4313          eq(root_change == 'created' and 3 or 2, #result.notifications)
4314          for i, pattern in ipairs({ 'a/**b', '{foo}' }) do
4315            t.assert_log('%[ERROR%].-Invalid glob.-' .. pesc(pattern), result.logfile)
4316            local message, level = unpack(result.notifications[i])
4317            eq(vim.log.levels.ERROR, level)
4318            matches('Invalid glob.-' .. pesc(pattern), message)
4319            matches(pesc('(watching ' .. root_dir .. ')'), message)
4320          end
4321          if root_change == 'created' then
4322            t.assert_log('%[INFO%].-ENOENT:.-' .. pesc(root_dir), result.logfile)
4323            eq(vim.log.levels.INFO, result.notifications[3][2])
4324            matches('file watcher failed: ENOENT:.-' .. pesc(root_dir), result.notifications[3][1])
4325          end
4326        end
4327      )
4328    end
4329
4330    test_filechanges('watch')
4331    test_filechanges('watchdirs')
4332    test_filechanges('inotify')
4333    test_filechanges('watchdirs', 'created')
4334    test_filechanges('watch', 'replaced')
4335    test_filechanges('watchdirs', 'replaced')
4336
4337    for _, stop_client in ipairs({ false, true }) do
4338      it(
4339        'shares identical registrations until ' .. (stop_client and 'client stop' or 'unregister'),
4340        function()
4341          local root_dir = tmpname(false)
4342          mkdir(root_dir)
4343          t.finally(function()
4344            n.rmdir(root_dir)
4345          end)
4346          local result = exec_lua(function(stop_client_)
4347            local client, server, wait_for_messages = _G.start_watchfiles_client(root_dir)
4348
4349            local watchers, send_event = _G.mock_watch()
4350            -- Repeating an ID must neither restart the watcher nor add an owner.
4351            for _, id in ipairs({ 'a', 'a', 'b', 'c', 'c' }) do
4352              client:_register({
4353                {
4354                  id = id,
4355                  method = 'workspace/didChangeWatchedFiles',
4356                  registerOptions = { watchers = { { globPattern = '**/*.py' } } },
4357                },
4358              })
4359            end
4360            assert(#watchers == 1, 'identical registrations must share one watcher')
4361
4362            client:_unregister({ { id = 'a', method = 'workspace/didChangeWatchedFiles' } })
4363            if not stop_client_ then
4364              client:_unregister({ { id = 'b', method = 'workspace/didChangeWatchedFiles' } })
4365            end
4366            assert(not watchers[1].stopped, 'watcher cancelled while registrations remain')
4367            send_event(root_dir .. '/file.py', vim._watch.FileChangeType.Created)
4368            send_event(root_dir .. '/file.txt', vim._watch.FileChangeType.Created)
4369            wait_for_messages(3)
4370            if stop_client_ then
4371              client:stop(true)
4372            else
4373              client:_unregister({ { id = 'c', method = 'workspace/didChangeWatchedFiles' } })
4374            end
4375            assert(watchers[1].stopped, 'watcher not cancelled after its last registration')
4376            return server.messages[3]
4377          end, stop_client)
4378
4379          eq({
4380            method = 'workspace/didChangeWatchedFiles',
4381            params = {
4382              changes = { { uri = vim.uri_from_fname(root_dir .. '/file.py'), type = created } },
4383            },
4384          }, result)
4385        end
4386      )
4387    end
4388
4389    it('correctly registers and unregisters', function()
4390      local root_dir = '/some_dir'
4391      local result = exec_lua(function()
4392        local client, server, wait_for_messages = _G.start_watchfiles_client(root_dir)
4393
4394        local _, send_event = _G.mock_watch()
4395
4396        vim.lsp.handlers['client/registerCapability'](nil, {
4397          registrations = {
4398            {
4399              id = 'watchfiles-test-0',
4400              method = 'workspace/didChangeWatchedFiles',
4401              registerOptions = {
4402                watchers = {
4403                  {
4404                    globPattern = '**/*.watch0',
4405                  },
4406                },
4407              },
4408            },
4409          },
4410        }, { client_id = client.id })
4411
4412        send_event(root_dir .. '/file.watch0', vim._watch.FileChangeType.Created)
4413        send_event(root_dir .. '/file.watch1', vim._watch.FileChangeType.Created)
4414
4415        wait_for_messages(3)
4416
4417        vim.lsp.handlers['client/registerCapability'](nil, {
4418          registrations = {
4419            {
4420              id = 'watchfiles-test-1',
4421              method = 'workspace/didChangeWatchedFiles',
4422              registerOptions = {
4423                watchers = {
4424                  {
4425                    globPattern = '**/*.watch1',
4426                  },
4427                },
4428              },
4429            },
4430          },
4431        }, { client_id = client.id })
4432
4433        vim.lsp.handlers['client/unregisterCapability'](nil, {
4434          unregisterations = {
4435            {
4436              id = 'watchfiles-test-0',
4437              method = 'workspace/didChangeWatchedFiles',
4438            },
4439          },
4440        }, { client_id = client.id })
4441
4442        send_event(root_dir .. '/file.watch0', vim._watch.FileChangeType.Created)
4443        send_event(root_dir .. '/file.watch1', vim._watch.FileChangeType.Created)
4444
4445        wait_for_messages(4)
4446
4447        return server.messages
4448      end)
4449
4450      local function watched_uri(fname)
4451        return vim.uri_from_fname(root_dir .. '/' .. fname)
4452      end
4453
4454      eq(4, #result)
4455      eq('workspace/didChangeWatchedFiles', result[3].method)
4456      eq({
4457        changes = {
4458          {
4459            type = created,
4460            uri = watched_uri('file.watch0'),
4461          },
4462        },
4463      }, result[3].params)
4464      eq('workspace/didChangeWatchedFiles', result[4].method)
4465      eq({
4466        changes = {
4467          {
4468            type = created,
4469            uri = watched_uri('file.watch1'),
4470          },
4471        },
4472      }, result[4].params)
4473    end)
4474
4475    it('correctly handles the registered watch kind with a literal baseUri', function()
4476      local root_dir = 'some_dir'
4477      local result = exec_lua(function()
4478        local client, server, wait_for_messages = _G.start_watchfiles_client(root_dir)
4479
4480        local _, send_event = _G.mock_watch()
4481
4482        local protocol = require('vim.lsp.protocol')
4483
4484        local watchers = {}
4485        local max_kind = protocol.WatchKind.Create
4486          + protocol.WatchKind.Change
4487          + protocol.WatchKind.Delete
4488        for i = 0, max_kind do
4489          table.insert(watchers, {
4490            globPattern = {
4491              baseUri = vim.uri_from_fname('/dir[1]'),
4492              pattern = 'watch' .. tostring(i),
4493            },
4494            kind = i,
4495          })
4496        end
4497        vim.lsp.handlers['client/registerCapability'](nil, {
4498          registrations = {
4499            {
4500              id = 'watchfiles-test-kind',
4501              method = 'workspace/didChangeWatchedFiles',
4502              registerOptions = {
4503                watchers = watchers,
4504              },
4505            },
4506          },
4507        }, { client_id = client.id })
4508
4509        for i = 0, max_kind do
4510          send_event('/dir1/watch' .. tostring(i), vim._watch.FileChangeType.Created)
4511          local filename = '/dir[1]/watch' .. tostring(i)
4512          send_event(filename, vim._watch.FileChangeType.Created)
4513          send_event(filename, vim._watch.FileChangeType.Changed)
4514          send_event(filename, vim._watch.FileChangeType.Deleted)
4515        end
4516
4517        wait_for_messages(3)
4518
4519        return server.messages
4520      end)
4521
4522      local function watched_uri(fname)
4523        return vim.uri_from_fname('/dir[1]/' .. fname)
4524      end
4525
4526      eq(3, #result)
4527      eq('workspace/didChangeWatchedFiles', result[3].method)
4528      eq({
4529        changes = {
4530          {
4531            type = created,
4532            uri = watched_uri('watch1'),
4533          },
4534          {
4535            type = changed,
4536            uri = watched_uri('watch2'),
4537          },
4538          {
4539            type = created,
4540            uri = watched_uri('watch3'),
4541          },
4542          {
4543            type = changed,
4544            uri = watched_uri('watch3'),
4545          },
4546          {
4547            type = deleted,
4548            uri = watched_uri('watch4'),
4549          },
4550          {
4551            type = created,
4552            uri = watched_uri('watch5'),
4553          },
4554          {
4555            type = deleted,
4556            uri = watched_uri('watch5'),
4557          },
4558          {
4559            type = changed,
4560            uri = watched_uri('watch6'),
4561          },
4562          {
4563            type = deleted,
4564            uri = watched_uri('watch6'),
4565          },
4566          {
4567            type = created,
4568            uri = watched_uri('watch7'),
4569          },
4570          {
4571            type = changed,
4572            uri = watched_uri('watch7'),
4573          },
4574          {
4575            type = deleted,
4576            uri = watched_uri('watch7'),
4577          },
4578        },
4579      }, result[3].params)
4580    end)
4581
4582    it('prunes duplicate events', function()
4583      local root_dir = 'some_dir'
4584      local result = exec_lua(function()
4585        local client, server, wait_for_messages = _G.start_watchfiles_client(root_dir)
4586
4587        local send_event --- @type function
4588        require('vim.lsp._watchfiles')._watchfunc = function(_, _, callback)
4589          send_event = callback
4590          return function()
4591            -- noop because this test never stops the watch
4592          end
4593        end
4594
4595        vim.lsp.handlers['client/registerCapability'](nil, {
4596          registrations = {
4597            {
4598              id = 'watchfiles-test-kind',
4599              method = 'workspace/didChangeWatchedFiles',
4600              registerOptions = {
4601                watchers = {
4602                  {
4603                    globPattern = '**/*',
4604                  },
4605                },
4606              },
4607            },
4608          },
4609        }, { client_id = client.id })
4610
4611        send_event('file1', vim._watch.FileChangeType.Created)
4612        send_event('file1', vim._watch.FileChangeType.Created) -- pruned
4613        send_event('file1', vim._watch.FileChangeType.Changed)
4614        send_event('file2', vim._watch.FileChangeType.Created)
4615        send_event('file1', vim._watch.FileChangeType.Changed) -- pruned
4616
4617        wait_for_messages(3)
4618
4619        return server.messages
4620      end)
4621
4622      eq(3, #result)
4623      eq('workspace/didChangeWatchedFiles', result[3].method)
4624      eq({
4625        changes = {
4626          {
4627            type = created,
4628            uri = vim.uri_from_fname('file1'),
4629          },
4630          {
4631            type = changed,
4632            uri = vim.uri_from_fname('file1'),
4633          },
4634          {
4635            type = created,
4636            uri = vim.uri_from_fname('file2'),
4637          },
4638        },
4639      }, result[3].params)
4640    end)
4641
4642    it("ignores registrations by servers when the client doesn't advertise support", function()
4643      exec_lua(function()
4644        _G.server = _G._create_server()
4645        require('vim.lsp._watchfiles')._watchfunc = function(_, _, _)
4646          -- Since the registration is ignored, this should not execute and `watching` should stay false
4647          _G.watching = true
4648          return function() end
4649        end
4650      end)
4651
4652      local function check_registered(capabilities)
4653        return exec_lua(function()
4654          _G.watching = false
4655          local client_id = assert(vim.lsp.start({
4656            name = 'watchfiles-test',
4657            cmd = _G.server.cmd,
4658            root_dir = 'some_dir',
4659            capabilities = capabilities,
4660          }, {
4661            reuse_client = function()
4662              return false
4663            end,
4664          }))
4665
4666          vim.lsp.handlers['client/registerCapability'](nil, {
4667            registrations = {
4668              {
4669                id = 'watchfiles-test-kind',
4670                method = 'workspace/didChangeWatchedFiles',
4671                registerOptions = {
4672                  watchers = {
4673                    {
4674                      globPattern = '**/*',
4675                    },
4676                  },
4677                },
4678              },
4679            },
4680          }, { client_id = client_id })
4681
4682          -- Ensure no errors occur when unregistering something that was never really registered.
4683          vim.lsp.handlers['client/unregisterCapability'](nil, {
4684            unregisterations = {
4685              {
4686                id = 'watchfiles-test-kind',
4687                method = 'workspace/didChangeWatchedFiles',
4688              },
4689            },
4690          }, { client_id = client_id })
4691
4692          vim.lsp.get_client_by_id(client_id):stop(true)
4693          return _G.watching
4694        end)
4695      end
4696
4697      eq(is_os('mac') or is_os('win'), check_registered(nil)) -- start{_client}() defaults to make_client_capabilities().
4698      eq(
4699        false,
4700        check_registered({
4701          workspace = {
4702            didChangeWatchedFiles = {
4703              dynamicRegistration = false,
4704            },
4705          },
4706        })
4707      )
4708      eq(
4709        true,
4710        check_registered({
4711          workspace = {
4712            didChangeWatchedFiles = {
4713              dynamicRegistration = true,
4714            },
4715          },
4716        })
4717      )
4718    end)
4719  end)
4720
4721  describe('vim.lsp.config() and vim.lsp.enable()', function()
4722    ---@param names string[]
4723    local function get_resolved(names)
4724      return exec_lua(function(names_)
4725        local rv = {}
4726        local cs = vim.lsp._enabled_configs
4727        for _, k in ipairs(names_) do
4728          rv[k] = not not (cs[k] and cs[k].resolved_config)
4729        end
4730        return rv
4731      end, names)
4732    end
4733
4734    it('merges settings from "*"', function()
4735      eq(
4736        {
4737          name = 'foo',
4738          cmd = { 'foo' },
4739          root_markers = { '.git' },
4740        },
4741        exec_lua(function()
4742          vim.lsp.config('*', { root_markers = { '.git' } })
4743          vim.lsp.config('foo', { cmd = { 'foo' } })
4744
4745          return vim.lsp.config['foo']
4746        end)
4747      )
4748    end)
4749
4750    it('config("bogus") shows a hint', function()
4751      matches(
4752        'hint%: to resolve a config',
4753        pcall_err(exec_lua, function()
4754          vim.print(vim.lsp.config('non-existent-config'))
4755        end)
4756      )
4757    end)
4758
4759    it('sets up an autocmd', function()
4760      eq(
4761        1,
4762        exec_lua(function()
4763          vim.lsp.config('foo', {
4764            cmd = { 'foo' },
4765            root_markers = { '.foorc' },
4766          })
4767          vim.lsp.enable('foo')
4768          return #vim.api.nvim_get_autocmds({
4769            group = 'nvim.lsp.enable',
4770            event = 'FileType',
4771          })
4772        end)
4773      )
4774    end)
4775
4776    it('handle nil config (some clients may not have a config!)', function()
4777      exec_lua(create_server_definition)
4778      exec_lua(function()
4779        local server = _G._create_server()
4780        vim.bo.filetype = 'lua'
4781        -- Attach a client without defining a config.
4782        local client_id = vim.lsp.start({
4783          name = 'test_ls',
4784          cmd = function(dispatchers, config)
4785            _G.test_resolved_root = config.root_dir --[[@type string]]
4786            return server.cmd(dispatchers, config)
4787          end,
4788        }, { bufnr = 0 })
4789
4790        local bufnr = vim.api.nvim_get_current_buf()
4791        local client = vim.lsp.get_client_by_id(client_id)
4792        assert(client.attached_buffers[bufnr])
4793
4794        -- Exercise the codepath which had a regression:
4795        vim.lsp.enable('test_ls')
4796        vim.api.nvim_exec_autocmds('FileType', { buf = bufnr })
4797
4798        -- enable() does _not_ detach the client since it doesn't actually have a config.
4799        -- XXX: otoh, is it confusing to allow `enable("foo")` if there a "foo" _client_ without a "foo" _config_?
4800        assert(client.attached_buffers[bufnr])
4801        assert(client_id == vim.lsp.get_client_by_id(bufnr).id)
4802      end)
4803    end)
4804
4805    it('attaches to buffers when they are opened', function()
4806      exec_lua(create_server_definition)
4807
4808      local tmp1 = t.tmpname(true)
4809      local tmp2 = t.tmpname(true)
4810
4811      exec_lua(function()
4812        local server = _G._create_server({
4813          handlers = {
4814            initialize = function(_, _, callback)
4815              callback(nil, { capabilities = {} })
4816            end,
4817          },
4818        })
4819
4820        vim.lsp.config('foo', {
4821          cmd = server.cmd,
4822          filetypes = { 'foo' },
4823          root_markers = { '.foorc' },
4824        })
4825
4826        vim.lsp.config('bar', {
4827          cmd = server.cmd,
4828          filetypes = { 'bar' },
4829          root_markers = { '.foorc' },
4830        })
4831
4832        vim.lsp.enable('foo')
4833        vim.lsp.enable('bar')
4834
4835        vim.cmd.edit(tmp1)
4836        vim.bo.filetype = 'foo'
4837        _G.foo_buf = vim.api.nvim_get_current_buf()
4838
4839        vim.cmd.edit(tmp2)
4840        vim.bo.filetype = 'bar'
4841        _G.bar_buf = vim.api.nvim_get_current_buf()
4842      end)
4843
4844      eq(
4845        { 1, 'foo', 1, 'bar' },
4846        exec_lua(function()
4847          local foos = vim.lsp.get_clients({ bufnr = assert(_G.foo_buf) })
4848          local bars = vim.lsp.get_clients({ bufnr = assert(_G.bar_buf) })
4849          return { #foos, foos[1].name, #bars, bars[1].name }
4850        end)
4851      )
4852    end)
4853
4854    it('attaches/detaches preexisting buffers', function()
4855      exec_lua(create_server_definition)
4856
4857      local tmp1 = t.tmpname(true)
4858      local tmp2 = t.tmpname(true)
4859
4860      exec_lua(function()
4861        vim.cmd.edit(tmp1)
4862        vim.bo.filetype = 'foo'
4863        _G.foo_buf = vim.api.nvim_get_current_buf()
4864
4865        vim.cmd.edit(tmp2)
4866        vim.bo.filetype = 'bar'
4867        _G.bar_buf = vim.api.nvim_get_current_buf()
4868
4869        local server = _G._create_server({
4870          handlers = {
4871            initialize = function(_, _, callback)
4872              callback(nil, { capabilities = {} })
4873            end,
4874          },
4875        })
4876
4877        vim.lsp.config('foo', {
4878          cmd = server.cmd,
4879          filetypes = { 'foo' },
4880          root_markers = { '.foorc' },
4881        })
4882
4883        vim.lsp.config('bar', {
4884          cmd = server.cmd,
4885          filetypes = { 'bar' },
4886          root_markers = { '.foorc' },
4887        })
4888
4889        vim.lsp.enable('foo')
4890        vim.lsp.enable('bar')
4891      end)
4892
4893      eq(
4894        { 1, 'foo', 1, 'bar' },
4895        exec_lua(function()
4896          local foos = vim.lsp.get_clients({ bufnr = assert(_G.foo_buf) })
4897          local bars = vim.lsp.get_clients({ bufnr = assert(_G.bar_buf) })
4898          return { #foos, foos[1].name, #bars, bars[1].name }
4899        end)
4900      )
4901
4902      -- Now disable the 'foo' lsp and confirm that it's detached from the buffer it was previous
4903      -- attached to.
4904      exec_lua([[vim.lsp.enable('foo', false)]])
4905      eq(
4906        { 0, 'foo', 1, 'bar' },
4907        exec_lua(function()
4908          local foos = vim.lsp.get_clients({ bufnr = assert(_G.foo_buf) })
4909          local bars = vim.lsp.get_clients({ bufnr = assert(_G.bar_buf) })
4910          return { #foos, 'foo', #bars, bars[1].name }
4911        end)
4912      )
4913    end)
4914
4915    it('in first FileType event (on startup)', function()
4916      local tmp = tmpname()
4917      write_file(tmp, string.dump(create_server_definition))
4918      n.clear({
4919        args = {
4920          '--cmd',
4921          string.format([[lua assert(loadfile(%q))()]], tmp),
4922          '--cmd',
4923          [[lua _G.server = _G._create_server({ handlers = {initialize = function(_, _, callback) callback(nil, {capabilities = {}}) end} })]],
4924          '--cmd',
4925          [[lua vim.lsp.config('foo', { cmd = _G.server.cmd, filetypes = { 'foo' }, root_markers = { '.foorc' } })]],
4926          '--cmd',
4927          [[au FileType * ++once lua vim.lsp.enable('foo')]],
4928          '-c',
4929          'set ft=foo',
4930        },
4931      })
4932
4933      eq(
4934        { 1, 'foo' },
4935        exec_lua(function()
4936          local foos = vim.lsp.get_clients({ bufnr = 0 })
4937          return { #foos, (foos[1] or {}).name }
4938        end)
4939      )
4940      exec_lua([[vim.lsp.enable('foo', false)]])
4941      eq(
4942        0,
4943        exec_lua(function()
4944          return #vim.lsp.get_clients({ bufnr = 0 })
4945        end)
4946      )
4947    end)
4948
4949    it('does not attach to buffers more than once if no root_dir', function()
4950      exec_lua(create_server_definition)
4951
4952      local tmp1 = t.tmpname(true)
4953
4954      eq(
4955        1,
4956        exec_lua(function()
4957          local server = _G._create_server({
4958            handlers = {
4959              initialize = function(_, _, callback)
4960                callback(nil, { capabilities = {} })
4961              end,
4962            },
4963          })
4964
4965          vim.lsp.config('foo', { cmd = server.cmd, filetypes = { 'foo' } })
4966          vim.lsp.enable('foo')
4967
4968          vim.cmd.edit(assert(tmp1))
4969          vim.bo.filetype = 'foo'
4970          vim.bo.filetype = 'foo'
4971
4972          return #vim.lsp.get_clients({ bufnr = vim.api.nvim_get_current_buf() })
4973        end)
4974      )
4975    end)
4976
4977    it('async root_dir, cmd(…,config) gets resolved config', function()
4978      exec_lua(create_server_definition)
4979
4980      local tmp1 = t.tmpname(true)
4981      exec_lua(function()
4982        local server = _G._create_server({
4983          handlers = {
4984            initialize = function(_, _, callback)
4985              callback(nil, { capabilities = {} })
4986            end,
4987          },
4988        })
4989
4990        vim.lsp.config('foo', {
4991          cmd = function(dispatchers, config)
4992            _G.test_resolved_root = config.root_dir --[[@type string]]
4993            return server.cmd(dispatchers, config)
4994          end,
4995          filetypes = { 'foo' },
4996          root_dir = function(bufnr, cb)
4997            assert(tmp1 == vim.api.nvim_buf_get_name(bufnr))
4998            vim.system({ 'sleep', '0' }, {}, function()
4999              cb('some_dir')
5000            end)
5001          end,
5002        })
5003        vim.lsp.enable('foo')
5004
5005        vim.cmd.edit(assert(tmp1))
5006        vim.bo.filetype = 'foo'
5007      end)
5008
5009      retry(nil, 1000, function()
5010        eq(
5011          'some_dir',
5012          exec_lua(function()
5013            return vim.lsp.get_clients({ bufnr = vim.api.nvim_get_current_buf() })[1].root_dir
5014          end)
5015        )
5016      end)
5017      eq(
5018        'some_dir',
5019        exec_lua(function()
5020          return _G.test_resolved_root
5021        end)
5022      )
5023    end)
5024
5025    it('starts correct LSP and stops incorrect LSP when filetype changes', function()
5026      exec_lua(create_server_definition)
5027
5028      local tmp1 = t.tmpname(true)
5029
5030      exec_lua(function()
5031        local server = _G._create_server({
5032          handlers = {
5033            initialize = function(_, _, callback)
5034              callback(nil, { capabilities = {} })
5035            end,
5036          },
5037        })
5038
5039        vim.lsp.config('foo', {
5040          cmd = server.cmd,
5041          filetypes = { 'foo' },
5042          root_markers = { '.foorc' },
5043        })
5044
5045        vim.lsp.config('bar', {
5046          cmd = server.cmd,
5047          filetypes = { 'bar' },
5048          root_markers = { '.foorc' },
5049        })
5050
5051        vim.lsp.enable('foo')
5052        vim.lsp.enable('bar')
5053
5054        vim.cmd.edit(tmp1)
5055      end)
5056
5057      local count_clients = function()
5058        return exec_lua(function()
5059          local foos = vim.lsp.get_clients({ name = 'foo', bufnr = 0 })
5060          local bars = vim.lsp.get_clients({ name = 'bar', bufnr = 0 })
5061          return { #foos, 'foo', #bars, 'bar' }
5062        end)
5063      end
5064
5065      -- No filetype on the buffer yet, so no LSPs.
5066      eq({ 0, 'foo', 0, 'bar' }, count_clients())
5067
5068      -- Set the filetype to 'foo', confirm a LSP starts.
5069      exec_lua([[vim.bo.filetype = 'foo']])
5070      eq({ 1, 'foo', 0, 'bar' }, count_clients())
5071
5072      -- Set the filetype to 'bar', confirm a new LSP starts, and the old one goes away.
5073      exec_lua([[vim.bo.filetype = 'bar']])
5074      eq({ 0, 'foo', 1, 'bar' }, count_clients())
5075    end)
5076
5077    it('sends didClose and didOpen when languageId changes', function()
5078      exec_lua(create_server_definition)
5079
5080      local tmp1 = t.tmpname(true)
5081
5082      exec_lua(function()
5083        _G.server = _G._create_server({
5084          handlers = {
5085            initialize = function(_, _, callback)
5086              callback(nil, { capabilities = { textDocumentSync = { openClose = true } } })
5087            end,
5088          },
5089        })
5090        vim.lsp.config('foo', { cmd = _G.server.cmd, filetypes = { 'foo', 'bar' } })
5091        vim.lsp.enable('foo')
5092        vim.cmd.edit(tmp1)
5093      end)
5094
5095      local function test_messages()
5096        local opens = 0
5097        local closes = 0
5098        local msgs = exec_lua([[ return _G.server.messages ]])
5099        local num_clients = exec_lua([[ return #vim.lsp.get_clients() ]])
5100        for _, msg in ipairs(msgs) do
5101          opens = opens + (msg.method == 'textDocument/didOpen' and 1 or 0)
5102          closes = closes + (msg.method == 'textDocument/didClose' and 1 or 0)
5103        end
5104        return { opens, 'did_open', closes, 'did_close', num_clients, 'clients' }
5105      end
5106
5107      -- No filetype on the buffer yet.
5108      eq({ 0, 'did_open', 0, 'did_close', 0, 'clients' }, test_messages())
5109
5110      -- Set the filetype to 'foo', confirm didOpen is sent.
5111      exec_lua([[vim.bo.filetype = 'foo']])
5112      retry(nil, 1000, function()
5113        eq({ 1, 'did_open', 0, 'did_close', 1, 'clients' }, test_messages())
5114      end)
5115
5116      -- Set to anohter lsp-supported filetype 'bar', confirm didClose and didOpen are sent.
5117      exec_lua([[vim.bo.filetype = 'bar']])
5118      retry(nil, 1000, function()
5119        eq({ 2, 'did_open', 1, 'did_close', 1, 'clients' }, test_messages())
5120      end)
5121    end)
5122
5123    it('validates config on attach', function()
5124      local tmp1 = t.tmpname(true)
5125      local logfile = exec_lua(function()
5126        return vim.lsp.log.get_filename()
5127      end)
5128
5129      exec_lua(function()
5130        vim.fn.writefile({ '' }, vim.lsp.log.get_filename())
5131      end)
5132
5133      local function test_cfg(cfg, err)
5134        exec_lua(function()
5135          vim.lsp.config['foo'] = {}
5136          vim.lsp.config('foo', cfg)
5137          vim.lsp.enable('foo')
5138          vim.cmd.edit(assert(tmp1))
5139          vim.bo.filetype = 'non.applicable.filetype'
5140        end)
5141
5142        -- Assert NO log for non-applicable 'filetype'. #35737
5143        if type(cfg.filetypes) == 'table' then
5144          t.assert_nolog(err, logfile)
5145        end
5146
5147        exec_lua(function()
5148          vim.bo.filetype = 'foo'
5149        end)
5150
5151        retry(nil, 1000, function()
5152          t.assert_log(err, logfile)
5153        end)
5154      end
5155
5156      test_cfg({
5157        filetypes = { 'foo' },
5158        cmd = { 'lolling' },
5159      }, 'invalid "foo" config: .* lolling is not executable')
5160
5161      test_cfg({
5162        cmd = { 'cat' },
5163        filetypes = true,
5164      }, 'invalid "foo" config: .* filetypes: expected table, got boolean')
5165    end)
5166
5167    it('does not start without workspace if workspace_required=true', function()
5168      exec_lua(create_server_definition)
5169
5170      local tmp1 = t.tmpname(true)
5171
5172      eq(
5173        { workspace_required = false },
5174        exec_lua(function()
5175          local server = _G._create_server({
5176            handlers = {
5177              initialize = function(_, _, callback)
5178                callback(nil, { capabilities = {} })
5179              end,
5180            },
5181          })
5182
5183          local ws_required = { cmd = server.cmd, workspace_required = true, filetypes = { 'foo' } }
5184          local ws_not_required = vim.deepcopy(ws_required)
5185          ws_not_required.workspace_required = false
5186
5187          vim.lsp.config('ws_required', ws_required)
5188          vim.lsp.config('ws_not_required', ws_not_required)
5189          vim.lsp.enable('ws_required')
5190          vim.lsp.enable('ws_not_required')
5191
5192          vim.cmd.edit(assert(tmp1))
5193          vim.bo.filetype = 'foo'
5194
5195          local clients = vim.lsp.get_clients({ bufnr = vim.api.nvim_get_current_buf() })
5196          assert(1 == #clients)
5197          return { workspace_required = clients[1].config.workspace_required }
5198        end)
5199      )
5200    end)
5201
5202    it('does not allow wildcards in config name', function()
5203      local err =
5204        '.../lsp.lua:0: name: expected non%-wildcard string, got foo%*%. Info: LSP config name cannot contain wildcard %("%*"%)'
5205
5206      matches(
5207        err,
5208        pcall_err(exec_lua, function()
5209          local _ = vim.lsp.config['foo*']
5210        end)
5211      )
5212      matches(
5213        err,
5214        pcall_err(exec_lua, function()
5215          vim.lsp.config['foo*'] = {}
5216        end)
5217      )
5218      matches(
5219        err,
5220        pcall_err(exec_lua, function()
5221          vim.lsp.config('foo*', {})
5222        end)
5223      )
5224      -- Exception for '*'
5225      pcall(exec_lua, function()
5226        vim.lsp.config('*', {})
5227      end)
5228    end)
5229
5230    it('root_markers priority', function()
5231      --- Setup directories for testing
5232      -- root/
5233      -- ├── dir_a/
5234      -- │   ├── dir_b/
5235      -- │   │   ├── target
5236      -- │   │   └── marker_d
5237      -- │   ├── marker_b
5238      -- │   └── marker_c
5239      -- └── marker_a
5240
5241      ---@param filepath string
5242      local function touch(filepath)
5243        local file = io.open(filepath, 'w')
5244        if file then
5245          file:close()
5246        end
5247      end
5248
5249      local tmp_root = tmpname(false)
5250      local marker_a = tmp_root .. '/marker_a'
5251      local dir_a = tmp_root .. '/dir_a'
5252      local marker_b = dir_a .. '/marker_b'
5253      local marker_c = dir_a .. '/marker_c'
5254      local dir_b = dir_a .. '/dir_b'
5255      local marker_d = dir_b .. '/marker_d'
5256      local target = dir_b .. '/target'
5257
5258      mkdir(tmp_root)
5259      touch(marker_a)
5260      mkdir(dir_a)
5261      touch(marker_b)
5262      touch(marker_c)
5263      mkdir(dir_b)
5264      touch(marker_d)
5265      touch(target)
5266
5267      exec_lua(create_server_definition)
5268      exec_lua(function()
5269        _G._custom_server = _G._create_server()
5270      end)
5271
5272      ---@param root_markers (string|string[])[]
5273      ---@param expected_root_dir string?
5274      local function markers_resolve_to(root_markers, expected_root_dir)
5275        exec_lua(function()
5276          vim.lsp.config['foo'] = {}
5277          vim.lsp.config('foo', {
5278            cmd = _G._custom_server.cmd,
5279            reuse_client = function()
5280              return false
5281            end,
5282            filetypes = { 'foo' },
5283            root_markers = root_markers,
5284          })
5285          vim.lsp.enable('foo')
5286          vim.cmd.edit(target)
5287          vim.bo.filetype = 'foo'
5288        end)
5289        retry(nil, 1000, function()
5290          eq(
5291            expected_root_dir,
5292            exec_lua(function()
5293              local clients = vim.lsp.get_clients()
5294              return clients[#clients].root_dir
5295            end)
5296          )
5297        end)
5298      end
5299
5300      markers_resolve_to({ 'marker_d' }, dir_b)
5301      markers_resolve_to({ 'marker_b' }, dir_a)
5302      markers_resolve_to({ 'marker_c' }, dir_a)
5303      markers_resolve_to({ 'marker_a' }, tmp_root)
5304      markers_resolve_to({ 'foo' }, nil)
5305      markers_resolve_to({ { 'marker_b', 'marker_a' }, 'marker_d' }, dir_a)
5306      markers_resolve_to({ 'marker_a', { 'marker_b', 'marker_d' } }, tmp_root)
5307      markers_resolve_to({ 'foo', { 'bar', 'baz' }, 'marker_d' }, dir_b)
5308    end)
5309
5310    it('vim.lsp.is_enabled()', function()
5311      exec_lua(function()
5312        vim.lsp.config('foo', {
5313          cmd = { 'foo' },
5314          root_markers = { '.foorc' },
5315        })
5316      end)
5317
5318      -- LSP config defaults to disabled.
5319      eq(false, exec_lua([[return vim.lsp.is_enabled('foo')]]))
5320
5321      -- Confirm we can enable it.
5322      exec_lua([[vim.lsp.enable('foo')]])
5323      eq(true, exec_lua([[return vim.lsp.is_enabled('foo')]]))
5324
5325      -- And finally, disable it again.
5326      exec_lua([[vim.lsp.enable('foo', false)]])
5327      eq(false, exec_lua([[return vim.lsp.is_enabled('foo')]]))
5328    end)
5329
5330    it('vim.lsp.get_configs()', function()
5331      exec_lua(function()
5332        vim.lsp.config('foo', {
5333          cmd = { 'foo' },
5334          filetypes = { 'foofile' },
5335          root_markers = { '.foorc' },
5336        })
5337        vim.lsp.config('bar', {
5338          cmd = { 'bar' },
5339          root_markers = { '.barrc' },
5340        })
5341        vim.lsp.enable('foo')
5342      end)
5343
5344      local function names(configs)
5345        local config_names = vim
5346          .iter(configs)
5347          :map(function(config)
5348            return config.name
5349          end)
5350          :totable()
5351        table.sort(config_names)
5352        return config_names
5353      end
5354
5355      eq({ 'foo' }, names(exec_lua([[return vim.lsp.get_configs { enabled = true }]])))
5356      -- Does NOT resolve non-enabled configs.
5357      eq({ foo = true, bar = false }, get_resolved({ 'bar', 'foo' }))
5358
5359      eq({ 'bar' }, names(exec_lua([[return vim.lsp.get_configs { enabled = false }]])))
5360
5361      -- With no filter, return all configs
5362      eq({ 'bar', 'foo' }, names(exec_lua([[return vim.lsp.get_configs()]])))
5363
5364      -- Confirm `filetype` works
5365      eq({ 'foo' }, names(exec_lua([[return vim.lsp.get_configs { filetype = 'foofile' }]])))
5366
5367      -- Confirm filters combine
5368      eq(
5369        { 'foo' },
5370        names(exec_lua([[return vim.lsp.get_configs { filetype = 'foofile', enabled = true }]]))
5371      )
5372      eq(
5373        {},
5374        names(exec_lua([[return vim.lsp.get_configs { filetype = 'foofile', enabled = false }]]))
5375      )
5376      -- Does NOT resolve non-enabled configs.
5377      eq({ foo = true, bar = false }, get_resolved({ 'bar', 'foo' }))
5378    end)
5379  end)
5380end)