-
-
Notifications
You must be signed in to change notification settings - Fork 6k
/
Copy pathlsp.lua
2386 lines (2197 loc) · 82.4 KB
/
lsp.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---@diagnostic disable: invisible
local default_handlers = require('vim.lsp.handlers')
local log = require('vim.lsp.log')
local lsp_rpc = require('vim.lsp.rpc')
local protocol = require('vim.lsp.protocol')
local util = require('vim.lsp.util')
local sync = require('vim.lsp.sync')
local semantic_tokens = require('vim.lsp.semantic_tokens')
local api = vim.api
local nvim_err_writeln, nvim_buf_get_lines, nvim_command, nvim_buf_get_option, nvim_exec_autocmds =
api.nvim_err_writeln,
api.nvim_buf_get_lines,
api.nvim_command,
api.nvim_buf_get_option,
api.nvim_exec_autocmds
local uv = vim.loop
local tbl_isempty, tbl_extend = vim.tbl_isempty, vim.tbl_extend
local validate = vim.validate
local if_nil = vim.F.if_nil
local lsp = {
protocol = protocol,
handlers = default_handlers,
buf = require('vim.lsp.buf'),
diagnostic = require('vim.lsp.diagnostic'),
codelens = require('vim.lsp.codelens'),
semantic_tokens = semantic_tokens,
util = util,
-- Allow raw RPC access.
rpc = lsp_rpc,
-- Export these directly from rpc.
rpc_response_error = lsp_rpc.rpc_response_error,
}
-- maps request name to the required server_capability in the client.
lsp._request_name_to_capability = {
['textDocument/hover'] = { 'hoverProvider' },
['textDocument/signatureHelp'] = { 'signatureHelpProvider' },
['textDocument/definition'] = { 'definitionProvider' },
['textDocument/implementation'] = { 'implementationProvider' },
['textDocument/declaration'] = { 'declarationProvider' },
['textDocument/typeDefinition'] = { 'typeDefinitionProvider' },
['textDocument/documentSymbol'] = { 'documentSymbolProvider' },
['textDocument/prepareCallHierarchy'] = { 'callHierarchyProvider' },
['callHierarchy/incomingCalls'] = { 'callHierarchyProvider' },
['callHierarchy/outgoingCalls'] = { 'callHierarchyProvider' },
['textDocument/rename'] = { 'renameProvider' },
['textDocument/prepareRename'] = { 'renameProvider', 'prepareProvider' },
['textDocument/codeAction'] = { 'codeActionProvider' },
['textDocument/codeLens'] = { 'codeLensProvider' },
['codeLens/resolve'] = { 'codeLensProvider', 'resolveProvider' },
['workspace/executeCommand'] = { 'executeCommandProvider' },
['workspace/symbol'] = { 'workspaceSymbolProvider' },
['textDocument/references'] = { 'referencesProvider' },
['textDocument/rangeFormatting'] = { 'documentRangeFormattingProvider' },
['textDocument/formatting'] = { 'documentFormattingProvider' },
['textDocument/completion'] = { 'completionProvider' },
['textDocument/documentHighlight'] = { 'documentHighlightProvider' },
['textDocument/semanticTokens/full'] = { 'semanticTokensProvider' },
['textDocument/semanticTokens/full/delta'] = { 'semanticTokensProvider' },
}
-- TODO improve handling of scratch buffers with LSP attached.
---@private
--- Concatenates and writes a list of strings to the Vim error buffer.
---
---@param ... string List to write to the buffer
local function err_message(...)
nvim_err_writeln(table.concat(vim.tbl_flatten({ ... })))
nvim_command('redraw')
end
---@private
--- Returns the buffer number for the given {bufnr}.
---
---@param bufnr (integer|nil) Buffer number to resolve. Defaults to current buffer
---@return integer bufnr
local function resolve_bufnr(bufnr)
validate({ bufnr = { bufnr, 'n', true } })
if bufnr == nil or bufnr == 0 then
return api.nvim_get_current_buf()
end
return bufnr
end
---@private
--- Called by the client when trying to call a method that's not
--- supported in any of the servers registered for the current buffer.
---@param method (string) name of the method
function lsp._unsupported_method(method)
local msg = string.format(
'method %s is not supported by any of the servers registered for the current buffer',
method
)
log.warn(msg)
return msg
end
---@private
--- Checks whether a given path is a directory.
---
---@param filename (string) path to check
---@return boolean # true if {filename} exists and is a directory, false otherwise
local function is_dir(filename)
validate({ filename = { filename, 's' } })
local stat = uv.fs_stat(filename)
return stat and stat.type == 'directory' or false
end
local wait_result_reason = { [-1] = 'timeout', [-2] = 'interrupted', [-3] = 'error' }
local valid_encodings = {
['utf-8'] = 'utf-8',
['utf-16'] = 'utf-16',
['utf-32'] = 'utf-32',
['utf8'] = 'utf-8',
['utf16'] = 'utf-16',
['utf32'] = 'utf-32',
UTF8 = 'utf-8',
UTF16 = 'utf-16',
UTF32 = 'utf-32',
}
local format_line_ending = {
['unix'] = '\n',
['dos'] = '\r\n',
['mac'] = '\r',
}
---@private
---@param bufnr (number)
---@return string
local function buf_get_line_ending(bufnr)
return format_line_ending[nvim_buf_get_option(bufnr, 'fileformat')] or '\n'
end
local client_index = 0
---@private
--- Returns a new, unused client id.
---
---@return integer client_id
local function next_client_id()
client_index = client_index + 1
return client_index
end
-- Tracks all clients created via lsp.start_client
local active_clients = {}
local all_buffer_active_clients = {}
local uninitialized_clients = {}
---@private
---@param bufnr? integer
---@param fn fun(client: lsp.Client, client_id: integer, bufnr: integer)
local function for_each_buffer_client(bufnr, fn, restrict_client_ids)
validate({
fn = { fn, 'f' },
restrict_client_ids = { restrict_client_ids, 't', true },
})
bufnr = resolve_bufnr(bufnr)
local client_ids = all_buffer_active_clients[bufnr]
if not client_ids or tbl_isempty(client_ids) then
return
end
if restrict_client_ids and #restrict_client_ids > 0 then
local filtered_client_ids = {}
for client_id in pairs(client_ids) do
if vim.list_contains(restrict_client_ids, client_id) then
filtered_client_ids[client_id] = true
end
end
client_ids = filtered_client_ids
end
for client_id in pairs(client_ids) do
local client = active_clients[client_id]
if client then
fn(client, client_id, bufnr)
end
end
end
-- Error codes to be used with `on_error` from |vim.lsp.start_client|.
-- Can be used to look up the string from a the number or the number
-- from the string.
lsp.client_errors = tbl_extend(
'error',
lsp_rpc.client_errors,
vim.tbl_add_reverse_lookup({
ON_INIT_CALLBACK_ERROR = table.maxn(lsp_rpc.client_errors) + 1,
})
)
---@private
--- Normalizes {encoding} to valid LSP encoding names.
---
---@param encoding (string) Encoding to normalize
---@return string # normalized encoding name
local function validate_encoding(encoding)
validate({
encoding = { encoding, 's' },
})
return valid_encodings[encoding:lower()]
or error(
string.format(
"Invalid offset encoding %q. Must be one of: 'utf-8', 'utf-16', 'utf-32'",
encoding
)
)
end
---@internal
--- Parses a command invocation into the command itself and its args. If there
--- are no arguments, an empty table is returned as the second argument.
---
---@param input string[]
---@return string command, string[] args #the command and arguments
function lsp._cmd_parts(input)
validate({
cmd = {
input,
function()
return vim.tbl_islist(input)
end,
'list',
},
})
local cmd = input[1]
local cmd_args = {}
-- Don't mutate our input.
for i, v in ipairs(input) do
validate({ ['cmd argument'] = { v, 's' } })
if i > 1 then
table.insert(cmd_args, v)
end
end
return cmd, cmd_args
end
---@private
--- Augments a validator function with support for optional (nil) values.
---
---@param fn (fun(v): boolean) The original validator function; should return a
---bool.
---@return fun(v): boolean # The augmented function. Also returns true if {v} is
---`nil`.
local function optional_validator(fn)
return function(v)
return v == nil or fn(v)
end
end
---@private
--- Validates a client configuration as given to |vim.lsp.start_client()|.
---
---@param config (table)
---@return table config Cleaned config, containing the command, its
---arguments, and a valid encoding.
local function validate_client_config(config)
validate({
config = { config, 't' },
})
validate({
handlers = { config.handlers, 't', true },
capabilities = { config.capabilities, 't', true },
cmd_cwd = { config.cmd_cwd, optional_validator(is_dir), 'directory' },
cmd_env = { config.cmd_env, 't', true },
detached = { config.detached, 'b', true },
name = { config.name, 's', true },
on_error = { config.on_error, 'f', true },
on_exit = { config.on_exit, 'f', true },
on_init = { config.on_init, 'f', true },
settings = { config.settings, 't', true },
commands = { config.commands, 't', true },
before_init = { config.before_init, 'f', true },
offset_encoding = { config.offset_encoding, 's', true },
flags = { config.flags, 't', true },
get_language_id = { config.get_language_id, 'f', true },
})
assert(
(
not config.flags
or not config.flags.debounce_text_changes
or type(config.flags.debounce_text_changes) == 'number'
),
'flags.debounce_text_changes must be a number with the debounce time in milliseconds'
)
local cmd, cmd_args
if type(config.cmd) == 'function' then
cmd = config.cmd
else
cmd, cmd_args = lsp._cmd_parts(config.cmd)
end
local offset_encoding = valid_encodings.UTF16
if config.offset_encoding then
offset_encoding = validate_encoding(config.offset_encoding)
end
return {
cmd = cmd,
cmd_args = cmd_args,
offset_encoding = offset_encoding,
}
end
---@private
--- Returns full text of buffer {bufnr} as a string.
---
---@param bufnr (number) Buffer handle, or 0 for current.
---@return string # Buffer text as string.
local function buf_get_full_text(bufnr)
local line_ending = buf_get_line_ending(bufnr)
local text = table.concat(nvim_buf_get_lines(bufnr, 0, -1, true), line_ending)
if nvim_buf_get_option(bufnr, 'eol') then
text = text .. line_ending
end
return text
end
---@private
--- Memoizes a function. On first run, the function return value is saved and
--- immediately returned on subsequent runs. If the function returns a multival,
--- only the first returned value will be memoized and returned. The function will only be run once,
--- even if it has side effects.
---
---@param fn (function) Function to run
---@return function fn Memoized function
local function once(fn)
local value
local ran = false
return function(...)
if not ran then
value = fn(...)
ran = true
end
return value
end
end
local changetracking = {}
do
---@private
---
--- LSP has 3 different sync modes:
--- - None (Servers will read the files themselves when needed)
--- - Full (Client sends the full buffer content on updates)
--- - Incremental (Client sends only the changed parts)
---
--- Changes are tracked per buffer.
--- A buffer can have multiple clients attached and each client needs to send the changes
--- To minimize the amount of changesets to compute, computation is grouped:
---
--- None: One group for all clients
--- Full: One group for all clients
--- Incremental: One group per `offset_encoding`
---
--- Sending changes can be debounced per buffer. To simplify the implementation the
--- smallest debounce interval is used and we don't group clients by different intervals.
---
--- @class CTGroup
--- @field sync_kind integer TextDocumentSyncKind, considers config.flags.allow_incremental_sync
--- @field offset_encoding "utf-8"|"utf-16"|"utf-32"
---
--- @class CTBufferState
--- @field name string name of the buffer
--- @field lines string[] snapshot of buffer lines from last didChange
--- @field lines_tmp string[]
--- @field pending_changes table[] List of debounced changes in incremental sync mode
--- @field timer nil|uv.uv_timer_t uv_timer
--- @field last_flush nil|number uv.hrtime of the last flush/didChange-notification
--- @field needs_flush boolean true if buffer updates haven't been sent to clients/servers yet
--- @field refs integer how many clients are using this group
---
--- @class CTGroupState
--- @field buffers table<integer, CTBufferState>
--- @field debounce integer debounce duration in ms
--- @field clients table<integer, table> clients using this state. {client_id, client}
---@private
---@param group CTGroup
---@return string
local function group_key(group)
if group.sync_kind == protocol.TextDocumentSyncKind.Incremental then
return tostring(group.sync_kind) .. '\0' .. group.offset_encoding
end
return tostring(group.sync_kind)
end
---@private
---@type table<CTGroup, CTGroupState>
local state_by_group = setmetatable({}, {
__index = function(tbl, k)
return rawget(tbl, group_key(k))
end,
__newindex = function(tbl, k, v)
rawset(tbl, group_key(k), v)
end,
})
---@private
---@return CTGroup
local function get_group(client)
local allow_inc_sync = if_nil(client.config.flags.allow_incremental_sync, true)
local change_capability =
vim.tbl_get(client.server_capabilities or {}, 'textDocumentSync', 'change')
local sync_kind = change_capability or protocol.TextDocumentSyncKind.None
if not allow_inc_sync and change_capability == protocol.TextDocumentSyncKind.Incremental then
sync_kind = protocol.TextDocumentSyncKind.Full
end
return {
sync_kind = sync_kind,
offset_encoding = client.offset_encoding,
}
end
---@private
---@param state CTBufferState
local function incremental_changes(state, encoding, bufnr, firstline, lastline, new_lastline)
local prev_lines = state.lines
local curr_lines = state.lines_tmp
local changed_lines = nvim_buf_get_lines(bufnr, firstline, new_lastline, true)
for i = 1, firstline do
curr_lines[i] = prev_lines[i]
end
for i = firstline + 1, new_lastline do
curr_lines[i] = changed_lines[i - firstline]
end
for i = lastline + 1, #prev_lines do
curr_lines[i - lastline + new_lastline] = prev_lines[i]
end
if tbl_isempty(curr_lines) then
-- Can happen when deleting the entire contents of a buffer, see https://github.com/neovim/neovim/issues/16259.
curr_lines[1] = ''
end
local line_ending = buf_get_line_ending(bufnr)
local incremental_change = sync.compute_diff(
state.lines,
curr_lines,
firstline,
lastline,
new_lastline,
encoding,
line_ending
)
-- Double-buffering of lines tables is used to reduce the load on the garbage collector.
-- At this point the prev_lines table is useless, but its internal storage has already been allocated,
-- so let's keep it around for the next didChange event, in which it will become the next
-- curr_lines table. Note that setting elements to nil doesn't actually deallocate slots in the
-- internal storage - it merely marks them as free, for the GC to deallocate them.
for i in ipairs(prev_lines) do
prev_lines[i] = nil
end
state.lines = curr_lines
state.lines_tmp = prev_lines
return incremental_change
end
---@private
function changetracking.init(client, bufnr)
assert(client.offset_encoding, 'lsp client must have an offset_encoding')
local group = get_group(client)
local state = state_by_group[group]
if state then
state.debounce = math.min(state.debounce, client.config.flags.debounce_text_changes or 150)
state.clients[client.id] = client
else
state = {
buffers = {},
debounce = client.config.flags.debounce_text_changes or 150,
clients = {
[client.id] = client,
},
}
state_by_group[group] = state
end
local buf_state = state.buffers[bufnr]
if buf_state then
buf_state.refs = buf_state.refs + 1
else
buf_state = {
name = api.nvim_buf_get_name(bufnr),
lines = {},
lines_tmp = {},
pending_changes = {},
needs_flush = false,
refs = 1,
}
state.buffers[bufnr] = buf_state
if group.sync_kind == protocol.TextDocumentSyncKind.Incremental then
buf_state.lines = nvim_buf_get_lines(bufnr, 0, -1, true)
end
end
end
---@private
function changetracking._get_and_set_name(client, bufnr, name)
local state = state_by_group[get_group(client)] or {}
local buf_state = (state.buffers or {})[bufnr]
local old_name = buf_state.name
buf_state.name = name
return old_name
end
---@private
function changetracking.reset_buf(client, bufnr)
changetracking.flush(client, bufnr)
local state = state_by_group[get_group(client)]
if not state then
return
end
assert(state.buffers, 'CTGroupState must have buffers')
local buf_state = state.buffers[bufnr]
buf_state.refs = buf_state.refs - 1
assert(buf_state.refs >= 0, 'refcount on buffer state must not get negative')
if buf_state.refs == 0 then
state.buffers[bufnr] = nil
changetracking._reset_timer(buf_state)
end
end
---@private
function changetracking.reset(client)
local state = state_by_group[get_group(client)]
if not state then
return
end
state.clients[client.id] = nil
if vim.tbl_count(state.clients) == 0 then
for _, buf_state in pairs(state.buffers) do
changetracking._reset_timer(buf_state)
end
state.buffers = {}
end
end
---@private
--
-- Adjust debounce time by taking time of last didChange notification into
-- consideration. If the last didChange happened more than `debounce` time ago,
-- debounce can be skipped and otherwise maybe reduced.
--
-- This turns the debounce into a kind of client rate limiting
--
---@param debounce integer
---@param buf_state CTBufferState
---@return number
local function next_debounce(debounce, buf_state)
if debounce == 0 then
return 0
end
local ns_to_ms = 0.000001
if not buf_state.last_flush then
return debounce
end
local now = uv.hrtime()
local ms_since_last_flush = (now - buf_state.last_flush) * ns_to_ms
return math.max(debounce - ms_since_last_flush, 0)
end
---@private
---@param bufnr integer
---@param sync_kind integer protocol.TextDocumentSyncKind
---@param state CTGroupState
---@param buf_state CTBufferState
local function send_changes(bufnr, sync_kind, state, buf_state)
if not buf_state.needs_flush then
return
end
buf_state.last_flush = uv.hrtime()
buf_state.needs_flush = false
if not api.nvim_buf_is_valid(bufnr) then
buf_state.pending_changes = {}
return
end
local changes
if sync_kind == protocol.TextDocumentSyncKind.None then
return
elseif sync_kind == protocol.TextDocumentSyncKind.Incremental then
changes = buf_state.pending_changes
buf_state.pending_changes = {}
else
changes = {
{ text = buf_get_full_text(bufnr) },
}
end
local uri = vim.uri_from_bufnr(bufnr)
for _, client in pairs(state.clients) do
if not client.is_stopped() and lsp.buf_is_attached(bufnr, client.id) then
client.notify('textDocument/didChange', {
textDocument = {
uri = uri,
version = util.buf_versions[bufnr],
},
contentChanges = changes,
})
end
end
end
---@private
function changetracking.send_changes(bufnr, firstline, lastline, new_lastline)
local groups = {}
for _, client in pairs(lsp.get_active_clients({ bufnr = bufnr })) do
local group = get_group(client)
groups[group_key(group)] = group
end
for _, group in pairs(groups) do
local state = state_by_group[group]
if not state then
error(
string.format(
'changetracking.init must have been called for all LSP clients. group=%s states=%s',
vim.inspect(group),
vim.inspect(vim.tbl_keys(state_by_group))
)
)
end
local buf_state = state.buffers[bufnr]
buf_state.needs_flush = true
changetracking._reset_timer(buf_state)
local debounce = next_debounce(state.debounce, buf_state)
if group.sync_kind == protocol.TextDocumentSyncKind.Incremental then
-- This must be done immediately and cannot be delayed
-- The contents would further change and startline/endline may no longer fit
local changes = incremental_changes(
buf_state,
group.offset_encoding,
bufnr,
firstline,
lastline,
new_lastline
)
table.insert(buf_state.pending_changes, changes)
end
if debounce == 0 then
send_changes(bufnr, group.sync_kind, state, buf_state)
else
local timer = assert(uv.new_timer(), 'Must be able to create timer')
buf_state.timer = timer
timer:start(
debounce,
0,
vim.schedule_wrap(function()
changetracking._reset_timer(buf_state)
send_changes(bufnr, group.sync_kind, state, buf_state)
end)
)
end
end
end
---@private
function changetracking._reset_timer(buf_state)
local timer = buf_state.timer
if timer then
buf_state.timer = nil
if not timer:is_closing() then
timer:stop()
timer:close()
end
end
end
--- Flushes any outstanding change notification.
---@private
function changetracking.flush(client, bufnr)
local group = get_group(client)
local state = state_by_group[group]
if not state then
return
end
if bufnr then
local buf_state = state.buffers[bufnr] or {}
changetracking._reset_timer(buf_state)
send_changes(bufnr, group.sync_kind, state, buf_state)
else
for buf, buf_state in pairs(state.buffers) do
changetracking._reset_timer(buf_state)
send_changes(buf, group.sync_kind, state, buf_state)
end
end
end
end
---@private
--- Default handler for the 'textDocument/didOpen' LSP notification.
---
---@param bufnr integer Number of the buffer, or 0 for current
---@param client table Client object
local function text_document_did_open_handler(bufnr, client)
changetracking.init(client, bufnr)
if not vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'openClose') then
return
end
if not api.nvim_buf_is_loaded(bufnr) then
return
end
local filetype = nvim_buf_get_option(bufnr, 'filetype')
local params = {
textDocument = {
version = 0,
uri = vim.uri_from_bufnr(bufnr),
languageId = client.config.get_language_id(bufnr, filetype),
text = buf_get_full_text(bufnr),
},
}
client.notify('textDocument/didOpen', params)
util.buf_versions[bufnr] = params.textDocument.version
-- Next chance we get, we should re-do the diagnostics
vim.schedule(function()
-- Protect against a race where the buffer disappears
-- between `did_open_handler` and the scheduled function firing.
if api.nvim_buf_is_valid(bufnr) then
local namespace = vim.lsp.diagnostic.get_namespace(client.id)
vim.diagnostic.show(namespace, bufnr)
end
end)
end
-- FIXME: DOC: Shouldn't need to use a dummy function
--
--- LSP client object. You can get an active client object via
--- |vim.lsp.get_client_by_id()| or |vim.lsp.get_active_clients()|.
---
--- - Methods:
---
--- - request(method, params, [handler], bufnr)
--- Sends a request to the server.
--- This is a thin wrapper around {client.rpc.request} with some additional
--- checking.
--- If {handler} is not specified, If one is not found there, then an error will occur.
--- Returns: {status}, {[client_id]}. {status} is a boolean indicating if
--- the notification was successful. If it is `false`, then it will always
--- be `false` (the client has shutdown).
--- If {status} is `true`, the function returns {request_id} as the second
--- result. You can use this with `client.cancel_request(request_id)`
--- to cancel the request.
---
--- - request_sync(method, params, timeout_ms, bufnr)
--- Sends a request to the server and synchronously waits for the response.
--- This is a wrapper around {client.request}
--- Returns: { err=err, result=result }, a dictionary, where `err` and `result` come from
--- the |lsp-handler|. On timeout, cancel or error, returns `(nil, err)` where `err` is a
--- string describing the failure reason. If the request was unsuccessful returns `nil`.
---
--- - notify(method, params)
--- Sends a notification to an LSP server.
--- Returns: a boolean to indicate if the notification was successful. If
--- it is false, then it will always be false (the client has shutdown).
---
--- - cancel_request(id)
--- Cancels a request with a given request id.
--- Returns: same as `notify()`.
---
--- - stop([force])
--- Stops a client, optionally with force.
--- By default, it will just ask the server to shutdown without force.
--- If you request to stop a client which has previously been requested to
--- shutdown, it will automatically escalate and force shutdown.
---
--- - is_stopped()
--- Checks whether a client is stopped.
--- Returns: true if the client is fully stopped.
---
--- - on_attach(client, bufnr)
--- Runs the on_attach function from the client's config if it was defined.
--- Useful for buffer-local setup.
---
--- - Members
--- - {id} (number): The id allocated to the client.
---
--- - {name} (string): If a name is specified on creation, that will be
--- used. Otherwise it is just the client id. This is used for
--- logs and messages.
---
--- - {rpc} (table): RPC client object, for low level interaction with the
--- client. See |vim.lsp.rpc.start()|.
---
--- - {offset_encoding} (string): The encoding used for communicating
--- with the server. You can modify this in the `config`'s `on_init` method
--- before text is sent to the server.
---
--- - {handlers} (table): The handlers used by the client as described in |lsp-handler|.
---
--- - {requests} (table): The current pending requests in flight
--- to the server. Entries are key-value pairs with the key
--- being the request ID while the value is a table with `type`,
--- `bufnr`, and `method` key-value pairs. `type` is either "pending"
--- for an active request, or "cancel" for a cancel request.
---
--- - {config} (table): copy of the table that was passed by the user
--- to |vim.lsp.start_client()|.
---
--- - {server_capabilities} (table): Response from the server sent on
--- `initialize` describing the server's capabilities.
function lsp.client()
error()
end
--- Create a new LSP client and start a language server or reuses an already
--- running client if one is found matching `name` and `root_dir`.
--- Attaches the current buffer to the client.
---
--- Example:
--- <pre>lua
--- vim.lsp.start({
--- name = 'my-server-name',
--- cmd = {'name-of-language-server-executable'},
--- root_dir = vim.fs.dirname(vim.fs.find({'pyproject.toml', 'setup.py'}, { upward = true })[1]),
--- })
--- </pre>
---
--- See |vim.lsp.start_client()| for all available options. The most important are:
---
--- - `name` arbitrary name for the LSP client. Should be unique per language server.
--- - `cmd` command (in list form) used to start the language server. Must be absolute, or found on
--- `$PATH`. Shell constructs like `~` are not expanded.
--- - `root_dir` path to the project root. By default this is used to decide if an existing client
--- should be re-used. The example above uses |vim.fs.find()| and |vim.fs.dirname()| to detect the
--- root by traversing the file system upwards starting from the current directory until either
--- a `pyproject.toml` or `setup.py` file is found.
--- - `workspace_folders` list of `{ uri:string, name: string }` tables specifying the project root
--- folders used by the language server. If `nil` the property is derived from `root_dir` for
--- convenience.
---
--- Language servers use this information to discover metadata like the
--- dependencies of your project and they tend to index the contents within the
--- project folder.
---
---
--- To ensure a language server is only started for languages it can handle,
--- make sure to call |vim.lsp.start()| within a |FileType| autocmd.
--- Either use |:au|, |nvim_create_autocmd()| or put the call in a
--- `ftplugin/<filetype_name>.lua` (See |ftplugin-name|)
---
---@param config table Same configuration as documented in |vim.lsp.start_client()|
---@param opts nil|table Optional keyword arguments:
--- - reuse_client (fun(client: client, config: table): boolean)
--- Predicate used to decide if a client should be re-used.
--- Used on all running clients.
--- The default implementation re-uses a client if name
--- and root_dir matches.
--- - bufnr (number)
--- Buffer handle to attach to if starting or re-using a
--- client (0 for current).
---@return number|nil client_id
function lsp.start(config, opts)
opts = opts or {}
local reuse_client = opts.reuse_client
or function(client, conf)
return client.config.root_dir == conf.root_dir and client.name == conf.name
end
config.name = config.name
if not config.name and type(config.cmd) == 'table' then
config.name = config.cmd[1] and vim.fs.basename(config.cmd[1]) or nil
end
local bufnr = opts.bufnr
if bufnr == nil or bufnr == 0 then
bufnr = api.nvim_get_current_buf()
end
for _, clients in ipairs({ uninitialized_clients, lsp.get_active_clients() }) do
for _, client in pairs(clients) do
if reuse_client(client, config) then
lsp.buf_attach_client(bufnr, client.id)
return client.id
end
end
end
local client_id = lsp.start_client(config)
if client_id == nil then
return nil -- lsp.start_client will have printed an error
end
lsp.buf_attach_client(bufnr, client_id)
return client_id
end
-- FIXME: DOC: Currently all methods on the `vim.lsp.client` object are
-- documented twice: Here, and on the methods themselves (e.g.
-- `client.request()`). This is a workaround for the vimdoc generator script
-- not handling method names correctly. If you change the documentation on
-- either, please make sure to update the other as well.
--
--- Starts and initializes a client with the given configuration.
---
--- Field `cmd` in {config} is required.
---
---@param config (table) Configuration for the server:
--- - cmd: (table|string|fun(dispatchers: table):table) command string or
--- list treated like |jobstart()|. The command must launch the language server
--- process. `cmd` can also be a function that creates an RPC client.
--- The function receives a dispatchers table and must return a table with the
--- functions `request`, `notify`, `is_closing` and `terminate`
--- See |vim.lsp.rpc.request()| and |vim.lsp.rpc.notify()|
--- For TCP there is a built-in rpc client factory: |vim.lsp.rpc.connect()|
---
--- - cmd_cwd: (string, default=|getcwd()|) Directory to launch
--- the `cmd` process. Not related to `root_dir`.
---
--- - cmd_env: (table) Environment flags to pass to the LSP on
--- spawn. Must be specified using a map-like table.
--- Non-string values are coerced to string.
--- Example:
--- <pre>
--- { PORT = 8080; HOST = "0.0.0.0"; }
--- </pre>
---
--- - detached: (boolean, default true) Daemonize the server process so that it runs in a
--- separate process group from Nvim. Nvim will shutdown the process on exit, but if Nvim fails to
--- exit cleanly this could leave behind orphaned server processes.
---
--- - workspace_folders: (table) List of workspace folders passed to the
--- language server. For backwards compatibility rootUri and rootPath will be
--- derived from the first workspace folder in this list. See `workspaceFolders` in
--- the LSP spec.
---
--- - capabilities: Map overriding the default capabilities defined by
--- |vim.lsp.protocol.make_client_capabilities()|, passed to the language
--- server on initialization. Hint: use make_client_capabilities() and modify
--- its result.
--- - Note: To send an empty dictionary use
--- `{[vim.type_idx]=vim.types.dictionary}`, else it will be encoded as an
--- array.
---
--- - handlers: Map of language server method names to |lsp-handler|
---
--- - settings: Map with language server specific settings. These are
--- returned to the language server if requested via `workspace/configuration`.
--- Keys are case-sensitive.
---
--- - commands: table Table that maps string of clientside commands to user-defined functions.
--- Commands passed to start_client take precedence over the global command registry. Each key
--- must be a unique command name, and the value is a function which is called if any LSP action
--- (code action, code lenses, ...) triggers the command.
---
--- - init_options Values to pass in the initialization request
--- as `initializationOptions`. See `initialize` in the LSP spec.
---
--- - name: (string, default=client-id) Name in log messages.
---
--- - get_language_id: function(bufnr, filetype) -> language ID as string.
--- Defaults to the filetype.
---
--- - offset_encoding: (default="utf-16") One of "utf-8", "utf-16",
--- or "utf-32" which is the encoding that the LSP server expects. Client does
--- not verify this is correct.
---
--- - on_error: Callback with parameters (code, ...), invoked
--- when the client operation throws an error. `code` is a number describing
--- the error. Other arguments may be passed depending on the error kind. See
--- `vim.lsp.rpc.client_errors` for possible errors.
--- Use `vim.lsp.rpc.client_errors[code]` to get human-friendly name.
---
--- - before_init: Callback with parameters (initialize_params, config)
--- invoked before the LSP "initialize" phase, where `params` contains the
--- parameters being sent to the server and `config` is the config that was
--- passed to |vim.lsp.start_client()|. You can use this to modify parameters before
--- they are sent.
---
--- - on_init: Callback (client, initialize_result) invoked after LSP
--- "initialize", where `result` is a table of `capabilities` and anything else
--- the server may send. For example, clangd sends
--- `initialize_result.offsetEncoding` if `capabilities.offsetEncoding` was
--- sent to it. You can only modify the `client.offset_encoding` here before
--- any notifications are sent. Most language servers expect to be sent client specified settings after
--- initialization. Neovim does not make this assumption. A
--- `workspace/didChangeConfiguration` notification should be sent
--- to the server during on_init.
---
--- - on_exit Callback (code, signal, client_id) invoked on client
--- exit.
--- - code: exit code of the process
--- - signal: number describing the signal used to terminate (if any)
--- - client_id: client handle
---
--- - on_attach: Callback (client, bufnr) invoked when client
--- attaches to a buffer.
---
--- - trace: ("off" | "messages" | "verbose" | nil) passed directly to the language
--- server in the initialize request. Invalid/empty values will default to "off"
---
--- - flags: A table with flags for the client. The current (experimental) flags are:
--- - allow_incremental_sync (bool, default true): Allow using incremental sync for buffer edits
--- - debounce_text_changes (number, default 150): Debounce didChange
--- notifications to the server by the given number in milliseconds. No debounce