Vim Recipes Typing Abbreviating Common Strings

Abbreviating Common Strings

Problem

You regularly have to enter the same text, but don't want to.

For instance, if you use Vim to write e-mail you may often mention the URL of your website. Instead of typing http://example.com/ every time, which is both annoying and error prone, you want to enter, say, myUrl and have it replaced with the address.

Solution

Use Vim's abbreviations feature to map concise abbreviations to frequently entered text.

To create the aforementioned abbreviation we use the :iabbrev command: :iabbrev myUrl http://example.com/. To use it, type the name of the abbreviation (myUrl in this case) and then hit <Space> or <Enter>. The name of the abbreviation is replaced with its payload.

The syntax for defining abbreviations is :iabbrev name payload, where name is the text you want replaced, and payload is what it should be replaced with.

Discussion

The abbreviation feature is smart enough not to expand abbreviation names that occur as part of another word, but its telepathic functionality is suboptimal. Useful abbreviation names are easy to type, but will not appear in normal text. The convention I use is to prefix them with my, then uppercase the first letter. (If you use a programming language that prefers "camelCased" variable names, you may see clashes. Either stop using Java®, or disable abbreviations for the source code.)

You can also abbreviate commands. For instance, if you wanted to type :docs instead of :help you could map one to the other with :cabbr docs help.

I suggest keeping your abbreviations in an abbreviations file in $VIM. You can then source it from your vimrc. For example, you can create the file by running vim $VIM/abbreviations, then populate it with your abbreviations:

iabbrev myUrl http://example.com/
iabbrev myEmail user@example.com

Then in vimrc just write source $VIM/abbreviations.