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.

commands.mddocs/advanced/

Commands [Advanced]

Complexity: Advanced | Category: Advanced | Keywords: commands, execute, register, custom

Common Tasks: Execute coc commands | List available commands | Register custom commands | Repeat commands

Execute and register custom coc commands.

Common Tasks

Execute a coc command

:CocCommand tsserver.restart

Run registered command by name.

Execute command programmatically

call CocAction('runCommand', 'editor.action.formatDocument')

Call command from Vim script.

List all available commands

let cmds = CocAction('commands')

Get list of registered commands.

Register custom command

call coc#add_command('mycommand', 'echo "Hello"', 'Say Hello')

Add custom Vim command to coc list.

Commands

:CocCommand

:CocCommand [command] [args...]

Execute a registered coc command.

Parameters:

  • command: Command name to execute (optional, opens picker if omitted)
  • args...: Command arguments

Example:

:CocCommand
:CocCommand tsserver.restart
:CocCommand editor.action.organizeImport

CocAction API

runCommand

CocAction('runCommand', command, ...args)

Run a coc command programmatically.

Parameters:

  • command: Command name (string)
  • ...args: Variable arguments for command

Example:

" Run command without arguments
call CocAction('runCommand', 'editor.action.formatDocument')

" Run command with arguments
call CocAction('runCommand', 'editor.action.addCommentLine')

commands

CocAction('commands')
" Returns: list

Get list of all available coc commands.

Returns: List of command objects with:

  • id: Command ID (string)
  • title: Command title/description (string)

Example:

let cmds = CocAction('commands')
echo 'Available commands: ' . len(cmds)

for cmd in cmds
  echo cmd.id . ' - ' . cmd.title
endfor

repeatCommand

CocAction('repeatCommand')

Repeat the last executed command.

Example:

call CocAction('repeatCommand')

Key Mappings

<Plug>(coc-command-repeat)

<Plug>(coc-command-repeat)

Repeat last coc command.

Example:

nmap <silent> <leader>. <Plug>(coc-command-repeat)

Functions

coc#add_command()

coc#add_command(id, cmd, [title])

Register a custom Vim command to appear in :CocCommand list.

Parameters:

  • id: Command ID/name (string)
  • cmd: Vim command to execute (string)
  • title: Optional title for the command (string)

Example:

" Register simple command
call coc#add_command('mycommand', 'echo "Hello"', 'Say Hello')

" Register command that runs function
call coc#add_command('format.buffer', 'call MyFormat()', 'Format current buffer')

function! MyFormat() abort
  call CocAction('format')
endfunction

Using CocList

:CocList commands

:CocList commands

Show interactive list of all coc commands.

Example:

:CocList commands

" With fuzzy search
:CocList --input=format commands

Global Variables

g:coc_vim_commands

g:coc_vim_commands

List of Vim commands registered by coc extensions.

Type: List (read-only)

Example:

if exists('g:coc_vim_commands')
  echo 'Registered commands: ' . len(g:coc_vim_commands)
endif

Configuration

Command settings in coc-settings.json:

{
  "commands": {
    "myCommand": {
      "command": "echo 'custom command'",
      "title": "My Custom Command"
    }
  }
}

Usage Examples

Basic Command Execution

" Execute command
:CocCommand tsserver.restart

" Execute with mapping
nnoremap <leader>cr :CocCommand tsserver.restart<CR>

List All Commands

function! ShowAllCommands() abort
  let cmds = CocAction('commands')

  echo '=== Available Commands ==='
  for cmd in cmds
    echo cmd.id
    if has_key(cmd, 'title')
      echo '  ' . cmd.title
    endif
  endfor
endfunction

command! ShowCommands call ShowAllCommands()

Interactive Command Picker

function! PickCommand() abort
  let cmds = CocAction('commands')
  let items = []

  for i in range(len(cmds))
    let cmd = cmds[i]
    let title = has_key(cmd, 'title') ? cmd.title : cmd.id
    call add(items, (i + 1) . '. ' . title)
  endfor

  let choice = inputlist(['Select command:'] + items)

  if choice > 0 && choice <= len(cmds)
    call CocAction('runCommand', cmds[choice - 1].id)
  endif
