or run

tessl search
Log in

Version

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

docs

index.md
tile.json

tessl/npm-coc-nvim

tessl install tessl/npm-coc-nvim@0.0.0

LSP based intellisense engine for neovim & vim8.

formatting.mddocs/intelligence/

Formatting [Basic]

Complexity: Basic | Category: Intelligence

Common Tasks: Format document | Format selection | Auto-format on save | Trim whitespace

Document and range formatting using language server formatters.

Table of Contents

  • Common Tasks
  • Key Mappings
  • CocAction API
  • Helper Functions
  • Buffer Variables
  • Configuration
  • Usage Examples
  • Error Handling
  • Troubleshooting
  • See Also

Common Tasks

Format Entire Buffer

nmap <leader>f <Plug>(coc-format)

Format the whole file using configured formatter.

Format Selected Range

xmap <leader>f <Plug>(coc-format-selected)

Format only the selected text.

Auto-Format on Save

autocmd BufWritePre *.ts,*.js call CocAction('format')

Automatically format file before saving.

Format with Function Call

:call CocAction('format')

Programmatically trigger formatting.

Key Mappings

<Plug>(coc-format)

<Plug>(coc-format)

Format entire current buffer using the configured formatter.

Example:

nmap <leader>f <Plug>(coc-format)

<Plug>(coc-format-selected)

<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 API

format

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

formatSelected

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>

Helper Functions

coc#on_enter()

coc#on_enter()
" Returns: string

Notify 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>"

Buffer Variables

b:coc_trim_trailing_whitespace

let b:coc_trim_trailing_whitespace = 1

Enable 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 = 1

b:coc_trim_final_newlines

let b:coc_trim_final_newlines = 1

Enable 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 = 1

Configuration

Formatting 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
}

Language-Specific Formatting

{
  "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"]
}

Usage Examples

Basic Formatting Setup

" 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>

Auto-Format on Save

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

Format with Feedback

function! FormatBuffer() abort
  let view = winsaveview()
  echo "Formatting..."
  call CocAction('format')
  call winrestview(view)
  echo "Formatted"
endfunction

nnoremap <silent> <leader>ff :call FormatBuffer()<CR>

Format Selection with Preview

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>

Trim Whitespace

" 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 Options

" 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>

Conditional Formatting

" 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>

Format on Type

" 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 Multiple Files

" 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 *.js

Format Range by Line Numbers

function! 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,20FormatLines

Toggle Auto-Format

let 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

Format with Prettier

" 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

" 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>

Preserve Cursor Position

" 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 Specific Language

" 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

Format Check

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

Error Handling

Formatter Not Available

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-prettier

Formatting Fails Silently

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

Format Changes Wrong Parts

Problem: 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
}

Troubleshooting

Formatting is slow

Problem: Format operation takes a long time.

Solutions:

  1. Check language server performance: :CocCommand workspace.showOutput
  2. Disable format-on-type: "coc.preferences.formatOnType": false
  3. Format only on save instead of continuously
  4. Consider faster formatter alternatives (e.g., prettier vs eslint)

Auto-format conflicts with other plugins

Problem: Multiple formatters try to format the same file.

Solutions:

  1. Disable other format plugins:
    let g:autoformat_enabled = 0
  2. Prioritize coc.nvim formatter:
    autocmd BufWritePre * if exists(':CocFormat') | CocFormat | endif
  3. Configure specific filetypes in coc-settings.json

Formatting breaks code

Problem: After formatting, code no longer works or compiles.

Solutions:

  1. Verify formatter configuration matches project style
  2. Check for .prettierrc or .editorconfig files
  3. Disable auto-format and format manually to test
  4. Update formatter extension: :CocUpdate
  5. Use project-local formatter version

Range formatting doesn't work

Problem: Formatting selection has no effect.

Solutions:

  1. Check if language server supports range formatting:
    " Some servers only support full document formatting
  2. Use visual selection properly: V for line-wise, v for character-wise
  3. Try formatting entire document instead
  4. Verify formatter supports partial formatting

Format-on-save not triggering

Problem: Auto-format doesn't work when saving files.

Solutions:

  1. Check autocmd is registered:
    :autocmd BufWritePre
  2. Verify filetype matches configuration:
    :set filetype?
  3. Check coc-settings.json configuration:
    {
      "coc.preferences.formatOnSaveFiletypes": ["javascript", "typescript"]
    }
  4. Ensure coc.nvim is running: :CocInfo

See Also

  • Code Actions - Auto-fix and organize imports
  • Configuration - Formatter settings
  • Extensions - Install formatter extensions
  • Diagnostics - View formatting errors
  • Workspace - Multi-file formatting