Wednesday 17 September 2008

Vim feature that makes editing easier

Vim, along with the Emacs is the best free text editing choice in the Linux and OSS world. It has tons of features and improvements that can make text editing a lot easier and faster. I'll mention some of its features on the blog that I use the most.
This post is not a beginners tutorial or guide and I'm assuming that the reader has basic Vim knowledge such as entering/exiting insert mode, basic movement keys etc.
So let's get started.

One word replacement

Let's assume we have this line of text in our file:

Nikola Tesla was tha greatest engineer in tha world


Assume that the Vim is in the command mode and that the cursor is on the letter 'w' of the word 'world' also. This line has two typos in it an that is the 'tha' words. We need to substitute that typos with the right word 'the'. In the Vim editor that is done easily with the simple ex command:

:s/tha/the/g


First letter s of this command means substitute. Expression after the first slash presents the text we need to replace, and the second expression after the second slash presents the text to substitute with. Finally the letter 'g' in this command after the last slash says vim to replace every 'tha' occurrence in the line with the right word 'the'.
But what if we use the above command on this kinda sentence?

Nikola Tesla was tha greatest engineer in thailand


First three letters of the word 'thailand' will be substituted as well; the word 'thailand' is also a typo here cause it needs to start with the capital letter, but ignore that for now. The problem can be fixed with regular expressions that can be used in vim during a text search. Regular expressions are complex topic and I'm not gonna explain them here in depth. Let's just say that \< and \> can be used to mark start and end end of the word respectively, and our ex command would look like this:

:s/\<tha\>/the/g


This command works only on the line in witch cursor resides. To substitute each and every bad occurrence with new in the file this command is used:

:%s/bad/new/g


Read the '%' character as: do the commands on the whole file.
Substitutions that needs to be done from line 1 to 10 for example is used like this:

:1,10s/bad/new/g


Isn't Vim great?

No comments: