forked from autozimu/LanguageClient-neovim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLanguageClient.vim
1849 lines (1608 loc) · 59.7 KB
/
LanguageClient.vim
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
if get(g:, 'LanguageClient_loaded')
finish
endif
let s:TYPE = {
\ 'string': type(''),
\ 'list': type([]),
\ 'dict': type({}),
\ 'funcref': type(function('call'))
\ }
let s:FLOAT_WINDOW_AVAILABLE = exists('*nvim_open_win')
let s:POPUP_WINDOW_AVAILABLE = exists('*popup_atcursor')
" timers to control throttling
let s:timers = {}
if !hlexists('LanguageClientCodeLens')
hi link LanguageClientCodeLens Title
endif
if !hlexists('LanguageClientWarningSign')
hi link LanguageClientWarningSign todo
endif
if !hlexists('LanguageClientWarning')
hi link LanguageClientWarning SpellCap
endif
if !hlexists('LanguageClientInfoSign')
hi link LanguageClientInfoSign LanguageClientWarningSign
endif
if !hlexists('LanguageClientInfo')
hi link LanguageClientInfo LanguageClientWarning
endif
if !hlexists('LanguageClientErrorSign')
hi link LanguageClientErrorSign error
endif
if !hlexists('LanguageClientError')
hi link LanguageClientError SpellBad
endif
function! s:AddPrefix(message) abort
return '[LC] ' . a:message
endfunction
function! s:Echo(message) abort
echo a:message
endfunction
function! s:Ellipsis(message) abort
let l:maxlen = &columns * &cmdheight - 2
if &showcmd
let maxlen -= 11
endif
if &ruler
let maxlen -= 18
endif
if len(a:message) < l:maxlen
let l:message = a:message
else
let l:message = a:message[:l:maxlen - 3] . '...'
endif
return l:message
endfunction
" `echo` message without trigger |hit-enter|
function! s:EchoEllipsis(message) abort
echo s:Ellipsis(a:message)
endfunction
" `echomsg` message without trigger |hit-enter|
function! s:EchomsgEllipsis(message) abort
" Credit: ALE, snippets from ale#cursor#TruncatedEcho()
let l:message = s:AddPrefix(a:message)
" Change tabs to spaces.
let l:message = substitute(l:message, "\t", ' ', 'g')
" Remove any newlines in the message.
let l:message = substitute(l:message, "\n", '', 'g')
" We need to remember the setting for shortmess and reset it again.
let l:shortmess_options = &l:shortmess
try
let l:cursor_position = getcurpos()
" The message is truncated and saved to the history.
setlocal shortmess+=T
exec "norm! :echomsg l:message\n"
" Reset the cursor position if we moved off the end of the line.
" Using :norm and :echomsg can move the cursor off the end of the
" line.
if l:cursor_position != getcurpos()
call setpos('.', l:cursor_position)
endif
finally
let &l:shortmess = l:shortmess_options
endtry
endfunction
function! s:Echomsg(message) abort
echomsg s:AddPrefix(a:message)
endfunction
function! s:Echoerr(message) abort
echohl Error | echomsg s:AddPrefix(a:message) | echohl None
endfunction
function! s:Echowarn(message) abort
echohl WarningMsg | echomsg s:AddPrefix(a:message) | echohl None
endfunction
" timeout: skip function call f until this timeout, in seconds.
function! s:Debounce(timeout, f) abort
" Map function to its last execute time.
let s:DebounceMap = {}
let l:lastexectime = get(s:DebounceMap, a:f)
if l:lastexectime == 0 || reltimefloat(reltime(l:lastexectime)) < a:timeout
let s:DebounceMap[a:f] = reltime()
return v:true
else
return v:false
endif
endfunction
function! s:Debug(message) abort
if !exists('g:LanguageClient_loggingLevel')
return
endif
if g:LanguageClient_loggingLevel ==? 'INFO' || g:LanguageClient_loggingLevel ==? 'DEBUG'
call s:Echoerr(a:message)
endif
endfunction
function! s:hasSnippetSupport() abort
if exists('g:LanguageClient_hasSnippetSupport')
return g:LanguageClient_hasSnippetSupport !=# 0
endif
" https://github.com/Shougo/neosnippet.vim
if exists('g:loaded_neosnippet')
return 1
endif
return 0
endfunction
function! s:getSelectionUI() abort
if type(get(g:, 'LanguageClient_selectionUI', v:null)) is s:TYPE.funcref
return 'funcref'
else
return get(g:, 'LanguageClient_selectionUI', v:null)
endif
endfunction
function! s:useVirtualText() abort
let l:use = s:GetVar('LanguageClient_useVirtualText')
if l:use isnot v:null
return l:use
endif
if exists('*nvim_buf_set_virtual_text')
return 'All'
else
return 'No'
endif
endfunction
function! s:IsTrue(v) abort
if type(a:v) ==# type(0)
return a:v ==# 0 ? v:false : v:true
elseif a:v is v:null
return v:false
else
return v:true
endif
endfunction
function! s:IsFalse(v) abort
return s:IsTrue(a:v) ? v:false : v:true
endfunction
" Get all listed buffer file names.
function! s:Bufnames() abort
return map(filter(range(0,bufnr('$')), 'buflisted(v:val)'), 'fnamemodify(bufname(v:val), '':p'')')
endfunction
" Clear and set virtual texts between line_start and line_end (exclusive).
function! s:set_virtual_texts(buf_id, ns_id, line_start, line_end, virtual_texts) abort
" VirtualText: map with keys line, text and hl_group.
let l:prefix = s:GetVar('LanguageClient_virtualTextPrefix')
if l:prefix is v:null
let l:prefix = ''
endif
if !exists('*nvim_buf_set_virtual_text')
return
endif
call nvim_buf_clear_namespace(a:buf_id, a:ns_id, a:line_start, a:line_end)
for vt in a:virtual_texts
call nvim_buf_set_virtual_text(a:buf_id, a:ns_id, vt['line'], [[l:prefix . vt['text'], vt['hl_group']]], {})
endfor
endfunction
function! s:place_sign(id, name, file, line) abort
if !exists('*sign_place')
execute 'sign place id=' . a:id . ' name=' . a:name . ' file=' . a:file . ' line=' . a:line
endif
call sign_place(0, 'LanguageClientNeovim', a:name, a:file, { 'lnum': a:line })
endfunction
" clears all signs on the buffer with the given name
function! s:clear_buffer_signs(file) abort
if !exists('*sign_unplace')
execute 'sign unplace * group=LanguageClientNeovim buffer=' . a:file
else
call sign_unplace('LanguageClientNeovim', { 'buffer': a:file })
endif
endfunction
" replaces the signs on a file with the ones passed as an argument
function! s:set_signs(file, signs) abort
call s:clear_buffer_signs(a:file)
for l:sign in a:signs
let l:line = l:sign['line'] + 1
let l:name = l:sign['name']
let l:id = l:sign['id']
call s:place_sign(l:id, l:name, a:file, l:line)
endfor
endfunction
" Execute serious of ex commands.
function! s:command(...) abort
for l:cmd in a:000
execute l:cmd
endfor
endfunction
function! s:getInput(prompt, default) abort
call inputsave()
let l:input = input(a:prompt, a:default)
call inputrestore()
return l:input
endfunction
function! s:inputlist(...) abort
call inputsave()
let l:selection = inputlist(a:000)
call inputrestore()
return l:selection
endfunction
function! s:selectionUI_funcref(source, sink) abort
if type(get(g:, 'LanguageClient_selectionUI')) is s:TYPE.funcref
call call(g:LanguageClient_selectionUI, [a:source, function(a:sink)])
elseif get(g:, 'LanguageClient_selectionUI', 'FZF') ==? 'FZF'
\ && get(g:, 'loaded_fzf')
call s:FZF(a:source, a:sink)
else
call s:Echoerr('Unsupported selection UI, use "FZF" or a funcref')
return
endif
endfunction
function! s:FZF(source, sink) abort
if !get(g:, 'loaded_fzf')
call s:Echoerr('FZF not loaded!')
return
endif
let l:options = s:GetVar('LanguageClient_fzfOptions')
if l:options is v:null
if exists('*fzf#vim#with_preview')
let l:options = fzf#vim#with_preview('right:50%:hidden', '?').options
else
let l:options = []
endif
endif
call fzf#run(fzf#wrap({
\ 'source': a:source,
\ 'sink': function(a:sink),
\ 'options': l:options,
\ }))
if has('nvim') && !has('nvim-0.4')
call feedkeys('i')
endif
endfunction
function! s:Edit(action, path) abort
" If editing current file, push current location to jump list.
let l:bufnr = bufnr(a:path)
if l:bufnr == bufnr('%')
execute 'normal! m`'
return
endif
let l:action = a:action
" Avoid the 'not saved' warning.
if l:action ==# 'edit' && l:bufnr != -1
execute 'buffer' l:bufnr
set buflisted
return
endif
execute l:action . ' ' . fnameescape(a:path)
endfunction
" Batch version of `matchdelete()`.
function! s:MatchDelete(ids) abort
for l:id in a:ids
call matchdelete(l:id)
endfor
endfunction
function! s:ApplySemanticHighlights(bufnr, ns_id, clears, highlights) abort
" TODO: implement this for vim8
if !has('nvim')
return
endif
for clear in a:clears
call nvim_buf_clear_namespace(a:bufnr, a:ns_id, clear.line_start, clear.line_end)
endfor
for hl in a:highlights
call nvim_buf_add_highlight(a:bufnr, a:ns_id, hl.group, hl.line, hl.character_start, hl.character_end)
endfor
endfunction
" Batch version of nvim_buf_add_highlight
function! s:AddHighlights(namespace, highlights) abort
if has('nvim')
let l:namespace_id = nvim_create_namespace(a:namespace)
for hl in a:highlights
call nvim_buf_add_highlight(0, l:namespace_id, hl.group, hl.line, hl.character_start, hl.character_end)
endfor
else
let match_ids = []
for hl in a:highlights
let match_id = matchaddpos(hl.group, [[hl.line + 1, hl.character_start + 1, hl.character_end - hl.character_start]])
let match_ids = add(match_ids, match_id)
endfor
call setbufvar(bufname(), a:namespace . '_IDS', match_ids)
endif
endfunction
function! s:SetHighlights(highlights, namespace) abort
call s:ClearHighlights(a:namespace)
call s:AddHighlights(a:namespace, a:highlights)
endfunction
function! s:ClearHighlights(namespace) abort
if has('nvim')
let l:namespace_id = nvim_create_namespace(a:namespace)
call nvim_buf_clear_namespace(0, l:namespace_id, 0, -1)
else
let match_ids = get(b:, a:namespace . '_IDS', [])
for mid in match_ids
" call inside a try/catch to avoid error for manually cleared matches
try | call matchdelete(mid) | catch
endtry
endfor
call setbufvar(bufname(), a:namespace . '_IDS', [])
endif
endfunction
" Get an variable value.
" Get variable from buffer local, or else global, or else default, or else v:null.
function! s:GetVar(...) abort
let name = a:1
if exists('b:' . name)
return get(b:, name)
elseif exists('g:' . name)
return get(g:, name)
else
return get(a:000, 1, v:null)
endif
endfunction
" if the argument is a list, return it unchanged, otherwise return the list
" containing the argument.
function! s:ToList(x) abort
if type(a:x) == v:t_list
return a:x
else
return [ a:x ]
endif
endfunction
function! s:ShouldUseFloatWindow() abort
let floatingHoverEnabled = s:GetVar('LanguageClient_useFloatingHover', v:true)
return s:FLOAT_WINDOW_AVAILABLE && floatingHoverEnabled
endfunction
function! s:CloseFloatingHover() abort
if !exists('s:float_win_id')
return
endif
autocmd! plugin-LC-neovim-close-hover
let winnr = win_id2win(s:float_win_id)
if winnr == 0
return
endif
execute winnr . 'wincmd c'
endfunction
function! s:CloseFloatingHoverOnCursorMove(opened) abort
if getpos('.') == a:opened
" Just after opening floating window, CursorMoved event is run.
" To avoid closing floating window immediately, check the cursor
" was really moved
return
endif
autocmd! plugin-LC-neovim-close-hover
let winnr = win_id2win(s:float_win_id)
if winnr == 0
return
endif
execute winnr . 'wincmd c'
endfunction
function! s:CloseFloatingHoverOnBufEnter(bufnr) abort
let winnr = win_id2win(s:float_win_id)
if winnr == 0
" Float window was already closed
autocmd! plugin-LC-neovim-close-hover
return
endif
if winnr == winnr()
" Cursor is moving into floating window. Do not close it
return
endif
if bufnr('%') == a:bufnr
" When current buffer opened hover window, it's not another buffer. Skipped
return
endif
autocmd! plugin-LC-neovim-close-hover
execute winnr . 'wincmd c'
endfunction
" Open preview window. Window is open in:
" - Floating window on Neovim (0.4.0 or later)
" - popup window on vim (8.2 or later)
" - Preview window on Neovim (0.3.0 or earlier) or Vim
"
" Receives two optional arguments which are the X and Y position
function! s:OpenHoverPreview(bufname, lines, filetype, ...) abort
" Use local variable since parameter is not modifiable
let lines = a:lines
let bufnr = bufnr('%')
let display_approach = ''
if s:ShouldUseFloatWindow()
let display_approach = 'float_win'
elseif s:POPUP_WINDOW_AVAILABLE && s:GetVar('LanguageClient_usePopupHover', v:true)
let display_approach = 'popup_win'
else
let display_approach = 'preview'
endif
if display_approach ==# 'float_win'
" When a language server takes a while to initialize and the user
" calls hover multiple times during that time (for example, via an
" automatic hover on cursor move setup), we will get a number of
" successive calls into this function resulting in many hover windows
" opened. This causes a number of issues, and we only really want one,
" so make sure that the previous hover window is closed.
call s:CloseFloatingHover()
let pos = getpos('.')
let l:hoverMarginSize = s:GetVar('LanguageClient_hoverMarginSize', 1)
" Calculate width and height and give margin to lines
let width = 0
for index in range(len(lines))
let line = lines[index]
if line !=# ''
" Give a left margin
let line = repeat(' ', l:hoverMarginSize) . line
endif
let lw = strdisplaywidth(line)
if lw > width
let width = lw
endif
let lines[index] = line
endfor
" Give margin
let width += l:hoverMarginSize
let l:topBottom = repeat([''], l:hoverMarginSize)
let lines = l:topBottom + lines + l:topBottom
let height = len(lines)
" Calculate anchor
" Prefer North, but if there is no space, fallback into South
let bottom_line = line('w0') + winheight(0) - 1
if pos[1] + height <= bottom_line
let vert = 'N'
let row = 1
else
let vert = 'S'
let row = 0
endif
" Prefer West, but if there is no space, fallback into East
if pos[2] + width <= &columns
let hor = 'W'
let col = 0
else
let hor = 'E'
let col = 1
endif
let relative = 'cursor'
let col = get(a:000, 0, col)
let row = get(a:000, 1, row)
if get(a:000, 0, v:null) isnot v:null && get(a:000, 1, v:null) isnot v:null
let relative = 'win'
endif
let s:float_win_id = nvim_open_win(bufnr, v:true, {
\ 'relative': relative,
\ 'anchor': vert . hor,
\ 'row': row,
\ 'col': col,
\ 'width': width,
\ 'height': height,
\ 'style': s:GetVar('LanguageClient_floatingWindowStyle', 'minimal'),
\ })
execute 'noswapfile edit!' a:bufname
let float_win_highlight = s:GetVar('LanguageClient_floatingHoverHighlight', 'Normal:CursorLine')
execute printf('setlocal winhl=%s', float_win_highlight)
elseif display_approach ==# 'popup_win'
let l:padding = [1, 1, 1, 1]
if get(a:000, 0, v:null) isnot v:null && get(a:000, 1, v:null) isnot v:null
let pop_win_id = popup_create(a:lines, {
\ 'line': get(a:000, 1) + 1,
\ 'col': get(a:000, 0) + 1,
\ 'padding': l:padding,
\ 'drag': 1,
\ 'border': [1,1,1,1],
\ 'moved': 'any'
\ })
else
let pop_win_id = popup_atcursor(a:lines, { 'padding': l:padding })
endif
call setbufvar(winbufnr(pop_win_id), '&filetype', a:filetype)
" trigger refresh on plasticboy/vim-markdown
call win_execute(pop_win_id, 'doautocmd InsertLeave')
elseif display_approach ==# 'preview'
execute 'silent! noswapfile pedit!' a:bufname
wincmd P
else
call s:Echoerr('Unknown display approach: ' . display_approach)
endif
if display_approach !=# 'popup_win'
setlocal buftype=nofile nobuflisted bufhidden=wipe nonumber norelativenumber signcolumn=no modifiable
if a:filetype isnot v:null
let &filetype = a:filetype
endif
call setline(1, lines)
" trigger refresh on plasticboy/vim-markdown
doautocmd InsertLeave
setlocal nomodified nomodifiable
wincmd p
endif
if display_approach ==# 'float_win'
" Unlike preview window, :pclose does not close window. Instead, close
" hover window automatically when cursor is moved.
let call_after_move = printf('<SID>CloseFloatingHoverOnCursorMove(%s)', string(pos))
let call_on_bufenter = printf('<SID>CloseFloatingHoverOnBufEnter(%d)', bufnr)
augroup plugin-LC-neovim-close-hover
execute 'autocmd CursorMoved,CursorMovedI,InsertEnter <buffer> call ' . call_after_move
execute 'autocmd BufEnter * call ' . call_on_bufenter
augroup END
endif
endfunction
function! s:MoveIntoHoverPreview(bufname) abort
for bufnr in range(1, bufnr('$'))
if bufname(bufnr) ==# a:bufname
let winnr = bufwinnr(bufnr)
if winnr != -1
execute winnr . 'wincmd w'
endif
return v:true
endif
endfor
return v:false
endfunction
let s:id = 1
let s:handlers = {}
" Note: vim execute callback for every line.
let s:content_length = 0
let s:input = ''
function! s:HandleMessage(job, lines, event) abort
if a:event ==# 'stdout'
while len(a:lines) > 0
let l:line = remove(a:lines, 0)
if l:line ==# ''
continue
elseif s:content_length == 0
let s:content_length = str2nr(substitute(l:line, '.*Content-Length:', '', ''))
continue
endif
let s:input .= strpart(l:line, 0, s:content_length)
if s:content_length < strlen(l:line)
call insert(a:lines, strpart(l:line, s:content_length), 0)
let s:content_length = 0
else
let s:content_length = s:content_length - strlen(l:line)
endif
if s:content_length > 0
continue
endif
try
let l:message = json_decode(s:input)
if type(l:message) !=# s:TYPE.dict
throw 'Messsage is not dict.'
endif
catch
call s:Debug('Error decoding message: ' . string(v:exception) .
\ ' Message: ' . s:input)
continue
finally
let s:input = ''
endtry
if has_key(l:message, 'method')
let l:id = get(l:message, 'id', v:null)
let l:method = get(l:message, 'method')
let l:params = get(l:message, 'params')
try
let l:params = type(l:params) == s:TYPE.list ? l:params : [l:params]
let l:result = call(l:method, l:params)
if l:id isnot v:null
call LanguageClient#Write(json_encode({
\ 'jsonrpc': '2.0',
\ 'id': l:id,
\ 'result': l:result,
\ }))
endif
catch
let l:exception = v:exception
if l:id isnot v:null
try
call LanguageClient#Write(json_encode({
\ 'jsonrpc': '2.0',
\ 'id': l:id,
\ 'error': {
\ 'code': -32603,
\ 'message': string(v:exception)
\ }
\ }))
catch
" TODO
endtry
endif
call s:Debug(string(l:exception))
endtry
elseif has_key(l:message, 'result') || has_key(l:message, 'error')
let l:id = get(l:message, 'id')
let l:Handle = get(s:handlers, l:id)
unlet s:handlers[l:id]
let l:type = type(l:Handle)
if l:type == s:TYPE.funcref || l:type == s:TYPE.string
call call(l:Handle, [l:message])
elseif l:type == s:TYPE.list
call add(l:Handle, l:message)
elseif l:type == s:TYPE.string && exists(l:Handle)
let l:outputs = eval(l:Handle)
call add(l:outputs, l:message)
else
call s:Echoerr('Unknown Handle type: ' . string(l:Handle))
endif
else
call s:Echoerr('Unknown message: ' . string(l:message))
endif
endwhile
elseif a:event ==# 'stderr'
call s:Echoerr('LanguageClient stderr: ' . string(a:lines))
elseif a:event ==# 'exit'
if type(a:lines) == type(0) && (a:lines == 0 || a:lines == 143)
return
endif
call s:Debug('LanguageClient exited with: ' . string(a:lines))
else
call s:Debug('LanguageClient unknown event: ' . a:event)
endif
endfunction
function! s:HandleStdoutVim(job, data) abort
return s:HandleMessage(a:job, [a:data], 'stdout')
endfunction
function! s:HandleStderrVim(job, data) abort
return s:HandleMessage(a:job, [a:data], 'stderr')
endfunction
function! s:HandleExitVim(job, data) abort
return s:HandleMessage(a:job, [a:data], 'exit')
endfunction
function! s:HandleOutputNothing(output) abort
endfunction
function! s:HandleOutput(output, ...) abort
let l:quiet = get(a:000, 0)
if has_key(a:output, 'result')
" let l:result = string(a:result)
" if l:result isnot v:null
" echomsg l:result
" endif
return get(a:output, 'result')
elseif has_key(a:output, 'error')
let l:error = get(a:output, 'error')
let l:message = get(l:error, 'message')
if !l:quiet
call s:Echoerr(l:message)
endif
return v:null
else
if !l:quiet
call s:Echoerr('Unknown output type: ' . json_encode(a:output))
endif
return v:null
endif
endfunction
let s:root = expand('<sfile>:p:h:h')
function! LanguageClient#binaryPath() abort
let l:path = s:GetVar('LanguageClient_binaryPath')
if l:path isnot v:null
return l:path
endif
let l:filename = 'languageclient'
if has('win32')
let l:filename .= '.exe'
endif
if exists('g:LanguageClient_devel')
if exists('$CARGO_TARGET_DIR')
let l:path = $CARGO_TARGET_DIR . '/debug/'
else
let l:path = s:root . '/target/debug/'
endif
else
let l:path = s:root . '/bin/'
endif
return l:path . l:filename
endfunction
function! s:Launch() abort
let l:binpath = LanguageClient#binaryPath()
if executable(l:binpath) != 1
call s:Echoerr('LanguageClient: binary (' . l:binpath . ') doesn''t exists! Please check installation guide.')
return 0
endif
if has('nvim')
let s:job = jobstart([l:binpath], {
\ 'on_stdout': function('s:HandleMessage'),
\ 'on_stderr': function('s:HandleMessage'),
\ 'on_exit': function('s:HandleMessage'),
\ })
if s:job == 0
call s:Echoerr('LanguageClient: Invalid arguments!')
return 0
elseif s:job == -1
call s:Echoerr('LanguageClient: Not executable!')
return 0
else
return 1
endif
elseif has('job')
let s:job = job_start([l:binpath], {
\ 'out_cb': function('s:HandleStdoutVim'),
\ 'err_cb': function('s:HandleStderrVim'),
\ 'exit_cb': function('s:HandleExitVim'),
\ })
if job_status(s:job) !=# 'run'
call s:Echoerr('LanguageClient: job failed to start or died!')
return 0
else
return 1
endif
else
echoerr 'Not supported: not nvim nor vim with +job.'
return 0
endif
endfunction
function! LanguageClient#Write(message) abort
let l:message = a:message . "\n"
if has('nvim')
" abort write if nvim is exiting
if get(v:, 'exiting', v:null) isnot v:null
return
endif
" jobsend respond 1 for success.
return !jobsend(s:job, l:message)
elseif has('channel')
return ch_sendraw(s:job, l:message)
else
echoerr 'Not supported: not nvim nor vim with +channel.'
endif
endfunction
function! s:SkipSendingMessage() abort
if expand('%') =~# '^jdt://'
return v:false
endif
let l:has_command = LanguageClient#HasCommand(&filetype)
return !l:has_command || &buftype !=# '' || &filetype ==# '' || expand('%') ==# ''
endfunction
function! LanguageClient#HasCommand(filetype) abort
let l:commands = s:GetVar('LanguageClient_serverCommands', {})
return has_key(l:commands, a:filetype)
endfunction
function! LanguageClient#Call(method, params, callback, ...) abort
if s:SkipSendingMessage()
echo '[LC] Server not configured for filetype ' . &filetype
return
endif
let l:id = s:id
let s:id = s:id + 1
if a:callback is v:null
let s:handlers[l:id] = function('s:HandleOutput')
else
let s:handlers[l:id] = a:callback
endif
let l:skipAddParams = get(a:000, 0, v:false)
let l:params = a:params
if type(a:params) == s:TYPE.dict && !skipAddParams
" TODO: put inside context.
let l:params = extend({
\ 'bufnr': bufnr(''),
\ 'languageId': &filetype,
\ }, l:params)
endif
return LanguageClient#Write(json_encode({
\ 'jsonrpc': '2.0',
\ 'id': l:id,
\ 'method': a:method,
\ 'params': l:params,
\ }))
endfunction
function! LanguageClient#Notify(method, params) abort
if s:SkipSendingMessage()
" call s:Debug('Skip sending message')
return
endif
let l:params = a:params
if type(params) == s:TYPE.dict
let l:params = extend({
\ 'bufnr': bufnr(''),
\ 'languageId': &filetype,
\ }, l:params)
endif
return LanguageClient#Write(json_encode({
\ 'jsonrpc': '2.0',
\ 'method': a:method,
\ 'params': l:params,
\ }))
endfunction
function! LanguageClient#textDocument_hover(...) abort
if s:ShouldUseFloatWindow() && s:MoveIntoHoverPreview('__LCNHover__')
return
endif
let l:Callback = get(a:000, 1, v:null)
let l:params = {
\ 'filename': LSP#filename(),
\ 'text': LSP#text(),
\ 'line': LSP#line(),
\ 'character': LSP#character(),
\ 'handle': s:IsFalse(l:Callback),
\ }
call extend(l:params, get(a:000, 0, {}))
return LanguageClient#Call('textDocument/hover', l:params, l:Callback)
endfunction
function! LanguageClient#closeFloatingHover() abort
call s:CloseFloatingHover()
endfunction
" Meta methods to go to various places.
function! LanguageClient#findLocations(...) abort
let l:Callback = get(a:000, 1, v:null)
let l:params = {
\ 'filename': LSP#filename(),
\ 'position': LSP#position(),
\ 'gotoCmd': v:null,
\ 'handle': s:IsFalse(l:Callback),
\ }
call extend(l:params, get(a:000, 0, {}))
return LanguageClient#Call('languageClient/findLocations', l:params, l:Callback)
endfunction
function! LanguageClient#textDocument_switchSourceHeader(...) abort
let l:Callback = get(a:000, 1, v:null)
let l:params = {
\ 'filename': LSP#filename(),
\ }
call extend(l:params, get(a:000, 0, {}))
return LanguageClient#Call('textDocument/switchSourceHeader', l:params, l:Callback)
endfunction
function! LanguageClient#textDocument_definition(...) abort
let l:Callback = get(a:000, 1, v:null)
let l:params = {
\ 'filename': LSP#filename(),
\ 'text': LSP#text(),
\ 'line': LSP#line(),
\ 'character': LSP#character(),
\ 'handle': s:IsFalse(l:Callback),
\ 'gotoCmd': v:null,
\ }
call extend(l:params, get(a:000, 0, {}))
return LanguageClient#Call('textDocument/definition', l:params, l:Callback)
endfunction
function! LanguageClient#textDocument_typeDefinition(...) abort
let l:params = {
\ 'method': 'textDocument/typeDefinition',
\ }
call extend(l:params, get(a:000, 0, {}))
return call('LanguageClient#findLocations', [l:params] + a:000[1:])
endfunction
function! LanguageClient#textDocument_implementation(...) abort
let l:params = {
\ 'method': 'textDocument/implementation',
\ }
call extend(l:params, get(a:000, 0, {}))
return call('LanguageClient#findLocations', [l:params] + a:000[1:])
endfunction
function! LanguageClient#textDocument_references(...) abort
let l:Callback = get(a:000, 1, v:null)
let l:params = {
\ 'filename': LSP#filename(),
\ 'text': LSP#text(),
\ 'line': LSP#line(),
\ 'character': LSP#character(),
\ 'includeDeclaration': v:true,
\ 'handle': s:IsFalse(l:Callback),
\ 'gotoCmd': v:null,
\ }
call extend(l:params, get(a:000, 0, {}))
return LanguageClient#Call('textDocument/references', l:params, l:Callback)
endfunction
function! LanguageClient#textDocument_rename(...) abort
let l:params = {
\ 'filename': LSP#filename(),
\ 'text': LSP#text(),
\ 'line': LSP#line(),
\ 'character': LSP#character(),
\ 'cword': expand('<cword>'),
\ 'handle': v:true,
\ }
call extend(l:params, a:0 >= 1 ? a:1 : {})
let l:Callback = a:0 >= 2 ? a:2 : v:null
return LanguageClient#Call('textDocument/rename', l:params, v:null)
endfunction