Skip to content

Instantly share code, notes, and snippets.

@techntools
Forked from Konfekt/file_preview.vim
Created March 11, 2025 15:34
Show Gist options
  • Save techntools/0cfbdf743b2cdda6fba68d01843ddb9f to your computer and use it in GitHub Desktop.
Save techntools/0cfbdf743b2cdda6fba68d01843ddb9f to your computer and use it in GitHub Desktop.
preview file under cursor in Vim using ctags as fallback
" Adapted from https://github.com/drmikehenry/vimfiles/blob/e5c369dadde340ead7438b0c4937c3f470acf524/vimrc#L3239
"
" With --extra=+f in ~/.ctags respectively --extras=+f in
" ~/.config/ctags/default.ctags, filenames are tags, too, so
" the following mappings will work when a file isn't in the path.
"
" For automatic (C)tags generation, see either
" https://tbaggery.com or https://bolt80.com/gutentags/
nnoremap <silent> gf :<c-u>call <sid>gf("gf")<cr>
nnoremap <silent> <c-w>f :<c-u>call <sid>gf("\<lt>c-w>f")<cr>
nnoremap <silent> <c-w>gf :<c-u>call <sid>gf("\<lt>c-w>gf")<cr>
nmap <silent> <C-w><C-f> <C-w>f
nnoremap <silent> gF :<c-u>call <sid>gf("gF")<cr>
nnoremap <silent> <c-w>F :<c-u>call <sid>gf("\<lt>c-w>F")<cr>
nnoremap <silent> <c-w>gF :<c-u>call <sid>gf("\<lt>c-w>gF")<cr>
function! s:gf(map)
try
if a:map ==# 'gf'
let fname = findfile(expand('<cfile>'), &path)
if !filereadable(fname) | throw 'PEDIT' | endif
exe 'pedit' fname
else
exe 'normal!' a:map
endif
catch /^Vim\%((\a\+)\)\=:E447\|^PEDIT$/
try
if a:map ==# "gf"
exe 'ptjump' expand('<cfile>:t')
elseif a:map ==# "gF"
exe 'tjump' expand('<cfile>:t')
elseif a:map ==# "\<c-w>f" || a:map ==# "\<c-w>F"
exe 'stjump' expand('<cfile>:t')
elseif a:map ==# "\<c-w>gf" || a:map ==# "\<c-w>gF"
exe 'tab stjump' expand('<cfile>:t')
endif
catch /^Vim\%((\a\+)\)\=:E\%(426\|433\)/
echomsg 'Error: neither path nor tag for this file name found!'
endtry
endtry
endfunction
" with set foldopen+=jumps the <c-w>Pzv<c-w>p to open the fold is not needed
nnoremap [i :<c-u>psearch! \C<c-r><c-w><CR><c-w>Pzv<c-w>p
nnoremap ]i :<c-u>.+1,$psearch! \C<c-r><c-w><CR><c-w>Pzv<c-w>p
" :tjump opens a menu if multiple tags match whereas :tag does not
nnoremap <c-]> g<C-]>
xnoremap <c-]> g<C-]>
" open tag in preview window
nnoremap g] <c-w>g}<c-w>Pzv<c-w>p
xnoremap g] <c-w>g}<c-w>Pzv<c-w>p
" (forcefully) close preview window and jump back
nnoremap <silent><expr> g[ ':<c-u>silent! pclose<cr>:silent! '..v:count1..'pop<cr>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment