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.

code-navigation.mddocs/navigation/

Code Navigation [Basic]

Complexity: Basic | Category: Navigation | Keywords: definition, references, jump, goto

Common Tasks: Jump to definition | Find references | View implementations

Navigate to definitions, declarations, implementations, type definitions, and references using LSP.

Table of Contents

  • Common Tasks
  • Choosing the Right API
  • Key Mappings
  • CocAction API
  • Global Functions
  • Utility Functions
  • Global Variables
  • Autocmd Events
  • Tag Integration
  • Configuration
  • Examples
  • Error Handling
  • Troubleshooting
  • Performance Tips
  • See Also

Common Tasks

Jump to Definition

gd
" Or programmatically:
call CocAction('jumpDefinition')

Most common navigation task - goes to where symbol is defined.

Find All References

gr
" Or with options:
let refs = CocAction('references', {'includeDeclaration': v:false})

Find everywhere a symbol is used.

Go to Implementation

gi
" Particularly useful for interfaces/abstract methods

View Type Definition

gy
" See the type definition of a variable

Open in Split

call CocAction('jumpDefinition', 'split')
" Opens definition in split window

Choosing the Right API

Need to Jump to Definition?

Decision Tree:

Want to jump? → Use <Plug>(coc-definition)
  ↓ Need split? → Use CocAction('jumpDefinition', 'split')
  ↓ Need tab? → Use CocAction('jumpDefinition', 'tabe')
  ↓ Custom logic? → Use CocAction('definitions') then coc#util#jump()

Need References?

Decision Tree:

Just navigate? → Use <Plug>(coc-references)
  ↓ Exclude declarations? → Use <Plug>(coc-references-used)
  ↓ Need the list? → Use CocAction('references')
  ↓ Need count? → len(CocAction('references'))

Multiple Results?

When there are multiple definitions/references:

  • g:coc_enable_locationlist = 1: Opens location list automatically
  • g:coc_enable_locationlist = 0: Opens quickfix list
  • Access via g:coc_jump_locations variable

Key Mappings

<Plug>(coc-definition)

<Plug>(coc-definition)

Jump to definition(s) of symbol under cursor. Opens in current window or location list if multiple.

Example:

nmap <silent> gd <Plug>(coc-definition)

Behavior:

  • Single result: Jumps directly
  • Multiple results: Opens location list
  • No results: Shows error message

<Plug>(coc-declaration)

<Plug>(coc-declaration)

Jump to declaration(s) of symbol under cursor. Declaration is where the symbol is declared (e.g., function prototype), while definition is where it's implemented.

Example:

nmap <silent> gD <Plug>(coc-declaration)

Use Case: In C/C++, jump to header declaration from implementation.

<Plug>(coc-implementation)

<Plug>(coc-implementation)

Jump to implementation(s) of interface or abstract method. Particularly useful in object-oriented languages.

Example:

nmap <silent> gi <Plug>(coc-implementation)

Use Case:

  • Jump from interface to implementing classes
  • Find concrete implementations of abstract methods

<Plug>(coc-type-definition)

<Plug>(coc-type-definition)

Jump to type definition of symbol under cursor. Shows where the type itself is defined.

Example:

nmap <silent> gy <Plug>(coc-type-definition)

Use Case:

let user: User = getUser();  // Cursor on 'user' → jumps to User interface

<Plug>(coc-references)

<Plug>(coc-references)

Jump to references of symbol under cursor. Includes declarations.

Example:

nmap <silent> gr <Plug>(coc-references)

Includes:

  • All places where symbol is used
  • The declaration itself
  • Import statements

<Plug>(coc-references-used)

<Plug>(coc-references-used)

Jump to references excluding declarations. Only shows actual usage.

Example:

nmap <silent> gu <Plug>(coc-references-used)

Use Case: Find where function is actually called, excluding its definition.

CocAction API

jumpDefinition

CocAction('jumpDefinition', [openCommand])

Jump to definition with optional open command.

Parameters:

  • openCommand: Optional command to open location
    • 'edit': Current window (default)
    • 'split': Horizontal split
    • 'vsplit': Vertical split
    • 'tabe': New tab
    • 'drop': Reuse existing window if open

Example:

" Jump in current window
call CocAction('jumpDefinition')

" Jump in split
call CocAction('jumpDefinition', 'split')

" Jump in new tab
call CocAction('jumpDefinition', 'tabe')

" Reuse window if already open
call CocAction('jumpDefinition', 'drop')

