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

Use of emphasis in speech

Generating a lot of language data with a theorem prover

"Litany Against Fear" in Present Tense

When it's time to party we will party hard

these are people who died

divine carrot

the frog

what it’s like to get nail phenolization

Why 0 to the power of 0 is 1

Lines and Points are Circles