Nice Tab Navigation in Vim


Making tabs in Vim is annoying. So I wrote a function to make it less annoying.

the code

function! SwitchTab(n) abort

    let l:total_tab_pages = tabpagenr('$')
    " alias for readability
    let l:last_tab_page = tabpagenr('$')

    if a:n == 0
        execute  l:last_tab_page . 'tabnext'
    else
        if l:total_tab_pages < a:n
            tabnew | call termopen($SHELL) | startinsert
        " workaround for  <a-1> not being recognized
        " switch to 1st tab if key pressed
        elseif tabpagenr() == a:n
            execute '1tabnext'
        else
            execute  a:n . 'tabnext'
        endif
    endif
endfunction

nnoremap <silent> <A-1> :call SwitchTab(1)<CR>
nnoremap <silent> <A-2> :call SwitchTab(2)<CR>
nnoremap <silent> <A-3> :call SwitchTab(3)<CR>

" switch to current tab page + 1 (creates new tab or goes to next)
nnoremap <silent> <A-S-n> :call SwitchTab(tabpagenr() + 1)<CR>
" switch to current tab page - 1 (creates new tab or goes to previous)
nnoremap <silent> <A-S-p> :call SwitchTab(tabpagenr() - 1)<CR>

Keeping with (my interpretation of) the UNIX philosophy, we switch to the next tab. If it doesn’t exist, we create a new one.

If we’re at the 1st tab and try to go to the previous one, instead of some pointless error message, it will wrap around to the last one.

Related Posts

e-ink reminisces

Edwin Edwards

Middle School by Bo Burnham

How to Disable Disqus Ads on your Blog

Derivation of Reservoir Sampling

Fun with Python Iterators: Linked Lists Made Easy

Notes for November 11, 2018

Underrated Vim Option: undofile and undodir

Hot Take on Solo Travel: Starve

Alan Perlis