Returns: Nothing (performs jump as side effect)

definitions

CocAction('definitions')
" Returns: list

Get definition locations without jumping. Useful for custom navigation logic.

Returns: List of location objects with:

  • uri: File URI ('file:///path/to/file.js')
  • range: Position range (LSP format, 0-indexed)
  • targetUri: Target file URI (if different)
  • targetRange: Target range

Example:

let defs = CocAction('definitions')
echo 'Found ' . len(defs) . ' definitions'

for def in defs
  let file = substitute(def.uri, 'file://', '', '')
  let line = def.range.start.line + 1
  echo file . ':' . line
endfor

Use Cases:

  • Count definitions
  • Filter definitions by path
  • Custom jump logic
  • Preview definitions without jumping

jumpDeclaration

CocAction('jumpDeclaration', [openCommand])

Jump to declaration with optional open command.

Parameters:

  • openCommand: Same options as jumpDefinition

Example:

call CocAction('jumpDeclaration', 'vsplit')

jumpImplementation

CocAction('jumpImplementation', [openCommand])

Jump to implementation with optional open command.

Example:

call CocAction('jumpImplementation')

" Or in split
call CocAction('jumpImplementation', 'split')

Use Case: Navigate from interface to concrete classes.

jumpTypeDefinition

CocAction('jumpTypeDefinition', [openCommand])

Jump to type definition with optional open command.

Example:

call CocAction('jumpTypeDefinition')

Use Case: See type definition while debugging type issues.

jumpReferences

CocAction('jumpReferences', [openCommand])

Jump to references with optional open command.

Example:

call CocAction('jumpReferences')

" Open in new tab
call CocAction('jumpReferences', 'tabe')

jumpUsed

CocAction('jumpUsed', [openCommand])

Jump to references excluding declarations.

Example:

call CocAction('jumpUsed')

Use Case: Find actual usage, not definitions.

declarations

CocAction('declarations')
" Returns: list

Get declaration locations without jumping.

Returns: List of location objects (same format as definitions)

implementations

CocAction('implementations')
" Returns: list

Get implementation locations without jumping.

Example:

let impls = CocAction('implementations')
if len(impls) == 0
  echo "No implementations found"
else
  echo len(impls) . " implementation(s) found"
endif

typeDefinitions

CocAction('typeDefinitions')
" Returns: list

Get type definition locations without jumping.

references

CocAction('references', [options])
" Returns: list

Get reference locations without jumping.

Parameters:

  • options: Optional dictionary with:
    • includeDeclaration: Include declaration in results (default: true)

Returns: List of location objects.

Example:

" With declarations
let refs = CocAction('references')

" Without declarations (usage only)
let refs = CocAction('references', {'includeDeclaration': v:false})

echo 'Found ' . len(refs) . ' references'

Global Functions

CocLocations()

CocLocations(id, method, [...])
" Returns: any

Query LSP locations synchronously. Advanced API for direct LSP communication.

Parameters:

  • id: Language server ID (e.g., 'tsserver', 'pylance')
  • method: LSP method name (e.g., 'textDocument/definition')
  • ...: Additional arguments for the LSP method

Returns: Result from LSP method.

Example:

let result = CocLocations('tsserver', 'textDocument/definition')

Use Case: Direct LSP communication for custom integrations.

CocLocationsAsync()

CocLocationsAsync(id, method, [...])

Query LSP locations asynchronously. Non-blocking version.

Example:

call CocLocationsAsync('tsserver', 'textDocument/references')

Utility Functions

coc#util#jump()

coc#util#jump(cmd, filepath, [line, col])

Jump to a specific location in a file. Low-level utility for custom navigation.

Parameters:

  • cmd: Open command ('edit', 'split', 'vsplit', 'tabe')
  • filepath: File path (absolute or relative)
  • line: Optional line number (1-based, Vim format)
  • col: Optional column number (1-based, Vim format)

Example:

" Jump to file
call coc#util#jump('edit', '/path/to/file.js')

" Jump to line and column
call coc#util#jump('edit', '/path/to/file.js', 42, 10)

" Open in split
call coc#util#jump('split', '/path/to/file.js', 42)

" Open in new tab
call coc#util#jump('tabe', 'src/main.js', 100, 5)

Use Case: Custom navigation logic after getting locations from API.

coc#util#jumpTo()

coc#util#jumpTo(line, character)

Jump to position in current buffer. Uses LSP format (0-indexed).

Parameters:

  • line: Line number (0-indexed, LSP format)
  • character: Character position (0-indexed, LSP format)

