Friday, May 9, 2008

Vim Tip: Mutliple windows and vimdiff

Vim Tip: Mutliple windows and vimdiff

Using multiple windows in VIM is a great way to do side-by-side editing, comparison and cut-and-paste (yank-and-put). Unlike other editors, you can do all this with your hands on home row. Learning to use multiple windows will also help you make better use of the built in :help, and also makes it easy to learn a powerful file comparison tool: vimdiff.

To open a file in a new window, use either ":split filename" or ":vsplit filename". vsplit is nice when you can devote an extra-wide window to VIM. If you leave of the filename argument, the split will be performed on the file you are already editing.

Navigating between windows is simple. Every window command starts with a "ctrl-w". Then you can move between windows with h,j,k,l or the arrow keys as you would normally move between lines. Some other useful window commands are:
ctrl-w c - Close this window
ctrl-w o - close all Other windows (mnemonic - Only)
ctrl-w 5+ - increase this window size by 5 lines
ctrl-w 5- - decrease this window size by 5 lines

With these window commands, we're ready to use "vimdiff". Start vimdiff from the command line:
% vimdiff a.txt b.txt
Vim will open the two files in "vsplit" mode, and will highlight differences between the two. I have attached an example of this. There are just a few more commands that are needed to be proficient with vimdiff:
do - (diff-obtain) obtain differences from other window into this one
dp - (diff-put) push differences in current window to the other window
zo - open a block of folded text