Friday, November 30, 2007

Shifting

It's often handy to shift blocks of text left and right, and Vim makes it easy. I like to set shiftwidth=1 in my vimrc file so I can have nice fine-grained control over my shifts. First you should define the following snippit (stolen from Vim Tips) in your vimrc:

vnoremap < <gv
vnoremap > >gv

Now highlight a column of text using blockwise visual selection (ctrl-v on Unix platforms, ctrl-q on Windows) and then hit > or <

>>>> (would shift four shiftwidths to the right)

You can also use traditional ex mode to accomplish the same. Go to the first column of a given block and type ma (in normal mode) to set mark a. Go the the end of the block you want to indent, first column, and set mark b by typing mb (in normal mode). Now issue the following ex-command.

:'a, 'b>> (shift two columns to the right)

Search Motions

You can use a search as a motion in conjunction with an operator. Say you have the following sentence:

A quick brown fox jumps over the lazy dog.

Vim (and Vi for that matter...) allow you to do things such as:

y/over (yanks "a quick brown fox jumps" into the default register)

c/over (puts you into insert mode with the sentence "over the lazy dog")

d/lazy (leaves you with the sentence "lazy dog")

etc...

Fast Select All

Want to select an entire file in visual mode very quickly? Try ggVG in normal mode.

Text Objects

Text objects are commands that can be used in combination with an operator or when in visual mode. Basically, you give a command followed by a description and Vim applies it to the relevant text object. Available commands include things like:

aw - a word
iw - inner word
aW - a word (leading and trailing whitespace included)
as - a sentence
etc...

In practice, these allow quick manipulation on the applied block of text. For example, you're in normal mode, and your cursor is positioned in the middle of a word. You type caw and Vim executes "change a word" deleting the existing word and switching to insert mode for you to perform your edit. For the full details on this feature see :help text-objects.

Tuesday, November 20, 2007

Filtering

Sometimes it's helpful to filter your current editing session through an external command. Vim makes this easy to accomplish with the following ex command, :%!command. To filter a file containing strictly numbers through the Unix sort command using numerical comparison, you would :%!sort -u

Friday, November 16, 2007

Mouse Support

I usually try to avoid the mouse for reasons of efficiency; however, there are times when the mouse can actually save you time. A good example of which is resizing windows. Vim 7.x has an option to respect the mouse even when you're not using Gvim. To enable mouse support type :set mouse=a.

Ex Commands

Vim supports tons of ex commands, which can be very useful for efficient editing. You can get a master-list of all the ex commands Vim supports by typing :help holy-grail.