Example:

" Jump to line 10, column 5 (LSP format)
call coc#util#jumpTo(9, 4)

" Note: LSP uses 0-indexing, Vim uses 1-indexing
" Line 10 in Vim = line 9 in LSP

Global Variables

g:coc_enable_locationlist

let g:coc_enable_locationlist = 1

Use location list for multiple jump targets. When disabled, uses quickfix list instead.

Type: Number Default: 1 Values:

  • 1: Use location list (buffer-local)
  • 0: Use quickfix list (global)

Example:

" Use quickfix instead of location list
let g:coc_enable_locationlist = 0

Behavior:

  • Location list: Per-window, doesn't affect other windows
  • Quickfix list: Global, shared across all windows

g:coc_jump_locations

g:coc_jump_locations

Runtime variable containing last jump locations.

Type: List (read-only) Structure: List of location objects

Example:

if exists('g:coc_jump_locations')
  echo 'Last jump had ' . len(g:coc_jump_locations) . ' locations'

  " Access first location
  if len(g:coc_jump_locations) > 0
    let loc = g:coc_jump_locations[0]
    echo 'First location: ' . loc.filename . ':' . loc.lnum
  endif
endif

Autocmd Events

User CocLocationsChange

autocmd User CocLocationsChange {command}

Triggered when location list is updated after a jump operation.

When Fired:

  • After definition jump with multiple results
  • After references search
  • After implementation search
  • Any time g:coc_jump_locations is populated

Example:

autocmd User CocLocationsChange call HandleLocations()

function! HandleLocations() abort
  let count = len(get(g:, 'coc_jump_locations', []))
  echo 'Found ' . count . ' locations'

  " Auto-open location list for multiple results
  if count > 1
    lopen
  endif
endfunction

Tag Integration

CocTagFunc()

CocTagFunc(pattern, flags, info)
" Returns: list or null

Tag function for Vim's tagfunc option. Integrates LSP definitions with Vim's tag system.

Parameters:

  • pattern: Tag pattern to search
  • flags: Tag search flags
  • info: Tag search info

Returns: List of tag matches or null.

Setup:

" Use coc.nvim for tag lookups
set tagfunc=CocTagFunc

Benefits:

  • Ctrl-] uses LSP definitions
  • Ctrl-t returns from LSP jumps
  • Tag stack integration
  • Works with existing Vim tag commands

Example:

set tagfunc=CocTagFunc

" Now Ctrl-] jumps to LSP definition
" Ctrl-t returns from jump
" :tag <name> searches LSP symbols

Configuration

Navigation settings in coc-settings.json:

{
  "coc.preferences.jumpCommand": "edit",
  "coc.preferences.currentFunctionSymbolAutoUpdate": true,
  "suggest.detailField": "preview"
}

Available Settings:

  • jumpCommand: Default command for jumps ("edit", "split", "vsplit", "tabe")
  • currentFunctionSymbolAutoUpdate: Auto-update current function in statusline

Examples

Basic Navigation Setup

" Standard navigation mappings
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gi <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)

" Custom jump commands
nnoremap <silent> <leader>gd :call CocAction('jumpDefinition', 'vsplit')<CR>
nnoremap <silent> <leader>gt :call CocAction('jumpDefinition', 'tabe')<CR>

" Navigate declarations
nmap <silent> gD <Plug>(coc-declaration)

Smart Definition Jump

" Jump to definition in split based on window size
function! SmartDefinition() abort
  let width = winwidth(0)
  if width > 160
    call CocAction('jumpDefinition', 'vsplit')
  elseif width > 80
    call CocAction('jumpDefinition', 'split')
  else
    call CocAction('jumpDefinition')
  endif
endfunction

nnoremap <silent> gd :call SmartDefinition()<CR>

Count References

function! CountReferences() abort
  let refs = CocAction('references')
  let total = len(refs)

  let refs_only = CocAction('references', {'includeDeclaration': v:false})
  let usage_count = len(refs_only)

  echo 'Total references: ' . total . ' (used: ' . usage_count . ')'
endfunction

nnoremap <silent> <leader>rc :call CountReferences()<CR>

Navigate with Breadcrumbs

" Track navigation history
let g:nav_stack = []

function! PushLocation() abort
  let pos = [bufnr('%'), line('.'), col('.')]
  call add(g:nav_stack, pos)
endfunction

