or run

tessl search
Log in

Version

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/coc.nvim@0.0.x

docs

advanced

commands.mdcursor-navigation.mdmulti-cursor.mdrpc-lsp.mdsnippets.md
index.md
tile.json

tessl/npm-coc-nvim

tessl install tessl/npm-coc-nvim@0.0.0

LSP based intellisense engine for neovim & vim8.

rpc-lsp.mddocs/advanced/

RPC and LSP Communication [Advanced]

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.

Table of Contents

  • Common Tasks
  • RPC Communication
  • RPC Functions
  • API Functions
  • Client Functions
  • Utility Functions
  • Usage Examples
  • Error Handling
  • Troubleshooting
  • See Also

Common Tasks

Send synchronous LSP request

let result = CocRequest('tsserver', 'textDocument/definition', params)

Get immediate response from language server.

Send asynchronous LSP request

call CocRequestAsync('tsserver', 'textDocument/hover', params, 'OnHoverResponse')

Non-blocking request with callback.

Register notification handler

call CocRegistNotification('tsserver', 'custom/notification', 'OnCustomNotify')

Handle server-initiated notifications.

Send RPC request to coc.nvim

let result = coc#rpc#request('documentSymbols', [bufnr('%')])

Interact with coc.nvim service directly.

RPC Communication

CocRequest()

CocRequest(id, method, [params])
" Returns: any

Send 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 dictionary

Returns: Response from language server.

Example:

let result = CocRequest('tsserver', 'textDocument/definition', params)

CocRequestAsync()

CocRequestAsync(id, method, [params], [callback])

Send asynchronous LSP request to language server.

Parameters:

  • id: Language server ID
  • method: LSP method name
  • params: Optional parameters
  • callback: 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
endfunction

CocNotify()

CocNotify(id, method, [params])

Send LSP notification (no response expected).

Parameters:

  • id: Language server ID
  • method: LSP method name
  • params: Optional parameters

Example:

call CocNotify('tsserver', 'textDocument/didChange', params)

CocLocations()

CocLocations(id, method, [...])
" Returns: any

Query LSP locations synchronously.

Parameters:

  • id: Language server ID
  • method: LSP method name (e.g., 'textDocument/definition')
  • ...: Additional arguments

Returns: Location list result.

Example:

let locations = CocLocations('tsserver', 'textDocument/definition')

CocLocationsAsync()

CocLocationsAsync(id, method, [...])

Query LSP locations asynchronously.

Parameters:

  • id: Language server ID
  • method: LSP method name
  • ...: Additional arguments

Example:

call CocLocationsAsync('tsserver', 'textDocument/references')

CocRegistNotification()

CocRegistNotification(id, method, callback)

Register handler for LSP notification.

Parameters:

  • id: Language server ID
  • method: LSP notification method
  • callback: Callback function name (string)

Example:

call CocRegistNotification('tsserver', 'custom/notification', 'OnCustomNotify')

function! OnCustomNotify(data) abort
  echo 'Received: ' . string(a:data)
endfunction

RPC Functions

coc#rpc#request()

coc#rpc#request(method, args)
" Returns: any

Send synchronous RPC request to coc.nvim service.

Parameters:

  • method: Method name
  • args: Arguments list

Returns: Method result.

Example:

let result = coc#rpc#request('documentSymbols', [bufnr('%')])

coc#rpc#notify()

coc#rpc#notify(method, args)

Send asynchronous RPC notification.

Parameters:

  • method: Method name
  • args: Arguments list

Example:

call coc#rpc#notify('workspace/didChangeConfiguration', [config])

coc#rpc#request_async()

coc#rpc#request_async(method, args, callback)

Send asynchronous RPC request with callback.

Parameters:

  • method: Method name
  • args: Arguments list
  • callback: 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
endfunction

coc#rpc#async_response()

coc#rpc#async_response(id, resp, isErr)

Handle async response. Internal use.

Parameters:

  • id: Request ID
  • resp: Response data
  • isErr: Error flag

coc#rpc#async_request()

coc#rpc#async_request(id, method, args)

Process async request from server. Internal use.

Parameters:

  • id: Request ID
  • method: Method name
  • args: Arguments

API Functions

coc#api#call()

coc#api#call(method, args)
" Returns: [error, result]

Call API method with error handling.

Parameters:

  • method: API method name
  • args: Method arguments

Returns: 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
endif

coc#api#exec()

coc#api#exec(method, args)
" Returns: any

Execute API method directly.

Parameters:

  • method: Method name
  • args: Arguments

Returns: Method result.

Example:

let result = coc#api#exec('listWorkspaceFolders', [])

coc#api#notify()

coc#api#notify(method, args)

Send API notification.

Parameters:

  • method: Method name
  • args: Arguments

Example:

call coc#api#notify('workspace/didChangeWatchedFiles', [changes])

coc#api#func_names()

coc#api#func_names()
" Returns: list

Get all API function names.

Returns: List of function names.

Example:

let functions = coc#api#func_names()
for func in functions
  echo func
endfor

Client Functions

coc#client#create()

coc#client#create(name, command)
" Returns: client

Create 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()

coc#client#get_client(name)
" Returns: client or null

Get client by name.

Parameters:

  • name: Client name

Returns: Client object or null if not found.

Example:

let client = coc#client#get_client('tsserver')

coc#client#request()

coc#client#request(name, method, args)
" Returns: any

Send request to specific client.

Parameters:

  • name: Client name
  • method: Method name
  • args: Arguments

Returns: Request result.

Example:

let result = coc#client#request('tsserver', 'completionItem/resolve', item)

coc#client#notify()

coc#client#notify(name, method, args)

Send notification to client.

