5 # The functions to send request messages to the language server are in this
8 # Refer to https://microsoft.github.io/language-server-protocol/specification
9 # for the Language Server Protocol (LSP) specificaiton.
11 import './options.vim' as opt
12 import './handlers.vim'
14 import './capabilities.vim'
17 import './selection.vim'
19 import './textedit.vim'
20 import './completion.vim'
22 import './signature.vim'
23 import './codeaction.vim'
24 import './codelens.vim'
25 import './callhierarchy.vim' as callhier
26 import './typehierarchy.vim' as typehier
27 import './inlayhints.vim'
29 # LSP server standard output handler
30 def Output_cb(lspserver: dict<any>, chan: channel, msg: any): void
32 lspserver.traceLog($'{strftime("%m/%d/%y %T")}: Received {msg->string()}')
35 lspserver.processMessages()
38 # LSP server error output handler
39 def Error_cb(lspserver: dict<any>, chan: channel, emsg: string): void
40 lspserver.errorLog(emsg)
43 # LSP server exit callback
44 def Exit_cb(lspserver: dict<any>, job: job, status: number): void
45 util.WarnMsg($'{strftime("%m/%d/%y %T")}: LSP server ({lspserver.name}) exited with status {status}')
46 lspserver.running = false
47 lspserver.ready = false
48 lspserver.requests = {}
53 def StartServer(lspserver: dict<any>, bnr: number): number
55 util.WarnMsg($'LSP server "{lspserver.name}" is already running')
59 var cmd = [lspserver.path]
60 cmd->extend(lspserver.args)
62 var opts = {in_mode: 'lsp',
66 out_cb: function(Output_cb, [lspserver]),
67 err_cb: function(Error_cb, [lspserver]),
68 exit_cb: function(Exit_cb, [lspserver])}
73 lspserver.requests = {}
74 lspserver.omniCompletePending = false
75 lspserver.completionLazyDoc = false
76 lspserver.completionTriggerChars = []
77 lspserver.signaturePopup = -1
79 var job = cmd->job_start(opts)
80 if job->job_status() == 'fail'
81 util.ErrMsg($'Failed to start LSP server {lspserver.path}')
85 # wait a little for the LSP server to start
89 lspserver.running = true
91 lspserver.initServer(bnr)
96 # process the "initialize" method reply from the LSP server
97 # Result: InitializeResult
98 def ServerInitReply(lspserver: dict<any>, initResult: dict<any>): void
99 if initResult->empty()
103 var caps: dict<any> = initResult.capabilities
104 lspserver.caps = caps
106 for [key, val] in initResult->items()
107 if key == 'capabilities'
111 lspserver.caps[$'~additionalInitResult_{key}'] = val
114 capabilities.ProcessServerCaps(lspserver, caps)
116 if caps->has_key('completionProvider')
117 if opt.lspOptions.autoComplete
118 lspserver.completionTriggerChars =
119 caps.completionProvider->get('triggerCharacters', [])
121 lspserver.completionLazyDoc =
122 caps.completionProvider->get('resolveProvider', false)
125 # send a "initialized" notification to server
126 lspserver.sendInitializedNotif()
127 # send any workspace configuration (optional)
128 if !lspserver.workspaceConfig->empty()
129 lspserver.sendWorkspaceConfig()
131 lspserver.ready = true
132 if exists($'#User#LspServerReady{lspserver.name}')
133 exe $'doautocmd <nomodeline> User LspServerReady{lspserver.name}'
135 # Used internally, and shouldn't be used by users
136 if exists($'#User#LspServerReady_{lspserver.id}')
137 exe $'doautocmd <nomodeline> User LspServerReady_{lspserver.id}'
140 # set the server debug trace level
141 if lspserver.traceLevel != 'off'
142 lspserver.setTrace(lspserver.traceLevel)
145 # if the outline window is opened, then request the symbols for the current
147 if bufwinid('LSP-Outline') != -1
148 lspserver.getDocSymbols(@%, true)
151 # Update the inlay hints (if enabled)
152 if opt.lspOptions.showInlayHints && (lspserver.isInlayHintProvider
153 || lspserver.isClangdInlayHintsProvider)
154 inlayhints.LspInlayHintsUpdateNow(bufnr())
158 # Request: "initialize"
159 # Param: InitializeParams
160 def InitServer(lspserver: dict<any>, bnr: number)
161 # interface 'InitializeParams'
162 var initparams: dict<any> = {}
163 initparams.processId = getpid()
164 initparams.clientInfo = {
166 version: v:versionlong->string(),
169 # Compute the rootpath (based on the directory of the buffer)
171 var rootSearchFiles = lspserver.rootSearchFiles
172 var bufDir = bnr->bufname()->fnamemodify(':p:h')
173 if !rootSearchFiles->empty()
174 rootPath = util.FindNearestRootDir(bufDir, rootSearchFiles)
179 # bufDir is within cwd
180 var bufDirPrefix = bufDir[0 : cwd->strcharlen() - 1]
182 ? bufDirPrefix ==? cwd
183 : bufDirPrefix == cwd
190 lspserver.workspaceFolders = [rootPath]
192 var rootUri = util.LspFileToUri(rootPath)
193 initparams.rootPath = rootPath
194 initparams.rootUri = rootUri
195 initparams.workspaceFolders = [{
196 name: rootPath->fnamemodify(':t'),
200 initparams.trace = 'off'
201 initparams.capabilities = capabilities.GetClientCaps()
202 if !lspserver.initializationOptions->empty()
203 initparams.initializationOptions = lspserver.initializationOptions
205 initparams.initializationOptions = {}
208 lspserver.rpcInitializeRequest = initparams
210 lspserver.rpc_a('initialize', initparams, ServerInitReply)
213 # Send a "initialized" notification to the language server
214 def SendInitializedNotif(lspserver: dict<any>)
215 # Notification: 'initialized'
216 # Params: InitializedParams
217 lspserver.sendNotification('initialized')
222 def ShutdownServer(lspserver: dict<any>): void
223 lspserver.rpc('shutdown', {})
226 # Send a 'exit' notification to the language server
227 def ExitServer(lspserver: dict<any>): void
228 # Notification: 'exit'
230 lspserver.sendNotification('exit')
234 def StopServer(lspserver: dict<any>): number
235 if !lspserver.running
236 util.WarnMsg($'LSP server {lspserver.name} is not running')
240 # Send the shutdown request to the server
241 lspserver.shutdownServer()
243 # Notify the server to exit
244 lspserver.exitServer()
246 # Wait for the server to process the exit notification and exit for a
247 # maximum of 2 seconds.
248 var maxCount: number = 1000
249 while lspserver.job->job_status() == 'run' && maxCount > 0
254 if lspserver.job->job_status() == 'run'
255 lspserver.job->job_stop()
257 lspserver.running = false
258 lspserver.ready = false
259 lspserver.requests = {}
263 # Set the language server trace level using the '$/setTrace' notification.
264 # Supported values for "traceVal" are "off", "messages" and "verbose".
265 def SetTrace(lspserver: dict<any>, traceVal: string)
266 # Notification: '$/setTrace'
267 # Params: SetTraceParams
268 var params = {value: traceVal}
269 lspserver.sendNotification('$/setTrace', params)
272 # Log a debug message to the LSP server debug file
273 def TraceLog(lspserver: dict<any>, msg: string)
275 util.TraceLog(lspserver.logfile, false, msg)
279 # Log an error message to the LSP server error file
280 def ErrorLog(lspserver: dict<any>, errmsg: string)
282 util.TraceLog(lspserver.errfile, true, errmsg)
286 # Return the next id for a LSP server request message
287 def NextReqID(lspserver: dict<any>): number
288 var id = lspserver.nextID
289 lspserver.nextID = id + 1
293 # create a LSP server request message
294 def CreateRequest(lspserver: dict<any>, method: string): dict<any>
297 id: lspserver.nextReqID(),
302 # Save the request, so that the corresponding response can be processed
303 lspserver.requests->extend({[req.id->string()]: req})
308 # create a LSP server response message
309 def CreateResponse(lspserver: dict<any>, req_id: number): dict<any>
317 # create a LSP server notification message
318 def CreateNotification(lspserver: dict<any>, notif: string): dict<any>
328 # send a response message to the server
329 def SendResponse(lspserver: dict<any>, request: dict<any>, result: any, error: dict<any>)
330 if (request.id->type() == v:t_string
331 && (request.id->trim() =~ '[^[:digit:]]\+'
332 || request.id->trim()->empty()))
333 || (request.id->type() != v:t_string && request.id->type() != v:t_number)
334 util.ErrMsg('request.id of response to LSP server is not a correct number')
337 var resp: dict<any> = lspserver.createResponse(
338 request.id->type() == v:t_string ? request.id->str2nr() : request.id)
340 resp->extend({result: result})
342 resp->extend({error: error})
344 lspserver.sendMessage(resp)
347 # Send a request message to LSP server
348 def SendMessage(lspserver: dict<any>, content: dict<any>): void
349 var job = lspserver.job
350 if job->job_status() != 'run'
351 # LSP server has exited
354 job->ch_sendexpr(content)
355 if content->has_key('id')
357 lspserver.traceLog($'{strftime("%m/%d/%y %T")}: Sent {content->string()}')
362 # Send a notification message to the language server
363 def SendNotification(lspserver: dict<any>, method: string, params: any = {})
364 var notif: dict<any> = CreateNotification(lspserver, method)
365 notif.params->extend(params)
366 lspserver.sendMessage(notif)
369 # Translate an LSP error code into a readable string
370 def LspGetErrorMessage(errcode: number): string
372 -32001: 'UnknownErrorCode',
373 -32002: 'ServerNotInitialized',
374 -32600: 'InvalidRequest',
375 -32601: 'MethodNotFound',
376 -32602: 'InvalidParams',
377 -32603: 'InternalError',
378 -32700: 'ParseError',
379 -32800: 'RequestCancelled',
380 -32801: 'ContentModified',
381 -32802: 'ServerCancelled',
382 -32803: 'RequestFailed'
385 return errmap->get(errcode, errcode->string())
388 # Process a LSP server response error and display an error message.
389 def ProcessLspServerError(method: string, responseError: dict<any>)
391 var emsg: string = responseError.message
392 emsg ..= $', error = {LspGetErrorMessage(responseError.code)}'
393 if responseError->has_key('data')
394 emsg ..= $', data = {responseError.data->string()}'
396 util.ErrMsg($'request {method} failed ({emsg})')
399 # Send a sync RPC request message to the LSP server and return the received
400 # reply. In case of an error, an empty Dict is returned.
401 def Rpc(lspserver: dict<any>, method: string, params: any, handleError: bool = true): dict<any>
407 var job = lspserver.job
408 if job->job_status() != 'run'
409 # LSP server has exited
414 lspserver.traceLog($'{strftime("%m/%d/%y %T")}: Sent {req->string()}')
417 # Do the synchronous RPC call
418 var reply = job->ch_evalexpr(req)
421 lspserver.traceLog($'{strftime("%m/%d/%y %T")}: Received {reply->string()}')
424 if reply->has_key('result')
429 if reply->has_key('error') && handleError
431 ProcessLspServerError(method, reply.error)
437 # LSP server asynchronous RPC callback
438 def AsyncRpcCb(lspserver: dict<any>, method: string, RpcCb: func, chan: channel, reply: dict<any>)
440 lspserver.traceLog($'{strftime("%m/%d/%y %T")}: Received {reply->string()}')
447 if reply->has_key('error')
449 ProcessLspServerError(method, reply.error)
453 if !reply->has_key('result')
454 util.ErrMsg($'request {method} failed (no result)')
458 RpcCb(lspserver, reply.result)
461 # Send a async RPC request message to the LSP server with a callback function.
462 # Returns the LSP message id. This id can be used to cancel the RPC request
463 # (if needed). Returns -1 on error.
464 def AsyncRpc(lspserver: dict<any>, method: string, params: any, Cbfunc: func): number
470 var job = lspserver.job
471 if job->job_status() != 'run'
472 # LSP server has exited
477 lspserver.traceLog($'{strftime("%m/%d/%y %T")}: Sent {req->string()}')
480 # Do the asynchronous RPC call
481 var Fn = function('AsyncRpcCb', [lspserver, method, Cbfunc])
484 if get(g:, 'LSPTest')
485 # When running LSP tests, make this a synchronous RPC call
486 reply = Rpc(lspserver, method, params)
487 Fn(test_null_channel(), reply)
489 # Otherwise, make an asynchronous RPC call
490 reply = job->ch_sendexpr(req, {callback: Fn})
499 # Wait for a response message from the LSP server for the request "req"
500 # Waits for a maximum of 5 seconds
501 def WaitForResponse(lspserver: dict<any>, req: dict<any>)
502 var maxCount: number = 2500
503 var key: string = req.id->string()
505 while lspserver.requests->has_key(key) && maxCount > 0
511 # Retrieve the Workspace configuration asked by the server.
512 # Request: workspace/configuration
513 def WorkspaceConfigGet(lspserver: dict<any>, configItem: dict<any>): dict<any>
514 if lspserver.workspaceConfig->empty()
517 if !configItem->has_key('section') || configItem.section->empty()
518 return lspserver.workspaceConfig
520 var config: dict<any> = lspserver.workspaceConfig
521 for part in configItem.section->split('\.')
522 if !config->has_key(part)
525 config = config[part]
530 # Send a "workspace/didChangeConfiguration" notification to the language
532 def SendWorkspaceConfig(lspserver: dict<any>)
533 # Params: DidChangeConfigurationParams
534 var params = {settings: lspserver.workspaceConfig}
535 lspserver.sendNotification('workspace/didChangeConfiguration', params)
538 # Send a file/document opened notification to the language server.
539 def TextdocDidOpen(lspserver: dict<any>, bnr: number, ftype: string): void
540 # Notification: 'textDocument/didOpen'
541 # Params: DidOpenTextDocumentParams
544 uri: util.LspBufnrToUri(bnr),
546 # Use Vim 'changedtick' as the LSP document version number
547 version: bnr->getbufvar('changedtick'),
548 text: bnr->getbufline(1, '$')->join("\n") .. "\n"
551 lspserver.sendNotification('textDocument/didOpen', params)
554 # Send a file/document closed notification to the language server.
555 def TextdocDidClose(lspserver: dict<any>, bnr: number): void
556 # Notification: 'textDocument/didClose'
557 # Params: DidCloseTextDocumentParams
560 uri: util.LspBufnrToUri(bnr)
563 lspserver.sendNotification('textDocument/didClose', params)
566 # Send a file/document change notification to the language server.
567 # Params: DidChangeTextDocumentParams
568 def TextdocDidChange(lspserver: dict<any>, bnr: number, start: number,
569 end: number, added: number,
570 changes: list<dict<number>>): void
571 # Notification: 'textDocument/didChange'
572 # Params: DidChangeTextDocumentParams
574 # var changeset: list<dict<any>>
576 ##### FIXME: Sending specific buffer changes to the LSP server doesn't
577 ##### work properly as the computed line range numbers is not correct.
578 ##### For now, send the entire buffer content to LSP server.
580 # for change in changes
582 # var start_lnum: number
583 # var end_lnum: number
584 # var start_col: number
585 # var end_col: number
586 # if change.added == 0
588 # start_lnum = change.lnum - 1
589 # end_lnum = change.end - 1
590 # lines = getbufline(bnr, change.lnum, change.end - 1)->join("\n") .. "\n"
593 # elseif change.added > 0
595 # start_lnum = change.lnum - 1
596 # end_lnum = change.lnum - 1
599 # lines = getbufline(bnr, change.lnum, change.lnum + change.added - 1)->join("\n") .. "\n"
602 # start_lnum = change.lnum - 1
603 # end_lnum = change.lnum + (-change.added) - 1
608 # var range: dict<dict<number>> = {'start': {'line': start_lnum, 'character': start_col}, 'end': {'line': end_lnum, 'character': end_col}}
609 # changeset->add({'range': range, 'text': lines})
614 uri: util.LspBufnrToUri(bnr),
615 # Use Vim 'changedtick' as the LSP document version number
616 version: bnr->getbufvar('changedtick')
619 {text: bnr->getbufline(1, '$')->join("\n") .. "\n"}
622 lspserver.sendNotification('textDocument/didChange', params)
625 # Return the current cursor position as a LSP position.
626 # find_ident will search for a identifier in front of the cursor, just like
627 # CTRL-] and c_CTRL-R_CTRL-W does.
629 # LSP line and column numbers start from zero, whereas Vim line and column
630 # numbers start from one. The LSP column number is the character index in the
631 # line and not the byte index in the line.
632 def GetPosition(lspserver: dict<any>, find_ident: bool): dict<number>
633 var lnum: number = line('.') - 1
634 var col: number = charcol('.') - 1
635 var line = getline('.')
638 # 1. skip to start of identifier
639 while line[col] != '' && line[col] !~ '\k'
643 # 2. back up to start of identifier
644 while col > 0 && line[col - 1] =~ '\k'
649 # Compute character index counting composing characters as separate
651 var pos = {line: lnum, character: util.GetCharIdxWithCompChar(line, col)}
652 lspserver.encodePosition(bufnr(), pos)
657 # Return the current file name and current cursor position as a LSP
658 # TextDocumentPositionParams structure
659 def GetTextDocPosition(lspserver: dict<any>, find_ident: bool): dict<dict<any>>
660 # interface TextDocumentIdentifier
662 return {textDocument: {uri: util.LspFileToUri(@%)},
663 position: lspserver.getPosition(find_ident)}
666 # Get a list of completion items.
667 # Request: "textDocument/completion"
668 # Param: CompletionParams
669 def GetCompletion(lspserver: dict<any>, triggerKind_arg: number, triggerChar: string): void
670 # Check whether LSP server supports completion
671 if !lspserver.isCompletionProvider
672 util.ErrMsg('LSP server does not support completion')
681 # interface CompletionParams
682 # interface TextDocumentPositionParams
683 var params = lspserver.getTextDocPosition(false)
684 # interface CompletionContext
685 params.context = {triggerKind: triggerKind_arg, triggerCharacter: triggerChar}
687 lspserver.rpc_a('textDocument/completion', params,
688 completion.CompletionReply)
691 # Get lazy properties for a completion item.
692 # Request: "completionItem/resolve"
693 # Param: CompletionItem
694 def ResolveCompletion(lspserver: dict<any>, item: dict<any>): void
695 # Check whether LSP server supports completion item resolve
696 if !lspserver.isCompletionResolveProvider
697 util.ErrMsg('LSP server does not support completion item resolve')
701 # interface CompletionItem
702 lspserver.rpc_a('completionItem/resolve', item,
703 completion.CompletionResolveReply)
706 # Jump to or peek a symbol location.
708 # Send 'msg' to a LSP server and process the reply. 'msg' is one of the
710 # textDocument/definition
711 # textDocument/declaration
712 # textDocument/typeDefinition
713 # textDocument/implementation
715 # Process the LSP server reply and jump to the symbol location. Before
716 # jumping to the symbol location, save the current cursor position in the tag
719 # If 'peekSymbol' is true, then display the symbol location in the preview
720 # window but don't jump to the symbol location.
722 # Result: Location | Location[] | LocationLink[] | null
723 def GotoSymbolLoc(lspserver: dict<any>, msg: string, peekSymbol: bool,
724 cmdmods: string, count: number)
725 var reply = lspserver.rpc(msg, lspserver.getTextDocPosition(true), false)
726 if reply->empty() || reply.result->empty()
728 if msg == 'textDocument/declaration'
729 emsg = 'symbol declaration is not found'
730 elseif msg == 'textDocument/typeDefinition'
731 emsg = 'symbol type definition is not found'
732 elseif msg == 'textDocument/implementation'
733 emsg = 'symbol implementation is not found'
735 emsg = 'symbol definition is not found'
742 var result = reply.result
743 var location: dict<any>
744 if result->type() == v:t_list
746 # When there are multiple symbol locations, and a specific one isn't
747 # requested with 'count', display the locations in a location list.
749 var title: string = ''
750 if msg == 'textDocument/declaration'
751 title = 'Declarations'
752 elseif msg == 'textDocument/typeDefinition'
753 title = 'Type Definitions'
754 elseif msg == 'textDocument/implementation'
755 title = 'Implementations'
757 title = 'Definitions'
760 if lspserver.needOffsetEncoding
761 # Decode the position encoding in all the symbol locations
762 result->map((_, loc) => {
763 lspserver.decodeLocation(loc)
768 symbol.ShowLocations(lspserver, result, peekSymbol, title)
773 # Select the location requested in 'count'
775 if idx >= result->len()
776 idx = result->len() - 1
778 location = result[idx]
782 lspserver.decodeLocation(location)
784 symbol.GotoSymbol(lspserver, location, peekSymbol, cmdmods)
787 # Request: "textDocument/definition"
788 # Param: DefinitionParams
789 def GotoDefinition(lspserver: dict<any>, peek: bool, cmdmods: string, count: number)
790 # Check whether LSP server supports jumping to a definition
791 if !lspserver.isDefinitionProvider
792 util.ErrMsg('Jumping to a symbol definition is not supported')
796 # interface DefinitionParams
797 # interface TextDocumentPositionParams
798 GotoSymbolLoc(lspserver, 'textDocument/definition', peek, cmdmods, count)
801 # Request: "textDocument/declaration"
802 # Param: DeclarationParams
803 def GotoDeclaration(lspserver: dict<any>, peek: bool, cmdmods: string, count: number)
804 # Check whether LSP server supports jumping to a declaration
805 if !lspserver.isDeclarationProvider
806 util.ErrMsg('Jumping to a symbol declaration is not supported')
810 # interface DeclarationParams
811 # interface TextDocumentPositionParams
812 GotoSymbolLoc(lspserver, 'textDocument/declaration', peek, cmdmods, count)
815 # Request: "textDocument/typeDefinition"
816 # Param: TypeDefinitionParams
817 def GotoTypeDef(lspserver: dict<any>, peek: bool, cmdmods: string, count: number)
818 # Check whether LSP server supports jumping to a type definition
819 if !lspserver.isTypeDefinitionProvider
820 util.ErrMsg('Jumping to a symbol type definition is not supported')
824 # interface TypeDefinitionParams
825 # interface TextDocumentPositionParams
826 GotoSymbolLoc(lspserver, 'textDocument/typeDefinition', peek, cmdmods, count)
829 # Request: "textDocument/implementation"
830 # Param: ImplementationParams
831 def GotoImplementation(lspserver: dict<any>, peek: bool, cmdmods: string, count: number)
832 # Check whether LSP server supports jumping to a implementation
833 if !lspserver.isImplementationProvider
834 util.ErrMsg('Jumping to a symbol implementation is not supported')
838 # interface ImplementationParams
839 # interface TextDocumentPositionParams
840 GotoSymbolLoc(lspserver, 'textDocument/implementation', peek, cmdmods, count)
843 # Request: "textDocument/switchSourceHeader"
844 # Param: TextDocumentIdentifier
845 # Clangd specific extension
846 def SwitchSourceHeader(lspserver: dict<any>)
848 uri: util.LspFileToUri(@%)
850 var reply = lspserver.rpc('textDocument/switchSourceHeader', param)
851 if reply->empty() || reply.result->empty()
852 util.WarnMsg('Source/Header file is not found')
856 # process the 'textDocument/switchSourceHeader' reply from the LSP server
858 var fname = util.LspUriToFile(reply.result)
859 # TODO: Add support for cmd modifiers
860 if (&modified && !&hidden) || &buftype != ''
861 # if the current buffer has unsaved changes and 'hidden' is not set,
862 # or if the current buffer is a special buffer, then ask to save changes
863 exe $'confirm edit {fname}'
869 # get symbol signature help.
870 # Request: "textDocument/signatureHelp"
871 # Param: SignatureHelpParams
872 def ShowSignature(lspserver: dict<any>): void
873 # Check whether LSP server supports signature help
874 if !lspserver.isSignatureHelpProvider
875 util.ErrMsg('LSP server does not support signature help')
879 # interface SignatureHelpParams
880 # interface TextDocumentPositionParams
881 var params = lspserver.getTextDocPosition(false)
882 lspserver.rpc_a('textDocument/signatureHelp', params,
883 signature.SignatureHelp)
886 # Send a file/document saved notification to the language server
887 def DidSaveFile(lspserver: dict<any>, bnr: number): void
888 # Check whether the LSP server supports the didSave notification
889 if !lspserver.supportsDidSave
890 # LSP server doesn't support text document synchronization
894 # Notification: 'textDocument/didSave'
895 # Params: DidSaveTextDocumentParams
896 var params = {textDocument: {uri: util.LspBufnrToUri(bnr)}}
897 # FIXME: Need to set "params.text" when
898 # 'lspserver.caps.textDocumentSync.save.includeText' is set to true.
899 lspserver.sendNotification('textDocument/didSave', params)
902 # get the hover information
903 # Request: "textDocument/hover"
905 def ShowHoverInfo(lspserver: dict<any>, cmdmods: string): void
906 # Check whether LSP server supports getting hover information.
907 # caps->hoverProvider can be a "boolean" or "HoverOptions"
908 if !lspserver.isHoverProvider
912 # interface HoverParams
913 # interface TextDocumentPositionParams
914 var params = lspserver.getTextDocPosition(false)
915 lspserver.rpc_a('textDocument/hover', params, (_, reply) => {
916 hover.HoverReply(lspserver, reply, cmdmods)
920 # Request: "textDocument/references"
921 # Param: ReferenceParams
922 def ShowReferences(lspserver: dict<any>, peek: bool): void
923 # Check whether LSP server supports getting reference information
924 if !lspserver.isReferencesProvider
925 util.ErrMsg('LSP server does not support showing references')
929 # interface ReferenceParams
930 # interface TextDocumentPositionParams
932 param = lspserver.getTextDocPosition(true)
933 param.context = {includeDeclaration: true}
934 var reply = lspserver.rpc('textDocument/references', param)
936 # Result: Location[] | null
937 if reply->empty() || reply.result->empty()
938 util.WarnMsg('No references found')
942 if lspserver.needOffsetEncoding
943 # Decode the position encoding in all the reference locations
944 reply.result->map((_, loc) => {
945 lspserver.decodeLocation(loc)
950 symbol.ShowLocations(lspserver, reply.result, peek, 'Symbol References')
953 # process the 'textDocument/documentHighlight' reply from the LSP server
954 # Result: DocumentHighlight[] | null
955 def DocHighlightReply(lspserver: dict<any>, docHighlightReply: any,
956 bnr: number, cmdmods: string): void
957 if docHighlightReply->empty()
958 if cmdmods !~ 'silent'
959 util.WarnMsg($'No highlight for the current position')
964 for docHL in docHighlightReply
965 lspserver.decodeRange(bnr, docHL.range)
966 var kind: number = docHL->get('kind', 1)
970 propName = 'LspReadRef'
973 propName = 'LspWriteRef'
976 propName = 'LspTextRef'
979 var docHL_range = docHL.range
980 var docHL_start = docHL_range.start
981 var docHL_end = docHL_range.end
982 prop_add(docHL_start.line + 1,
983 util.GetLineByteFromPos(bnr, docHL_start) + 1,
984 {end_lnum: docHL_end.line + 1,
985 end_col: util.GetLineByteFromPos(bnr, docHL_end) + 1,
988 catch /E966\|E964/ # Invalid lnum | Invalid col
989 # Highlight replies arrive asynchronously and the document might have
990 # been modified in the mean time. As the reply is stale, ignore invalid
991 # line number and column number errors.
996 # Request: "textDocument/documentHighlight"
997 # Param: DocumentHighlightParams
998 def DocHighlight(lspserver: dict<any>, cmdmods: string): void
999 # Check whether LSP server supports getting highlight information
1000 if !lspserver.isDocumentHighlightProvider
1001 util.ErrMsg('LSP server does not support document highlight')
1005 # interface DocumentHighlightParams
1006 # interface TextDocumentPositionParams
1007 var params = lspserver.getTextDocPosition(false)
1008 lspserver.rpc_a('textDocument/documentHighlight', params, (_, reply) => {
1009 DocHighlightReply(lspserver, reply, bufnr(), cmdmods)
1013 # Request: "textDocument/documentSymbol"
1014 # Param: DocumentSymbolParams
1015 def GetDocSymbols(lspserver: dict<any>, fname: string, showOutline: bool): void
1016 # Check whether LSP server supports getting document symbol information
1017 if !lspserver.isDocumentSymbolProvider
1018 util.ErrMsg('LSP server does not support getting list of symbols')
1022 # interface DocumentSymbolParams
1023 # interface TextDocumentIdentifier
1024 var params = {textDocument: {uri: util.LspFileToUri(fname)}}
1025 lspserver.rpc_a('textDocument/documentSymbol', params, (_, reply) => {
1027 symbol.DocSymbolOutline(lspserver, reply, fname)
1029 symbol.DocSymbolPopup(lspserver, reply, fname)
1034 # Request: "textDocument/formatting"
1035 # Param: DocumentFormattingParams
1037 # Request: "textDocument/rangeFormatting"
1038 # Param: DocumentRangeFormattingParams
1039 def TextDocFormat(lspserver: dict<any>, fname: string, rangeFormat: bool,
1040 start_lnum: number, end_lnum: number)
1041 # Check whether LSP server supports formatting documents
1042 if !lspserver.isDocumentFormattingProvider
1043 util.ErrMsg('LSP server does not support formatting documents')
1049 cmd = 'textDocument/rangeFormatting'
1051 cmd = 'textDocument/formatting'
1054 # interface DocumentFormattingParams
1055 # interface TextDocumentIdentifier
1056 # interface FormattingOptions
1057 var fmtopts: dict<any> = {
1058 tabSize: shiftwidth(),
1059 insertSpaces: &expandtab ? true : false,
1063 uri: util.LspFileToUri(fname)
1069 var r: dict<dict<number>> = {
1070 start: {line: start_lnum - 1, character: 0},
1071 end: {line: end_lnum - 1, character: charcol([end_lnum, '$']) - 1}}
1075 var reply = lspserver.rpc(cmd, param)
1077 # result: TextEdit[] | null
1079 if reply->empty() || reply.result->empty()
1084 var bnr: number = fname->bufnr()
1086 # file is already removed
1090 if lspserver.needOffsetEncoding
1091 # Decode the position encoding in all the reference locations
1092 reply.result->map((_, textEdit) => {
1093 lspserver.decodeRange(bnr, textEdit.range)
1098 # interface TextEdit
1099 # Apply each of the text edit operations
1100 var save_cursor: list<number> = getcurpos()
1101 textedit.ApplyTextEdits(bnr, reply.result)
1102 save_cursor->setpos('.')
1105 # Request: "textDocument/prepareCallHierarchy"
1106 def PrepareCallHierarchy(lspserver: dict<any>): dict<any>
1107 # interface CallHierarchyPrepareParams
1108 # interface TextDocumentPositionParams
1109 var param: dict<any>
1110 param = lspserver.getTextDocPosition(false)
1111 var reply = lspserver.rpc('textDocument/prepareCallHierarchy', param)
1112 if reply->empty() || reply.result->empty()
1116 # Result: CallHierarchyItem[] | null
1117 var choice: number = 1
1118 if reply.result->len() > 1
1119 var items: list<string> = ['Select a Call Hierarchy Item:']
1120 for i in reply.result->len()->range()
1121 items->add(printf("%d. %s", i + 1, reply.result[i].name))
1123 choice = items->inputlist()
1124 if choice < 1 || choice > items->len()
1129 return reply.result[choice - 1]
1132 # Request: "callHierarchy/incomingCalls"
1133 def IncomingCalls(lspserver: dict<any>, fname: string)
1134 # Check whether LSP server supports call hierarchy
1135 if !lspserver.isCallHierarchyProvider
1136 util.ErrMsg('LSP server does not support call hierarchy')
1140 callhier.IncomingCalls(lspserver)
1143 def GetIncomingCalls(lspserver: dict<any>, item_arg: dict<any>): any
1144 # Request: "callHierarchy/incomingCalls"
1145 # Param: CallHierarchyIncomingCallsParams
1149 var reply = lspserver.rpc('callHierarchy/incomingCalls', param)
1154 if lspserver.needOffsetEncoding
1155 # Decode the position encoding in all the incoming call locations
1156 var bnr = util.LspUriToBufnr(item_arg.uri)
1157 reply.result->map((_, hierItem) => {
1158 lspserver.decodeRange(bnr, hierItem.from.range)
1166 # Request: "callHierarchy/outgoingCalls"
1167 def OutgoingCalls(lspserver: dict<any>, fname: string)
1168 # Check whether LSP server supports call hierarchy
1169 if !lspserver.isCallHierarchyProvider
1170 util.ErrMsg('LSP server does not support call hierarchy')
1174 callhier.OutgoingCalls(lspserver)
1177 def GetOutgoingCalls(lspserver: dict<any>, item_arg: dict<any>): any
1178 # Request: "callHierarchy/outgoingCalls"
1179 # Param: CallHierarchyOutgoingCallsParams
1183 var reply = lspserver.rpc('callHierarchy/outgoingCalls', param)
1188 if lspserver.needOffsetEncoding
1189 # Decode the position encoding in all the outgoing call locations
1190 var bnr = util.LspUriToBufnr(item_arg.uri)
1191 reply.result->map((_, hierItem) => {
1192 lspserver.decodeRange(bnr, hierItem.to.range)
1200 # Request: "textDocument/inlayHint"
1202 def InlayHintsShow(lspserver: dict<any>, bnr: number)
1203 # Check whether LSP server supports type hierarchy
1204 if !lspserver.isInlayHintProvider && !lspserver.isClangdInlayHintsProvider
1205 util.ErrMsg('LSP server does not support inlay hint')
1209 var binfo = bnr->getbufinfo()
1213 var lastlnum = binfo[0].linecount
1214 var lastline = bnr->getbufline('$')
1216 if !lastline->empty() && !lastline[0]->empty()
1217 lastcol = lastline[0]->strchars()
1220 textDocument: {uri: util.LspBufnrToUri(bnr)},
1223 start: {line: 0, character: 0},
1224 end: {line: lastlnum - 1, character: lastcol - 1}
1228 lspserver.encodeRange(bnr, param.range)
1231 if lspserver.isClangdInlayHintsProvider
1232 # clangd-style inlay hints
1233 msg = 'clangd/inlayHints'
1235 msg = 'textDocument/inlayHint'
1237 var reply = lspserver.rpc_a(msg, param, (_, reply) => {
1238 inlayhints.InlayHintsReply(lspserver, bnr, reply)
1242 def DecodeTypeHierarchy(lspserver: dict<any>, isSuper: bool, typeHier: dict<any>)
1243 if !lspserver.needOffsetEncoding
1246 var bnr = util.LspUriToBufnr(typeHier.uri)
1247 lspserver.decodeRange(bnr, typeHier.range)
1248 lspserver.decodeRange(bnr, typeHier.selectionRange)
1249 var subType: list<dict<any>>
1251 subType = typeHier->get('parents', [])
1253 subType = typeHier->get('children', [])
1255 if !subType->empty()
1256 # Decode the position encoding in all the type hierarchy items
1257 subType->map((_, typeHierItem) => {
1258 DecodeTypeHierarchy(lspserver, isSuper, typeHierItem)
1264 # Request: "textDocument/typehierarchy"
1265 # Support the clangd version of type hierarchy retrieval method.
1266 # The method described in the LSP 3.17.0 standard is not supported as clangd
1267 # doesn't support that method.
1268 def TypeHierarchy(lspserver: dict<any>, direction: number)
1269 # Check whether LSP server supports type hierarchy
1270 if !lspserver.isTypeHierarchyProvider
1271 util.ErrMsg('LSP server does not support type hierarchy')
1275 # interface TypeHierarchy
1276 # interface TextDocumentPositionParams
1277 var param: dict<any>
1278 param = lspserver.getTextDocPosition(false)
1279 # 0: children, 1: parent, 2: both
1280 param.direction = direction
1282 var reply = lspserver.rpc('textDocument/typeHierarchy', param)
1283 if reply->empty() || reply.result->empty()
1284 util.WarnMsg('No type hierarchy available')
1288 var isSuper = (direction == 1)
1290 DecodeTypeHierarchy(lspserver, isSuper, reply.result)
1292 typehier.ShowTypeHierarchy(lspserver, isSuper, reply.result)
1295 # Decode the ranges in "WorkspaceEdit"
1296 def DecodeWorkspaceEdit(lspserver: dict<any>, workspaceEdit: dict<any>)
1297 if !lspserver.needOffsetEncoding
1300 if workspaceEdit->has_key('changes')
1301 for [uri, changes] in workspaceEdit.changes->items()
1302 var bnr: number = util.LspUriToBufnr(uri)
1306 # Decode the position encoding in all the text edit locations
1307 changes->map((_, textEdit) => {
1308 lspserver.decodeRange(bnr, textEdit.range)
1314 if workspaceEdit->has_key('documentChanges')
1315 for change in workspaceEdit.documentChanges
1316 if !change->has_key('kind')
1317 var bnr: number = util.LspUriToBufnr(change.textDocument.uri)
1321 # Decode the position encoding in all the text edit locations
1322 change.edits->map((_, textEdit) => {
1323 lspserver.decodeRange(bnr, textEdit.range)
1331 # Request: "textDocument/rename"
1332 # Param: RenameParams
1333 def RenameSymbol(lspserver: dict<any>, newName: string)
1334 # Check whether LSP server supports rename operation
1335 if !lspserver.isRenameProvider
1336 util.ErrMsg('LSP server does not support rename operation')
1340 # interface RenameParams
1341 # interface TextDocumentPositionParams
1342 var param: dict<any> = {}
1343 param = lspserver.getTextDocPosition(true)
1344 param.newName = newName
1346 var reply = lspserver.rpc('textDocument/rename', param)
1348 # Result: WorkspaceEdit | null
1349 if reply->empty() || reply.result->empty()
1354 # result: WorkspaceEdit
1355 DecodeWorkspaceEdit(lspserver, reply.result)
1356 textedit.ApplyWorkspaceEdit(reply.result)
1359 # Decode the range in "CodeAction"
1360 def DecodeCodeAction(lspserver: dict<any>, actionList: list<dict<any>>)
1361 if !lspserver.needOffsetEncoding
1364 actionList->map((_, act) => {
1365 if !act->has_key('disabled') && act->has_key('edit')
1366 DecodeWorkspaceEdit(lspserver, act.edit)
1372 # Request: "textDocument/codeAction"
1373 # Param: CodeActionParams
1374 def CodeAction(lspserver: dict<any>, fname_arg: string, line1: number,
1375 line2: number, query: string)
1376 # Check whether LSP server supports code action operation
1377 if !lspserver.isCodeActionProvider
1378 util.ErrMsg('LSP server does not support code action operation')
1382 # interface CodeActionParams
1383 var params: dict<any> = {}
1384 var fname: string = fname_arg->fnamemodify(':p')
1385 var bnr: number = fname_arg->bufnr()
1386 var r: dict<dict<number>> = {
1389 character: line1 == line2 ? util.GetCharIdxWithCompChar(getline('.'), charcol('.') - 1) : 0
1393 character: util.GetCharIdxWithCompChar(getline(line2), charcol([line2, '$']) - 1)
1396 lspserver.encodeRange(bnr, r)
1397 params->extend({textDocument: {uri: util.LspFileToUri(fname)}, range: r})
1398 var d: list<dict<any>> = []
1399 for lnum in range(line1, line2)
1400 var diagsInfo: list<dict<any>> = diag.GetDiagsByLine(bnr, lnum, lspserver)->deepcopy()
1401 if lspserver.needOffsetEncoding
1402 diagsInfo->map((_, di) => {
1403 lspserver.encodeRange(bnr, di.range)
1407 d->extend(diagsInfo)
1409 params->extend({context: {diagnostics: d, triggerKind: 1}})
1411 var reply = lspserver.rpc('textDocument/codeAction', params)
1413 # Result: (Command | CodeAction)[] | null
1414 if reply->empty() || reply.result->empty()
1415 # no action can be performed
1416 util.WarnMsg('No code action is available')
1420 DecodeCodeAction(lspserver, reply.result)
1422 codeaction.ApplyCodeAction(lspserver, reply.result, query)
1425 # Request: "textDocument/codeLens"
1426 # Param: CodeLensParams
1427 def CodeLens(lspserver: dict<any>, fname: string)
1428 # Check whether LSP server supports code lens operation
1429 if !lspserver.isCodeLensProvider
1430 util.ErrMsg('LSP server does not support code lens operation')
1434 var params = {textDocument: {uri: util.LspFileToUri(fname)}}
1435 var reply = lspserver.rpc('textDocument/codeLens', params)
1436 if reply->empty() || reply.result->empty()
1437 util.WarnMsg($'No code lens actions found for the current file')
1441 var bnr = fname->bufnr()
1443 # Decode the position encoding in all the code lens items
1444 if lspserver.needOffsetEncoding
1445 reply.result->map((_, codeLensItem) => {
1446 lspserver.decodeRange(bnr, codeLensItem.range)
1451 codelens.ProcessCodeLens(lspserver, bnr, reply.result)
1454 # Request: "codeLens/resolve"
1456 def ResolveCodeLens(lspserver: dict<any>, bnr: number,
1457 codeLens: dict<any>): dict<any>
1458 if !lspserver.isCodeLensResolveProvider
1462 if lspserver.needOffsetEncoding
1463 lspserver.encodeRange(bnr, codeLens.range)
1466 var reply = lspserver.rpc('codeLens/resolve', codeLens)
1471 var codeLensItem: dict<any> = reply.result
1473 # Decode the position encoding in the code lens item
1474 if lspserver.needOffsetEncoding
1475 lspserver.decodeRange(bnr, codeLensItem.range)
1481 # List project-wide symbols matching query string
1482 # Request: "workspace/symbol"
1483 # Param: WorkspaceSymbolParams
1484 def WorkspaceQuerySymbols(lspserver: dict<any>, query: string, firstCall: bool, cmdmods: string = '')
1485 # Check whether the LSP server supports listing workspace symbols
1486 if !lspserver.isWorkspaceSymbolProvider
1487 util.ErrMsg('LSP server does not support listing workspace symbols')
1491 # Param: WorkspaceSymbolParams
1495 var reply = lspserver.rpc('workspace/symbol', param)
1496 if reply->empty() || reply.result->empty()
1497 util.WarnMsg($'Symbol "{query}" is not found')
1501 var symInfo: list<dict<any>> = reply.result
1503 if lspserver.needOffsetEncoding
1504 # Decode the position encoding in all the symbol locations
1505 symInfo->map((_, sym) => {
1506 if sym->has_key('location')
1507 lspserver.decodeLocation(sym.location)
1513 if firstCall && symInfo->len() == 1
1514 # If there is only one symbol, then jump to the symbol location
1515 var symLoc: dict<any> = symInfo[0]->get('location', {})
1517 symbol.GotoSymbol(lspserver, symLoc, false, cmdmods)
1520 symbol.WorkspaceSymbolPopup(lspserver, query, symInfo, cmdmods)
1524 # Add a workspace folder to the language server.
1525 def AddWorkspaceFolder(lspserver: dict<any>, dirName: string): void
1526 if !lspserver.caps->has_key('workspace')
1527 || !lspserver.caps.workspace->has_key('workspaceFolders')
1528 || !lspserver.caps.workspace.workspaceFolders->has_key('supported')
1529 || !lspserver.caps.workspace.workspaceFolders.supported
1530 util.ErrMsg('LSP server does not support workspace folders')
1534 if lspserver.workspaceFolders->index(dirName) != -1
1535 util.ErrMsg($'{dirName} is already part of this workspace')
1539 # Notification: 'workspace/didChangeWorkspaceFolders'
1540 # Params: DidChangeWorkspaceFoldersParams
1541 var params = {event: {added: [dirName], removed: []}}
1542 lspserver.sendNotification('workspace/didChangeWorkspaceFolders', params)
1544 lspserver.workspaceFolders->add(dirName)
1547 # Remove a workspace folder from the language server.
1548 def RemoveWorkspaceFolder(lspserver: dict<any>, dirName: string): void
1549 if !lspserver.caps->has_key('workspace')
1550 || !lspserver.caps.workspace->has_key('workspaceFolders')
1551 || !lspserver.caps.workspace.workspaceFolders->has_key('supported')
1552 || !lspserver.caps.workspace.workspaceFolders.supported
1553 util.ErrMsg('LSP server does not support workspace folders')
1557 var idx: number = lspserver.workspaceFolders->index(dirName)
1559 util.ErrMsg($'{dirName} is not currently part of this workspace')
1563 # Notification: "workspace/didChangeWorkspaceFolders"
1564 # Param: DidChangeWorkspaceFoldersParams
1565 var params = {event: {added: [], removed: [dirName]}}
1566 lspserver.sendNotification('workspace/didChangeWorkspaceFolders', params)
1568 lspserver.workspaceFolders->remove(idx)
1571 def DecodeSelectionRange(lspserver: dict<any>, bnr: number, selRange: dict<any>)
1572 lspserver.decodeRange(bnr, selRange.range)
1573 if selRange->has_key('parent')
1574 DecodeSelectionRange(lspserver, bnr, selRange.parent)
1578 # select the text around the current cursor location
1579 # Request: "textDocument/selectionRange"
1580 # Param: SelectionRangeParams
1581 def SelectionRange(lspserver: dict<any>, fname: string)
1582 # Check whether LSP server supports selection ranges
1583 if !lspserver.isSelectionRangeProvider
1584 util.ErrMsg('LSP server does not support selection ranges')
1588 # clear the previous selection reply
1589 lspserver.selection = {}
1591 # interface SelectionRangeParams
1592 # interface TextDocumentIdentifier
1595 uri: util.LspFileToUri(fname)
1597 positions: [lspserver.getPosition(false)]
1599 var reply = lspserver.rpc('textDocument/selectionRange', param)
1601 if reply->empty() || reply.result->empty()
1605 # Decode the position encoding in all the selection range items
1606 if lspserver.needOffsetEncoding
1607 var bnr = fname->bufnr()
1608 reply.result->map((_, selItem) => {
1609 DecodeSelectionRange(lspserver, bnr, selItem)
1614 selection.SelectionStart(lspserver, reply.result)
1617 # Expand the previous selection or start a new one
1618 def SelectionExpand(lspserver: dict<any>)
1619 # Check whether LSP server supports selection ranges
1620 if !lspserver.isSelectionRangeProvider
1621 util.ErrMsg('LSP server does not support selection ranges')
1625 selection.SelectionModify(lspserver, true)
1628 # Shrink the previous selection or start a new one
1629 def SelectionShrink(lspserver: dict<any>)
1630 # Check whether LSP server supports selection ranges
1631 if !lspserver.isSelectionRangeProvider
1632 util.ErrMsg('LSP server does not support selection ranges')
1636 selection.SelectionModify(lspserver, false)
1639 # fold the entire document
1640 # Request: "textDocument/foldingRange"
1641 # Param: FoldingRangeParams
1642 def FoldRange(lspserver: dict<any>, fname: string)
1643 # Check whether LSP server supports fold ranges
1644 if !lspserver.isFoldingRangeProvider
1645 util.ErrMsg('LSP server does not support folding')
1649 # interface FoldingRangeParams
1650 # interface TextDocumentIdentifier
1651 var params = {textDocument: {uri: util.LspFileToUri(fname)}}
1652 var reply = lspserver.rpc('textDocument/foldingRange', params)
1653 if reply->empty() || reply.result->empty()
1657 # result: FoldingRange[]
1658 var end_lnum: number
1659 var last_lnum: number = line('$')
1660 for foldRange in reply.result
1661 end_lnum = foldRange.endLine + 1
1662 if end_lnum < foldRange.startLine + 2
1663 end_lnum = foldRange.startLine + 2
1665 exe $':{foldRange.startLine + 2}, {end_lnum}fold'
1666 # Open all the folds, otherwise the subsequently created folds are not
1672 :setlocal foldcolumn=2
1676 # process the 'workspace/executeCommand' reply from the LSP server
1677 # Result: any | null
1678 def WorkspaceExecuteReply(lspserver: dict<any>, execReply: any)
1679 # Nothing to do for the reply
1682 # Request the LSP server to execute a command
1683 # Request: workspace/executeCommand
1684 # Params: ExecuteCommandParams
1685 def ExecuteCommand(lspserver: dict<any>, cmd: dict<any>)
1686 # Need to check for lspserver.caps.executeCommandProvider?
1688 lspserver.rpc_a('workspace/executeCommand', params, WorkspaceExecuteReply)
1691 # Display the LSP server capabilities (received during the initialization
1693 def GetCapabilities(lspserver: dict<any>): list<string>
1695 var heading = $"'{lspserver.path}' Language Server Capabilities"
1696 var underlines = repeat('=', heading->len())
1697 l->extend([heading, underlines])
1698 for k in lspserver.caps->keys()->sort()
1699 l->add($'{k}: {lspserver.caps[k]->string()}')
1704 # Display the LSP server initialize request and result
1705 def GetInitializeRequest(lspserver: dict<any>): list<string>
1707 var heading = $"'{lspserver.path}' Language Server Initialize Request"
1708 var underlines = repeat('=', heading->len())
1709 l->extend([heading, underlines])
1710 if lspserver->has_key('rpcInitializeRequest')
1711 for k in lspserver.rpcInitializeRequest->keys()->sort()
1712 l->add($'{k}: {lspserver.rpcInitializeRequest[k]->string()}')
1718 # Store a log or trace message received from the language server.
1719 def AddMessage(lspserver: dict<any>, msgType: string, newMsg: string)
1720 # A single message may contain multiple lines separate by newline
1721 var msgs = newMsg->split("\n")
1722 lspserver.messages->add($'{strftime("%m/%d/%y %T")}: [{msgType}]: {msgs[0]}')
1723 lspserver.messages->extend(msgs[1 : ])
1724 # Keep only the last 500 messages to reduce the memory usage
1725 if lspserver.messages->len() >= 600
1726 lspserver.messages = lspserver.messages[-500 : ]
1730 # Display the log messages received from the LSP server (window/logMessage)
1731 def GetMessages(lspserver: dict<any>): list<string>
1732 if lspserver.messages->empty()
1733 return [$'No messages received from "{lspserver.name}" server']
1737 var heading = $"'{lspserver.path}' Language Server Messages"
1738 var underlines = repeat('=', heading->len())
1739 l->extend([heading, underlines])
1740 l->extend(lspserver.messages)
1744 # Send a 'textDocument/definition' request to the LSP server to get the
1745 # location where the symbol under the cursor is defined and return a list of
1746 # Dicts in a format accepted by the 'tagfunc' option.
1747 # Returns null if the LSP server doesn't support getting the location of a
1748 # symbol definition or the symbol is not defined.
1749 def TagFunc(lspserver: dict<any>, pat: string, flags: string, info: dict<any>): any
1750 # Check whether LSP server supports getting the location of a definition
1751 if !lspserver.isDefinitionProvider
1755 # interface DefinitionParams
1756 # interface TextDocumentPositionParams
1757 var reply = lspserver.rpc('textDocument/definition',
1758 lspserver.getTextDocPosition(false))
1759 if reply->empty() || reply.result->empty()
1763 var taglocations: list<dict<any>>
1764 if reply.result->type() == v:t_list
1765 taglocations = reply.result
1767 taglocations = [reply.result]
1770 if lspserver.needOffsetEncoding
1771 # Decode the position encoding in all the reference locations
1772 taglocations->map((_, loc) => {
1773 lspserver.decodeLocation(loc)
1778 return symbol.TagFunc(lspserver, taglocations, pat)
1781 # Returns unique ID used for identifying the various servers
1782 var UniqueServerIdCounter = 0
1783 def GetUniqueServerId(): number
1784 UniqueServerIdCounter = UniqueServerIdCounter + 1
1785 return UniqueServerIdCounter
1788 export def NewLspServer(serverParams: dict<any>): dict<any>
1789 var lspserver: dict<any> = {
1790 id: GetUniqueServerId(),
1791 name: serverParams.name,
1792 path: serverParams.path,
1793 args: serverParams.args->deepcopy(),
1801 callHierarchyType: '',
1802 completionTriggerChars: [],
1803 customNotificationHandlers: serverParams.customNotificationHandlers->deepcopy(),
1804 customRequestHandlers: serverParams.customRequestHandlers->deepcopy(),
1805 debug: serverParams.debug,
1806 features: serverParams.features->deepcopy(),
1807 forceOffsetEncoding: serverParams.forceOffsetEncoding,
1808 initializationOptions: serverParams.initializationOptions->deepcopy(),
1810 omniCompletePending: false,
1811 peekSymbolFilePopup: -1,
1812 peekSymbolPopup: -1,
1813 processDiagHandler: serverParams.processDiagHandler,
1814 rootSearchFiles: serverParams.rootSearch->deepcopy(),
1815 runIfSearchFiles: serverParams.runIfSearch->deepcopy(),
1816 runUnlessSearchFiles: serverParams.runUnlessSearch->deepcopy(),
1819 syncInit: serverParams.syncInit,
1820 traceLevel: serverParams.traceLevel,
1821 typeHierFilePopup: -1,
1823 workspaceConfig: serverParams.workspaceConfig->deepcopy(),
1824 workspaceSymbolPopup: -1,
1825 workspaceSymbolQuery: ''
1827 lspserver.logfile = $'lsp-{lspserver.name}.log'
1828 lspserver.errfile = $'lsp-{lspserver.name}.err'
1830 # Add the LSP server functions
1832 startServer: function(StartServer, [lspserver]),
1833 initServer: function(InitServer, [lspserver]),
1834 stopServer: function(StopServer, [lspserver]),
1835 shutdownServer: function(ShutdownServer, [lspserver]),
1836 exitServer: function(ExitServer, [lspserver]),
1837 setTrace: function(SetTrace, [lspserver]),
1838 traceLog: function(TraceLog, [lspserver]),
1839 errorLog: function(ErrorLog, [lspserver]),
1840 nextReqID: function(NextReqID, [lspserver]),
1841 createRequest: function(CreateRequest, [lspserver]),
1842 createResponse: function(CreateResponse, [lspserver]),
1843 sendResponse: function(SendResponse, [lspserver]),
1844 sendMessage: function(SendMessage, [lspserver]),
1845 sendNotification: function(SendNotification, [lspserver]),
1846 rpc: function(Rpc, [lspserver]),
1847 rpc_a: function(AsyncRpc, [lspserver]),
1848 waitForResponse: function(WaitForResponse, [lspserver]),
1849 processReply: function(handlers.ProcessReply, [lspserver]),
1850 processNotif: function(handlers.ProcessNotif, [lspserver]),
1851 processRequest: function(handlers.ProcessRequest, [lspserver]),
1852 processMessages: function(handlers.ProcessMessages, [lspserver]),
1853 encodePosition: function(offset.EncodePosition, [lspserver]),
1854 decodePosition: function(offset.DecodePosition, [lspserver]),
1855 encodeRange: function(offset.EncodeRange, [lspserver]),
1856 decodeRange: function(offset.DecodeRange, [lspserver]),
1857 encodeLocation: function(offset.EncodeLocation, [lspserver]),
1858 decodeLocation: function(offset.DecodeLocation, [lspserver]),
1859 getPosition: function(GetPosition, [lspserver]),
1860 getTextDocPosition: function(GetTextDocPosition, [lspserver]),
1861 textdocDidOpen: function(TextdocDidOpen, [lspserver]),
1862 textdocDidClose: function(TextdocDidClose, [lspserver]),
1863 textdocDidChange: function(TextdocDidChange, [lspserver]),
1864 sendInitializedNotif: function(SendInitializedNotif, [lspserver]),
1865 sendWorkspaceConfig: function(SendWorkspaceConfig, [lspserver]),
1866 getCompletion: function(GetCompletion, [lspserver]),
1867 resolveCompletion: function(ResolveCompletion, [lspserver]),
1868 gotoDefinition: function(GotoDefinition, [lspserver]),
1869 gotoDeclaration: function(GotoDeclaration, [lspserver]),
1870 gotoTypeDef: function(GotoTypeDef, [lspserver]),
1871 gotoImplementation: function(GotoImplementation, [lspserver]),
1872 tagFunc: function(TagFunc, [lspserver]),
1873 switchSourceHeader: function(SwitchSourceHeader, [lspserver]),
1874 showSignature: function(ShowSignature, [lspserver]),
1875 didSaveFile: function(DidSaveFile, [lspserver]),
1876 hover: function(ShowHoverInfo, [lspserver]),
1877 showReferences: function(ShowReferences, [lspserver]),
1878 docHighlight: function(DocHighlight, [lspserver]),
1879 getDocSymbols: function(GetDocSymbols, [lspserver]),
1880 textDocFormat: function(TextDocFormat, [lspserver]),
1881 prepareCallHierarchy: function(PrepareCallHierarchy, [lspserver]),
1882 incomingCalls: function(IncomingCalls, [lspserver]),
1883 getIncomingCalls: function(GetIncomingCalls, [lspserver]),
1884 outgoingCalls: function(OutgoingCalls, [lspserver]),
1885 getOutgoingCalls: function(GetOutgoingCalls, [lspserver]),
1886 inlayHintsShow: function(InlayHintsShow, [lspserver]),
1887 typeHierarchy: function(TypeHierarchy, [lspserver]),
1888 renameSymbol: function(RenameSymbol, [lspserver]),
1889 codeAction: function(CodeAction, [lspserver]),
1890 codeLens: function(CodeLens, [lspserver]),
1891 resolveCodeLens: function(ResolveCodeLens, [lspserver]),
1892 workspaceQuery: function(WorkspaceQuerySymbols, [lspserver]),
1893 addWorkspaceFolder: function(AddWorkspaceFolder, [lspserver]),
1894 removeWorkspaceFolder: function(RemoveWorkspaceFolder, [lspserver]),
1895 selectionRange: function(SelectionRange, [lspserver]),
1896 selectionExpand: function(SelectionExpand, [lspserver]),
1897 selectionShrink: function(SelectionShrink, [lspserver]),
1898 foldRange: function(FoldRange, [lspserver]),
1899 executeCommand: function(ExecuteCommand, [lspserver]),
1900 workspaceConfigGet: function(WorkspaceConfigGet, [lspserver]),
1901 getCapabilities: function(GetCapabilities, [lspserver]),
1902 getInitializeRequest: function(GetInitializeRequest, [lspserver]),
1903 addMessage: function(AddMessage, [lspserver]),
1904 getMessages: function(GetMessages, [lspserver])
1910 # vim: tabstop=8 shiftwidth=2 softtabstop=2