function! PopLocation() abort
  if len(g:nav_stack) == 0
    echo "Navigation stack empty"
    return
  endif

  let pos = remove(g:nav_stack, -1)
  execute 'buffer ' . pos[0]
  call cursor(pos[1], pos[2])
endfunction

" Push before jumping
nnoremap <silent> gd :call PushLocation()<CR><Plug>(coc-definition)
nnoremap <silent> <C-o> :call PopLocation()<CR>

Custom Reference List

" Build custom location list from references
function! CustomReferenceList() abort
  let refs = CocAction('references')
  let qflist = []

  for ref in refs
    let uri = ref.uri
    let filepath = substitute(uri, 'file://', '', '')
    let range = ref.range

    call add(qflist, {
      \ 'filename': filepath,
      \ 'lnum': range.start.line + 1,
      \ 'col': range.start.character + 1,
      \ 'text': 'Reference'
      \ })
  endfor

  call setqflist(qflist)
  copen
endfunction

nnoremap <silent> <leader>rl :call CustomReferenceList()<CR>

Error Handling

No Definition Found

" Check if definition exists before jumping
function! SafeDefinitionJump() abort
  let defs = CocAction('definitions')

  if len(defs) == 0
    echohl WarningMsg
    echo "No definition found"
    echohl None
    return
  endif

  call CocAction('jumpDefinition')
endfunction

nnoremap <silent> gd :call SafeDefinitionJump()<CR>

Multiple Definitions

" Handle multiple definitions explicitly
function! HandleMultipleDefinitions() abort
  let defs = CocAction('definitions')

  if len(defs) == 0
    echo "No definition found"
  elseif len(defs) == 1
    call CocAction('jumpDefinition')
  else
    echo len(defs) . " definitions found - opening location list"
    call CocAction('jumpDefinition')
    " Location list opens automatically
  endif
endfunction

LSP Not Ready

" Wait for LSP before jumping
function! WaitForLSP() abort
  if !get(g:, 'coc_service_initialized', 0)
    echo "Waiting for coc.nvim to initialize..."
    return v:false
  endif
  return v:true
endfunction

function! SafeJump() abort
  if !WaitForLSP()
    return
  endif
  call CocAction('jumpDefinition')
endfunction

Troubleshooting

Jump Commands Not Working

Problem: gd or other jump commands do nothing.

Solutions:

  1. Check LSP is running: :CocInfo
  2. Verify mapping exists: :nmap gd
  3. Check language server supports navigation: See :CocCommand workspace.showOutput
  4. Ensure buffer is attached: CocAction('ensureDocument')

No Results Found

Problem: "No definition/reference found" messages.

Solutions:

  1. Verify cursor is on a symbol (not whitespace or comment)
  2. Check language server is working: :CocList services
  3. Try restarting LSP: :CocRestart
  4. Check if symbol is in workspace: Might be in external library

Location List Not Opening

Problem: Multiple results don't show location list.

Solutions:

  1. Check setting: let g:coc_enable_locationlist = 1
  2. Verify event fires: Add debug autocmd
  3. Try quickfix: let g:coc_enable_locationlist = 0

Wrong File Opens

Problem: Jump goes to wrong location.

Solutions:

  1. Check file URIs: May have URI prefix issues
  2. Verify workspace root: Wrong root can cause incorrect paths
  3. Check g:coc_uri_prefix_replace_patterns if using remote dev

Tag Stack Integration Issues

Problem: Ctrl-t doesn't work after LSP jump.

Solutions:

  1. Ensure tagfunc is set: set tagfunc=CocTagFunc
  2. Use :tag command instead of <Plug> mappings
  3. Check Vim version supports tagfunc (Vim 8.1.1228+)

Performance Tips

Large Projects

" Limit reference search scope for performance
let refs = CocAction('references', {
  \ 'includeDeclaration': v:false,
  \ 'maxResults': 100
  \ })

Async Operations

" Use async for non-blocking navigation
call CocActionAsync('jumpDefinition')

" Or for getting results:
call CocLocationsAsync('tsserver', 'textDocument/references')

Cache Considerations

  • LSP servers cache symbol information
  • First navigation may be slower (building index)
  • Subsequent navigations are faster
  • Restart LSP to rebuild cache if stale: :CocRestart

See Also

  • Symbols & Outline - Browse document and workspace symbols
  • Call Hierarchy - View function call trees
  • Workspace - Workspace-wide symbol search
  • Hover & Signatures - View documentation without jumping
  • List Interface - Alternative fuzzy-search navigation
  • Cursor Navigation - Low-level cursor position APIs