Parameters:

  • name: Client name
  • method: Method name
  • args: Arguments

Example:

call coc#client#notify('tsserver', 'textDocument/didChange', params)

coc#client#request_async()

coc#client#request_async(name, method, args, callback)

Send async request to client.

Parameters:

  • name: Client name
  • method: Method name
  • args: Arguments
  • callback: Callback function name (string)

Example:

call coc#client#request_async('tsserver', 'hover', args, 'OnHover')

Utility Functions

coc#util#rebuild()

coc#util#rebuild()

Rebuild native modules for all extensions.

Example:

call coc#util#rebuild()

coc#util#install_extension()

coc#util#install_extension(names)

Install extensions programmatically.

Parameters:

  • names: List of extension names

Example:

call coc#util#install_extension(['coc-json', 'coc-tsserver'])

coc#util#update_extensions()

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()

coc#util#jump(cmd, filepath, [line, col])

Jump to file location.

Parameters:

  • cmd: Open command (e.g., 'edit', 'split', 'vsplit')
  • filepath: File path
  • line: 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()

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()

coc#util#open_file(cmd, file)
" Returns: number

Open 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 open

Returns: 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()

coc#util#vim_info()
" Returns: dictionary

Collect comprehensive Vim/Neovim environment information for the backend server. Returns dictionary with system capabilities and configuration.

Returns: Dictionary containing:

  • apiversion: API version
  • mode: Current mode
  • config: User configuration
  • floating: Float window support
  • extensionRoot: Extension directory
  • globalExtensions: Global extensions list
  • lines, columns: Screen dimensions
  • cmdheight: Command height
  • pid: Process ID
  • version: Vim/Neovim version
  • completeOpt: Complete options
  • isVim: Boolean for Vim vs Neovim
  • isCygwin: Boolean for Cygwin
  • isMacvim: Boolean for MacVim
  • colorscheme: Current colorscheme
  • background: Background color
  • And many more system properties

Example:

let info = coc#util#vim_info()
echo 'Vim version: ' . info.version
echo 'Float support: ' . info.floating
echo 'Extensions root: ' . info.extensionRoot

coc#util#variables()

coc#util#variables(bufnr)
" Returns: dictionary

Retrieve all coc-related variables from a buffer. Filters and returns only variables prefixed with 'coc'.

Parameters:

  • bufnr: Buffer number

Returns: 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)
endif

Usage Examples

Custom LSP Request

function! 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
endfunction

Async LSP Request

function! 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
endfunction

Register Custom Notification

function! RegisterCustomHandlers() abort
  call CocRegistNotification('tsserver', '$/progress', 'OnProgress')
endfunction

function! OnProgress(data) abort
  echo 'Progress: ' . a:data.message
endfunction

autocmd User CocNvimInit call RegisterCustomHandlers()

Direct RPC Call

function! GetSymbols() abort
  let symbols = coc#rpc#request('documentSymbols', [bufnr('%')])
  return symbols
endfunction

Custom Client

function! 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'
endfunction

Batch Requests

function! 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
endfunction

Monitor Notifications

let 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_notifications

Error Handling

Synchronous Request Errors

Issue: 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
endtry

Async Callback Errors

Issue: 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
endfunction

Client Not Found

Issue: 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
endif

Invalid Parameters

Issue: 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)
endfunction

Troubleshooting

Problem: Requests timing out

Symptoms: LSP requests hang or return timeout errors.

Solutions:

  1. Check if language server is responsive: :CocCommand workspace.showOutput
  2. Increase timeout in settings: "languageserver.timeout": 10000
  3. Use async requests instead of synchronous ones
  4. Restart language server: :CocRestart

Problem: Notifications not received

Symptoms: Registered notification handlers not called.

Solutions:

  1. Verify handler is registered after server starts:
    autocmd User CocNvimInit call RegisterHandlers()
  2. Check server capabilities support the notification
  3. Use wildcard to catch all notifications for debugging:
    call CocRegistNotification('tsserver', '*', 'DebugNotify')

Problem: RPC connection errors

Symptoms: "RPC connection lost" or "service not ready" errors.

Solutions:

  1. Check coc service status: :CocInfo
  2. Review service logs: :CocCommand workspace.showOutput
  3. Restart coc service: :CocRestart
  4. Check for conflicting plugins or Node.js version issues
  5. Verify coc.nvim is properly installed: :checkhealth coc

Problem: Custom client not starting

Symptoms: coc#client#create() returns null.

Solutions:

  1. Verify command exists and is executable:
    echo executable('mylsp-server')
  2. Test command manually in terminal
  3. Check server output: :CocCommand workspace.showOutput mylsp
  4. Provide full path to executable:
    let client = coc#client#create('mylsp', ['/full/path/to/server'])

Problem: API methods not found

Symptoms: "Method not found" errors when calling API.

Solutions:

  1. List available methods:
    echo coc#api#func_names()
  2. Check coc.nvim version supports the method
  3. Verify method name spelling and case
  4. Update coc.nvim to latest version

Problem: Async callbacks not firing

Symptoms: Callback functions never execute.

Solutions:

  1. Verify callback function exists before making request:
    if exists('*OnComplete')
      call CocRequestAsync('server', 'method', params, 'OnComplete')
    endif
  2. Check for errors in :messages
  3. Ensure callback has correct signature: function! Name(error, result)
  4. Use function reference instead of string:
    call coc#rpc#request_async('method', [], function('s:callback'))

See Also

  • Commands - Register and execute custom commands
  • Cursor Navigation - Position APIs for LSP requests
  • Configuration - Configure language servers
  • Service Management - Control coc.nvim service
  • Extensions - Manage language server extensions