-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathinit.lua
More file actions
3265 lines (2961 loc) · 103 KB
/
Copy pathinit.lua
File metadata and controls
3265 lines (2961 loc) · 103 KB
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
--- mod-version:3.11
--
-- LSP client for Pragtical
-- @copyright Jefferson Gonzalez
-- @license MIT
--
-- Note: Annotations syntax documentation which is supported by
-- https://github.com/LuaLS/lua-language-server can be read here:
-- https://github.com/LuaLS/lua-language-server/wiki/Annotations
-- TODO Change the code to make it possible to use more than one LSP server
-- for a single file if possible and needed, for eg:
-- One lsp may not support goto definition but another one registered
-- for the current document filetype may do.
local core = require "core"
local common = require "core.common"
local config = require "core.config"
local command = require "core.command"
local style = require "core.style"
local keymap = require "core.keymap"
local translate = require "core.doc.translate"
local autocomplete = require "plugins.autocomplete"
local Doc = require "core.doc"
local DocView = require "core.docview"
local MarkdownView = require "core.markdownview"
local StatusView = require "core.statusview"
local RootView = require "core.rootview"
local contextmenu
local json = require "plugins.lsp.json"
local util = require "plugins.lsp.util"
local listbox = require "plugins.lsp.listbox"
local protocol = require "plugins.lsp.protocol"
local diagnostics = require "plugins.lsp.diagnostics"
local workspaceedit = require "plugins.lsp.workspaceedit"
local Server = require "plugins.lsp.server"
local Timer = require "plugins.lsp.timer"
local RenameSymbol = require "plugins.lsp.ui.renamesymbol"
local SymbolResults = require "plugins.lsp.ui.symbolresults"
local SymbolsTree = require "plugins.lsp.ui.symbolstree"
local MessageBox = require "widget.messagebox"
local snippets_found, snippets = pcall(require, "plugins.snippets")
---@alias lsp.plugin.location lsp.protocol.Location | lsp.protocol.LocationLink
---@alias lsp.plugin.locationlist lsp.plugin.location[]
---@alias lsp.plugin.symbollist lsp.protocol.DocumentSymbol[] | lsp.protocol.SymbolInformation[]
---@alias lsp.plugin.textedit lsp.protocol.TextEdit | lsp.protocol.InsertReplaceEdit
---@alias lsp.plugin.codeaction lsp.protocol.CodeAction | lsp.protocol.Command
---@class lsp.plugin.contentchange
---@field range lsp.protocol.Range
---@field text string
---@class lsp.plugin.positionparams : lsp.protocol.TextDocumentPositionParams
---@field context? lsp.protocol.CompletionContext | { includeDeclaration: boolean }
---@field newName? string
---@class lsp.plugin.workspaceconfigitem
---@field section? string
---@field scopeUri? lsp.protocol.DocumentUri
---@class lsp.plugin.workspaceconfigparams
---@field items lsp.plugin.workspaceconfigitem[]
---@class lsp.plugin.showdocumentparams
---@field external? boolean
---@field uri lsp.protocol.DocumentUri
---@field selection? lsp.protocol.Range
---@field takeFocus? boolean
---@class lsp.plugin.publishdiagnosticsparams
---@field uri lsp.protocol.DocumentUri
---@field diagnostics lsp.protocol.Diagnostic[]
---@class lsp.plugin.showmessageparams
---@field type lsp.protocol.MessageType
---@field message string
--
-- Main plugin functionality
--
local lsp = {}
--
-- Plugin settings
--
---Configuration options for the LSP plugin.
---@class config.plugins.lsp
---Set to a file path to log all json
---@field log_file string
---Setting to true prettyfies json for more readability on the log
---but this setting will impact performance so only enable it when
---in need of easy to read json output when developing the plugin.
---@field prettify_json boolean
---Show a symbol hover information when mouse cursor is on top.
---@field mouse_hover boolean
---The amount of time in milliseconds before showing the tooltip.
---@field mouse_hover_delay integer
---Show diagnostic messages
---@field show_diagnostics boolean
---Amount of milliseconds to delay updating the inline diagnostics.
---@field diagnostics_delay number
---Wether to enable snippets processing.
---@field snippets boolean
---Allow the application of additional text edits on completion, eg: #includes, imports, etc...
---@field apply_additional_edits boolean
---Stop servers that aren't needed by any of the open files
---@field stop_unneeded_servers boolean
---The amount of seconds to keep the server active before stopping it
---@field server_quit_timeout number
---Send a server stderr output to pragtical log
---@field log_server_stderr boolean
---Force verbosity off even if a server is configured with verbosity on
---@field force_verbosity_off boolean
---Yield when reading from LSP which may give you better UI responsiveness
---when receiving large responses, but will affect LSP performance.
---@field more_yielding boolean
---The amount of times per second to check for new server data.
---@field checks_per_second number
---Determines the default visibility of the symbols tree.
---@field symbolstree_visibility "show" | "hide" | "auto"
---Request a document format after a save.
---@field request_format_on_save bool
config.plugins.lsp = common.merge({
mouse_hover = true,
mouse_hover_delay = 300,
show_diagnostics = true,
diagnostics_delay = 500,
snippets = true,
apply_additional_edits = true,
stop_unneeded_servers = true,
server_quit_timeout = 60,
log_file = "",
prettify_json = false,
log_server_stderr = false,
force_verbosity_off = false,
more_yielding = false,
checks_per_second = 25,
autostart_server = true,
symbolstree_visibility = "auto",
symbolstree_width = 300 * SCALE,
request_format_on_save = false,
-- The config specification used by the settings gui
config_spec = {
name = "Language Server Protocol",
{
label = "Mouse Hover",
description = "Show a symbol hover information when mouse cursor is on top.",
path = "mouse_hover",
type = "TOGGLE",
default = true
},
{
label = "Mouse Hover Delay",
description = "The amount of time in milliseconds before showing the tooltip.",
path = "mouse_hover_delay",
type = "NUMBER",
default = 300,
min = 50,
max = 2000
},
{
label = "Diagnostics",
description = "Show inline diagnostic messages with lint+.",
path = "show_diagnostics",
type = "TOGGLE",
default = false
},
{
label = "Diagnostics Delay",
description = "Amount of milliseconds to delay the update of inline diagnostics.",
path = "diagnostics_delay",
type = "NUMBER",
default = 500,
min = 100,
max = 10000
},
{
label = "Snippets",
description = "Snippets processing using lsp_snippets, may need a restart.",
path = "snippets",
type = "TOGGLE",
default = true
},
{
label = "Apply Additional Completion Edits",
description = "Allow the application of additional text edits on completion, eg: #includes, imports, etc...",
path = "apply_additional_edits",
type = "TOGGLE",
default = true
},
{
label = "Autostart Server",
description = "Automatically start server when opening a file",
path = "autostart_server",
type = "TOGGLE",
default = true
},
{
label = "Stop Servers",
description = "Stop servers that aren't needed by any of the open files.",
path = "stop_unneeded_servers",
type = "TOGGLE",
default = true
},
{
label = "Stop Servers Timeout",
description = "Amount of seconds to keep a server active before stopping it.",
path = "server_quit_timeout",
type = "NUMBER",
default = 60,
min = 0,
max = 300
},
{
label = "Log File",
description = "Absolute path to a '.log' file for logging all json.",
path = "log_file",
type = "FILE",
filters = {"%.log$"}
},
{
label = "Prettify JSON",
description = "Prettify json for more readability but impacts performance.",
path = "prettify_json",
type = "TOGGLE",
default = false
},
{
label = "Log Standard Error",
description = "Send a server stderr output to pragtical log.",
path = "log_server_stderr",
type = "TOGGLE",
default = false
},
{
label = "Force Verbosity Off",
description = "Turn verbosity off even if a server is configured with verbosity on.",
path = "force_verbosity_off",
type = "TOGGLE",
default = false
},
{
label = "More Yielding",
description = "Yield when reading from LSP which may give you better UI responsiveness.",
path = "more_yielding",
type = "TOGGLE",
default = false
},
{
label = "Checks Per Second",
description = "The amount of times per second to check for new server data. Higher is faster but consumes more CPU.",
path = "checks_per_second",
type = "NUMBER",
default = 25,
min = 10,
max = 100,
step = 1
},
{
label = "Symbols Tree Visibility",
description = "Default visibility mode of the document symbols tree.",
path = "symbolstree_visibility",
type = "selection",
default = "auto",
values = {
{ "Auto", "auto" },
{ "Show", "show" },
{ "Hide", "hide" },
},
on_apply = function(value)
if value == "auto" then
lsp.symbols_tree:set_auto_hide(true)
else
lsp.symbols_tree:set_auto_hide(false)
if value == "show" then
lsp.symbols_tree:show()
else
lsp.symbols_tree:hide()
end
end
end
},
{
label = "Symbols Tree Width",
description = "Default width for the symbols tree pane.",
path = "symbolstree_width",
type = "number",
default = 300 * SCALE,
get_value = function(value)
return value / SCALE
end,
set_value = function(value)
return value * SCALE
end,
on_apply = function(value)
lsp.symbols_tree:set_size(value)
end
},
{
label = "Request Document Format on Save",
description = "Request a document format after save. Due to the nature of LSP this will produce a second document save after receiving the formatted code.",
path = "request_format_on_save",
type = "TOGGLE",
default = false
},
}
}, config.plugins.lsp)
---List of registered servers
---@type table<string, lsp.server.options>
lsp.servers = {}
---List of running servers
---@type table<string, lsp.server>
lsp.servers_running = {}
---Flag that indicates if last autocomplete request was a trigger
---to prevent requesting another autocompletion request until the
---autocomplete box is hidden since some lsp servers loose context
---and return wrong results (eg: lua-language-server)
---@type boolean
lsp.in_trigger = false
---Flag that indicates if the user typed something on the editor to try and
---call autocomplete only when neccesary.
---@type boolean
lsp.user_typed = false
---Used on the hover timer to display hover info
---@class lsp.hover_position
---@field doc core.doc | nil
---@field line integer
---@field col integer
---@field triggered boolean
lsp.hover_position = {doc = nil, line = 0, col = 0, triggered = false}
---@type lsp.timer
lsp.hover_timer = Timer(300, true)
lsp.hover_timer.on_timer = function()
lsp.request_hover(
lsp.hover_position.doc,
lsp.hover_position.line,
lsp.hover_position.col
)
end
--
-- Private functions
--
---Generate an lsp location object
---@param doc core.doc
---@param line integer
---@param col integer
---@return lsp.plugin.positionparams
local function get_buffer_position_params(doc, line, col)
return {
textDocument = {
uri = util.touri(core.project_absolute_path(doc.filename)),
},
position = {
line = line - 1,
character = util.doc_utf8_to_utf16(doc, line, col) - 1
}
}
end
---Generate an lsp text document range object.
---@param doc core.doc
---@param line1 integer
---@param col1 integer
---@param line2 integer
---@param col2 integer
---@return lsp.protocol.CodeActionParams
local function get_buffer_range_params(doc, line1, col1, line2, col2)
if line2 < line1 or (line2 == line1 and col2 < col1) then
line1, col1, line2, col2 = line2, col2, line1, col1
end
return {
textDocument = {
uri = util.touri(core.project_absolute_path(doc.filename)),
},
range = {
start = {
line = line1 - 1,
character = util.doc_utf8_to_utf16(doc, line1, col1) - 1
},
["end"] = {
line = line2 - 1,
character = util.doc_utf8_to_utf16(doc, line2, col2) - 1
}
},
context = {
diagnostics = {}
}
}
end
---@param a lsp.protocol.Position
---@param b lsp.protocol.Position
local function position_le(a, b)
return a.line < b.line or (a.line == b.line and a.character <= b.character)
end
---@param range lsp.protocol.Range
---@param diagnostic lsp.protocol.Diagnostic
local function range_intersects_diagnostic(range, diagnostic)
local d_range = diagnostic.range
return position_le(range.start, d_range["end"])
and position_le(d_range.start, range["end"])
end
---Collect document diagnostics that overlap a range.
---@param doc core.doc
---@param range lsp.protocol.Range
---@return lsp.protocol.Diagnostic[]
local function get_code_action_diagnostics(doc, range)
local diagnostic_messages = diagnostics.get(doc.filename)
or diagnostics.get(core.project_absolute_path(doc.filename))
or diagnostics.get(core.normalize_to_project_dir(doc.abs_filename or doc.filename))
local result = {}
for _, diagnostic in ipairs(diagnostic_messages or {}) do
if range_intersects_diagnostic(range, diagnostic) then
table.insert(result, diagnostic)
end
end
return result
end
---Check if the current document range has diagnostics that can drive actions.
---@param doc core.doc
---@param line1 integer
---@param col1 integer
---@param line2 integer
---@param col2 integer
---@return boolean
local function has_code_action_diagnostics(doc, line1, col1, line2, col2)
local request_params = get_buffer_range_params(doc, line1, col1, line2, col2)
return #get_code_action_diagnostics(doc, request_params.range) > 0
end
---Recursive function to generate a list of symbols ready
---to use for the lsp.request_document_symbols() action.
---@param list lsp.plugin.symbollist
---@param parent? string
local function get_symbol_lists(list, parent)
local symbols = {}
local symbol_names = {}
parent = parent or ""
parent = #parent > 0 and (parent .. "/") or parent
for _, symbol in pairs(list) do
-- Include symbol kind to be able to filter by it
local symbol_name = parent
.. symbol.name
.. "||" .. Server.get_symbol_kind(symbol.kind)
table.insert(symbol_names, symbol_name)
symbols[symbol_name] = { kind = symbol.kind }
if symbol.location then
symbols[symbol_name].location = symbol.location
else
if symbol.range then
symbols[symbol_name].range = symbol.range
end
if symbol.uri then
symbols[symbol_name].uri = symbol.uri
end
end
if symbol.children and #symbol.children > 0 then
local child_symbols, child_names = get_symbol_lists(
symbol.children, parent .. symbol.name
)
for _, name in pairs(child_names) do
table.insert(symbol_names, name)
symbols[name] = child_symbols[name]
end
end
end
return symbols, symbol_names
end
local function log(server, message, ...)
if server.verbose then
core.log("["..server.name.."] " .. message, ...)
else
core.log_quiet("["..server.name.."] " .. message, ...)
end
end
---Check if active view is a DocView and return it
---@return core.docview|nil
local function get_active_docview()
local av = core.active_view
if getmetatable(av) == DocView and av.doc and av.doc.filename then
return av
end
return nil
end
---Generates a code preview of a location
---@param location lsp.plugin.location
local function get_location_preview(location)
local line1, col1 = util.toselection(
location.range or location.targetRange
)
local filename = core.normalize_to_project_dir(
util.tofilename(location.uri or location.targetUri)
)
local abs_filename = core.project_absolute_path(filename)
local file = io.open(abs_filename)
if not file then
return "", filename .. ":" .. tostring(line1) .. ":" .. tostring(col1)
end
local preview = ""
-- sometimes the lsp can send the location of a definition where the
-- doc comments should be written but if no docs are written the line
-- is empty and subsequent line is the one we are interested in.
local line_count = 1
for line in file:lines() do
if line_count >= line1 then
preview = line:gsub("^%s+", "")
:gsub("%s+$", "")
if preview ~= "" then
break
else
-- change also the location table
if location.range then
location.range.start.line = location.range.start.line + 1
location.range['end'].line = location.range['end'].line + 1
elseif location.targetRange then
location.targetRange.start.line = location.targetRange.start.line + 1
location.targetRange['end'].line = location.targetRange['end'].line + 1
end
end
end
line_count = line_count + 1
end
file:close()
local position = filename .. ":" .. tostring(line1) .. ":" .. tostring(col1)
return preview, position
end
---Generate a list ready to use for the lsp.request_references() action.
---@param locations lsp.plugin.locationlist
local function get_references_lists(locations)
local references, reference_names = {}, {}
for _, location in pairs(locations) do
local preview, position = get_location_preview(location)
local name = preview .. "||" .. position
table.insert(reference_names, name)
references[name] = location
end
return references, reference_names
end
---Apply a completion text edit to a document if possible.
---@param server lsp.server
---@param doc core.doc
---@param text_edit lsp.plugin.textedit
---@param is_snippet boolean
---@param update_cursor_position boolean
---@return boolean True on success
local function apply_completion_edit(
server, doc, text_edit, is_snippet, update_cursor_position
)
local range = nil
if text_edit.range then
range = text_edit.range
elseif text_edit.insert then
range = text_edit.insert
elseif text_edit.replace then
range = text_edit.replace
end
if not range then return false end
local text = text_edit.newText
local line1, col1, line2, col2
local current_text = ""
if
not server.capabilities.positionEncoding
or
server.capabilities.positionEncoding == protocol.PositionEncodingKind.UTF16
then
line1, col1, line2, col2 = util.toselection(range, doc)
else
core.error(
"[LSP] Unsupported position encoding: ",
server.capabilities.positionEncoding
)
return false
end
if lsp.in_trigger then
local cline2, ccol2 = doc:get_selection()
local cline1, ccol1 = doc:position_offset(line2, col2, translate.start_of_word)
current_text = doc:get_text(cline1, ccol1, cline2, ccol2)
end
if is_snippet and snippets_found and config.plugins.lsp.snippets then
doc:remove(line1, col1, line2, col2 + #current_text)
doc:set_selection(line1, col1, line1, col1)
snippets.execute {format = 'lsp', template = text}
return true
end
if not workspaceedit.apply_text_edit(server, doc, text_edit, #current_text) then
return false
end
if update_cursor_position then
doc:move_to_cursor(nil, #text)
end
return true
end
---Callback given to autocomplete plugin which is executed once for each
---element of the autocomplete box which is hovered with the idea of providing
---better description of the selected element by requesting the LSP server for
---detailed information/documentation.
---@param index integer
---@param item autocomplete.item
local function autocomplete_onhover(index, item)
local completion_item = item.data.completion_item
if item.data.server.verbose then
item.data.server:log(
"Resolve item: %s", util.jsonprettify(json.encode(completion_item))
)
end
-- Only send resolve request if data field (which should contain
-- the item id) is available.
if completion_item.data then
item.data.server:push_request('completionItem/resolve', {
params = completion_item,
callback = function(server, response)
if response.result then
local symbol = response.result
if symbol.detail and #item.desc <= 0 then
item.desc = symbol.detail
end
if symbol.documentation then
if #item.desc > 0 then
item.desc = item.desc .. "\n\n"
end
if
type(symbol.documentation) == "table"
and
symbol.documentation.value
then
item.desc = item.desc .. symbol.documentation.value
else
item.desc = item.desc .. symbol.documentation
end
end
item.desc = item.desc:gsub("[%s\n]+$", "")
:gsub("^[%s\n]+", "")
:gsub("\n\n\n+", "\n\n")
if server.verbose then
server:log(
"Resolve response: %s", util.jsonprettify(json.encode(symbol))
)
end
elseif server.verbose then
server:log("Resolve returned empty response")
end
item.data.resolved = true
end
})
end
end
---Callback that handles insertion of an autocompletion item that has
---the information of insertion
---@param index integer
---@param item autocomplete.item
local function autocomplete_onselect(index, item)
local completion = item.data.completion_item
local dv = get_active_docview()
local edit_applied = false
if completion.textEdit then
if dv then
-- Restore previous partial since the complete request is async and
-- new text could have been written while retrieving autocomplete items
-- which results in invalid insert positions if we don't revert partial
local current_partial = {autocomplete.get_partial_symbol()}
if current_partial[1] ~= item.data.partial[1] then
local partial, pl1, pc1, pl2, pc2 = table.unpack(current_partial)
dv.doc:remove(pl1, pc1, pl2, pc2)
partial, pl1, pc1 = table.unpack(item.data.partial)
dv.doc:insert(pl1, pc1, partial)
end
local is_snippet = completion.insertTextFormat
and completion.insertTextFormat == protocol.InsertTextFormat.Snippet
edit_applied = apply_completion_edit(
item.data.server, dv.doc, completion.textEdit, is_snippet, true
)
if edit_applied then
-- Retrigger code completion if last char is a trigger
-- this is useful for example with clangd when autocompleting
-- a #include, if user types < a list of paths will appear
-- when selecting a path that ends with / as <AL/ the
-- autocompletion will be retriggered to show a list of
-- header files that belong to that directory.
lsp.in_trigger = false
local line, col = dv.doc:get_selection()
local char = dv.doc:get_char(line, col-1)
local char_prev = dv.doc:get_char(line, col-2)
if char:match("%p") or (char == " " and char_prev:match("%p")) then
if not util.table_empty(dv.doc.lsp_changes) then
lsp.update_document(dv.doc, true)
else
lsp.request_completion(dv.doc, line, col, true)
end
end
end
end
elseif
dv and snippets_found and config.plugins.lsp.snippets
and
completion.insertText and completion.insertTextFormat
and
completion.insertTextFormat == protocol.InsertTextFormat.Snippet
then
---@type core.doc
local doc = dv.doc
if dv then
local _, line1, col1, line2, col2 = autocomplete.get_partial_symbol()
doc:set_selection(line1, col1, line2, col2)
snippets.execute {format = 'lsp', template = completion.insertText}
edit_applied = true
end
end
if
dv and edit_applied and completion.additionalTextEdits
and
config.plugins.lsp.apply_additional_edits
then
-- TODO: Breaks snippets execution, in future we should apply additional
-- edits first and update completion item range before insert
core.add_thread(function()
while not item.data.resolved do coroutine.yield() end
workspaceedit.apply_text_edits(
item.data.server, dv.doc, completion.additionalTextEdits
)
end)
end
return edit_applied
end
--
-- Public functions
--
---Open a document location returned by LSP
---@param location lsp.plugin.location
function lsp.goto_location(location)
local doc_view = core.root_view:open_doc(
core.open_doc(
common.home_expand(
util.tofilename(location.uri or location.targetUri)
)
)
)
local line1, col1 = util.toselection(
location.range or location.targetRange, doc_view.doc
)
doc_view.doc:set_selection(line1, col1, line1, col1)
end
lsp.get_location_preview = get_location_preview
---Register an LSP server to be launched on demand
---@param options lsp.server.options
function lsp.add_server(options)
local required_fields = {
"name", "language", "file_patterns"
}
for _, field in pairs(required_fields) do
if not options[field] then
core.error(
"[LSP] You need to provide a '%s' field for the server.",
field
)
return false
end
end
if snippets_found and config.plugins.lsp.snippets then
options.snippets = true
end
options.transport = options.transport or "stdio"
if options.transport == "tcp" then
if not options.host or options.host == "" then
core.error("[LSP] Provide a host for tcp lsp servers.")
return false
end
if not options.port then
core.error("[LSP] Provide a port for tcp lsp servers.")
return false
end
end
if options.transport == "stdio" and (not options.command or #options.command <= 0) then
core.error("[LSP] Provide a command table list with the lsp command.")
return false
end
if not options.quit_timeout then
options.quit_timeout = config.plugins.lsp.server_quit_timeout or 60
end
-- some lsp servers may be installed with different binary names
-- so if command name is a list, search for one that exists
if options.command and type(options.command[1]) == "table" then
options.command[1] = util.get_best_executable(options.command[1])
end
-- On Windows use cmd.exe only for commands that need shell resolution or
-- script interpretation. Native .exe/.com programs are launched directly so
-- process termination targets the actual server.
if
PLATFORM == "Windows"
and options.command
and not options.windows_skip_cmd
and not util.win_command_is_executable(options.command[1])
then
table.insert(options.command, 1, "/C")
table.insert(options.command, 1, "cmd.exe")
end
if config.plugins.lsp.force_verbosity_off then
options.verbose = false
end
lsp.servers[options.name] = options
return true
end
---Get valid running lsp servers for a given filename
---@param filename string
---@param initialized boolean
---@return table active_servers
function lsp.get_active_servers(filename, initialized)
local servers = {}
for name, server in pairs(lsp.servers) do
if common.match_pattern(filename, server.file_patterns) then
if lsp.servers_running[name] then
local add_server = true
if
initialized
and
(
not lsp.servers_running[name].initialized
or
not lsp.servers_running[name].capabilities
)
then
add_server = false
end
if add_server then
table.insert(servers, name)
end
end
end
end
return servers
end
-- Used on lsp.get_workspace_settings()
local cached_workspace_settings = {}
local cached_workspace_settings_timestamp = 0
---Get table of configuration settings in the following way:
---1. Scan the USERDIR for .pragtical_lsp.lua or .pragtical_lsp.json (in that order)
---2. Merge server.settings
---4. Scan workspace if set also for .pragtical_lsp.lua/json and merge them or
---3. Scan server.path also for .pragtical_lsp.lua/json and merge them
---Note: settings are cached for 5 seconds for faster retrieval
--- on repetitive calls to this function.
---@param server lsp.server
---@param workspace? string
---@return lsp.protocol.LSPObject
function lsp.get_workspace_settings(server, workspace)
-- Search settings on the following directories, subsequent settings
-- overwrite the previous ones
local paths = { USERDIR }
local cached_index = USERDIR
local settings = {}
if not workspace and server.path then
table.insert(paths, server.path)
cached_index = cached_index .. tostring(server.path)
elseif workspace then
table.insert(paths, workspace)
cached_index = cached_index .. tostring(workspace)
end
if
cached_workspace_settings_timestamp > os.time()
and
cached_workspace_settings[cached_index]
then
return cached_workspace_settings[cached_index]
else
local position = 1
for _, path in pairs(paths) do
if path then
local settings_new = nil
path = path:gsub("\\+$", ""):gsub("/+$", "")
if util.file_exists(path .. "/.pragtical_lsp.lua") then
local settings_lua = dofile(path .. "/.pragtical_lsp.lua")
if type(settings_lua) == "table" then
settings_new = settings_lua
end
elseif util.file_exists(path .. "/.pragtical_lsp.json") then
local file = io.open(path .. "/.pragtical_lsp.json", "r")
if file then
local settings_json = file:read("*a")
settings_new = json.decode(settings_json)
file:close()
end
end
-- overwrite global settings by those specified in the server if any
if position == 1 and server.settings then
if settings_new then
settings_new = util.deep_merge(settings_new, server.settings)
else
settings_new = server.settings
end
end
-- overwrite previous settings with new ones
if settings_new then
settings = util.deep_merge(settings, settings_new)
end
end
position = position + 1
end
-- store settings on cache for 5 seconds for fast repeated calls
cached_workspace_settings[cached_index] = settings
cached_workspace_settings_timestamp = os.time() + 5
end
return settings
end
-- TODO Update workspace folders of already running lsp servers if required
--- Start all applicable lsp servers for a given file.
--- @param filename string
--- @param project_directory string
function lsp.start_server(filename, project_directory)
local server_started = false
local server_registered = false
local servers_not_found = {}
for name, server in pairs(lsp.servers) do
if common.match_pattern(filename, server.file_patterns) then
server_registered = true
if lsp.servers_running[name] then
server_started = true
end
local command_exists = false
if server.command and server.command[1] then
if util.command_exists(server.command[1]) then
command_exists = true