endfunction

nnoremap <silent> <leader>cc :call PickCommand()<CR>

Repeat Last Command

" Repeat with mapping
nmap <leader>. <Plug>(coc-command-repeat)

" Repeat programmatically
nnoremap <silent> <leader>r :call CocAction('repeatCommand')<CR>

Register Custom Commands

" Register multiple custom commands
function! RegisterMyCommands() abort
  call coc#add_command('format.buffer', 'call CocAction("format")', 'Format Buffer')
  call coc#add_command('organize.imports', 'call CocAction("organizeImport")', 'Organize Imports')
  call coc#add_command('restart.server', 'CocRestart', 'Restart Coc')
  call coc#add_command('open.config', 'CocConfig', 'Open Config')
endfunction

autocmd User CocNvimInit call RegisterMyCommands()

Command History

let g:command_history = []

function! TrackCommand(cmd) abort
  call insert(g:command_history, {
    \ 'command': a:cmd,
    \ 'time': strftime('%Y-%m-%d %H:%M:%S')
    \ })

  if len(g:command_history) > 50
    call remove(g:command_history, 50, -1)
  endif
endfunction

function! ShowCommandHistory() abort
  if len(g:command_history) == 0
    echo 'No command history'
    return
  endif

  echo '=== Command History ==='
  for entry in g:command_history
    echo entry.time . ' - ' . entry.command
  endfor
endfunction

command! CommandHistory call ShowCommandHistory()

" Track when running commands
function! RunAndTrack(cmd) abort
  call TrackCommand(a:cmd)
  call CocAction('runCommand', a:cmd)
endfunction

Search Commands

function! SearchCommands(query) abort
  let cmds = CocAction('commands')
  let matches = []

  for cmd in cmds
    if cmd.id =~? a:query
      call add(matches, cmd)
    elseif has_key(cmd, 'title') && cmd.title =~? a:query
      call add(matches, cmd)
    endif
  endfor

  if len(matches) == 0
    echo 'No commands matching: ' . a:query
    return
  endif

  echo 'Found ' . len(matches) . ' commands:'
  for cmd in matches
    echo '  ' . cmd.id
  endfor
endfunction

command! -nargs=1 SearchCmd call SearchCommands(<q-args>)

Quick Commands

" Define quick access to common commands
nnoremap <silent> <leader>qf :CocCommand editor.action.formatDocument<CR>
nnoremap <silent> <leader>qi :CocCommand editor.action.organizeImport<CR>
nnoremap <silent> <leader>qr :CocCommand tsserver.restart<CR>

Command Aliases

function! CreateCommandAlias(alias, command) abort
  execute 'command! -nargs=0 ' . a:alias . ' CocCommand ' . a:command
endfunction

" Create aliases
call CreateCommandAlias('Format', 'editor.action.formatDocument')
call CreateCommandAlias('Organize', 'editor.action.organizeImport')
call CreateCommandAlias('Restart', 'tsserver.restart')

" Usage:
" :Format
" :Organize

Conditional Commands

function! RunCommandIfExists(cmd) abort
  let cmds = CocAction('commands')
  let exists = v:false

  for c in cmds
    if c.id ==# a:cmd
      let exists = v:true
      break
    endif
  endfor

  if exists
    call CocAction('runCommand', a:cmd)
  else
    echo 'Command not found: ' . a:cmd
  endif
endfunction

command! -nargs=1 SafeCommand call RunCommandIfExists(<q-args>)

Command by Extension

function! ListCommandsByExtension(ext) abort
  let cmds = CocAction('commands')
  let matches = []

  for cmd in cmds
    " Commands typically prefixed with extension name
    if cmd.id =~# '^' . a:ext . '\.'
      call add(matches, cmd)
    endif
  endfor

  if len(matches) == 0
    echo 'No commands for extension: ' . a:ext
    return
  endif

  echo 'Commands for ' . a:ext . ':'
  for cmd in matches
    echo '  ' . cmd.id
  endfor
endfunction

command! -nargs=1 ExtCommands call ListCommandsByExtension(<q-args>)

" Usage:
" :ExtCommands tsserver
" :ExtCommands eslint

