tessl install tessl/npm-coc-nvim@0.0.0LSP based intellisense engine for neovim & vim8.
Complexity: Advanced | Category: Advanced | Keywords: rpc, lsp, request, notify, client
Common Tasks: Send LSP requests | Register notifications | Create custom clients
Low-level APIs for direct RPC communication, LSP requests, and advanced language server integrations.
let result = CocRequest('tsserver', 'textDocument/definition', params)Get immediate response from language server.
call CocRequestAsync('tsserver', 'textDocument/hover', params, 'OnHoverResponse')Non-blocking request with callback.
call CocRegistNotification('tsserver', 'custom/notification', 'OnCustomNotify')Handle server-initiated notifications.
let result = coc#rpc#request('documentSymbols', [bufnr('%')])Interact with coc.nvim service directly.
CocRequest(id, method, [params])
" Returns: anySend synchronous LSP request to language server.
Parameters:
id: Language server ID (e.g., 'tsserver', 'pyright')method: LSP method name (e.g., 'textDocument/definition')params: Optional parameters dictionaryReturns: Response from language server.
Example:
let result = CocRequest('tsserver', 'textDocument/definition', params)CocRequestAsync(id, method, [params], [callback])Send asynchronous LSP request to language server.
Parameters:
id: Language server IDmethod: LSP method nameparams: Optional parameterscallback: Optional callback function name (string)Example:
call CocRequestAsync('tsserver', 'textDocument/hover', params, 'OnHoverResponse')
function! OnHoverResponse(error, response) abort
if a:error
echo 'Error: ' . a:error
else
echo a:response
endif
endfunctionCocNotify(id, method, [params])Send LSP notification (no response expected).
Parameters:
id: Language server IDmethod: LSP method nameparams: Optional parametersExample:
call CocNotify('tsserver', 'textDocument/didChange', params)CocLocations(id, method, [...])
" Returns: anyQuery LSP locations synchronously.
Parameters:
id: Language server IDmethod: LSP method name (e.g., 'textDocument/definition')...: Additional argumentsReturns: Location list result.
Example:
let locations = CocLocations('tsserver', 'textDocument/definition')CocLocationsAsync(id, method, [...])Query LSP locations asynchronously.
Parameters:
id: Language server IDmethod: LSP method name...: Additional argumentsExample:
call CocLocationsAsync('tsserver', 'textDocument/references')CocRegistNotification(id, method, callback)Register handler for LSP notification.
Parameters:
id: Language server IDmethod: LSP notification methodcallback: Callback function name (string)Example:
call CocRegistNotification('tsserver', 'custom/notification', 'OnCustomNotify')
function! OnCustomNotify(data) abort
echo 'Received: ' . string(a:data)
endfunctioncoc#rpc#request(method, args)
" Returns: anySend synchronous RPC request to coc.nvim service.
Parameters:
method: Method nameargs: Arguments listReturns: Method result.
Example:
let result = coc#rpc#request('documentSymbols', [bufnr('%')])coc#rpc#notify(method, args)Send asynchronous RPC notification.
Parameters:
method: Method nameargs: Arguments listExample:
call coc#rpc#notify('workspace/didChangeConfiguration', [config])coc#rpc#request_async(method, args, callback)Send asynchronous RPC request with callback.
Parameters:
method: Method nameargs: Arguments listcallback: Callback function (function reference or string)Example:
call coc#rpc#request_async('hover', [], function('s:on_hover'))
function! s:on_hover(error, result) abort
if !a:error
echo a:result
endif
endfunctioncoc#rpc#async_response(id, resp, isErr)Handle async response. Internal use.
Parameters:
id: Request IDresp: Response dataisErr: Error flagcoc#rpc#async_request(id, method, args)Process async request from server. Internal use.
Parameters:
id: Request IDmethod: Method nameargs: Argumentscoc#api#call(method, args)
" Returns: [error, result]Call API method with error handling.
Parameters:
method: API method nameargs: Method argumentsReturns: List with [error, result] where error is string or null.
Example:
let [err, result] = coc#api#call('showMessage', ['Hello'])
if err
echo 'Error: ' . err
else
echo 'Result: ' . result
endifcoc#api#exec(method, args)
" Returns: anyExecute API method directly.
Parameters:
method: Method nameargs: ArgumentsReturns: Method result.
Example:
let result = coc#api#exec('listWorkspaceFolders', [])coc#api#notify(method, args)Send API notification.
Parameters:
method: Method nameargs: ArgumentsExample:
call coc#api#notify('workspace/didChangeWatchedFiles', [changes])coc#api#func_names()
" Returns: listGet all API function names.
Returns: List of function names.
Example:
let functions = coc#api#func_names()
for func in functions
echo func
endforcoc#client#create(name, command)
" Returns: clientCreate new language client.
Parameters:
name: Client name (string)command: Start command (string or list)Returns: Client object or null on failure.
Example:
let client = coc#client#create('mylsp', 'mylsp-server')coc#client#get_client(name)
" Returns: client or nullGet client by name.
Parameters:
name: Client nameReturns: Client object or null if not found.
Example:
let client = coc#client#get_client('tsserver')coc#client#request(name, method, args)
" Returns: anySend request to specific client.
Parameters:
name: Client namemethod: Method nameargs: ArgumentsReturns: Request result.
Example:
let result = coc#client#request('tsserver', 'completionItem/resolve', item)coc#client#notify(name, method, args)Send notification to client.
Parameters:
name: Client namemethod: Method nameargs: ArgumentsExample:
call coc#client#notify('tsserver', 'textDocument/didChange', params)coc#client#request_async(name, method, args, callback)Send async request to client.
Parameters:
name: Client namemethod: Method nameargs: Argumentscallback: Callback function name (string)Example:
call coc#client#request_async('tsserver', 'hover', args, 'OnHover')coc#util#rebuild()Rebuild native modules for all extensions.
Example:
call coc#util#rebuild()coc#util#install_extension(names)Install extensions programmatically.
Parameters:
names: List of extension namesExample:
call coc#util#install_extension(['coc-json', 'coc-tsserver'])coc#util#update_extensions([sync])Update all extensions.
Parameters:
sync: Optional boolean for synchronous update (default: 0)Example:
" Async update
call coc#util#update_extensions()
" Sync update
call coc#util#update_extensions(1)coc#util#jump(cmd, filepath, [line, col])Jump to file location.
Parameters:
cmd: Open command (e.g., 'edit', 'split', 'vsplit')filepath: File pathline: Optional line number (1-indexed)col: Optional column (1-indexed)Example:
call coc#util#jump('edit', 'src/main.js', 42, 10)coc#util#open_terminal(opts)Open terminal window.
Parameters:
opts: Options dictionary (e.g., {'cwd': getcwd()})Example:
call coc#util#open_terminal({'cwd': getcwd()})coc#util#open_file(cmd, file)
" Returns: numberOpen a file using specified command with proper path escaping and relative path conversion.
Parameters:
cmd: Vim command (e.g., 'edit', 'split', 'tabnew')file: File path to openReturns: Buffer number of opened file
Example:
" Open in current window
let bufnr = coc#util#open_file('edit', 'src/main.js')
" Open in split
call coc#util#open_file('split', 'README.md')
" Open in new tab
call coc#util#open_file('tabnew', 'package.json')coc#util#vim_info()
" Returns: dictionaryCollect comprehensive Vim/Neovim environment information for the backend server. Returns dictionary with system capabilities and configuration.
Returns: Dictionary containing:
apiversion: API versionmode: Current modeconfig: User configurationfloating: Float window supportextensionRoot: Extension directoryglobalExtensions: Global extensions listlines, columns: Screen dimensionscmdheight: Command heightpid: Process IDversion: Vim/Neovim versioncompleteOpt: Complete optionsisVim: Boolean for Vim vs NeovimisCygwin: Boolean for CygwinisMacvim: Boolean for MacVimcolorscheme: Current colorschemebackground: Background colorExample:
let info = coc#util#vim_info()
echo 'Vim version: ' . info.version
echo 'Float support: ' . info.floating
echo 'Extensions root: ' . info.extensionRootcoc#util#variables(bufnr)
" Returns: dictionaryRetrieve all coc-related variables from a buffer. Filters and returns only variables prefixed with 'coc'.
Parameters:
bufnr: Buffer numberReturns: Dictionary of coc variables
Example:
let vars = coc#util#variables(bufnr('%'))
if has_key(vars, 'coc_diagnostic_info')
echo 'Diagnostics: ' . string(vars.coc_diagnostic_info)
endiffunction! CustomDefinition() abort
let params = {
\ 'textDocument': {'uri': 'file://' . expand('%:p')},
\ 'position': {'line': line('.') - 1, 'character': col('.') - 1}
\ }
let result = CocRequest('tsserver', 'textDocument/definition', params)
echo result
endfunctionfunction! AsyncHover() abort
let params = {
\ 'textDocument': {'uri': 'file://' . expand('%:p')},
\ 'position': {'line': line('.') - 1, 'character': col('.') - 1}
\ }
call CocRequestAsync('tsserver', 'textDocument/hover', params, 'HandleHover')
endfunction
function! HandleHover(error, response) abort
if a:error
echohl ErrorMsg
echo 'Hover error: ' . a:error
echohl None
else
if has_key(a:response, 'contents')
echo a:response.contents
endif
endif
endfunctionfunction! RegisterCustomHandlers() abort
call CocRegistNotification('tsserver', '$/progress', 'OnProgress')
endfunction
function! OnProgress(data) abort
echo 'Progress: ' . a:data.message
endfunction
autocmd User CocNvimInit call RegisterCustomHandlers()function! GetSymbols() abort
let symbols = coc#rpc#request('documentSymbols', [bufnr('%')])
return symbols
endfunctionfunction! CreateCustomClient() abort
let client = coc#client#create('mylsp', ['mylsp-server', '--stdio'])
if client is v:null
echo 'Failed to create client'
return
endif
echo 'Client created: mylsp'
endfunctionfunction! BatchRequests() abort
let files = ['file1.js', 'file2.js', 'file3.js']
let results = []
for file in files
let params = {'textDocument': {'uri': 'file://' . file}}
let symbols = CocRequest('tsserver', 'textDocument/documentSymbol', params)
call add(results, symbols)
endfor
return results
endfunctionlet g:lsp_notifications = []
function! MonitorNotifications() abort
call CocRegistNotification('tsserver', '*', 'LogNotification')
endfunction
function! LogNotification(data) abort
call add(g:lsp_notifications, {
\ 'time': strftime('%H:%M:%S'),
\ 'data': a:data
\ })
endfunction
command! ShowNotifications echo g:lsp_notificationsIssue: Synchronous requests block Vim and may timeout.
Solution:
try
let result = CocRequest('tsserver', 'textDocument/definition', params)
catch /^Vim:Interrupt$/
echo 'Request interrupted'
catch /timeout/
echo 'Request timed out'
catch
echo 'Request failed: ' . v:exception
endtryIssue: Callbacks must handle both errors and successful responses.
Pattern:
function! HandleResponse(error, result) abort
if a:error
" Check error type
if type(a:error) == v:t_string
echohl ErrorMsg
echo 'Error: ' . a:error
echohl None
else
echo 'Unknown error'
endif
return
endif
" Process result
if type(a:result) == v:t_dict
" Handle dict result
elseif type(a:result) == v:t_list
" Handle list result
endif
endfunctionIssue: Language server may not be running or registered.
Solution:
let client = coc#client#get_client('tsserver')
if client is v:null
echo 'Language server not found. Run :CocRestart'
return
endifIssue: LSP requests require specific parameter formats.
Solution:
" Always validate parameters before sending
function! SafeRequest(server, method, params) abort
" Validate server
if empty(a:server)
echoerr 'Server ID required'
return v:null
endif
" Validate params structure
if type(a:params) != v:t_dict
echoerr 'Params must be a dictionary'
return v:null
endif
" Required LSP fields
if a:method =~# 'textDocument'
if !has_key(a:params, 'textDocument')
echoerr 'Missing textDocument parameter'
return v:null
endif
endif
return CocRequest(a:server, a:method, a:params)
endfunctionSymptoms: LSP requests hang or return timeout errors.
Solutions:
:CocCommand workspace.showOutput"languageserver.timeout": 10000:CocRestartSymptoms: Registered notification handlers not called.
Solutions:
autocmd User CocNvimInit call RegisterHandlers()call CocRegistNotification('tsserver', '*', 'DebugNotify')Symptoms: "RPC connection lost" or "service not ready" errors.
Solutions:
:CocInfo:CocCommand workspace.showOutput:CocRestart:checkhealth cocSymptoms: coc#client#create() returns null.
Solutions:
echo executable('mylsp-server'):CocCommand workspace.showOutput mylsplet client = coc#client#create('mylsp', ['/full/path/to/server'])Symptoms: "Method not found" errors when calling API.
Solutions:
echo coc#api#func_names()Symptoms: Callback functions never execute.
Solutions:
if exists('*OnComplete')
call CocRequestAsync('server', 'method', params, 'OnComplete')
endif:messagesfunction! Name(error, result)call coc#rpc#request_async('method', [], function('s:callback'))