Jump to existing tab using fzf in Vim

fzf is a powerful console tool which can help you a lot during daily development. And what’s really awesome is it’s also integated in Vim. fzf.vim provides a set of ready-made commands and this wiki page gives basic tutorial about how to write your own fzf function in vimrc and many useful snippets.

For a long time, I’m looking for a quick way to jump to one tab when opening a lot tabs in Vim. I thought fzf may do that like how it does to open file or open a buffer. However, I could not find such solution after google. So, I implemented it in vimrc as below:

" Jump to tab: <Leader>t
function tabName(n)
    let buflist = tabpagebuflist(a:n)
    let winnr = tabpagewinnr(a:n)
    return fnamemodify(bufname(buflist[winnr - 1]), ':t')

function! s:jumpToTab(line)
    let pair = split(a:line, ' ')
    let cmd = pair[0].'gt'
    execute 'normal' cmd

nnoremap <silent> <Leader>t :call fzf#run({
\   'source':  reverse(map(range(1, tabpagenr('$')), 'v:val." "." ".tabName(v:val)')),
\   'sink':    function('<sid>jumpToTab'),
\   'down':    tabpagenr('$') + 2
\ })<CR>

fzf#run is the core of Vim integration. It takes a list of string itmes from source and shows them in fzf windows. One or multiple items are chosen by you and sent as parameter to sink which usually is a vim function to do whatever you want to do with the chosen items.

down gives the position and size of the list pane. up, left or right can be used.

Here, source gets a list of strings whose format is tabnumber tabname. The tab name can be got by function tabName. jumpToTab at sink receives the selected item, gets the tab number using split and then execute command :normal 2gt if the tab number is 2.

So after pressing <Leader>t, a window containing a list of filenames of all tabs pops up to let user choose the tab to jump.