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

Sammy Cottrell

Jump or die, dumbass

beats you

kairos

Mechanistic Interpretability and Lean 4

John Arbuthnot

zeno timer trick

WHY ARE YOU SO CALM?! My scooter accident

Beyond strength

The amount of honor to go around is very limited