Wednesday, January 20, 2010

Vim tabbed browsing settings

I've recently switched over from Windows 7 to Linux (Ubuntu), and I quite enjoy it. I have only on rare occasion booted up my Windows partition to play Half Life 2.

As for my text editor, I was originally using gedit, but now I've switched over to using vim. I found the shortcuts to be confusing at first but I'm slowly getting used to them. Very recently, I learned about how to open up multiple files and switch between them in a Vim session. You can use the command ':e filename' to open a file into a new "buffer" within your Vim session. To switch between the open files (buffers), you can use the commands :bn (buffer next), and :bp (buffer previous). You can close an open file with the command :bd (buffer delete).

Among many other settings, Vim lets you map/remap keys to commands. So, after typing :bp, :bn, and :bd for several days, I figured I would map a few keys so that manipulating the Vim buffers would feel just like using a tabbed program like Google Chrome or Notepad++.

Here are the settings if you wish to use them yourself:

noremap <silent> <C-Pageup> :bp<CR>
noremap <silent> <C-Pagedown> :bn<CR>
noremap <silent> <C-W> :bd <CR>

Ctrl-PageUp is always used to go left in a tab bar, so I have assigned it to open the previous buffer. Ctrl-PageDown is always used to go right in a tab bar, so I have assigned it to open the next buffer. Ctrl-W is always used to close a tab, so I have assigned it to delete the current buffer.

If you do not know how to set Vim settings, or what these settings mean, read on. To set these settings persistently (so that they are present every time you open vim), you can place them in your ~/.vimrc file. If that file doesn't exist, create it and paste those three lines in there. If it exists, just append them to the end of the file (and make sure these key mappings don't conflict with any existing key mappings).

To explain the settings:
  • noremap this is the command which tells vim we are performing a key-mapping. This particular command means that Vim will attempt to make the key mapping work in all modes other than INSERT. Meaning that it will work when you are in command mode, visual mode, and operator pending mode.

  • <silent> means that Vim will execute the command without printing it on the command line (at the bottom of the screen) or putting it in your command history.

  • <C-Pageup> this is the keyboard command we want to map. C stands for Ctrl.

  • :bp this is the Vim command we want to execute when the key command (e.g. Ctrl-Pageup) is pressed.

  • <CR> We add this for convenience. This executes a carriage return right after our command. Without this, we would have to press Enter after pushing our keyboard command (e.g. Ctrl-PageUp) to have the Vim command get executed.
I hope to have sped up your lives a little bit with these settings.