Tabs in Vim

Vim logo

Version 7 of Vim introduced tabs to the editor, and these are a few of my tab-related tips.

Open Files in Tabs

If you want to open multiple files in their own tabs in a new Vim session, use the -p flag on the command line for vim or gvim. For example, to open all files in the current directory, use the following:

vim -p *

When you give Vim multiple files to edit, its default behavior is to use several buffers. If you want to use tabs as the default behavior instead (that is, without typing the -p flag every time), set up a couple shell aliases. For bash, place these in your ~/.bashrc:

alias vim='vim -p'
alias gvim='gvim -p'

Also, Vim will open a maximum of 10 tabs like this by default. To increase that limit to, for example, 50, add the following to your ~/.vimrc:

set tabpagemax=50

Easier Tab Navigation

When you have more than a few tabs open, it can become difficult to navigate them with only the keyboard. You can use {count}gt to go to the count-th tab (starting with 1), but counting them yourself is a waste of time. Placing the tab number on its label solves this problem.

Vim tab labels

Here's how I set a custom tab label:

function! GuiTabLabel()
  " buffer_number[+] buffer_name [(number_windows)]

  " Add buffer number
  let label = v:lnum

  " Add '+' if one of the buffers in the tab page is modified
  let bufnrlist = tabpagebuflist(v:lnum)
  for bufnr in bufnrlist
    if getbufvar(bufnr, "&modified")
      let label .= '+'

  " Append the buffer name
  let label .= ' ' . bufname(bufnrlist[tabpagewinnr(v:lnum) - 1])

  " Append the number of windows in the tab page if more than one
  let wincount = tabpagewinnr(v:lnum, '$')
  if wincount > 1
    let label .= ' (' . wincount . ')'

  return label

set guitablabel=%{GuiTabLabel()}