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'
        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'
            execute  a:n . 'tabnext'

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

Random Thought: LC Theorem

I finally have an answer to "who's your favorite singer?"

My Top Tip for Helping People Get Started Programming


Random paper on angles

An Image is Worth 16x16 Words

Random stuff

Lossless Data Compression with Neural Networks by Fabrice Bellard

Downscaling Numerical Weather Models With GANs (My CI 2019 Paper)

Learning Differential Forms and Questions