Async Command Execution

function! RunCommandAsync(cmd) abort
  call CocActionAsync('runCommand', a:cmd)
  echo 'Running: ' . a:cmd . ' (async)'
endfunction

command! -nargs=1 AsyncCmd call RunCommandAsync(<q-args>)

Command Groups

let g:command_groups = {
  \ 'format': ['editor.action.formatDocument', 'editor.action.organizeImport'],
  \ 'server': ['tsserver.restart', 'eslint.restart'],
  \ 'refactor': ['editor.action.rename', 'editor.action.refactor']
  \ }

function! RunCommandGroup(group) abort
  if !has_key(g:command_groups, a:group)
    echo 'Unknown command group: ' . a:group
    return
  endif

  echo 'Running command group: ' . a:group
  for cmd in g:command_groups[a:group]
    call CocAction('runCommand', cmd)
  endfor
endfunction

command! -nargs=1 RunGroup call RunCommandGroup(<q-args>)

" Usage:
" :RunGroup format
" :RunGroup server

Command with Confirmation

function! RunCommandWithConfirm(cmd) abort
  if confirm('Run command: ' . a:cmd . '?', "&Yes\n&No") == 1
    call CocAction('runCommand', a:cmd)
    echo 'Command executed'
  else
    echo 'Cancelled'
  endif
endfunction

command! -nargs=1 ConfirmCmd call RunCommandWithConfirm(<q-args>)

Save Favorite Commands

let g:favorite_commands = []

function! AddFavoriteCommand(cmd) abort
  if index(g:favorite_commands, a:cmd) < 0
    call add(g:favorite_commands, a:cmd)
    echo 'Added to favorites: ' . a:cmd
  else
    echo 'Already in favorites'
  endif
endfunction

function! ShowFavorites() abort
  if len(g:favorite_commands) == 0
    echo 'No favorite commands'
    return
  endif

  echo '=== Favorite Commands ==='
  for i in range(len(g:favorite_commands))
    echo (i + 1) . '. ' . g:favorite_commands[i]
  endfor
endfunction

command! -nargs=1 AddFavorite call AddFavoriteCommand(<q-args>)
command! Favorites call ShowFavorites()

Error Handling

Command Not Found

Issue: Attempting to run non-existent command.

Solution:

function! SafeRunCommand(cmd) abort
  let cmds = CocAction('commands')
  let found = v:false

  for c in cmds
    if c.id ==# a:cmd
      let found = v:true
      break
    endif
  endfor

  if !found
    echohl ErrorMsg
    echo 'Command not found: ' . a:cmd
    echo 'Available commands: :CocList commands'
    echohl None
    return
  endif

  call CocAction('runCommand', a:cmd)
endfunction

Command Execution Failure

Issue: Command runs but fails with error.

Solution:

function! RunCommandWithErrorHandling(cmd, ...) abort
  try
    if a:0 > 0
      call CocAction('runCommand', a:cmd, a:000)
    else
      call CocAction('runCommand', a:cmd)
    endif
    echo 'Command completed: ' . a:cmd
  catch
    echohl ErrorMsg
    echo 'Command failed: ' . a:cmd
    echo 'Error: ' . v:exception
    echohl None
  endtry
endfunction

Async Command Timeout

Issue: Long-running commands don't complete.

Solution:

let g:command_timeout = {}

function! RunCommandWithTimeout(cmd, timeout_ms) abort
  let request_id = localtime()
  let g:command_timeout[request_id] = {
    \ 'cmd': a:cmd,
    \ 'start': reltime()
    \ }

  call CocActionAsync('runCommand', a:cmd, function('s:on_command_complete', [request_id]))

  " Set timeout timer
  call timer_start(a:timeout_ms, function('s:check_timeout', [request_id]))
endfunction

function! s:on_command_complete(request_id, error, result) abort
  if has_key(g:command_timeout, a:request_id)
    call remove(g:command_timeout, a:request_id)
  endif

  if a:error
    echo 'Command error: ' . a:error
  else
    echo 'Command completed'
  endif
endfunction

