Image of the glider from the Game of Life by John Conway
Skip to content

Search and Indent in Vim

Vim is my beloved editor of choice. Not because I am opinionated about Vi versus Emacs, but because vi was the editor that I picked up, and I have been using it since. I would probably come to enjoy Emacs as well, if I were to take the time to use it.

Anyway, I don't want to start that discussion here. What I do want to discuss is a couple handy tricks that I learned today, while coding. If you're a Vim user, you will probably find these helpful as well.

First, searching with super star. That is, while in normal mode (not visual or insert mode), while pressing the "*" key, you will search for more words in the text file that you cursor is over. Put your cursor over the word "for" in your python source file, and press the "*" key to see all other "for" loops in the file. Frankly, this will save me a ton of typing, as I don't have to reach for ":/" anymore. Nice.

However, "*" only searches forward. Perhaps you want to search in reverse. Easy. The hash "#" character comes in handy for that. It behaves exactly the same way as super star, that is searching for more words beneath your cursor, just towards the beginning of the file, rather than the end. Very nice.

Oh, we're not done with searching yet, though. Find yourself in a lot of nested parens? Unsure which beginning paren matches its ending mate? "%" will become your best friend. "%" not only matches married parens, but it works on braces and brackets as well. Also, it will match multiline C-style comments "/* */". Sweet.

Last, indenting. Being a web developer, I hate taking an existing HTML document that hasn't been properly indented, and trying to parse through it finding beginning and ending tags. So, I would indent the file as appropriate going into insert mode, and pressing the following keystrokes in order: home, tab, down, home, tab, down, etc. As obvious, you are pressing at least 3 keystrokes for every line that needs indenting, not to mention, you need to be in insert mode, and if only indenting one line, this can be a pain. Even worse, if you have to reverse indent. Well, fortunately, there is a quick solution, all of which can be done in normal mode.

">>" will indent the line the cursor is on forward.
"< <" will indent the line the cursor is on backward. "." will repeat the previous edit. So, lets take a look. In normal mode, how would my previous keystrokes look: >>, down, ., down, ., down, ., etc. Only 2 keystrokes per line, and I never need to leave normal mode. So, you can see that this would come in handy:

>>... will indent the line forward 3 times.
<<..... will indent the line backward 3 times. Ooooh I'm in love. I can't tell you how much time this will save me, as well as the saved number of keystrokes. Searching and indenting with as little typing as possible. Hope this was helpful to some.

{ 11 } Comments