tessl install tessl/npm-coc-nvim@0.0.0LSP based intellisense engine for neovim & vim8.
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.
:CocCommand tsserver.restartRun registered command by name.
call CocAction('runCommand', 'editor.action.formatDocument')Call command from Vim script.
let cmds = CocAction('commands')Get list of registered commands.
call coc#add_command('mycommand', 'echo "Hello"', 'Say Hello')Add custom Vim command to coc list.
:CocCommand [command] [args...]Execute a registered coc command.
Parameters:
command: Command name to execute (optional, opens picker if omitted)args...: Command argumentsExample:
:CocCommand
:CocCommand tsserver.restart
:CocCommand editor.action.organizeImportCocAction('runCommand', command, ...args)Run a coc command programmatically.
Parameters:
command: Command name (string)...args: Variable arguments for commandExample:
" Run command without arguments
call CocAction('runCommand', 'editor.action.formatDocument')
" Run command with arguments
call CocAction('runCommand', 'editor.action.addCommentLine')CocAction('commands')
" Returns: listGet 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
endforCocAction('repeatCommand')Repeat the last executed command.
Example:
call CocAction('repeatCommand')<Plug>(coc-command-repeat)Repeat last coc command.
Example:
nmap <silent> <leader>. <Plug>(coc-command-repeat)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:CocList commandsShow interactive list of all coc commands.
Example:
:CocList commands
" With fuzzy search
:CocList --input=format commandsg:coc_vim_commandsList 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)
endifCommand settings in coc-settings.json:
{
"commands": {
"myCommand": {
"command": "echo 'custom command'",
"title": "My Custom Command"
}
}
}" Execute command
:CocCommand tsserver.restart
" Execute with mapping
nnoremap <leader>cr :CocCommand tsserver.restart<CR>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()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 with mapping
nmap <leader>. <Plug>(coc-command-repeat)
" Repeat programmatically
nnoremap <silent> <leader>r :call CocAction('repeatCommand')<CR>" 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()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)
endfunctionfunction! 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>)" 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>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
" :Organizefunction! 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>)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 eslintfunction! RunCommandAsync(cmd) abort
call CocActionAsync('runCommand', a:cmd)
echo 'Running: ' . a:cmd . ' (async)'
endfunction
command! -nargs=1 AsyncCmd call RunCommandAsync(<q-args>)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 serverfunction! 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>)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()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)
endfunctionIssue: 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
endfunctionIssue: 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
endfunctionIssue: 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)
endfunctionSymptoms: Registered commands don't show up in picker.
Solutions:
autocmd User CocNvimInit call RegisterCommands()" Wrong: missing title
call coc#add_command('test', 'echo "test"')
" Right: includes title
call coc#add_command('test', 'echo "test"', 'Test Command'):CocRestartSymptoms: Command runs without errors but doesn't perform expected action.
Solutions:
echo &filetype
echo &buftype:CocCommand workspace.showOutput:verbose command CocCommandSymptoms: CocAction('repeatCommand') does nothing.
Solutions:
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
endfunctionSymptoms: Command registration fails or overwrites existing command.
Solutions:
" Bad: generic name
call coc#add_command('format', ...)
" Good: namespaced
call coc#add_command('myproject.format', ...)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)
endfunctionSymptoms: Commands take too long to execute.
Solutions:
call CocActionAsync('runCommand', 'slow.command'):CocCommand workspace.showOutput:profile start command-profile.log
:profile func *
:CocCommand your.command
:profile stopSymptoms: No error message when command fails.
Solutions:
:messages for errors{
"coc.preferences.extensionUpdateCheck": "daily",
"suggest.timeout": 5000
}try
call CocAction('runCommand', 'command.name')
catch
echohl ErrorMsg
echo 'Command failed: ' . v:exception
echohl None
endtry