Tuesday, February 7, 2012

Commenting Multiple Lines in Vim

I do a bit of programming in Fortran and periodically I find myself wanting to comment out a block of code for whatever reason. In Vim this is relatively easy. Just highlight the lines you would like to comment and type:
:s/^/\!
The s is for subtitute, the ^ character designates the front of each line, and the exclamation (which has to be escaped with the \ character) is the comment character for Fortran. This can be replaced by any comment character the language you may use requires, but not all characters will need to be escaped like the exclamation does. Similarly to uncomment selected lines:
:s/^/\!/
 Now, I find this tedious and frustrating to type in and/or remember. To streamline the commenting and uncommenting process, I make use of abbreviations. Essentially, you define an abbreviation and what should be substituted for that abbreviation. When you type the abbreviation, Vim will automatically substitute it for you. The syntax is as follows:
:ab <abbreviation> <unabbreviated substitution>
where ':ab' is the command  (you type this in the Vim window), <abbreviation> is what you type, and <unabbreviated substitution> in what replaces the abbreviation. Also note that spaces in the unabbreviated substitution are acceptable. You also do not inclue the '<>' characters.

Here is how it would work with commenting multiple lines:
:ab com s/^/\!
:ab ucom s/^/\!/
Now, all you need to type in once the lines are selected is,
:com
:ucom
to comment or uncomment those lines.

This method will only work for the particular instance of Vim that you are working in, meaning you would need to type this at the start of each session. An easier method would be to place the commands in your .vimrc or .gvimrc file, without the leading colon, and they will be defined every time you start up Vim.

No comments:

Post a Comment