-
Notifications
You must be signed in to change notification settings - Fork 271
/
Copy pathLanguageClient.py
1510 lines (1264 loc) · 51.6 KB
/
LanguageClient.py
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
import inspect
import json
import linecache
import os
import re
import subprocess
import threading
from functools import wraps, partial
from typing import List, Dict, Any, Union # noqa: F401
import neovim
from .RPC import RPC
from .Sign import Sign
from .TextDocumentItem import TextDocumentItem
from .logger import logger, logpath_server, setLoggingLevel
from .state import (
state, update_state, execute_command, echo, echomsg, echoerr,
echo_ellipsis, echo_signature, make_serializable, set_state, alive)
from .util import (
get_rootPath, path_to_uri, uri_to_path, get_command_goto_file, get_command_update_signs,
convert_vim_command_args_to_kwargs, apply_TextEdit, markedString_to_str,
convert_lsp_completion_item_to_vim_style)
from .MessageType import MessageType
from .DiagnosticSeverity import DiagnosticSeverity
from .CommandsClient import CommandsClient
def deco_args(f=None, warn=True):
"""
Decorate an LSP function such that
- check if server is alive
- unify function calls from python and vimscript
- gather declared parameters
Decorator pattern of optioanl arguments copied from
<https://blogs.it.ox.ac.uk/inapickle/2012/01/05/python-decorators-with-optional-arguments/>.
"""
if f is None:
# If called without method, we've been called with optional arguments.
# We return a decorator with the optional arguments filled in.
# Next time round we'll be decorating method.
return partial(deco_args, warn=warn)
@wraps(f)
def wrapper(*args, **kwargs):
languageId, = gather_args(["languageId"])
if not alive(languageId, warn):
return None
arg_spec = inspect.getfullargspec(f)
kwargs_with_defaults = dict(zip(reversed(arg_spec.args),
arg_spec.defaults or ()))
kwargs_with_defaults.update({
"self": args[0],
"languageId": languageId,
})
kwargs_with_defaults.update(kwargs)
try:
final_args = gather_args(arg_spec.args, args, kwargs_with_defaults)
except Exception:
logger.error("Failed to gather_args")
return None
return f(*final_args)
return wrapper
def gather_args(keys: List, args: List = [], kwargs: Dict = {}) -> List:
"""
Gather needed arguments.
"""
res = {} # type: Dict[str, Any]
for k in keys:
res[k] = None
if len(args) > 1 and len(args[1]) > 0: # from vimscript side
kwargs.update(args[1][0])
res.update(kwargs)
cursor = [] # type: List[int]
for k in keys:
if res[k] is not None:
continue
elif k == "languageId":
res[k] = state["nvim"].current.buffer.options["filetype"]
elif k == "buftype":
res[k] = state["nvim"].current.buffer.options["buftype"]
elif k == "uri":
filename = kwargs.get("filename") or state["nvim"].current.buffer.name
res[k] = path_to_uri(filename)
elif k == "line":
cursor = state["nvim"].current.window.cursor
res[k] = cursor[0] - 1
elif k == "character":
res[k] = cursor[1]
elif k == "cword":
res[k] = state["nvim"].funcs.expand("<cword>")
elif k == "bufnames":
res[k] = [b.name for b in state["nvim"].buffers]
elif k == "columns":
res[k] = state["nvim"].options["columns"]
else:
logger.warn("Unknown parameter key: " + k)
result = [res[k] for k in keys]
logger.debug("Gathered arguments: {} = {}".format(keys, result))
return result
def get_selectionUI() -> str:
"""
Determine selectionUI.
"""
if state["nvim"].vars.get("loaded_fzf") == 1:
return "fzf"
else:
return "location-list"
def sync_settings() -> None:
update_state({
"serverCommands": state["nvim"].vars.get("LanguageClient_serverCommands", {}),
"changeThreshold": state["nvim"].vars.get("LanguageClient_changeThreshold", 0),
"selectionUI": state["nvim"].vars.get("LanguageClient_selectionUI") or get_selectionUI(),
"trace": state["nvim"].vars.get("LanguageClient_trace", "off"),
"diagnosticsEnable": state["nvim"].vars.get("LanguageClient_diagnosticsEnable", True),
"diagnosticsList": state["nvim"].vars.get("LanguageClient_diagnosticsList", "quickfix"),
"autoStart": state["nvim"].vars.get("LanguageClient_autoStart", False),
"diagnosticsDisplay": state["nvim"].vars.get("LanguageClient_diagnosticsDisplay", {}),
"settingsPath": state["nvim"].vars.get(
"LanguageClient_settingsPath",
os.path.join(".vim", "settings.json")
),
"loadSettings": state["nvim"].vars.get("LanguageClient_loadSettings", False),
})
windowLogMessageLevel = state["nvim"].vars.get("LanguageClient_windowLogMessageLevel")
if windowLogMessageLevel is not None:
update_state({
"windowLogMessageLevel": MessageType[windowLogMessageLevel],
})
def get_current_buffer_text() -> str:
text = str.join("\n", state["nvim"].current.buffer)
if state["nvim"].current.buffer.options["endofline"]:
text += "\n"
return text
def get_file_line(filepath: str, line: int) -> str:
modified_buffers = [buffer for buffer in state["nvim"].buffers
if buffer.name == filepath and
buffer.options["mod"]]
if len(modified_buffers) == 0:
return linecache.getline(filepath, line).strip()
else:
return modified_buffers[0][line - 1]
def apply_TextDocumentEdit(textDocumentEdit: Dict) -> None:
"""
Apply a TextDocumentEdit.
"""
filename = uri_to_path(textDocumentEdit["textDocument"]["uri"])
edits = textDocumentEdit["edits"]
# Sort edits. From bottom to top, right to left.
edits = sorted(reversed(edits), key=lambda edit: (
-1 * edit["range"]["start"]["line"],
-1 * edit["range"]["start"]["character"],
))
buffer = next((buffer for buffer in state["nvim"].buffers
if buffer.name == filename), None)
# Open file if needed.
if buffer is None:
state["nvim"].command("exe 'edit ' . fnameescape('{}')".format(filename))
buffer = next((buffer for buffer in state["nvim"].buffers
if buffer.name == filename), None)
text = buffer[:]
for edit in edits:
text = apply_TextEdit(text, edit)
if buffer.options["fixendofline"] and text[-1] == "":
buffer[:] = text[:-1]
else:
buffer[:] = text
def apply_WorkspaceEdit(workspaceEdit: Dict) -> None:
"""
Apply a WorkspaceEdit.
"""
logger.info("Begin apply_WorkspaceEdit " + str(workspaceEdit))
if workspaceEdit.get("documentChanges") is not None:
for textDocumentEdit in workspaceEdit.get("documentChanges"):
apply_TextDocumentEdit(textDocumentEdit)
else:
for (uri, edits) in workspaceEdit["changes"].items():
textDocumentEdit = {
"textDocument": {
"uri": uri,
},
"edits": edits,
}
apply_TextDocumentEdit(textDocumentEdit)
def set_cursor(uri: str, line: int, character: int) -> None:
"""
Set cursor position.
"""
cmd = "buffer {} | normal! {}G{}|".format(
uri_to_path(uri), line + 1, character + 1)
execute_command(cmd)
def define_signs() -> None:
"""
Define sign styles.
"""
cmd = "echo "
for level in state["diagnosticsDisplay"].values():
name = level["name"]
sign_text = level["signText"]
sign_text_highlight = level["signTexthl"]
cmd += "| execute 'sign define LanguageClient{} text={} texthl={}'".format(
name, sign_text, sign_text_highlight)
execute_command(cmd)
def fzf(source: List, sink: str) -> None:
"""
Start fzf selection.
"""
execute_command("""
call fzf#run(fzf#wrap({{
'source': {},
'sink': function('{}')
}}))
""".replace("\n", "").format(json.dumps(source), sink))
state["nvim"].feedkeys("i")
def show_diagnostics(uri: str, diagnostics: List) -> None:
"""
Show diagnostics.
"""
path = uri_to_path(uri)
buffer = state["nvim"].current.buffer
if state.get(uri, {}).get("highlight_source_id") is None:
update_state({
uri: {
"highlight_source_id": state["nvim"].new_highlight_source(),
}
})
highlight_source_id = state[uri]["highlight_source_id"]
buffer.clear_highlight(highlight_source_id)
signs = []
qflist = []
for entry in diagnostics:
start_line = entry["range"]["start"]["line"]
start_character = entry["range"]["start"]["character"]
end_character = entry["range"]["end"]["character"]
severity = DiagnosticSeverity(entry.get("severity", 3))
display = state["diagnosticsDisplay"][severity.value]
text_highlight = display["texthl"]
buffer.add_highlight(text_highlight, start_line,
start_character, end_character,
highlight_source_id)
signs.append(Sign(start_line + 1, severity))
qflist.append({
"filename": path,
"lnum": start_line + 1,
"col": start_character + 1,
"nr": entry.get("code"),
"text": entry["message"],
"type": DiagnosticSeverity(severity.value).name,
})
signs = sorted(set(signs))
cmd = get_command_update_signs(state[uri].get("signs", []), signs, path)
execute_command(cmd)
set_state([uri, "signs"], signs)
if state["diagnosticsList"] == "quickfix":
state["nvim"].funcs.setqflist(qflist)
elif state["diagnosticsList"] == "location":
state["nvim"].funcs.setloclist(0, qflist)
def show_line_diagnostic(uri: str, line: int, columns: int) -> None:
logger.info("Begin show_line_diagnostic")
entry = state.get(uri, {}).get("line_diagnostics", {}).get(line, "")
if entry == state["last_line_diagnostic"]:
return
update_state({
"last_line_diagnostic": entry,
})
echo_ellipsis(entry, columns)
@neovim.plugin
class LanguageClient:
_instance = None # type: LanguageClient
def __init__(self, nvim):
logger.info("__init__")
type(self)._instance = self
self.nvim = nvim
update_state({
"nvim": nvim,
})
update_state({
"autoStart": state["nvim"].vars.get("LanguageClient_autoStart", False),
})
@neovim.function("LanguageClient_getState", sync=True)
def getState_vim(self, args: List) -> str:
"""
Return state object. Skip unserializable parts.
Note: this function serves only cases that state is needed from
vimscript. For uses inside python, import state directly.
"""
state_copy = make_serializable(state)
return json.dumps(state_copy)
@neovim.function("LanguageClient_registerServerCommands")
def registerServerCommands(self, args: List) -> None:
"""
Add or update serverCommands.
"""
serverCommands = args[0] # Dict[str, List[str]]
update_state({
"serverCommands": serverCommands
})
@neovim.function("LanguageClient_alive", sync=True)
def alive_vim(self, args: List) -> bool:
languageId, = gather_args(["languageId"])
return alive(languageId, warn=False)
@neovim.function("LanguageClient_setLoggingLevel")
def setLoggingLevel_vim(self, args: List) -> None:
setLoggingLevel(args[0])
@neovim.command("LanguageClientStart", nargs="*", range="")
def start(self, args=None, warn=True) -> None:
sync_settings()
languageId, = gather_args(["languageId"])
if alive(languageId, warn=False):
echomsg("Language client has already started.")
return
if languageId not in state["serverCommands"]:
if not warn:
return
msg = "No language server command found for type: {}.".format(languageId)
logger.error(msg)
echoerr(msg)
return
logger.info("Begin LanguageClientStart")
command = state["serverCommands"][languageId]
command = [os.path.expandvars(os.path.expanduser(cmd))
for cmd in command]
try:
proc = subprocess.Popen(
# ["/bin/bash", "/tmp/wrapper.sh"],
command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=open(logpath_server, "wb"))
except Exception as ex:
msg = "Failed to start language server: " + ex.args[1]
logger.exception(msg)
echoerr(msg)
return
rpc = RPC(proc.stdout, proc.stdin, self.handle_request_and_notify, languageId)
thread = threading.Thread(target=rpc.serve, name="RPC-" + languageId, daemon=True)
thread.start()
update_state({
"servers": {
languageId: proc,
},
"rpcs": {
languageId: rpc,
}
})
if len(state["servers"]) == 1:
define_signs()
# TODO: possibly expand special variables like '%:h'
kwargs = convert_vim_command_args_to_kwargs(args)
rootPath = kwargs.get("rootPath")
logger.info("End LanguageClientStart")
self.initialize(rootPath=rootPath, languageId=languageId)
self.textDocument_didOpen(languageId=languageId)
self.textDocument_didChange(languageId=languageId)
if state["nvim"].call("exists", "#User#LanguageClientStarted") == 1:
state["nvim"].command("doautocmd User LanguageClientStarted")
@neovim.command("LanguageClientStop")
@deco_args
def stop(self, languageId: str) -> None:
self.exit(languageId=languageId)
update_state({
"servers": {
languageId: None
}
})
if state["nvim"].call("exists", "#User#LanguageClientStopped") == 1:
state["nvim"].command("doautocmd User LanguageClientStopped")
@neovim.function("LanguageClient_initialize")
@deco_args
def initialize(self, rootPath: str, settingsPath: str, languageId: str, handle=True) -> Dict:
logger.info("Begin initialize")
if rootPath is None:
rootPath = get_rootPath(state["nvim"].current.buffer.name, languageId)
logger.info("rootPath: " + rootPath)
update_state({
"rootUris": {
languageId: path_to_uri(rootPath)
}
})
if settingsPath is None:
settingsPath = os.path.join(rootPath, state["settingsPath"])
logger.info("settingsPath: " + settingsPath)
settings = {} # type: Dict
if state["loadSettings"]:
if os.path.isfile(settingsPath):
settings = json.load(open(settingsPath))
else:
logger.info("settingsPath is not a file")
result = state["rpcs"][languageId].call("initialize", {
"processId": os.getpid(),
"rootPath": rootPath,
"rootUri": state["rootUris"][languageId],
"initializationOptions": settings.get("initializationOptions"),
"capabilities": {
"workspace": {
"applyEdit": True
},
"textDocument": {
"completion": {
"completionItem": {
"snippetSupport": True
}
}
}
},
"trace": state["trace"],
})
if result is None or not handle:
return result
update_state({
"capabilities": {
languageId: result["capabilities"]
}
})
if "initializationOptions" in settings:
del settings["initializationOptions"]
self.workspace_didChangeConfiguration(settings=settings, languageId=languageId)
self.registerCMSource(languageId, result)
logger.info("End initialize")
return result
def registerCMSource(self, languageId: str, result: Dict) -> None:
completionProvider = result["capabilities"].get("completionProvider")
if completionProvider is None:
return
trigger_patterns = []
for c in completionProvider.get("triggerCharacters", []):
trigger_patterns.append(re.escape(c))
try:
state["nvim"].call("cm#register_source", dict(
name="LanguageClient_{}".format(languageId),
priority=9,
scopes=[languageId],
cm_refresh_patterns=trigger_patterns,
abbreviation="",
cm_refresh="LanguageClient_completionManager_refresh"))
logger.info("register completion manager source ok.")
except Exception as ex:
logger.warn("register completion manager source failed. Error: " +
repr(ex))
@neovim.autocmd(
"BufReadPost", pattern="*",
eval="[{'buftype': &buftype, 'languageId': &filetype, 'filename': expand('%:p')}]")
def handle_BufReadPost(self, args: List) -> None:
logger.info("Begin handle BufReadPost")
buftype, languageId, uri = gather_args(["buftype", "languageId", "uri"], args=args)
if buftype != "" or not uri:
return
# Language server is running but file is not within rootUri.
if (state["rootUris"].get(languageId) and
not uri.startswith(state["rootUris"][languageId])):
return
# Opened before.
if state.get(uri, {}).get("textDocument") is not None:
return
if alive(languageId, warn=False):
self.textDocument_didOpen(uri=uri, languageId=languageId)
show_diagnostics(uri, state.get(uri, {}).get("diagnostics", []))
line, columns = gather_args(["line", "columns"])
show_line_diagnostic(uri, line, columns)
elif state["autoStart"]:
self.start(warn=False)
logger.info("End handleBufReadPost")
@deco_args(warn=False)
def textDocument_didOpen(self, uri: str, languageId: str) -> None:
logger.info("Begin textDocument/didOpen")
text = get_current_buffer_text()
textDocumentItem = TextDocumentItem(uri, languageId, text)
set_state([uri, "textDocument"], textDocumentItem)
state["rpcs"][languageId].notify("textDocument/didOpen", {
"textDocument": {
"uri": textDocumentItem.uri,
"languageId": textDocumentItem.languageId,
"version": textDocumentItem.version,
"text": textDocumentItem.text,
}
})
state["nvim"].current.buffer.options["omnifunc"] = "LanguageClient#complete"
logger.info("End textDocument/didOpen")
@neovim.function("LanguageClient_textDocument_didClose")
@deco_args(warn=False)
def textDocument_didClose(self, uri: str, languageId: str) -> None:
logger.info("textDocument/didClose")
state["rpcs"][languageId].notify("textDocument/didClose", {
"textDocument": {
"uri": uri
}
})
set_state([uri, "textDocument"], None)
@deco_args(warn=False)
def workspace_didChangeConfiguration(self, settings: Dict, languageId: str) -> None:
logger.info("workspace/didChangeConfiguration")
state["rpcs"][languageId].notify("workspace/didChangeConfiguration", {
"settings": settings
})
@neovim.function("LanguageClient_workspace_didChangeConfiguration")
def workspace_didChangeConfiguration_vim(self, args: List) -> None:
self.workspace_didChangeConfiguration(settings=args[0])
def _textDocument_hover(self, uri: str, languageId: str,
line: int, character: int) -> Dict:
logger.info("Begin textDocument/hover")
self.textDocument_didChange()
result = state["rpcs"][languageId].call("textDocument/hover", {
"textDocument": {
"uri": uri
},
"position": {
"line": line,
"character": character
}
})
logger.info("End textDocument/hover")
return result
@neovim.function("LanguageClient_textDocument_hoverSync", sync=True)
@deco_args
def textDocument_hoverSync(self, uri: str, languageId: str,
line: int, character: int) -> Dict:
return self._textDocument_hover(uri, languageId, line, character)
@neovim.function("LanguageClient_textDocument_hover")
@deco_args
def textDocument_hover(self, uri: str, languageId: str,
line: int, character: int, handle=True) -> Dict:
result = self._textDocument_hover(uri, languageId, line, character)
if result is None or not handle:
return result
contents = result.get("contents")
if contents is None:
contents = "No info."
if isinstance(contents, list):
info = str.join("\n", [markedString_to_str(s) for s in contents])
else:
info = markedString_to_str(contents)
echo(info)
return result
@neovim.function("LanguageClient_textDocument_definition")
@deco_args
def textDocument_definition(
self, uri: str, languageId: str, line: int, character: int,
bufnames: List[str], handle=True) -> Union[Dict, List]:
logger.info("Begin textDocument/definition")
self.textDocument_didChange()
result = state["rpcs"][languageId].call("textDocument/definition", {
"textDocument": {
"uri": uri
},
"position": {
"line": line,
"character": character
}
})
if result is None or not handle:
return result
if isinstance(result, list) and len(result) > 1:
# TODO
msg = ("Handling multiple definitions is not implemented yet."
" Jumping to first.")
logger.error(msg)
echoerr(msg)
if isinstance(result, list):
if len(result) == 0:
echo("Not found.")
return result
defn = result[0]
else:
defn = result
if not defn.get("uri"):
return None
if not defn["uri"].startswith("file:///"):
echo("{}:{}".format(defn["uri"], defn["range"]["start"]["line"]))
return result
path = uri_to_path(defn["uri"])
line = defn["range"]["start"]["line"] + 1
character = defn["range"]["start"]["character"] + 1
cmd = get_command_goto_file(path, bufnames, line, character)
execute_command(cmd)
logger.info("End textDocument/definition")
return result
@neovim.function("LanguageClient_textDocument_rename")
@deco_args
def textDocument_rename(
self, uri: str, languageId: str, line: int, character: int,
cword: str, newName: str, handle=True) -> Dict:
logger.info("Begin textDocument/rename")
self.textDocument_didChange()
if newName is None:
state["nvim"].funcs.inputsave()
newName = state["nvim"].funcs.input("Rename to: ", cword)
state["nvim"].funcs.inputrestore()
workspaceEdit = state["rpcs"][languageId].call("textDocument/rename", {
"textDocument": {
"uri": uri
},
"position": {
"line": line,
"character": character,
},
"newName": newName
})
if workspaceEdit is None or not handle:
return workspaceEdit
apply_WorkspaceEdit(workspaceEdit)
set_cursor(uri, line, character)
logger.info("End textDocument/rename")
return workspaceEdit
@neovim.function("LanguageClient_textDocument_documentSymbol")
@deco_args
def textDocument_documentSymbol(self, uri: str, languageId: str, handle=True) -> List:
logger.info("Begin textDocument/documentSymbol")
self.textDocument_didChange()
symbols = state["rpcs"][languageId].call("textDocument/documentSymbol", {
"textDocument": {
"uri": uri
}
})
if symbols is None or not handle:
return symbols
if state["selectionUI"] == "fzf":
source = []
for sb in symbols:
name = sb["name"]
start = sb["location"]["range"]["start"]
line = start["line"] + 1
character = start["character"] + 1
entry = "{}:{}:\t{}".format(line, character, name)
source.append(entry)
fzf(source, "LanguageClient#FZFSinkTextDocumentDocumentSymbol")
elif state["selectionUI"] == "location-list":
loclist = []
path = uri_to_path(uri)
for sb in symbols:
name = sb["name"]
start = sb["location"]["range"]["start"]
line = start["line"] + 1
character = start["character"] + 1
loclist.append({
"filename": path,
"lnum": line,
"col": character,
"text": name,
})
state["nvim"].funcs.setloclist(0, loclist)
echo("Document symbols populated to location list.")
else:
msg = "No selection UI found. Consider install fzf or denite.vim."
logger.warn(msg)
echoerr(msg)
logger.info("End textDocument/documentSymbol")
return symbols
@neovim.function("LanguageClient_FZFSinkTextDocumentDocumentSymbol")
def fzfSinkTextDocumentDocumentSymbol(self, args: List) -> None:
splitted = args[0].split(":")
line = splitted[0]
character = splitted[1]
execute_command("normal! {}G{}|".format(line, character))
@neovim.function("LanguageClient_workspace_symbol")
@deco_args
def workspace_symbol(self, languageId: str, query: str, handle=True) -> List:
logger.info("Begin workspace/symbol")
if query is None:
query = ""
symbols = state["rpcs"][languageId].call("workspace/symbol", {
"query": query
})
if symbols is None or not handle:
return symbols
if state["selectionUI"] == "fzf":
source = []
for sb in symbols:
path = os.path.relpath(sb["location"]["uri"], state["rootUris"][languageId])
start = sb["location"]["range"]["start"]
line = start["line"] + 1
character = start["character"] + 1
name = sb["name"]
entry = "{}:{}:{}\t{}".format(path, line, character, name)
source.append(entry)
fzf(source, "LanguageClient#FZFSinkWorkspaceSymbol")
elif state["selectionUI"] == "location-list":
loclist = []
for sb in symbols:
path = uri_to_path(sb["location"]["uri"])
start = sb["location"]["range"]["start"]
line = start["line"] + 1
character = start["character"] + 1
name = sb["name"]
loclist.append({
"filename": path,
"lnum": line,
"col": character,
"text": name,
})
state["nvim"].funcs.setloclist(0, loclist)
echo("Workspace symbols populated to location list.")
else:
msg = "No selection UI found. Consider install fzf or denite.vim."
logger.warn(msg)
echoerr(msg)
logger.info("End workspace/symbol")
return symbols
@neovim.function("LanguageClient_FZFSinkWorkspaceSymbol")
def fzfSinkWorkspaceSymbol(self, args: List):
bufnames, languageId = gather_args(["bufnames", "languageId"])
splitted = args[0].split(":")
path = uri_to_path(os.path.join(state["rootUris"][languageId], splitted[0]))
line = splitted[1]
character = splitted[2]
cmd = get_command_goto_file(path, bufnames, line, character)
execute_command(cmd)
@neovim.function("LanguageClient_textDocument_references")
@deco_args
def textDocument_references(
self, uri: str, languageId: str, line: int, character: int,
includeDeclaration: bool = True, handle=True) -> List:
logger.info("Begin textDocument/references")
self.textDocument_didChange()
locations = state["rpcs"][languageId].call("textDocument/references", {
"textDocument": {
"uri": uri,
},
"position": {
"line": line,
"character": character,
},
"context": {
"includeDeclaration": includeDeclaration,
},
})
if locations is None:
return locations
# enhance with the line's contents for Denite
for loc in locations:
path = uri_to_path(loc["uri"])
start = loc["range"]["start"]
line = start["line"] + 1
character = start["character"] + 1
text = get_file_line(path, line)
loc['text'] = text
if not handle:
return locations
if state["selectionUI"] == "fzf":
source = [] # type: List[str]
for loc in locations:
path = os.path.relpath(loc["uri"],
state["rootUris"][languageId])
start = loc["range"]["start"]
line = start["line"] + 1
character = start["character"] + 1
text = loc["text"]
entry = "{}:{}:{}: {}".format(path, line, character, text)
source.append(entry)
fzf(source, "LanguageClient#FZFSinkTextDocumentReferences")
elif state["selectionUI"] == "location-list":
loclist = []
for loc in locations:
path = uri_to_path(loc["uri"])
start = loc["range"]["start"]
line = start["line"] + 1
character = start["character"] + 1
text = loc["text"]
loclist.append({
"filename": path,
"lnum": line,
"col": character,
"text": text
})
state["nvim"].funcs.setloclist(0, loclist)
echo("References populated to location list.")
else:
msg = "No selection UI found. Consider install fzf or denite.vim."
logger.warn(msg)
echoerr(msg)
logger.info("End textDocument/references")
return locations
@neovim.function("LanguageClient_rustDocument_implementations")
@deco_args
def rustDocument_implementations(
self, uri: str, languageId: str, line: int, character: int,
handle=True) -> List:
logger.info("Begin rustDocument/implementations")
self.textDocument_didChange()
locations = state["rpcs"][languageId].call("rustDocument/implementations", {
"textDocument": {
"uri": uri,
},
"position": {
"line": line,
"character": character,
}
})
if locations is None or not handle:
return locations
if state["selectionUI"] == "fzf":
source = [] # type: List[str]
for loc in locations:
path = os.path.relpath(loc["uri"],
state["rootUris"][languageId])
start = loc["range"]["start"]
line = start["line"] + 1
character = start["character"] + 1
text = get_file_line(uri_to_path(loc["uri"]), line)
entry = "{}:{}:{}: {}".format(path, line, character, text)
source.append(entry)
fzf(source, "LanguageClient#FZFSinkTextDocumentReferences")
elif state["selectionUI"] == "location-list":
loclist = []
for loc in locations:
path = uri_to_path(loc["uri"])
start = loc["range"]["start"]
line = start["line"] + 1
character = start["character"] + 1
text = get_file_line(path, line)
loclist.append({
"filename": path,
"lnum": line,
"col": character,
"text": text
})
state["nvim"].funcs.setloclist(0, loclist)
echo("References populated to location list.")
else:
msg = "No selection UI found. Consider install fzf or denite.vim."
logger.warn(msg)
echoerr(msg)
logger.info("End rustDocument/implementations")
return locations
@neovim.function("LanguageClient_FZFSinkTextDocumentReferences")
def fzfSinkTextDocumentReferences(self, args: List) -> None:
bufnames, languageId = gather_args(["bufnames", "languageId"])
splitted = args[0].split(":")
path = uri_to_path(os.path.join(state["rootUris"][languageId], splitted[0]))
line = splitted[1]
character = splitted[2]
cmd = get_command_goto_file(path, bufnames, line, character)
execute_command(cmd)
@neovim.autocmd("TextChanged", pattern="*",
eval="[{'filename': expand('%:p'), 'buftype': &buftype}]")
def handle_TextChanged(self, args: List) -> None:
logger.info("Begin handle TextChanged")
uri, buftype = gather_args(["uri", "buftype"], args=args)
if buftype != "" or state.get(uri, {}).get("textDocument") is None:
return
text_doc = state[uri]["textDocument"]
if text_doc.skip_change(state["changeThreshold"]):
return
self.textDocument_didChange()
@neovim.autocmd("TextChangedI", pattern="*",
eval="[{'filename': expand('%:p'), 'buftype': &buftype}]")
def handle_TextChangedI(self, args: List) -> None:
logger.info("Begin handle TextChangedI")
self.handle_TextChanged(args)
@neovim.function("textDocument_didChange")
@deco_args(warn=False)
def textDocument_didChange(self, uri: str, languageId: str) -> None: