tessl install tessl/npm-coc-nvim@0.0.0LSP based intellisense engine for neovim & vim8.
Complexity: Basic | Category: Intelligence
Common Tasks: Format document | Format selection | Auto-format on save | Trim whitespace
Document and range formatting using language server formatters.
nmap <leader>f <Plug>(coc-format)Format the whole file using configured formatter.
xmap <leader>f <Plug>(coc-format-selected)Format only the selected text.
autocmd BufWritePre *.ts,*.js call CocAction('format')Automatically format file before saving.
:call CocAction('format')Programmatically trigger formatting.
<Plug>(coc-format)Format entire current buffer using the configured formatter.
Example:
nmap <leader>f <Plug>(coc-format)<Plug>(coc-format-selected)Format selected range. Works as operator in normal mode or with visual selection.
Example:
" As operator
nmap <leader>f <Plug>(coc-format-selected)
" Visual mode
xmap <leader>f <Plug>(coc-format-selected)CocAction('format')Format the current buffer using the language server or configured formatter.
Example:
nnoremap <silent> <leader>ff :call CocAction('format')<CR>
" Auto-format on save
autocmd BufWritePre *.ts,*.tsx,*.js,*.jsx call CocAction('format')CocAction('formatSelected', [mode])Format selected range.
Parameters:
mode: Visual mode indicator ('v', 'V', or 'x')Example:
" Format visual selection
xnoremap <silent> <leader>f :call CocAction('formatSelected', visualmode())<CR>
" Format current line
nnoremap <silent> <leader>fl :call CocAction('formatSelected', 'line')<CR>coc#on_enter()
" Returns: stringNotify coc.nvim that Enter was pressed. Handles format-on-enter functionality.
Returns: Key sequence string for insert mode.
Example:
inoremap <silent><expr> <CR> coc#pum#visible() ? coc#pum#confirm()
\ : "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"let b:coc_trim_trailing_whitespace = 1Enable trimming trailing whitespace on save for current buffer.
Type: Number
Default: 0
Example:
" Enable for specific filetypes
autocmd FileType javascript,typescript let b:coc_trim_trailing_whitespace = 1let b:coc_trim_final_newlines = 1Enable trimming final newlines on save for current buffer.
Type: Number
Default: 0
Example:
" Enable for all files
autocmd BufWritePre * let b:coc_trim_final_newlines = 1Formatting settings in coc-settings.json:
{
"coc.preferences.formatOnSaveFiletypes": [
"javascript",
"typescript",
"json",
"html",
"css"
],
"coc.preferences.formatOnType": false,
"coc.preferences.trimTrailingWhitespace": true,
"coc.preferences.trimFinalNewlines": true
}{
"javascript.format.enable": true,
"typescript.format.enable": true,
"json.format.enable": true,
"prettier.enable": true,
"prettier.singleQuote": true,
"prettier.semi": false,
"prettier.tabWidth": 2,
"eslint.format.enable": true,
"eslint.autoFixOnSave": true,
"python.formatting.provider": "black",
"python.formatting.blackArgs": ["--line-length", "100"]
}" Format whole file
nmap <leader>f <Plug>(coc-format)
" Format selection
xmap <leader>f <Plug>(coc-format-selected)
nmap <leader>f <Plug>(coc-format-selected)
" Quick format shortcut
nnoremap <silent> <C-f> :call CocAction('format')<CR>" Format on save for specific filetypes
autocmd BufWritePre *.ts,*.tsx,*.js,*.jsx,*.json call CocAction('format')
" Format using configuration
function! s:FormatOnSave() abort
" Get filetypes from config
let filetypes = coc#util#get_config('coc.preferences.formatOnSaveFiletypes')
if index(filetypes, &filetype) >= 0
call CocAction('format')
endif
endfunction
autocmd BufWritePre * call s:FormatOnSave()function! FormatBuffer() abort
let view = winsaveview()
echo "Formatting..."
call CocAction('format')
call winrestview(view)
echo "Formatted"
endfunction
nnoremap <silent> <leader>ff :call FormatBuffer()<CR>function! FormatSelection() abort
let saved_view = winsaveview()
let start = line("'<")
let end = line("'>")
echo "Formatting lines " . start . "-" . end . "..."
call CocAction('formatSelected', visualmode())
call winrestview(saved_view)
echo "Selection formatted"
endfunction
xnoremap <silent> <leader>f :<C-u>call FormatSelection()<CR>" Enable trimming for specific filetypes
augroup TrimWhitespace
autocmd!
autocmd FileType javascript,typescript,python let b:coc_trim_trailing_whitespace = 1
autocmd FileType javascript,typescript,python let b:coc_trim_final_newlines = 1
augroup END
" Manual trim function
function! TrimWhitespace() abort
let saved_view = winsaveview()
keeppatterns %s/\s\+$//e
call winrestview(saved_view)
echo "Trailing whitespace removed"
endfunction
command! TrimWhitespace call TrimWhitespace()" Format with custom options
function! FormatWithOptions() abort
" Save current options
let saved_tabstop = &tabstop
let saved_shiftwidth = &shiftwidth
" Set formatting options
setlocal tabstop=2
setlocal shiftwidth=2
" Format
call CocAction('format')
" Restore options
let &tabstop = saved_tabstop
let &shiftwidth = saved_shiftwidth
echo "Formatted with custom options"
endfunction
nnoremap <silent> <leader>fo :call FormatWithOptions()<CR>" Only format if formatter is available
function! SmartFormat() abort
if CocHasProvider('formatProvider')
call CocAction('format')
echo "Formatted"
else
echo "No formatter available for " . &filetype
" Fall back to Vim's built-in formatting
normal! gg=G
endif
endfunction
nnoremap <silent> <leader>f :call SmartFormat()<CR>" Enable format on type for specific characters
function! FormatOnType() abort
" This is typically configured in coc-settings.json
" but can be toggled programmatically
call coc#config('coc.preferences.formatOnType', v:true)
echo "Format on type enabled"
endfunction
function! DisableFormatOnType() abort
call coc#config('coc.preferences.formatOnType', v:false)
echo "Format on type disabled"
endfunction
command! FormatOnTypeEnable call FormatOnType()
command! FormatOnTypeDisable call DisableFormatOnType()" Format all files in current directory
function! FormatAllFiles(pattern) abort
let files = glob(a:pattern, 0, 1)
let count = 0
for file in files
execute 'edit ' . file
if CocHasProvider('formatProvider')
call CocAction('format')
write
let count += 1
endif
endfor
echo count . " files formatted"
endfunction
command! -nargs=1 FormatAll call FormatAllFiles(<q-args>)
" Usage: :FormatAll *.jsfunction! FormatRange(start, end) abort
" Save cursor position
let saved_view = winsaveview()
" Select range
execute 'normal! ' . a:start . 'GV' . a:end . 'G'
" Format selection
call CocAction('formatSelected', 'V')
" Restore cursor
call winrestview(saved_view)
echo "Lines " . a:start . "-" . a:end . " formatted"
endfunction
command! -range FormatLines call FormatRange(<line1>, <line2>)
" Usage: :10,20FormatLineslet g:auto_format_enabled = 1
function! ToggleAutoFormat() abort
if g:auto_format_enabled
let g:auto_format_enabled = 0
autocmd! AutoFormat
echo "Auto-format disabled"
else
let g:auto_format_enabled = 1
augroup AutoFormat
autocmd!
autocmd BufWritePre *.ts,*.js,*.tsx,*.jsx call CocAction('format')
augroup END
echo "Auto-format enabled"
endif
endfunction
command! ToggleFormat call ToggleAutoFormat()
nnoremap <silent> <leader>tf :ToggleFormat<CR>
" Initialize auto-format group
augroup AutoFormat
autocmd!
autocmd BufWritePre *.ts,*.js,*.tsx,*.jsx call CocAction('format')
augroup END" Ensure Prettier is used for formatting
function! FormatWithPrettier() abort
" Check if coc-prettier is installed
if index(CocAction('loadedExtensions'), 'coc-prettier') < 0
echo "coc-prettier not installed"
return
endif
call CocAction('runCommand', 'prettier.formatFile')
echo "Formatted with Prettier"
endfunction
nnoremap <silent> <leader>fp :call FormatWithPrettier()<CR>" Format and save in one command
function! FormatAndSave() abort
call CocAction('format')
write
echo "Formatted and saved"
endfunction
command! W call FormatAndSave()
nnoremap <silent> <leader>w :call FormatAndSave()<CR>" Format while preserving exact cursor position
function! FormatPreserveCursor() abort
" Save position
let saved_view = winsaveview()
let saved_line = line('.')
let saved_col = col('.')
" Format
call CocAction('format')
" Restore position
call winrestview(saved_view)
call cursor(saved_line, saved_col)
endfunction
nnoremap <silent> <leader>F :call FormatPreserveCursor()<CR>" Format using specific language formatter
function! FormatWithLanguage(lang) abort
let saved_ft = &filetype
execute 'setfiletype ' . a:lang
call CocAction('format')
execute 'setfiletype ' . saved_ft
endfunction
command! -nargs=1 FormatAs call FormatWithLanguage(<q-args>)
" Usage: :FormatAs javascript" Check if formatting would make changes
function! FormatCheck() abort
let before = getline(1, '$')
let saved_view = winsaveview()
call CocAction('format')
let after = getline(1, '$')
if before == after
echo "No formatting changes needed"
else
echo "File was formatted"
endif
call winrestview(saved_view)
endfunction
command! FormatCheck call FormatCheck()Problem: Format command has no effect or shows error.
Solutions:
" Check if formatter provider exists
if CocHasProvider('formatProvider')
echo "Formatter available"
else
echo "No formatter for " . &filetype
endif
" Check language server status
:CocInfo
" Verify extension is installed
:CocList extensions
" Install formatter extension (e.g., coc-prettier)
:CocInstall coc-prettierProblem: Format command runs but doesn't change code.
Solutions:
" Check for errors in output
:CocCommand workspace.showOutput
" Verify file is saved (some formatters require saved files)
:w
" Try manual formatting with feedback
function! FormatWithError() abort
try
call CocAction('format')
echo "Formatted successfully"
catch
echo "Format error: " . v:exception
endtry
endfunctionProblem: Formatter modifies code incorrectly or unexpectedly.
Solutions:
" Check formatter configuration
:CocConfig
" Verify filetype is correct
:set filetype?
" Use specific formatter
" In coc-settings.json:
{
"prettier.onlyUseLocalVersion": true,
"prettier.requireConfig": true
}
" Disable problematic formatter
{
"eslint.format.enable": false
}Problem: Format operation takes a long time.
Solutions:
:CocCommand workspace.showOutput"coc.preferences.formatOnType": falseProblem: Multiple formatters try to format the same file.
Solutions:
let g:autoformat_enabled = 0autocmd BufWritePre * if exists(':CocFormat') | CocFormat | endifProblem: After formatting, code no longer works or compiles.
Solutions:
.prettierrc or .editorconfig files:CocUpdateProblem: Formatting selection has no effect.
Solutions:
" Some servers only support full document formattingV for line-wise, v for character-wiseProblem: Auto-format doesn't work when saving files.
Solutions:
:autocmd BufWritePre:set filetype?{
"coc.preferences.formatOnSaveFiletypes": ["javascript", "typescript"]
}:CocInfo