function! s:check_timeout(request_id, timer) abort
  if has_key(g:command_timeout, a:request_id)
    let cmd = g:command_timeout[a:request_id].cmd
    call remove(g:command_timeout, a:request_id)
    echohl WarningMsg
    echo 'Command timeout: ' . cmd
    echohl None
  endif
endfunction

Invalid Arguments

Issue: Command requires specific argument format.

Solution:

function! ValidateAndRunCommand(cmd, args) abort
  " Validate args is a list
  if type(a:args) != v:t_list
    echohl ErrorMsg
    echo 'Invalid arguments: must be a list'
    echohl None
    return
  endif

  " Check command exists
  let cmds = CocAction('commands')
  let found = v:false
  for c in cmds
    if c.id ==# a:cmd
      let found = v:true
      break
    endif
  endfor

  if !found
    echohl ErrorMsg
    echo 'Command not found: ' . a:cmd
    echohl None
    return
  endif

  " Execute with validated args
  call call('CocAction', ['runCommand', a:cmd] + a:args)
endfunction

Troubleshooting

Problem: Commands not appearing in :CocCommand list

Symptoms: Registered commands don't show up in picker.

Solutions:

  1. Verify registration timing - register after CocNvimInit:
    autocmd User CocNvimInit call RegisterCommands()
  2. Check command syntax in coc#add_command():
    " Wrong: missing title
    call coc#add_command('test', 'echo "test"')
    
    " Right: includes title
    call coc#add_command('test', 'echo "test"', 'Test Command')
  3. Restart coc.nvim: :CocRestart

Problem: Command executes but has no effect

Symptoms: Command runs without errors but doesn't perform expected action.

Solutions:

  1. Check command context (buffer type, file type):
    echo &filetype
    echo &buftype
  2. Verify LSP server is running for language-specific commands:
    :CocCommand workspace.showOutput
  3. Check for conflicting keymaps or commands:
    :verbose command CocCommand

Problem: RepeatCommand not working

Symptoms: CocAction('repeatCommand') does nothing.

Solutions:

  1. Ensure a command was executed first
  2. Check if last command is repeatable (some commands can't be repeated)
  3. Use explicit command instead:
    let g:last_coc_command = ''
    
    function! TrackAndRunCommand(cmd) abort
      let g:last_coc_command = a:cmd
      call CocAction('runCommand', a:cmd)
    endfunction
    
    function! RepeatLastCommand() abort
      if !empty(g:last_coc_command)
        call CocAction('runCommand', g:last_coc_command)
      endif
    endfunction

Problem: Custom command IDs conflict

Symptoms: Command registration fails or overwrites existing command.

Solutions:

  1. Use unique namespaced IDs:
    " Bad: generic name
    call coc#add_command('format', ...)
    
    " Good: namespaced
    call coc#add_command('myproject.format', ...)
  2. Check for existing commands before registering:
    function! SafeRegisterCommand(id, cmd, title) abort
      let cmds = CocAction('commands')
      for c in cmds
        if c.id ==# a:id
          echo 'Command already exists: ' . a:id
          return
        endif
      endfor
      call coc#add_command(a:id, a:cmd, a:title)
    endfunction

Problem: Command execution is slow

Symptoms: Commands take too long to execute.

Solutions:

  1. Use async execution:
    call CocActionAsync('runCommand', 'slow.command')
  2. Check LSP server performance:
    :CocCommand workspace.showOutput
  3. Profile command execution:
    :profile start command-profile.log
    :profile func *
    :CocCommand your.command
    :profile stop

Problem: Commands fail silently

Symptoms: No error message when command fails.

Solutions:

  1. Check :messages for errors
  2. Enable verbose logging:
    {
      "coc.preferences.extensionUpdateCheck": "daily",
      "suggest.timeout": 5000
    }
  3. Wrap commands in try-catch:
    try
      call CocAction('runCommand', 'command.name')
    catch
      echohl ErrorMsg
      echo 'Command failed: ' . v:exception
      echohl None
    endtry

See Also

  • RPC and LSP Communication - Low-level command execution
  • Configuration - Configure command behavior
  • List Interface - Browse commands with CocList
  • Service Management - Control coc service
  • Extensions - Extension-provided commands