-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathinit.lua
1796 lines (1499 loc) · 51.8 KB
/
init.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
-- Copyright (c) 2021-2024 Florian Fischer. All rights reserved.
--
-- This file is part of vis-lspc.
--
-- vis-lspc is free software: you can redistribute it and/or modify it under the
-- terms of the GNU General Public License as published by the Free Software
-- Foundation, either version 3 of the License, or (at your option) any later
-- version.
--
-- vis-lspc is distributed in the hope that it will be useful, but WITHOUT ANY
-- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License along with
-- vis-lspc found in the LICENSE file. If not, see <https://www.gnu.org/licenses/>.
--
-- We require vis compiled with the communicate patch
if not vis.communicate then
vis:info('LSPC Error: language server support requires vis communicate patch')
return {}
end
local source_str = debug.getinfo(1, 'S').source:sub(2)
local source_path = source_str:match('(.*/)')
-- state of our language server client
local lspc = dofile(source_path .. 'lspc.lua')
-- initialise the logging system
lspc.logger = dofile(source_path .. 'log.lua').lazyNew('lspc', lspc)
local parser = dofile(source_path .. 'parser.lua')
-- initialise the util module
local util = dofile(source_path .. 'util.lua').init(lspc)
-- load a suitable json module
lspc.json = dofile(source_path .. 'json.lua')
local jsonrpc = {}
jsonrpc.error_codes = {
-- json rpc errors
ParseError = -32700,
InvalidRequest = -32600,
MethodNotFound = -32601,
InvalidParams = -32602,
InternalError = -32603,
ServerNotInitialized = -32002,
UnknownErrorCode = -32001,
-- lsp errors
ContentModified = -32801,
RequestCancelled = -32800,
}
-- get vis's pid to pass it to the language servers
local vis_pid
do
local vis_proc_file = io.open('/proc/self/stat', 'r')
if vis_proc_file then
vis_pid = vis_proc_file:read('*n')
vis_proc_file:close()
else -- fallback if /proc/self/stat
local out = util.capture_cmd('sh -c "echo $PPID"')
vis_pid = tonumber(out)
end
end
assert(vis_pid)
-- mapping function between vis lexer names and LSP languageIds
local function syntax_to_languageId(syntax)
-- LuaFormatter off
local map = {
ansi_c = 'c',
javascript = 'jsx',
typescript = 'tsx',
}
-- LuaFormatter on
return map[syntax] or syntax
end
-- map of known language servers per syntax
lspc.ls_map = dofile(source_path .. 'supported-servers.lua')
-- return the name of the language server for this syntax
local function get_ls_name_for_syntax(syntax)
local ls_def = lspc.ls_map[syntax]
if not ls_def then
return nil, 'No language server available for ' .. syntax
end
return ls_def.name
end
-- Document position code
-- https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentPositionParams
-- We use the following position/location/file related types in vis-lspc:
-- pos - like in vis a 0-based byte offset into the file.
-- path - posix path used by vis
-- uri - file uri used by LSP
-- lsp_position - 0-based tuple (line, character)
-- lsp_document_position - aka. LSP TextDocumentPosition, tuple of (uri, lsp_position)
-- vis_selection - 1-based tuple (line, cul) (character)
-- Can be used with with Selection:to
-- vis_document_position - 1-based tuple of (path, line, cul)
-- vis_range - tuple of 0-based byte offsets (finish, start)
-- lsp_range - aka. Range, tuple of two lsp_positions (start, end)
-- There exist helper function to convert from one type into another
-- aswell as helper to retrieve the current primary selection from a vis.window
local function path_to_uri(path)
return 'file://' .. path
end
-- uri decode logic taken from
-- https://stackoverflow.com/questions/20405985/lua-decodeuri-luvit
local uri_decode_table = {}
for i = 0, 255 do
uri_decode_table[string.format('%02x', i)] = string.char(i)
uri_decode_table[string.format('%02X', i)] = string.char(i)
end
local function decode_uri(s)
return (s:gsub('%%(%x%x)', uri_decode_table))
end
local function uri_to_path(uri)
return decode_uri(uri:gsub('file://', ''))
end
-- get the vis_selection from current primary selection
local function get_selection(win)
return {line = win.selection.line, col = win.selection.col}
end
-- get the 0-based byte offset from a selection
-- ATTENTION: this function modifies the primary selection so it is not
-- safe to call it for example during WIN_HIGHLIGHT events
local function vis_sel_to_pos(win, selection)
local old_selection = get_selection(win)
-- move primary selection
win.selection:to(selection.line, selection.col)
local pos = win.selection.pos
-- restore old primary selection
win.selection:to(old_selection.line, old_selection.col)
return pos
end
-- get the line and column from a 0-based byte offset
-- ATTENTION: this function modifies the primary selection so it is not
-- safe to call it for example during WIN_HIGHLIGHT events
local function vis_pos_to_sel(win, pos)
local old_selection = get_selection(win)
-- move primary selection
win.selection.pos = pos
local sel = get_selection(win)
-- restore old primary selection
win.selection:to(old_selection.line, old_selection.col)
return sel
end
-- convert lsp_position to vis_selection
local function lsp_pos_to_vis_sel(pos)
return {line = pos.line + 1, col = pos.character + 1}
end
-- convert vis_selection to lsp_position
local function vis_sel_to_lsp_pos(pos)
return {line = pos.line - 1, character = pos.col - 1}
end
-- convert our vis_document_position to lsp_document_position aka. TextDocumentPosition
local function vis_doc_pos_to_lsp(doc_pos)
return {
textDocument = {uri = path_to_uri(doc_pos.file)},
position = vis_sel_to_lsp_pos({line = doc_pos.line, col = doc_pos.col}),
}
end
-- convert lsp_document_position to vis_document_position
local function lsp_doc_pos_to_vis(doc_pos)
local pos = lsp_pos_to_vis_sel(doc_pos.position)
return {
file = uri_to_path(doc_pos.textDocument.uri),
line = pos.line,
col = pos.col,
}
end
-- get document position of the main curser
local function vis_get_doc_pos(win)
return {
file = win.file.path,
line = win.selection.line,
col = win.selection.col,
}
end
-- convert a lsp_range to a vis_range
-- ATTENTION: this function modifies the primary selection so it is not
-- safe to call it for example during WIN_HIGHLIGHT events
local function lsp_range_to_vis_range(win, lsp_range)
local start = lsp_pos_to_vis_sel(lsp_range.start)
local start_pos = vis_sel_to_pos(win, start)
local finish = lsp_pos_to_vis_sel(lsp_range['end'])
local finish_pos = vis_sel_to_pos(win, finish)
return {start = start_pos, finish = finish_pos}
end
-- return true if p1 is before p2
local function lsp_pos_before(p1, p2)
return p1.line < p2.line or (p1.line == p2.line and p1.character < p2.character)
end
-- return true if r1 starts before r2
local function lsp_range_starts_before(r1, r2)
return lsp_pos_before(r1.start, r2.start)
end
-- concatenate all numeric values in choices and pass it on stdin to lspc.menu_cmd
local function lspc_select(choices)
local menu_input = ''
local i = 0
for _, c in ipairs(choices) do
i = i + 1
menu_input = menu_input .. c .. '\n'
end
-- select the only possible choice
if i < 2 then
return choices[1]
end
local fullscreen = lspc.menu_cmd == 'fzf'
local status, output = util.vis_pipe(menu_input, lspc.menu_cmd, fullscreen)
local choice = nil
if status == 0 then
-- trim newline from selection
if output:sub(-1) == '\n' then
choice = output:sub(1, -2)
else
choice = output
end
end
vis:redraw()
return choice
end
local function lspc_select_location(locations)
-- Collect all paths with a list of their locations so we
-- can sort the locations before calling file_line_iterator_to_n
local collected = {}
for _, location in ipairs(locations) do
local path = uri_to_path(location.uri or location.targetUri)
local range = location.range or location.targetSelectionRange
local position = lsp_pos_to_vis_sel(range.start)
if collected[path] == nil then
table.insert(collected, path)
collected[path] = {}
end
table.insert(collected[path], {
['location'] = location,
['position'] = position,
})
end
local choices = {}
local cwd_components = util.capture_cmd('pwd')
-- Strip trailing newline
cwd_components = util.split_path_into_components(cwd_components:sub(1, #cwd_components - 1))
for _, path in ipairs(collected) do
-- Sort positions
table.sort(collected[path], function(a, b)
return a['position'].line < b['position'].line
end)
local rel_path = util.get_relative_path(cwd_components, path)
-- Use the already open file if present to get accurate line content for references
local line_iter
if lspc.open_files[path] ~= nil then
line_iter = function(n)
if n == -1 then
return nil
end
return lspc.open_files[path].file.lines[n]
end
else
line_iter = util.file_line_iterator_to_n(path)
end
for _, val in ipairs(collected[path]) do
local position = val['position']
local location = val['location']
local choice = rel_path .. ':' .. position.line .. ':' .. position.col .. ':' ..
line_iter(position.line)
table.insert(choices, choice)
choices[choice] = location
end
-- close the iterator
line_iter(-1)
end
-- select a location
local choice = lspc_select(choices)
if not choice then
return nil
end
return choices[choice]
end
-- get a user confirmation
-- return true if user selected yes, false otherwise
local function lspc_confirm(prompt)
local choices = 'no\nyes'
local cmd = lspc.confirm_cmd
if prompt then
cmd = cmd .. ' -p \'' .. prompt .. '\''
end
lspc:log('get confirmation using: ' .. cmd)
local choice = nil
local status, output = util.vis_pipe(choices, cmd)
if status == 0 then
-- trim newline from selection
if output:sub(-1) == '\n' then
choice = output:sub(1, -2)
else
choice = output
end
end
vis:redraw()
return choice == 'yes'
end
local function vis_open_file(file, cmd)
vis:command(('%s %s'):format(cmd, file:gsub('[\\\t "\']', '\\%1'):gsub('\n', '\\n')))
end
-- open a doc_pos using the vis command <cmd>
local function vis_open_doc_pos(doc_pos, cmd, win)
if win and win ~= vis.win then
vis.win = win
end
assert(cmd)
if vis.win.file.path ~= doc_pos.file then
if vis.win.file.modified and cmd == 'e' then
if lspc_confirm('Save currently open file:') then
vis:command('w')
else
vis:info('Not opening new file, current file has unsaved changes')
return
end
end
vis_open_file(doc_pos.file, cmd)
if doc_pos.line then
vis.win.selection:to(doc_pos.line, doc_pos.col or 0)
end
vis:command('lspc-open')
else
vis.win.selection:to(doc_pos.line, doc_pos.col)
end
end
-- Support jumping between document positions
-- Stack of edited document positions
local doc_pos_history = {}
local function vis_push_doc_pos(win)
local old_doc_pos = vis_get_doc_pos(win)
table.insert(doc_pos_history, old_doc_pos)
end
-- open a new doc_pos remembering the old if it is replaced
local function vis_open_new_doc_pos(doc_pos, cmd, win)
win = win or vis.win
if cmd == 'e' then
vis_push_doc_pos(win)
end
vis_open_doc_pos(doc_pos, cmd, win)
end
lspc.open_file = function(win, path, line, col, cmd)
vis_open_new_doc_pos({file = path, line = line, col = col}, cmd or 'e', win)
end
local function vis_pop_doc_pos(win)
local last_doc_pos = table.remove(doc_pos_history)
if not last_doc_pos then
return 'Document history is empty'
end
vis_open_doc_pos(last_doc_pos, 'e', win)
end
-- apply a textEdit received from the language server
local function vis_apply_textEdit(win, file, textEdit)
assert(win.file == file)
local range = lsp_range_to_vis_range(win, textEdit.range)
file:delete(range)
file:insert(range.start, textEdit.newText)
win.selection.anchored = false
win.selection.pos = range.start + string.len(textEdit.newText)
win:draw()
end
-- apply a list of textEdits received from the language server
local function vis_apply_textEdits(win, file, textEdits)
assert(win.file == file)
local edits = {}
for _, textEdit in ipairs(textEdits) do
local range = lsp_range_to_vis_range(win, textEdit.range)
table.insert(edits, {
mark = file:mark_set(range.start),
len = range.finish - range.start,
newText = textEdit.newText,
})
end
for _, edit in ipairs(edits) do
local pos = file:mark_get(edit.mark)
file:delete(pos, edit.len)
file:insert(pos, edit.newText)
end
win:draw()
end
--- Close the message window
-- TODO: close the dedicated lspc message window
local function lspc_close_message_win()
if lspc.show_message == 'message' then
vis:message('')
vis:command('q')
end
end
--- Present a message to the user
-- TODO: use a dedicated lspc message window
local function lspc_show_message(msg, hdr, syntax)
local current_win = vis.win
if lspc.show_message == 'message' then
local to_show = (hdr or '') .. msg .. '\n'
vis:message(to_show)
vis.win.selection = vis.win.file.size - #to_show
vis:feedkeys('zt')
elseif lspc.show_message == 'open' then
vis:command('open')
if syntax then
vis:command('set syntax ' .. syntax)
end
vis.win.file:insert(0, msg)
vis.win.selection.pos = 0
else
lspc:err('invalid message configuration "' .. lspc.show_message .. '".')
end
-- reset the focus to the current window
vis.win = current_win
end
-- apply a WorkspaceEdit received from the language server
local function vis_apply_workspaceEdit(_, _, workspaceEdit)
local file_edits = workspaceEdit.changes
assert(file_edits or workspaceEdit.documentChanges)
-- try to convert NOT SUPPORTED TextDocumentEdit[]
-- We do not announce support for versioned DocumentChanges in our
-- client capabilities, but some LSP servers ignore our capabilities
-- sending them anyway.
if not file_edits then
file_edits = {}
for _, edit in ipairs(workspaceEdit.documentChanges) do
file_edits[edit.textDocument.uri] = edit.edits
end
end
-- generate change summary
local summary = '--- workspace edit summary ---\n'
for uri, edits in pairs(file_edits) do
local path = uri_to_path(uri)
summary = summary .. path .. ':\n'
for i, edit in ipairs(edits) do
summary = summary .. '\t' .. i .. '.: ' .. lspc.json.encode(edit) .. '\n'
end
end
lspc_show_message(summary)
vis:redraw()
-- get user confirmation
local confirmation = lspc_confirm('apply changes:')
-- close summary window
lspc_close_message_win()
if not confirmation then
return
end
-- apply changes to open files
for uri, edits in pairs(file_edits) do
local path = uri_to_path(uri)
-- search all open windows for this uri
local win_with_file
for win in vis:windows() do
if win.file and win.file.path == path then
win_with_file = win
break
end
end
-- The file is not currently opened -> open it
local opened
if not win_with_file then
vis_open_file(path, 'o')
win_with_file = vis.win
opened = true
end
-- Remember the current primary cursor position
local old_pos = win_with_file.selection.pos
for _, edit in ipairs(edits) do
vis_apply_textEdit(win_with_file, win_with_file.file, edit)
end
-- Restore the remembered primary cursor position
if lspc.workspace_edit_remember_cursor then
win_with_file.selection.pos = old_pos
end
-- save changes and close the opened window
if opened then
vis:command('wq')
end
end
end
-- translate file line number to the relative row the line is displayed in the view of a window
-- returns an integer relative to the window if line is in view (starting at 1)
-- returns nil otherwise
local function file_lineno_to_viewport_lineno(win, file_lineno)
-- The line is not in the current viewport
if file_lineno < win.viewport.lines.start or file_lineno > win.viewport.lines.finish then
return nil
end
-- The line is in the viewport and there is no wrapped line
if win.viewport.lines.finish - win.viewport.lines.start == win.viewport.height then
return file_lineno - win.viewport.lines.start
else -- Determine the position in the viewport considering possible prior wrapped lines
local view_lineno = 0
for n = win.viewport.lines.start, file_lineno do
view_lineno = view_lineno + 1
-- Wrapped line this shifts our displayed line down
if #win.file.lines[n] > win.viewport.width then
view_lineno = view_lineno + math.floor(#win.file.lines[n] / win.viewport.width)
end
end
return view_lineno
end
end
local function lspc_highlight_server_diagnostics(win, server_diagnostics, style)
if not style then
style = lspc.diagnostic_style_id or win.STYLE_LEXER_MAX
end
local level_mapping = {
[1] = lspc.diagnostic_styles.error,
[2] = lspc.diagnostic_styles.warning,
[3] = lspc.diagnostic_styles.information,
[4] = lspc.diagnostic_styles.hint,
}
for _, diagnostic in ipairs(server_diagnostics) do
local diagnostic_style = level_mapping[diagnostic.severity] or level_mapping[1]
assert(win:style_define(style, diagnostic_style))
if lspc.highlight_diagnostics == 'range' then
local range = diagnostic.vis_range
-- LSP ranges use an exclusive finish
local finish = range.finish - 1
-- make sure to highlight only ranges which actually contain the diagnostic
if diagnostic.content == win.file:content(range) then
win:style(style, range.start, finish)
end
elseif lspc.highlight_diagnostics == 'line' then
if not win.style_pos then
lspc:err('Vis build does not support style_pos')
return
end
local start_line = diagnostic.range.start.line
local end_line = diagnostic.range['end'].line
for line = start_line, end_line, 1 do
local row = file_lineno_to_viewport_lineno(win, line)
if row then
-- Heuristic how many cells need to be styled
-- (at least one plus the decimal places of the line number).
for i = 0, #('' .. line) do
win:style_pos(style, i, row)
end
end
end
end
end
end
local function lspc_highlight_diagnostics(win, diagnostics, style)
for _, server_diagnostics in pairs(diagnostics) do
lspc_highlight_server_diagnostics(win, server_diagnostics, style)
end
end
-- send a rpc message to a language server
local function ls_rpc(ls, req)
req.jsonrpc = '2.0'
local content_part = lspc.json.encode(req)
local content_len = string.len(content_part)
local header_part = 'Content-Length: ' .. tostring(content_len)
local msg = header_part .. '\r\n\r\n' .. content_part
lspc:log('LSPC Sending -> ' .. ls.name .. ': ' .. msg)
ls.fd:write(msg)
ls.fd:flush()
end
-- send a rpc notification to a language server
local function ls_send_notification(ls, method, params)
ls_rpc(ls, {method = method, params = params})
end
local function ls_send_did_change(ls, file)
lspc:log('send didChange')
local new_version = assert(lspc.open_files[file.path]).version + 1
lspc.open_files[file.path].version = new_version
local document = {uri = path_to_uri(file.path), version = new_version}
local changes = {{text = file:content(0, file.size)}}
local params = {textDocument = document, contentChanges = changes}
ls_send_notification(ls, 'textDocument/didChange', params)
end
-- send a rpc method call to a language server
local function ls_call_method(ls, method, params, win, ctx)
local id = ls.id
ls.id = ls.id + 1
local req = {id = id, method = method, params = params}
ls.inflight[id] = req
ls_rpc(ls, req)
-- remember the current window to apply the effects of a
-- method call in the original window
ls.inflight[id].win = win
-- remember the user provided ctx value
-- ctx can be used to remember arbitrary data from method invocation till
-- method response handling
-- The goto-location methods remember in ctx how to open the location
ls.inflight[id].ctx = ctx
end
-- call textDocument/<method> and send a didChange notification upfront
-- to make sure the server sees our current state.
-- This is not ideal since we are sending more data than needed and
-- the server has less time to parse the new file content and do its work
-- resulting in longer stalls after method invocation.
local function ls_call_text_document_method(ls, method, params, win, ctx)
ls_send_did_change(ls, win.file)
ls:call_method('textDocument/' .. method, params, win, ctx)
end
local function lspc_handle_goto_method_response(req, result)
if not result or next(result) == nil then
lspc:warn(req.method .. ' found no results')
return
end
local location
-- result actually a list of results
if type(result) == 'table' then
location = lspc_select_location(result)
if not location then
return
end
else
location = result
end
assert(location)
-- location is a Location
local lsp_doc_pos
if location.uri then
lspc:log('Handle location: ' .. lspc.json.encode(location))
lsp_doc_pos = {
textDocument = {uri = location.uri},
position = {
line = location.range.start.line,
character = location.range.start.character,
},
}
-- location is a LocationLink
elseif location.targetUri then
lspc:log('Handle locationLink: ' .. lspc.json.encode(location))
lsp_doc_pos = {
textDocument = {uri = location.targetUri},
position = {
line = location.targetSelectionRange.start.line,
character = location.targetSelectionRange.start.character,
},
}
else
lspc:warn('Unknown location type: ' .. lspc.json.encode(location))
end
local doc_pos = lsp_doc_pos_to_vis(lsp_doc_pos)
vis_open_new_doc_pos(doc_pos, req.ctx, req.win)
end
local function lspc_handle_completion_method_response(win, result, old_pos)
if not result or not result.items then
lspc:warn('no completion available')
return
end
local completions = result
if result.isIncomplete ~= nil then
completions = result.items
end
local choices = {}
for _, completion in ipairs(completions) do
table.insert(choices, completion.label)
choices[completion.label] = completion
end
-- select a completion
local choice = lspc_select(choices)
if not choice then
return
end
local completion = choices[choice]
if completion.textEdit then
vis_apply_textEdit(win, win.file, completion.textEdit)
return
end
if completion.insertText or completion.label then
-- Does our current state correspont to the state when the completion method
-- was called.
-- Otherwise we don't have a good way to apply the 'insertText' completion
if win.selection.pos ~= old_pos then
lspc:warn('can not apply textInsert because the cursor position changed')
end
local new_word = completion.insertText or completion.label
local old_word_range = win.file:text_object_word(old_pos)
local old_word = win.file:content(old_word_range)
lspc:log(string.format('Completion old_pos=%d, old_range={start=%d, finish=%d}, old_word=%s',
old_pos, old_word_range.start, old_word_range.finish,
old_word:gsub('\n', '\\n')))
-- update old_word_range and old_word and return if old_word is a prefix of the completion
local function does_completion_apply_to_pos(pos)
old_word_range = win.file:text_object_word(pos)
old_word = win.file:content(old_word_range)
local is_prefix = new_word:sub(1, string.len(old_word)) == old_word
return is_prefix
end
-- search for a possible completion token which we should replace with this insertText
local matches = does_completion_apply_to_pos(old_pos)
if not matches then
lspc:log('Cursor looks like its not on the completion token')
-- try the common case the cursor is behind its completion token: fooba┃
local next_pos_candidate = old_pos - 1
matches = does_completion_apply_to_pos(next_pos_candidate)
if matches then
old_pos = next_pos_candidate
end
end
local completion_start
-- we found a completion token -> replace it
if matches then
lspc:log('replace the token: ' .. old_word .. ' we found being a prefix of the completion')
win.file:delete(old_word_range)
completion_start = old_word_range.start
else
completion_start = old_pos
end
-- apply insertText
win.file:insert(completion_start, new_word)
win.selection.pos = completion_start + string.len(new_word)
win:draw()
return
end
-- neither insertText nor textEdit where present
lspc:err('Unsupported completion')
end
local function lspc_handle_hover_method_response(win, result, old_pos)
if not result or not result.contents then
lspc:warn('no hover available')
return
end
local sel = vis_pos_to_sel(win, old_pos)
local hover_header =
'--- hover: ' .. (win.file.path or '') .. ': ' .. sel.line .. ', ' .. sel.col .. ' ---\n'
local hover_msg = ''
-- The most common markup kind in LSP is markdown
local markup_kind = 'markdown'
-- result is MarkedString[]
if type(result.contents) == 'table' and #result.contents > 0 then
lspc:log('hover returned list of length ' .. #result.contents)
for i, marked_string in ipairs(result.contents) do
if i == 1 then
hover_msg = marked_string.value or marked_string
else
hover_msg = hover_msg .. '\n---\n' .. (marked_string.value or marked_string)
end
end
else -- result is either MarkedString or MarkupContent
hover_msg = result.contents.value or result.contents
if result.contents.kind and result.contents.kind == 'plaintext' then
markup_kind = 'text'
end
end
lspc_show_message(hover_msg, hover_header, markup_kind)
end
local function lspc_handle_signature_help_method_response(win, result, call_pos)
if not result or not result.signatures or #result.signatures == 0 then
lspc:warn('no signature help available')
return
end
local signatures = result.signatures
local sel = vis_pos_to_sel(win, call_pos)
local help_header = '--- signature help: ' .. (win.file.path or '') .. ': ' .. sel.line .. ', ' ..
sel.col .. ' ---\n'
-- local help_msg = lspc.json.encode(result)
local help_msg = ''
for _, signature in ipairs(signatures) do
local sig_msg = signature.label
if signature.documentation then
local doc = signature.documentation.value or signature.documentation
sig_msg = sig_msg .. '\n\tdocumentation: ' .. doc
end
help_msg = help_msg .. '\n' .. sig_msg
end
-- strip first new line from the message
help_msg = help_msg:sub(2)
lspc_show_message(help_msg, help_header)
end
local function lspc_handle_rename_method_response(win, result)
-- result must always be valid because otherwise we would caught the error
-- in ls_handle_method_response
vis_apply_workspaceEdit(win, win.file, result)
end
local function lspc_handle_formatting_method_response(win, result)
-- The result of textDocument/formatting is defined as TextEdit[] | null
if result then
vis_apply_textEdits(win, win.file, result)
end
end
local function lspc_handle_initialize_response(ls, result)
ls.initialized = true
ls.capabilities = result.capabilities
local params = {}
setmetatable(params, {__jsontype = 'object'})
ls_send_notification(ls, 'initialized', params)
-- According to nvim-lspconfig sendig the lsp server settings shortly after
-- initialization is a undocumented convention.
-- See https://github.com/neovim/nvim-lspconfig/blob/ed88435764d8b00442e66d39ec3d9c360e560783/CONTRIBUTING.md
if ls.settings then
ls_send_notification(ls, 'workspace/didChangeConfiguration', {
settings = ls.settings,
})
end
vis.events.emit(lspc.events.LS_INITIALIZED, ls)
end
-- method response dispatcher
local function ls_handle_method_response(ls, method_response, req)
local win = req.win
local method = req.method
local err = method_response.error
if err then
local err_msg = err.message
local err_code = err.code
lspc:err(err_msg .. ' (' .. err_code .. ') occurred during ' .. method)
-- Don't try to handle error responses any further
return
end
local result = method_response.result
-- LuaFormatter off
if method == 'textDocument/definition' or
method == 'textDocument/declaration' or
method == 'textDocument/typeDefinition' or
method == 'textDocument/implementation' or
method == 'textDocument/references' then
-- LuaFormatter on
lspc_handle_goto_method_response(req, result)
elseif method == 'initialize' then
lspc_handle_initialize_response(ls, result)
elseif method == 'textDocument/completion' then
lspc_handle_completion_method_response(win, result, req.ctx)
elseif method == 'textDocument/hover' then
lspc_handle_hover_method_response(win, result, req.ctx)
elseif method == 'textDocument/signatureHelp' then
lspc_handle_signature_help_method_response(win, result, req.ctx)
elseif method == 'textDocument/rename' then
lspc_handle_rename_method_response(win, result)
elseif method == 'textDocument/formatting' then
lspc_handle_formatting_method_response(win, result)
elseif method == 'shutdown' then
ls_send_notification(ls, 'exit')
ls.fd:close()
-- remove the ls from lspc.running
for ls_name, rls in pairs(lspc.running) do
if ls == rls then
lspc.running[ls_name] = nil
break
end
end
else
lspc:warn('received unknown method ' .. method)
end
ls.inflight[method_response.id] = nil
end