-
Notifications
You must be signed in to change notification settings - Fork 9
/
init.lua
1392 lines (1322 loc) · 56 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 2018-2024 Mitchell. See LICENSE.
local json = require('lsp.dkjson')
--- A client for Textadept that communicates over the [Language Server Protocol][] (LSP) with
-- language servers in order to provide autocompletion, calltips, go to definition, and more.
-- It implements version 3.17.0 of the protocol, but does not support all protocol features. The
-- `Server.new()` function contains the client's current set of capabilities.
--
-- Install this module by copying it into your *~/.textadept/modules/* directory or Textadept's
-- *modules/* directory, and then putting the following in your *~/.textadept/init.lua*:
--
-- local lsp = require('lsp')
--
-- You can then set up some language server commands. For example:
--
-- lsp.server_commands.cpp = 'clangd'
-- lsp.server_commands.go = 'gopls'
--
-- (For more example configurations, see the [wiki][].)
--
-- When either C++ or Go files are opened, their associated language servers are automatically
-- started (one per project). Note that language servers typically require a root URI, so this
-- module uses `io.get_project_root()` for this. If the file being opened is not part of a
-- project recognized by Textadept, the language server will not be started.
--
-- Language Server features are available from the Tools > Language Server menu. Note that not
-- all language servers may support the menu options.
--
-- **Note:** If you want to inspect the LSP messages sent back and forth, you can use the Lua
-- command entry to set `require('lsp').log_rpc = true`. It doesn't matter if any LSPs are
-- already active -- from this point forward all messages will be logged. View the log via the
-- "Tools > Language Server > View Log" menu item.
--
-- **Warning:** Buggy language servers that do not respect the protocol may cause this module
-- and Textadept to hang, waiting for a response. There is no recourse other than to force-quit
-- Textadept and restart.
--
-- [Language Server Protocol]: https://microsoft.github.io/language-server-protocol/specification
-- [wiki]: https://github.com/orbitalquark/textadept/wiki/LSP-Configurations
--
-- ### Lua Language Server
--
-- This module comes with a simple Lua language server that starts up when Textadept opens a
-- Lua file, or whenever you request documentation for a symbol in the Lua command entry. The
-- server looks in the project root for a *.lua-lsp* configuration file. That file can have
-- the following fields:
--
-- - `ignore`: List of globs that match directories and files to ignore. Globs are relative to
-- the project root. The default directories ignored are .bzr, .git, .hg, .svn, _FOSSIL_,
-- and node_modules. Setting this field overrides the default.
-- - `max_scan`: Maximum number of files to scan before giving up. This is not the number of
-- Lua files scanned, but the number of files encountered in non-ignored directories.
-- The primary purpose of this field is to avoid hammering the disk when accidentally
-- opening a large project or root. The default value is 10,000.
--
-- For example:
--
-- ignore = {'.git', 'build', 'test'}
-- max_scan = 20000
--
-- ### Key Bindings
--
-- Windows and Linux | macOS | Terminal | Command
-- -|-|-|-
-- **Tools**| | |
-- Ctrl+Space | ⌘Space<br/> ^Space | ^Space | Complete symbol
-- Ctrl+? | ⌘?<br/>^? | M-?<br/>Ctrl+?<sup>‡</sup> | Show documentation
-- F12 | F12 | F12 | Go To Definition
--
-- ‡: Windows terminal version only.
-- @module lsp
local M = {}
-- Localizations.
local _L = _L
if not rawget(_L, 'Language Server') then
-- Dialogs.
_L['language server is already running'] = 'language server is already running'
_L['language server shell command:'] = 'language server shell command:'
_L['Stop Server?'] = 'Stop Server?'
_L['Stop the language server for'] = 'Stop the language server for'
_L['Symbol name or name part:'] = 'Symbol name or name part:'
-- Status.
_L['LSP server started'] = 'LSP server started'
_L['Unable to start LSP server'] = 'Unable to start LSP server'
_L['Note: completion list incomplete'] = 'Note: completion list incomplete'
_L['Loading Textadept documentation...'] = 'Loading Textadept documentation...'
_L['Showing diagnostics'] = 'Showing diagnostics'
_L['Hiding diagnostics'] = 'Hiding diagnostics'
-- Menu.
_L['Language Server'] = 'Lan_guage Server'
_L['Start Server...'] = '_Start Server...'
_L['Stop Server'] = 'Sto_p Server'
_L['Go To Workspace Symbol...'] = 'Go To _Workspace Symbol...'
_L['Go To Document Symbol...'] = 'Go To Document S_ymbol...'
_L['Autocomplete'] = '_Autocomplete'
_L['Show Documentation'] = 'Show _Documentation'
_L['Show Hover Information'] = 'Show _Hover Information'
_L['Show Signature Help'] = 'Show Si_gnature Help'
_L['Go To Declaration'] = 'Go To De_claration'
_L['Go To Definition'] = 'Go To De_finition'
_L['Go To Type Definition'] = 'Go To _Type Definition'
_L['Go To Implementation'] = 'Go To _Implementation'
_L['Find References'] = 'Find _References'
_L['Select Around'] = 'Select Aro_und'
_L['Select All Symbol'] = 'Select Al_l Symbol'
_L['Toggle Show Diagnostics'] = 'Toggle Show Diag_nostics'
_L['Show Log'] = 'Show L_og'
_L['Clear Log'] = 'Cl_ear Log'
end
-- Events.
local lsp_events = {'lsp_initialized', 'lsp_notification', 'lsp_request'}
for _, v in ipairs(lsp_events) do events[v:upper()] = v end
--- Emitted when an LSP connection has been initialized.
-- This is useful for sending server-specific notifications to the server upon init via
-- `Server:notify()`.
-- Emitted by `lsp.start()`.
-- Arguments:
--
-- - *lang*: The lexer name of the LSP language.
-- - *server*: The LSP server.
-- @field _G.events.LSP_INITIALIZED
--- Emitted when an LSP server emits an unhandled notification.
-- This is useful for handling server-specific notifications.
-- An event handler should return `true`.
-- Arguments:
--
-- - *lang*: The lexer name of the LSP language.
-- - *server*: The LSP server.
-- - *method*: The string LSP notification method name.
-- - *params*: The table of LSP notification params. Contents may be server-specific.
-- @field _G.events.LSP_NOTIFICATION
--- Emitted when an LSP server emits an unhandled request.
-- This is useful for handling server-specific requests. Responses are sent using
-- `Server:respond()`.
-- An event handler should return `true`.
-- Arguments:
--
-- - *lang*: The lexer name of the LSP language.
-- - *server*: The LSP server.
-- - *id*: The integer LSP request ID.
-- - *method*: The string LSP request method name.
-- - *params*: The table of LSP request params.
-- @field _G.events.LSP_REQUEST
--- Log RPC correspondence to the LSP message buffer.
-- The default value is `false`.
M.log_rpc = false
--- Whether or not to automatically show completions when a trigger character is typed (e.g. '.').
-- The default value is `true`.
M.show_completions = true
--- Whether or not to allow completions to insert snippets instead of plain text, for language
-- servers that support it.
-- The default value is `true`.
M.snippet_completions = true
--- Whether or not to automatically show signature help when a trigger character is typed
-- (e.g. '(').
-- The default value is `true`.
M.show_signature_help = true
--- Whether or not to automatically show symbol information via mouse hovering.
-- The default value is `true`.
M.show_hover = true
--- Whether or not to show diagnostics.
-- The default value is `true`, and shows them as annotations.
M.show_diagnostics = true
--- Whether or not to show all diagnostics if `show_diagnostics` is `true`.
-- The default value is `false`, and assumes any diagnostics on the current line or next line
-- are due to an incomplete statement during something like an autocompletion, signature help,
-- etc. request.
M.show_all_diagnostics = false
--- The number of characters typed after which autocomplete is automatically triggered.
-- The default value is `nil`, which disables this feature. A value greater than or equal to
-- 3 is recommended to enable this feature.
M.autocomplete_num_chars = nil
--- Map of lexer names to LSP language server commands or configurations, or functions that
-- return either a server command or a configuration.
-- Commands are simple string shell commands. Configurations are tables with the following keys:
--
-- - *command*: String shell command used to run the LSP language server.
-- - *init_options*: Table of initialization options to pass to the language server in the
-- "initialize" request.
M.server_commands = {}
--- Map of lexer names to maps of project roots and their active LSP servers.
local servers = {}
--- Map of LSP CompletionItemKinds to images used in autocompletion lists.
-- @table xpm_map
-- @local
-- This separation is needed to prevent LDoc from parsing the following table.
local xpm_map = {
0, -- text
textadept.editing.XPM_IMAGES.METHOD, -- method
textadept.editing.XPM_IMAGES.METHOD, -- function
textadept.editing.XPM_IMAGES.SLOT, -- constructor
textadept.editing.XPM_IMAGES.VARIABLE, -- field
textadept.editing.XPM_IMAGES.VARIABLE, -- variable
textadept.editing.XPM_IMAGES.CLASS, -- class
textadept.editing.XPM_IMAGES.TYPEDEF, -- interface
textadept.editing.XPM_IMAGES.NAMESPACE, -- module
textadept.editing.XPM_IMAGES.VARIABLE, -- property
0, -- unit
0, -- value
textadept.editing.XPM_IMAGES.TYPEDEF, -- enum
0, -- keyword
0, -- snippet
0, -- color
0, -- file
0, -- reference
0, -- folder
textadept.editing.XPM_IMAGES.VARIABLE, -- enum member
textadept.editing.XPM_IMAGES.VARIABLE, -- constant
textadept.editing.XPM_IMAGES.STRUCT, -- struct
textadept.editing.XPM_IMAGES.SIGNAL, -- event
0, -- operator
0 -- type parameter
}
local completion_item_kind_set = {} -- for LSP capabilities
for i = 1, #xpm_map do completion_item_kind_set[i] = i end
--- Map of LSP SymbolKinds to names shown in symbol lists.
local symbol_kinds = {
'File', 'Module', 'Namespace', 'Package', 'Class', 'Method', 'Property', 'Field', 'Constructor',
'Enum', 'Interface', 'Function', 'Variable', 'Constant', 'String', 'Number', 'Boolean', 'Array',
'Object', 'Key', 'Null', 'EnumMember', 'Struct', 'Event', 'Operator', 'TypeParameter'
}
local symbol_kind_set = {} -- for LSP capabilities
for i = 1, #symbol_kinds do symbol_kind_set[i] = i end
local log_lines, log_buffer = {}, nil
--- Logs the given arguments to the log buffer.
local function log(...)
log_lines[#log_lines + 1] = table.concat(table.pack(...))
if not log_buffer then return end
if not _BUFFERS[log_buffer] then
log_buffer = nil
for _, buffer in ipairs(_BUFFERS) do
if buffer._type ~= '[LSP]' then goto continue end
log_buffer = buffer
break
::continue::
end
if not log_buffer then return end
end
ui.print_silent_to('[LSP]', log_lines[#log_lines])
end
--- Table of lexers to running language servers.
local Server = {}
--- Starts, initializes, and returns a new language server.
-- @param lang Lexer name of the language server.
-- @param root Root directory of the project for this language server.
-- @param cmd String command to start the language server.
-- @param init_options Optional table of options to be passed to the language server for
-- initialization.
-- @local
function Server.new(lang, root, cmd, init_options)
log('Starting language server: ', cmd)
local server = setmetatable({lang = lang, root = root, request_id = 0, incoming_messages = {}},
{__index = Server})
server.proc = assert(os.spawn(cmd, function(output) server:handle_stdout(output) end,
function(output) log(output) end, function(status)
log('Server exited with status ', status)
servers[lang][root] = nil
end))
local root = io.get_project_root()
local result = server:request('initialize', {
processId = json.null, --
clientInfo = {name = 'textadept', version = _RELEASE},
-- TODO: locale
rootUri = root and (not WIN32 and 'file://' .. root or 'file:///' .. root:gsub('\\', '/')) or
nil, --
initializationOptions = init_options, --
capabilities = {
-- workspace = nil, -- workspaces are not supported at all
textDocument = {
synchronization = {
-- willSave = true,
-- willSaveWaitUntil = true,
didSave = true
}, --
completion = {
-- dynamicRegistration = false, -- not supported
completionItem = {
snippetSupport = M.snippet_completions,
-- commitCharactersSupport = true,
documentationFormat = {'plaintext'},
-- deprecatedSupport = false, -- simple autocompletion list
preselectSupport = true
-- tagSupport = {valueSet = {}},
-- insertReplaceSupport = true,
-- resolveSupport = {properties = {}},
-- insertTextModeSupport = {valueSet = {}},
-- labelDetailsSupport = true
}, --
completionItemKind = {valueSet = completion_item_kind_set}
-- contextSupport = true,
-- insertTextMode = 1,
-- completionList = {}
}, --
hover = {
-- dynamicRegistration = false, -- not supported
contentFormat = {'plaintext'}
}, --
signatureHelp = {
-- dynamicRegistration = false, -- not supported
signatureInformation = {
documentationFormat = {'plaintext'}, --
parameterInformation = {labelOffsetSupport = true}, --
activeParameterSupport = true
} --
-- contextSupport = true
},
-- declaration = {
-- dynamicRegistration = false, -- not supported
-- linkSupport = true
-- }
-- definition = {
-- dynamicRegistration = false, -- not supported
-- linkSupport = true
-- },
-- typeDefinition = {
-- dynamicRegistration = false, -- not supported
-- linkSupport = true
-- },
-- implementation = {
-- dynamicRegistration = false, -- not supported
-- linkSupport = true
-- },
-- references = {dynamicRegistration = false}, -- not supported
-- documentHighlight = {dynamicRegistration = false}, -- not supported
documentSymbol = {
-- dynamicRegistration = false, -- not supported
symbolKind = {valueSet = symbol_kind_set}
-- hierarchicalDocumentSymbolSupport = true,
-- tagSupport = {valueSet = {}},
-- labelSupport = true
}, --
-- codeAction = {
-- dynamicRegistration = false, -- not supported
-- codeActionLiteralSupport = {valueSet = {}},
-- isPreferredSupport = true,
-- disabledSupport = true,
-- dataSupport = true,
-- resolveSupport = {properties = {}},
-- honorsChangeAnnotations = true
-- },
-- codeLens = {dynamicRegistration = false}, -- not supported
-- documentLink = {
-- dynamicRegistration = false, -- not supported
-- tooltipSupport = true
-- },
-- colorProvider = {dynamicRegistration = false}, -- not supported
-- formatting = {dynamicRegistration = false}, -- not supported
-- rangeFormatting = {dynamicRegistration = false}, -- not supported
-- onTypeFormatting = {dynamicRegistration = false}, -- not supported
-- rename = {
-- dynamicRegistration = false, -- not supported
-- prepareSupport = false,
-- prepareSupportDefaultBehavior = 1,
-- honorsChangeAnnotations = true
-- },
publishDiagnostics = empty_object -- {
-- relatedInformation = true
-- tagSupport = {valueSet = {}},
-- versionSupport = true,
-- codeDescriptionSupport = true,
-- dataSupport = true
-- },
-- foldingRange = {
-- dynamicRegistration = false, -- not supported
-- rangeLimit = ?,
-- lineFoldingOnly = true,
-- foldingRangeKind = {valueSet = {'comment', 'imports', 'region'}},
-- foldingRange = {collapsedText = true}
-- },
-- selectionRange = {dynamicRegistration = false}, -- not supported
-- linkedEditingRange = {dynamicRegistration = false}, -- not supported
-- callHierarchy = {dynamicRegistration = false}, -- not supported
-- semanticTokens = {
-- dynamicRegistration = false, -- not supported
-- requests = {},
-- tokenTypes = {},
-- tokenModifiers = {},
-- formats = {},
-- overlappingTokenSupport = true,
-- multilineTokenSupport = true,
-- serverCancelSupport = true,
-- augmentsSyntaxTokens = true
-- },
-- moniker = {dynamicRegistration = false}, -- not supported
-- typeHierarchy = {dynamicRegistration = false}, -- not supported
-- inlineValue = {dynamicRegistration = false}, -- not supported
-- inlayHint = {
-- dynamicRegistration = false, -- not supported
-- resolveSupport = {properties = {}}
-- },
-- diagnostic = {
-- dynamicRegistration = false, -- not supported
-- relatedDocumentSupport = true
-- }
} --
-- notebookDocument = nil, -- notebook documents are not supported at all
-- window = {
-- workDoneProgress = true,
-- showMessage = {messageActionItem = {additionalPropertiesSupport = true}},
-- showDocument = {support = true}
-- },
-- general = {
-- staleRequestSupport = {
-- cancel = true,
-- retryOnContentModified = {}
-- },
-- regularExpressions = {},
-- markdown = {},
-- positionEncodings = 'utf-8'
-- },
-- experimental = nil
}
})
server.capabilities = result.capabilities
if server.capabilities.completionProvider then
server.auto_c_triggers = {}
for _, char in ipairs(server.capabilities.completionProvider.triggerCharacters or {}) do
if char ~= ' ' then server.auto_c_triggers[string.byte(char)] = true end
end
server.auto_c_fill_ups = table.concat(
server.capabilities.completionProvider.allCommitCharacters or {})
end
if server.capabilities.signatureHelpProvider then
server.call_tip_triggers = {}
for _, char in ipairs(server.capabilities.signatureHelpProvider.triggerCharacters or {}) do
server.call_tip_triggers[string.byte(char)] = true
end
end
server.info = result.serverInfo
if server.info then
log(string.format('Connected to %s %s', server.info.name,
server.info.version or '(unknown version)'))
end
server:notify('initialized') -- required by protocol
events.emit(events.LSP_INITIALIZED, server.lang, server)
return server
end
--- Reads and returns an incoming JSON message from this language server.
-- @return table of data from JSON
-- @local
function Server:read()
if self.wait then
while #self.incoming_messages == 0 do ui.update() end
self.wait = false
end
if #self.incoming_messages > 0 then
local message = table.remove(self.incoming_messages, 1)
log('Processing cached message: ', message.id)
return message
end
local line = self.proc:read()
while not line:find('^\n?Content%-Length: %d+$') do line = self.proc:read() end
local len = tonumber(line:match('%d+$'))
while #line > 0 do line = self.proc:read() end -- skip other headers
local data = self.proc:read(len)
if M.log_rpc then log('RPC recv: ', data) end
return json.decode(data)
end
--- Sends a request to this language server and returns the result of the request.
-- Any intermediate notifications from the server are processed, but any intermediate requests
-- from the server are ignored.
-- Note: at this time, requests are synchronous, so the id number for a response will be the
-- same as the id number for a request.
-- @param method String method name of the request.
-- @param params Table of parameters for the request.
-- @return table result of the request, or nil if the result was `json.null`.
-- @local
function Server:request(method, params)
-- Prepare and send the JSON message.
self.request_id = self.request_id + 1
local message = {jsonrpc = '2.0', id = self.request_id, method = method, params = params}
local data = json.encode(message)
if M.log_rpc then log('RPC send: ', data) end
self.proc:write(string.format('Content-Length: %d\r\n\r\n%s\r\n', #data + 2, data))
-- Read incoming JSON messages until the proper response is found.
repeat
message = self:read()
-- TODO: error handling for message
if not message.id then
self:handle_notification(message.method, message.params)
elseif message.method and not message.result then -- params may be nil
self:handle_request(message.id, message.method, message.params)
message.id = nil
end
until message.id
-- Return the response's result.
if message.error then log('Server returned an error: ', message.error.message) end
return message.result ~= json.null and message.result or nil
end
local empty_object = json.decode('{}')
--- Sends a notification to this language server.
-- @param method String method name of the notification.
-- @param params Table of parameters for the notification.
-- @local
function Server:notify(method, params)
local message = {jsonrpc = '2.0', method = method, params = params or empty_object}
local data = json.encode(message)
if M.log_rpc then log('RPC send: ', data) end
self.proc:write(string.format('Content-Length: %d\r\n\r\n%s\r\n', #data + 2, data))
end
--- Responds to an unsolicited request from this language server.
-- @param id Numeric ID of the request.
-- @param result Table result of the request.
-- @local
function Server:respond(id, result)
local message = {jsonrpc = '2.0', id = id, result = result}
local data = json.encode(message)
if M.log_rpc then log('RPC send: ', data) end
self.proc:write(string.format('Content-Length: %d\r\n\r\n%s\r\n', #data + 2, data))
end
--- Helper function for processing a single message from the Language Server's notification stream.
-- Cache any incoming messages (particularly responses) that happen to be picked up.
-- @param data String message from the Language Server.
-- @local
function Server:handle_data(data)
if M.log_rpc then log('RPC recv: ', data) end
local message = json.decode(data)
if not message.id then
self:handle_notification(message.method, message.params)
elseif message.method and not message.result then -- params may be nil
self:handle_request(message.id, message.method, message.params)
else
log('Caching incoming server message: ', message.id)
table.insert(self.incoming_messages, message)
end
end
--- Processes unsolicited, incoming stdout from the Language Server, primarily to look for
-- notifications and act on them.
-- @param output String stdout from the Language Server.
-- @local
function Server:handle_stdout(output)
if output:find('^\n?Content%-Length:') then
local len = tonumber(output:match('^\n?Content%-Length: (%d+)'))
local _, _, e = output:find('\r\n\r\n?()')
if e + len - 1 <= #output then
self:handle_data(output:sub(e, e + len - 1))
self:handle_stdout(output:sub(e + len)) -- process any other messages
else
self._buf, self._len = output:sub(e), len
end
elseif self._buf then
if #self._buf + #output >= self._len then
local e = self._len - #self._buf
self:handle_data(self._buf .. output:sub(1, e))
self._buf, self._len = nil, nil
self:handle_stdout(output:sub(e + 1))
else
self._buf = self._buf .. output
end
elseif not output:find('^%s*$') then
log('Unhandled server output: ', output)
end
end
--- Converts the given LSP DocumentUri into a valid filename and returns it.
-- @param uri LSP DocumentUri to convert into a filename.
local function tofilename(uri)
local filename = uri:gsub(not WIN32 and '^file://' or '^file:///', '')
filename = filename:gsub('%%(%x%x)', function(hex) return string.char(tonumber(hex, 16)) end)
if WIN32 then filename = filename:gsub('/', '\\') end
return filename
end
--- Converts the given filename into a valid LSP DocumentUri and returns it.
-- @param filename String filename to convert into an LSP DocumentUri.
local function touri(filename)
if filename:find('^%a%a+:') then return filename end -- different scheme like "untitled:"
return not WIN32 and 'file://' .. filename or 'file:///' .. filename:gsub('\\', '/')
end
--- Returns the start and end buffer positions for the given LSP Range.
-- @param range LSP Range.
local function tobufferrange(range)
local s = buffer:position_from_line(range.start.line + 1) + range.start.character
local e = buffer:position_from_line(range['end'].line + 1) + range['end'].character
return s, e
end
--- Handles an unsolicited notification from this language server.
-- @param method String method name of the notification.
-- @param params Table of parameters for the notification.
-- @local
function Server:handle_notification(method, params)
if method == 'window/showMessage' then
-- Show a message to the user.
ui.statusbar_text = params.message
elseif method == 'window/logMessage' then
-- Silently log a message.
local level = {'ERROR', 'WARN', 'INFO', 'LOG'}
log(string.format('%s: %s', level[params.type], params.message))
elseif method == 'telemetry/event' then
-- Silently log an event.
log('TELEMETRY: ', json.encode(params))
elseif method == 'textDocument/publishDiagnostics' and M.show_diagnostics then
-- Annotate the buffer based on diagnostics.
if buffer.filename ~= tofilename(params.uri) then return end
-- Record current line scroll state.
local current_line = buffer:line_from_position(buffer.current_pos)
local orig_lines_from_top = view:visible_from_doc_line(current_line) - view.first_visible_line
-- Clear any existing diagnostics.
for _, indic in ipairs{textadept.run.INDIC_WARNING, textadept.run.INDIC_ERROR} do
buffer.indicator_current = indic
buffer:indicator_clear_range(1, buffer.length)
end
buffer:annotation_clear_all()
-- Add diagnostics.
for _, diagnostic in ipairs(params.diagnostics) do
buffer.indicator_current = (not diagnostic.severity or diagnostic.severity == 1) and
textadept.run.INDIC_ERROR or textadept.run.INDIC_WARNING -- TODO: diagnostic.tags
local s, e = tobufferrange(diagnostic.range)
local line = buffer:line_from_position(e)
if M.show_all_diagnostics or (current_line ~= line and current_line + 1 ~= line) then
buffer:indicator_fill_range(s, e - s)
buffer.annotation_text[line] = diagnostic.message
buffer.annotation_style[line] = buffer:style_of_name(lexer.ERROR)
-- TODO: diagnostics should be persistent in projects.
end
end
if #params.diagnostics > 0 then buffer._lsp_diagnostic_time = os.time() end
-- Restore line scroll state.
local lines_from_top = view:visible_from_doc_line(current_line) - view.first_visible_line
view:line_scroll(0, lines_from_top - orig_lines_from_top)
elseif method:find('^%$/') then
log('Ignoring notification: ', method)
elseif not events.emit(events.LSP_NOTIFICATION, self.lang, self, method, params) then
-- Unknown notification.
log('Unexpected notification: ', method)
end
end
--- Responds to a request from this language server.
-- @param id ID number of the server's request.
-- @param method String method name of the request.
-- @param params Table of parameters for the request.
-- @local
function Server:handle_request(id, method, params)
if method == 'window/showMessageRequest' then
-- Show a message to the user and wait for a response.
local icons = {'dialog-error', 'dialog-warning', 'dialog-information'}
local dialog_options = {icon = icons[params.type], title = 'Message', text = params.message}
-- Present options in the message and respond with the selected option.
for i = 1, #params.actions do dialog_options['button' .. i] = params.actions[i].title end
local result = {title = params.actions[ui.dialogs.message(dialog_options)]}
if not result.title then result = json.null end
self:respond(id, result)
elseif not events.emit(events.LSP_REQUEST, self.lang, self, id, method, params) then
-- Unknown notification.
log('Responding with null to server request: ', method)
self:respond(id, nil)
end
end
--- Synchronizes the current buffer with this language server.
-- Changes are not synchronized in real-time, but whenever a request is about to be sent.
-- @local
function Server:sync_buffer()
self:notify('textDocument/didChange', {
textDocument = {
uri = touri(buffer.filename or 'untitled:'), -- if server supports untitledDocumentCompletions
version = os.time() -- just make sure it keeps increasing
}, --
contentChanges = {{text = buffer:get_text()}}
})
if WIN32 then self.wait = true end -- prefer async response reading
end
--- Notifies this language server that the current buffer was opened, provided the language
-- server has not previously been notified.
-- @local
function Server:notify_opened()
if not self._opened then self._opened = {} end
if not buffer.filename or self._opened[buffer.filename] then return end
self:notify('textDocument/didOpen', {
textDocument = {
uri = touri(buffer.filename), languageId = buffer.lexer_language, version = 0,
text = buffer:get_text()
}
})
self._opened[buffer.filename] = true
end
--- Returns a running language server, if one exists, for the current language and project.
-- Sub-projects use their parent project's language server.
local function get_server()
local lang = buffer.lexer_language
if not servers[lang] then servers[lang] = {} end
local root = io.get_project_root()
if not root and lang == 'lua' then root = '' end -- special case
if not root then return nil end
local lang_servers = servers[lang]
local server = lang_servers[root]
if server then return server end
for path, server in pairs(lang_servers) do if root:sub(1, #path) == path then return server end end
end
--- Starts a language server based on the current language and project.
-- @param cmd Optional language server command to run. The default is read from `server_commands`.
function M.start(cmd)
if get_server() then return end -- already running
local lang = buffer.lexer_language
if not cmd then cmd = M.server_commands[lang] end
local init_options = nil
if type(cmd) == 'function' then cmd, init_options = cmd() end
if type(cmd) == 'table' then cmd, init_options = cmd.command, cmd.init_options end
if not cmd then return end
local root = buffer.filename and io.get_project_root(buffer.filename)
if not root and lang == 'lua' and cmd:find('server%.lua') then root = '' end -- special case
if not root then return end
servers[lang][root] = true -- sentinel until initialization is complete
local ok, server = xpcall(Server.new, function(errmsg)
local message = _L['Unable to start LSP server'] .. ': ' .. errmsg
log(debug.traceback(message))
ui.statusbar_text = message
end, lang, root, cmd, init_options)
servers[lang][root] = ok and server or nil -- replace sentinel
if not ok then return end
server:notify_opened()
ui.statusbar_text = _L['LSP server started']
end
--- Stops a running language server based on the current language.
function M.stop()
local server = get_server()
if not server then return end
server:request('shutdown')
server:notify('exit')
servers[server.lang][server.root] = nil
end
--- Returns a LSP TextDocumentPositionParams structure based on the given or current position
-- in the current buffer.
-- @param position Optional buffer position to use. If `nil`, uses the current buffer position.
-- @return table LSP TextDocumentPositionParams
local function get_buffer_position_params(position)
local line = buffer:line_from_position(position or buffer.current_pos)
return {
textDocument = {
uri = touri(buffer.filename or 'untitled:') -- server may support untitledDocumentCompletions
}, --
position = {
line = line - 1,
character = (position or buffer.current_pos) - buffer:position_from_line(line)
}
}
end
--- Jumps to the given LSP Location structure.
-- @param location LSP Location to jump to.
local function goto_location(location)
textadept.history.record() -- store current position in jump history
ui.goto_file(tofilename(location.uri), false, view)
buffer:set_sel(tobufferrange(location.range))
textadept.history.record() -- store new position in jump history
end
--- Jumps to the symbol selected from a list of LSP SymbolInformation or structures.
-- @param symbols List of LSP SymbolInformation or DocumentSymbol structures.
local function goto_selected_symbol(symbols)
-- Prepare items for display in a list dialog.
local items = {}
for _, symbol in ipairs(symbols) do
items[#items + 1] = symbol.name
items[#items + 1] = symbol_kinds[symbol.kind]
if not symbol.location then
-- LSP DocumentSymbol has `range` instead of `location`.
symbol.location = {
uri = not WIN32 and buffer.filename or buffer.filename:gsub('\\', '/'), range = symbol.range
}
end
items[#items + 1] = tofilename(symbol.location.uri)
end
-- Show the dialog and jump to the selected symbol.
local i = ui.dialogs.list{
title = 'Go To Symbol', columns = {'Name', 'Kind', 'Location'}, items = items
}
if i then goto_location(symbols[i].location) end
end
--- Jumps to a symbol selected from a list based on project symbols that match the given symbol,
-- or based on buffer symbols.
-- @param symbol Optional string symbol to query for in the current project. If `nil`, symbols
-- are presented from the current buffer.
function M.goto_symbol(symbol)
local server = get_server()
if not server or not buffer.filename then return end
server:sync_buffer()
local symbols
if symbol and server.capabilities.workspaceSymbolProvider then
-- Fetching project symbols that match the query.
symbols = server:request('workspace/symbol', {query = symbol})
elseif server.capabilities.documentSymbolProvider then
-- Fetching symbols in the current buffer.
symbols = server:request('textDocument/documentSymbol',
{textDocument = {uri = touri(buffer.filename)}})
end
if symbols and #symbols > 0 then goto_selected_symbol(symbols) end
end
local snippets
local auto_c_incomplete = false
--- Autocompleter function for a language server.
-- @function _G.textadept.editing.autocompleters.lsp
textadept.editing.autocompleters.lsp = function()
local server = get_server()
if not (server and server.capabilities.completionProvider and (buffer.filename or
(server.capabilities.experimental and
server.capabilities.experimental.untitledDocumentCompletions))) then return end
server:sync_buffer()
-- Fetch a completion list.
local completions = server:request('textDocument/completion', get_buffer_position_params())
if not completions then return end
auto_c_incomplete = completions.isIncomplete
if auto_c_incomplete then ui.statusbar_text = _L['Note: completion list incomplete'] end
if completions.items then completions = completions.items end
if #completions == 0 then return end
snippets = {}
-- Associate completion items with icons.
local symbols = {}
for _, symbol in ipairs(completions) do
local label = symbol.insertText or symbol.label
if symbol.insertTextFormat == 2 then -- snippet
label = symbol.filterText or symbol.label
snippets[label] = symbol.insertText
end
if label:find(' ') then buffer.auto_c_separator = string.byte('\n') end
if symbol.kind and xpm_map[symbol.kind] > 0 then
symbols[#symbols + 1] = string.format('%s?%d', label, xpm_map[symbol.kind]) -- TODO: auto_c_type_separator
else
symbols[#symbols + 1] = label
end
-- TODO: if symbol.preselect then symbols.selected = label end?
end
-- Return the autocompletion list.
local len_entered
if symbols[1].textEdit then
local s, e = tobufferrange(symbols[1].textEdit.range)
len_entered = e - s
else
local s = buffer:word_start_position(buffer.current_pos, true)
len_entered = buffer.current_pos - s
end
if server.auto_c_fill_ups ~= '' then buffer.auto_c_fill_ups = server.auto_c_fill_ups end
return len_entered, symbols
end
local snippet_to_insert
-- Insert autocompletions as snippets and not plain text, if applicable.
events.connect(events.AUTO_C_COMPLETED, function(text, position, code)
if not snippets then return end
local snippet = snippets[text]
snippets = nil
if not snippet then return end
snippet = snippet:sub(#text + 1 + (code ~= 0 and utf8.len(utf8.char(code)) or 0))
if code == 0 then
textadept.snippets.insert(snippet)
else
snippet_to_insert = snippet -- fill-up character will be inserted after this event
end
end)
events.connect(events.CHAR_ADDED, function(code)
if not snippet_to_insert then return end
textadept.snippets.insert(snippet_to_insert) -- insert after fill-up character
snippet_to_insert = nil
return true -- other events may interfere with snippet insertion
end, 1)
events.connect(events.AUTO_C_CANCELED, function() snippets = nil end)
--- Requests autocompletion at the current position, returning `true` on success.
function M.autocomplete() return textadept.editing.autocomplete('lsp') end
--- Shows a calltip with information about the identifier at the given or current position.
-- @param position Optional buffer position of the identifier to show information for. If `nil`,
-- uses the current buffer position.
function M.hover(position)
local server = get_server()
if not (server and (buffer.filename or
(server.capabilities.experimental and server.capabilities.experimental.untitledDocumentHover)) and
server.capabilities.hoverProvider) then return end
server:sync_buffer()
local hover = server:request('textDocument/hover', get_buffer_position_params(position))
if not hover then return end
local contents = hover.contents
if type(contents) == 'table' then
-- LSP MarkedString[] or MarkupContent.
for i, content in ipairs(contents) do
if type(content) == 'table' then contents[i] = content.value end
end
contents = contents.value or table.concat(contents, '\n')
end
if not contents or contents == '' then return end
view:call_tip_show(position or buffer.current_pos, contents)
end
--- Active call tip signatures.
-- @field activeSignature
-- @field activeParameter
-- @table signatures
-- @local
local signatures
local last_pos
--- Shows the currently active signature and highlights its current parameter if possible.
local function show_signature()
local signature = signatures[(signatures.activeSignature or 0) + 1]
if not view:call_tip_active() then last_pos = buffer.current_pos end
view:call_tip_show(last_pos, signature.text)
local params = signature.parameters
if not params then return end
local param = params[(signature.activeParameter or signatures.activeParameter or 0) + 1]
local offset = #signatures == 1 and 1 or 2 -- account for Lua indices and cycle arrows
if param and type(param.label) == 'table' then
view:call_tip_set_hlt(param.label[1] + offset, param.label[2] + offset)
end
end
--- Shows a calltip for the current function.
-- If a call tip is already shown, cycles to the next one if it exists unless specified otherwise.
-- @param no_cycle Flag that indicates to not cycle to the next call tip. This is used to update
-- the current highlighted parameter.
function M.signature_help(no_cycle)
if view:call_tip_active() and signatures and #signatures > 1 and not no_cycle then
events.emit(events.CALL_TIP_CLICK, 1)
return
end
local server = get_server()
if not (server and server.capabilities.signatureHelpProvider and (buffer.filename or
(server.capabilities.experimental and
server.capabilities.experimental.untitledDocumentSignatureHelp))) then return end
server:sync_buffer()
local params = get_buffer_position_params()
if view:call_tip_active() then params.isRetrigger = true end
local signature_help = server:request('textDocument/signatureHelp', params)
if not signature_help or not signature_help.signatures or #signature_help.signatures == 0 then
signatures = {} -- reset
return
end
signatures = signature_help.signatures
signatures.activeSignature = signature_help.activeSignature
signatures.activeParameter = signature_help.activeParameter
for _, signature in ipairs(signatures) do
local doc = signature.documentation or ''
-- Construct calltip text.
if type(doc) == 'table' then doc = doc.value end -- LSP MarkupContent
doc = string.format('%s\n%s', signature.label, doc)
-- Wrap long lines in a rudimentary way.
local lines, edge_column = {}, view.edge_column
if edge_column == 0 then edge_column = not CURSES and 100 or 80 end
for line in doc:gmatch('[^\n]+') do
for j = 1, #line, edge_column do lines[#lines + 1] = line:sub(j, j + edge_column - 1) end
end
doc = table.concat(lines, '\n')
-- Add arrow indicators for multiple signatures.
if #signatures > 1 then doc = '\001' .. doc:gsub('\n', '\n\002', 1) end
signature.text = doc
end
show_signature()
end
-- Cycle through signatures.
events.connect(events.CALL_TIP_CLICK, function(position)
local server = get_server()
if not (server and server.capabilities.signatureHelpProvider and signatures and
signatures.activeSignature) then return end
signatures.activeSignature = signatures.activeSignature + (position == 1 and -1 or 1)
if signatures.activeSignature >= #signatures then
signatures.activeSignature = 0
elseif signatures.activeSignature < 0 then
signatures.activeSignature = #signatures - 1
end
show_signature()
end)
-- Close the call tip when a trigger's complement is typed (e.g. ')').
events.connect(events.KEYPRESS, function(key)
if not view:call_tip_active() then return end