Code refactoring, formatting, renaming, and automated fixes. Integrates with language servers to provide context-aware code transformations, style formatting, and intelligent refactoring capabilities for improved code quality and developer productivity.
Context-aware code transformations and quick fixes provided by language servers based on cursor position and selected code.
<Plug>(coc-codeaction)
" Trigger available code actions at cursor position
" Shows menu of available actions from language server
" Mode: Normal
<Plug>(coc-codeaction-line)
" Trigger code actions for entire current line
" Mode: Normal
<Plug>(coc-codeaction-cursor)
" Trigger code actions for cursor position only
" Mode: Normal
<Plug>(coc-codeaction-selected)
" Trigger code actions for selected text
" Mode: Visual, Normal (with operator)
CocAction('codeAction' [, {mode}])
" Execute code action programmatically
" Parameters:
" {mode} - string: 'line'|'cursor'|'selected'|'' (optional)
" Returns: void (shows action menu)Usage Examples:
" Code action mappings
nmap <silent> <space>a <Plug>(coc-codeaction)
nmap <silent> <space>al <Plug>(coc-codeaction-line)
nmap <silent> <space>ac <Plug>(coc-codeaction-cursor)
xmap <silent> <space>a <Plug>(coc-codeaction-selected)
" Set operator for code actions
nmap <silent> <space>A <Plug>(coc-codeaction-selected)
" Quick access to most common actions
function! CodeActionMenu()
let actions = CocAction('getCodeActions', '', ['refactor', 'quickfix'])
if len(actions) > 0
call CocAction('doCodeAction')
else
echo "No code actions available"
endif
endfunction
nnoremap <silent> <space>ca :call CodeActionMenu()<CR>Apply automatic fixes for common issues and errors detected by language servers and linters.
<Plug>(coc-fix-current)
" Apply quick fix for current diagnostic issue
" Automatically selects best available fix
" Mode: Normal
CocAction('doQuickfix')
" Apply quick fix programmatically
" Returns: boolean - success status
CocAction('quickfixes')
" Get available quick fixes
" Returns: array of quick fix actions
CocAction('doCodeAction', {action})
" Execute specific code action
" Parameters:
" {action} - dict: code action objectUsage Examples:
" Quick fix mapping
nmap <silent> <space>qf <Plug>(coc-fix-current)
" Auto-fix on save
augroup auto_fix
autocmd!
autocmd BufWritePre *.js,*.ts,*.json call CocAction('format')
autocmd BufWritePre * if &filetype != 'markdown' | call CocActionAsync('doQuickfix') | endif
augroup end
" Batch fix all issues in buffer
function! FixAllIssues()
let diagnostics = CocAction('diagnosticList')
for diagnostic in diagnostics
call cursor(diagnostic.lnum + 1, diagnostic.col + 1)
let fixes = CocAction('quickfixes')
if len(fixes) > 0
call CocAction('doCodeAction', fixes[0])
endif
endfor
endfunction
command! FixAll call FixAllIssues()Format code according to language-specific style guides and configuration with support for document and selection formatting.
<Plug>(coc-format)
" Format entire document
" Uses language server formatting provider
" Mode: Normal
<Plug>(coc-format-selected)
" Format selected text only
" Mode: Visual, Normal (with operator)
CocAction('format')
" Format document programmatically
" Returns: boolean - success status
CocAction('formatSelected' [, {mode}])
" Format selection programmatically
" Parameters:
" {mode} - string: visual mode type (optional)
" Returns: boolean - success statusUsage Examples:
" Format mappings
nmap <silent> <space>f <Plug>(coc-format)
xmap <silent> <space>f <Plug>(coc-format-selected)
" Set operator for formatting
nmap <silent> <space>F <Plug>(coc-format-selected)
" Format on save for specific filetypes
augroup format_on_save
autocmd!
autocmd BufWritePre *.js,*.ts,*.json,*.css,*.html call CocAction('format')
augroup end
" Conditional formatting based on file size
function! SmartFormat()
if line('$') > 1000
echo "File too large for formatting"
return
endif
call CocAction('format')
endfunction
nnoremap <silent> <space>sf :call SmartFormat()<CR>Intelligent symbol renaming with scope analysis and cross-file reference updates using language server capabilities.
<Plug>(coc-rename)
" Rename symbol under cursor
" Shows input prompt for new name
" Updates all references across workspace
" Mode: Normal
CocAction('rename')
" Trigger rename programmatically
" Returns: void (shows rename prompt)
CocAction('renameCurrentWord')
" Rename current word specifically
" Alternative interface for rename actionUsage Examples:
" Rename mapping
nmap <silent> <space>rn <Plug>(coc-rename)
" Rename with confirmation
function! ConfirmRename()
let word = expand('<cword>')
let new_name = input('Rename "' . word . '" to: ', word)
if !empty(new_name) && new_name != word
call CocAction('rename', new_name)
else
echo "Rename cancelled"
endif
endfunction
nnoremap <silent> <space>R :call ConfirmRename()<CR>
" Batch rename across files
function! BatchRename(old_pattern, new_pattern)
let files = CocAction('workspaceSymbols', a:old_pattern)
for file in files
execute 'edit ' . file.filename
call CocAction('rename', a:new_pattern)
endfor
endfunction
command! -nargs=* BatchRename call BatchRename(<f-args>)Advanced refactoring operations including extract method, inline variable, move class, and other structural code transformations.
<Plug>(coc-refactor)
" Show available refactoring options
" Context-sensitive refactoring menu
" Mode: Normal
<Plug>(coc-command-repeat)
" Repeat last coc command
" Useful for repeated operations
" Mode: Normal
CocAction('refactor')
" Trigger refactoring programmatically
" Returns: void (shows refactoring menu)
CocAction('repeatCommand')
" Repeat last command programmatically
" Returns: void
CocAction('organizeImport')
" Organize and sort import statements
" Returns: boolean - success status
CocAction('addMissingImports')
" Add missing import statements
" Returns: boolean - success statusUsage Examples:
" Refactoring mapping
nmap <silent> <space>rf <Plug>(coc-refactor)
" Organize imports on save
augroup organize_imports
autocmd!
autocmd BufWritePre *.js,*.ts,*.py call CocAction('organizeImport')
augroup end
" Custom refactoring menu
function! RefactoringMenu()
let actions = ['Extract Method', 'Extract Variable', 'Inline Variable', 'Organize Imports']
let choice = inputlist(['Select refactoring:'] + map(copy(actions), 'v:key + 1 . ". " . v:val'))
if choice == 1
call CocAction('refactor', 'extract')
elseif choice == 2
call CocAction('refactor', 'extractVariable')
elseif choice == 3
call CocAction('refactor', 'inline')
elseif choice == 4
call CocAction('organizeImport')
endif
endfunction
nnoremap <silent> <space>rm :call RefactoringMenu()<CR>Interactive code annotations providing contextual actions and information directly in the editor.
<Plug>(coc-codelens-action)
" Execute code lens action at cursor
" Runs action associated with code lens annotation
" Mode: Normal
CocAction('codeLensAction')
" Execute code lens action programmatically
" Returns: void
CocAction('runCommand', {command})
" Run specific command from code lens
" Parameters:
" {command} - string: command identifierUsage Examples:
" Code lens mapping
nmap <silent> <space>cl <Plug>(coc-codelens-action)
" Toggle code lens display
function! ToggleCodeLens()
if get(g:, 'coc_enable_codelens', 1)
let g:coc_enable_codelens = 0
call CocAction('codeLensAction', 'disable')
echo "Code lens disabled"
else
let g:coc_enable_codelens = 1
call CocAction('codeLensAction', 'enable')
echo "Code lens enabled"
endif
endfunction
nnoremap <silent> <space>tl :call ToggleCodeLens()<CR>Customize formatting behavior through language server settings and coc.nvim configuration options.
" Key formatting configuration options:
"coc.preferences.formatOnSaveFiletypes": string[]
" File types to format automatically on save
"coc.preferences.formatOnType": boolean
" Enable format on type (while typing)
"{language}.format.enable": boolean
" Enable formatting for specific language
"{language}.format.{option}": any
" Language-specific formatting options
"prettier.singleQuote": boolean
"prettier.tabWidth": number
"prettier.semi": boolean
" Prettier-specific options (if using coc-prettier)Usage Examples:
" Comprehensive formatting configuration
{
"coc.preferences.formatOnSaveFiletypes": [
"javascript", "typescript", "json", "css", "html", "python"
],
"coc.preferences.formatOnType": true,
"typescript.format.enable": true,
"typescript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": true,
"python.formatting.provider": "autopep8",
"prettier.singleQuote": true,
"prettier.tabWidth": 2,
"prettier.semi": false
}
" Disable formatting for large files
{
"coc.preferences.maxFileSize": "1MB"
}Advanced multi-cursor editing capabilities for simultaneous edits across multiple locations.
<Plug>(coc-cursors-operator)
" Set operator for multi-cursor selection
" Use with motion commands (e.g., iw, ap)
" Mode: Normal
<Plug>(coc-cursors-range)
" Create cursors for visual selection
" Mode: Visual
<Plug>(coc-cursors-word)
" Select current word for multi-cursor
" Mode: Normal
<Plug>(coc-cursors-position)
" Add cursor at current position
" Mode: Normal
CocAction('cursorsSelect', {bufnr}, {mode}, {type})
" Create cursors programmatically
" Parameters:
" {bufnr} - number: buffer number
" {mode} - string: selection mode
" {type} - string: selection typeUsage Examples:
" Multi-cursor mappings
nmap <silent> <C-c> <Plug>(coc-cursors-position)
nmap <silent> <C-d> <Plug>(coc-cursors-word)
xmap <silent> <C-d> <Plug>(coc-cursors-range)
nmap <C-d> <Plug>(coc-cursors-operator)
" Select all occurrences of word
nnoremap <silent> <space>* :call CocAction('cursorsSelect', bufnr('%'), 'word', 'n')<CR>
" Multi-cursor with search
function! MultiCursorSearch()
let pattern = input('Multi-cursor search: ')
if !empty(pattern)
call CocAction('cursorsSelect', bufnr('%'), 'search', pattern)
endif
endfunction
nnoremap <silent> <space>/ :call MultiCursorSearch()<CR>Semantic text objects for functions, classes, and other code structures using LSP symbol information.
<Plug>(coc-funcobj-i)
" Select inside function/method
" Mode: Visual, Operator-pending
<Plug>(coc-funcobj-a)
" Select around function/method (including signature)
" Mode: Visual, Operator-pending
<Plug>(coc-classobj-i)
" Select inside class/interface/struct
" Mode: Visual, Operator-pending
<Plug>(coc-classobj-a)
" Select around class/interface/struct
" Mode: Visual, Operator-pending
CocAction('selectSymbolRange', {inner}, {visualmode}, {symbolTypes})
" Select symbol range programmatically
" Parameters:
" {inner} - boolean: select inside (true) or around (false)
" {visualmode} - string: current visual mode
" {symbolTypes} - array: symbol types to selectUsage Examples:
" Function text objects
xmap if <Plug>(coc-funcobj-i)
omap if <Plug>(coc-funcobj-i)
xmap af <Plug>(coc-funcobj-a)
omap af <Plug>(coc-funcobj-a)
" Class text objects
xmap ic <Plug>(coc-classobj-i)
omap ic <Plug>(coc-classobj-i)
xmap ac <Plug>(coc-classobj-a)
omap ac <Plug>(coc-classobj-a)
" Custom text object for methods only
function! SelectMethod(inner)
call CocAction('selectSymbolRange', a:inner, visualmode(), ['Method'])
endfunction
xnoremap <silent> im :<C-u>call SelectMethod(v:true)<CR>
onoremap <silent> im :<C-u>call SelectMethod(v:true)<CR>
xnoremap <silent> am :<C-u>call SelectMethod(v:false)<CR>
onoremap <silent> am :<C-u>call SelectMethod(v:false)<CR>