-
Notifications
You must be signed in to change notification settings - Fork 21
/
init.lua
2618 lines (2370 loc) · 82.3 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
--- mod-version:3
--
-- LSP client for lite-xl
-- @copyright Jefferson Gonzalez
-- @license MIT
--
-- Note: Annotations syntax documentation which is supported by
-- https://github.com/sumneko/lua-language-server can be read here:
-- https://emmylua.github.io/annotation.html
-- 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 StatusView = require "core.statusview"
local RootView = require "core.rootview"
local LineWrapping
-- If the lsp plugin is loaded from users init.lua it will load linewrapping
-- even if it was disabled from the settings ui, so we queue this check since
-- there is no way to automatically load settings ui before the user module.
core.add_thread(function()
if config.plugins.linewrapping or type(config.plugins.linewrapping) == "nil" then
LineWrapping = require "plugins.linewrapping"
end
end)
local json = require "plugins.lsp.json"
local util = require "plugins.lsp.util"
local listbox = require "plugins.lsp.listbox"
local diagnostics = require "plugins.lsp.diagnostics"
local Server = require "plugins.lsp.server"
local Timer = require "plugins.lsp.timer"
local SymbolResults = require "plugins.lsp.symbolresults"
local MessageBox = require "libraries.widget.messagebox"
local snippets_found, snippets = pcall(require, "plugins.snippets")
---@type lsp.helpdoc
local HelpDoc = require "plugins.lsp.helpdoc"
--
-- 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
---Stop servers that aren't needed by any of the open files
---@field stop_unneeded_servers boolean
---Send a server stderr output to lite 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
config.plugins.lsp = common.merge({
mouse_hover = true,
mouse_hover_delay = 300,
show_diagnostics = true,
diagnostics_delay = 500,
snippets = true,
stop_unneeded_servers = true,
log_file = "",
prettify_json = false,
log_server_stderr = false,
force_verbosity_off = false,
more_yielding = false,
autostart_server = true,
-- 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 = "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 = "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 lite 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
}
}
}, config.plugins.lsp)
--
-- Main plugin functionality
--
local 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 x number
---@field y number
---@field triggered boolean
---@field utf8_range table | nil
lsp.hover_position = {doc = nil, x = -1, y = -1, triggered = false, utf8_range = nil}
---@type lsp.timer
lsp.hover_timer = Timer(300, true)
lsp.hover_timer.on_timer = function()
local doc, line, col = lsp.get_hovered_location(lsp.hover_position.x, lsp.hover_position.y)
if not doc then return end
lsp.hover_position.triggered = true
lsp.hover_position.utf8_range = nil
lsp.hover_position.doc = doc
lsp.request_hover(doc, line, col)
end
--
-- Private functions
--
---Generate an lsp location object
---@param doc core.doc
---@param line integer
---@param col integer
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
---Recursive function to generate a list of symbols ready
---to use for the lsp.request_document_symbols() action.
---@param list table<integer, table>
---@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 table
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 table
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 an lsp textEdit to a document if possible.
---@param server lsp.server
---@param doc core.doc
---@param text_edit table
---@param is_snippet boolean
---@param update_cursor_position boolean
---@return boolean True on success
local function apply_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 == Server.position_encoding_kind.UTF16
then
line1, col1, line2, col2 = util.toselection(range, doc)
else
line1, col1, line2, col2 = util.toselection(range)
core.error(
"[LSP] Unsupported position encoding: ",
server.capabilities.positionEncoding
)
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
doc:remove(line1, col1, line2, col2+#current_text)
if is_snippet and snippets_found and config.plugins.lsp.snippets then
doc:set_selection(line1, col1, line1, col1)
snippets.execute {format = 'lsp', template = text}
return true
end
doc:insert(line1, col1, text)
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 table
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
if
symbol.documentation.kind
and
symbol.documentation.kind == "markdown"
then
item.desc = util.strip_markdown(item.desc)
end
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 symbol.additionalTextEdits then
completion_item.additionalTextEdits = symbol.additionalTextEdits
end
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
end
})
end
end
---Callback that handles insertion of an autocompletion item that has
---the information of insertion
---@param index integer
---@param item table
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
local is_snippet = completion.insertTextFormat
and completion.insertTextFormat == Server.insert_text_format.Snippet
edit_applied = apply_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 == Server.insert_text_format.Snippet
then
---@type core.doc
local doc = dv.doc
if dv then
local line2, col2 = doc:get_selection()
local line1, col1 = doc:position_offset(line2, col2, translate.start_of_word)
doc:set_selection(line1, col1, line2, col2)
snippets.execute {format = 'lsp', template = completion.insertText}
edit_applied = true
end
end
if edit_applied and completion.additionalTextEdits and #completion.additionalTextEdits > 0 then
-- TODO: do we need to sort this? Or is it expected to be already sorted?
-- TODO: are the edit ranges considered as if the "main" textEdit was applied already?
-- Apply the edits in reverse order, so that their ranges are not shifted
-- around by previous edits
for i=#completion.additionalTextEdits,1,-1 do
local edit = completion.additionalTextEdits[i]
apply_edit(item.data.server, dv.doc, edit, false, false)
end
end
return edit_applied
end
--
-- Public functions
--
---Open a document location returned by LSP
---@param location table
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", "command"
}
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
if #options.command <= 0 then
core.error("[LSP] Provide a command table list with the lsp command.")
return false
end
-- some lsp servers may be installed with different binary names
-- so if command name is a list, search for one that exists
if type(options.command[1]) == "table" then
options.command[1] = util.get_best_executable(options.command[1])
end
-- On Windows using cmd.exe allows us to take advantage of its ability to run
-- the correct executable, as well as running scripts.
if PLATFORM == "Windows" and not options.windows_skip_cmd 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 .lite_lsp.lua or .lite_lsp.json (in that order)
---2. Merge server.settings
---4. Scan workspace if set also for .lite_lsp.lua/json and merge them or
---3. Scan server.path also for .lite_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 table
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 .. "/.lite_lsp.lua") then
local settings_lua = dofile(path .. "/.lite_lsp.lua")
if type(settings_lua) == "table" then
settings_new = settings_lua
end
elseif util.file_exists(path .. "/.lite_lsp.json") then
local file = io.open(path .. "/.lite_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 util.command_exists(server.command[1]) then
command_exists = true
else
table.insert(servers_not_found, name)
end
if not lsp.servers_running[name] and command_exists then
core.log("[LSP] starting " .. name)
---@type lsp.server
local client = Server(server)
client.yield_on_reads = config.plugins.lsp.more_yielding
lsp.servers_running[name] = client
-- We overwrite the default log function to log messages on lite
function client:log(message, ...)
core.log_quiet(
"[LSP/%s]: " .. message .. "\n",
self.name,
...
)
end
function client:on_shutdown()
local sname = self.name
core.log(
"[LSP]: %s was shutdown, revise your configuration",
sname
)
local last_shutdown = lsp.servers_running[sname].last_shutdown or 0
lsp.servers_running = util.table_remove_key(
lsp.servers_running,
sname
)
if system.get_time() - last_shutdown >= 5 then
lsp.start_servers()
if lsp.servers_running[sname] then
lsp.servers_running[sname].last_shutdown = system.get_time()
core.log(
"[LSP]: %s automatically restarted",
sname
)
end
end
end
-- Respond to workspace/configuration request
client:add_request_listener(
"workspace/configuration",
function(server, request)
local settings_default = lsp.get_workspace_settings(server)
local settings_list = {}
for _, item in pairs(request.params.items) do
local value = nil
-- No workspace was specified so we return from default settings
if not item.scopeUri then
value = util.table_get_field(settings_default, item.section)
-- A workspace was specified so we return from that workspace
else
local settings_workspace = lsp.get_workspace_settings(
server, util.tofilename(item.scopeUri)
)
value = util.table_get_field(settings_workspace, item.section)
end
if not value then
server:log("Asking for '%s' config but not set", item.section)
else
server:log("Asking for '%s' config", item.section)
end
table.insert(settings_list, value or json.null)
end
server:push_response(request.method, request.id, settings_list)
end
)
-- Respond to window/showDocument request
client:add_request_listener(
"window/showDocument",
function(server, request)
if request.params.external then
MessageBox.info(
server.name .. " LSP Server",
"Wants to externally open:\n'" .. request.params.uri .. "'",
function(_, button_id)
if button_id == 1 then
util.open_external(request.params.uri)
end
end,
MessageBox.BUTTONS_YES_NO
)
else
local document = util.tofilename(request.params.uri)
---@type core.docview
local doc_view = core.root_view:open_doc(
core.open_doc(common.home_expand(document))
)
if request.params.selection then
local line1, col1, line2, col2 = util.toselection(
request.params.selection, doc_view.doc
)
doc_view.doc:set_selection(line1, col1, line2, col2)
end
if request.params.takeFocus then
system.raise_window()
end
end
server:push_response(request.method, request.id, {success=true})
end
)
-- Display server messages on lite UI
client:add_message_listener(
"window/logMessage",
function(server, params)
if core.log then
log(server, "%s", params.message)
end
end
)
-- Register/unregister diagnostic messages
client:add_message_listener(
"textDocument/publishDiagnostics",
function(server, params)
local abs_filename = util.tofilename(params.uri)
local filename = core.normalize_to_project_dir(abs_filename)
if server.verbose then
core.log_quiet(
"["..server.name.."] %s diagnostics for: %s",
filename,
params.diagnostics and #params.diagnostics or 0
)
end
if params.diagnostics and #params.diagnostics > 0 then
local added = diagnostics.add(filename, params.diagnostics)
if
added and diagnostics.lintplus_found
and
config.plugins.lsp.show_diagnostics
and
util.doc_is_open(abs_filename)
then
-- we delay rendering of diagnostics for 2 seconds to prevent
-- the constant reporting of errors while typing.
diagnostics.lintplus_populate_delayed(filename)
end
else
diagnostics.clear(filename)
diagnostics.lintplus_clear_messages(filename)
end
end
)
-- Register/unregister diagnostic messages
client:add_message_listener(
"window/showMessage",
function(server, params)
local log_func = "log_quiet"
if params.type == Server.message_type.Error then
log_func = "error"
elseif params.type == Server.message_type.Warning then
log_func = "warn"
elseif params.type == Server.message_type.Info then
log_func = "log"
elseif params.type == Server.message_type.Debug then
log_func = "log_quiet"
end
core[log_func]("["..server.name.."] message: %s", params.message)
end
)
-- Send settings table after initialization if available.
client:add_event_listener("initialized", function(server)
if config.plugins.lsp.force_verbosity_off then
core.log_quiet("["..server.name.."] " .. "Initialized")
else
log(server, "Initialized")
end
local settings = lsp.get_workspace_settings(server)
if not util.table_empty(settings) then
server:push_notification("workspace/didChangeConfiguration", {
params = {settings = settings}
})
end
-- Send open document request if needed
for _, docu in ipairs(core.docs) do
if docu.filename then
if common.match_pattern(docu.filename, server.file_patterns) then
lsp.open_document(docu)
end
end
end
end)
-- Start the server initialization process
client:initialize(project_directory, "Lite XL", VERSION)
end
end
end
if server_registered and not server_started then
for _,_ in pairs(servers_not_found) do
core.error(
"[LSP] servers registered but not installed: %s",
table.concat(servers_not_found, ", ")
)
break
end
end
end
---Stops all running servers.
function lsp.stop_servers()
for name, _ in pairs(lsp.servers) do
if lsp.servers_running[name] then
lsp.servers_running[name]:exit()
core.log("[LSP] stopped %s", name)
lsp.servers_running = util.table_remove_key(lsp.servers_running, name)
end
end
end