Vim for rails developers: indenting code
I use Vim mainly to write code and, in order to maintain some sanity, I like my code indented. I like to have a mapping for indenting the entire file I’m editing. My first attempt to solve this simple problem was:
map <silent> <F5> gg=G<CR>
imap <silent> <F5> <Esc> gg=G<CR>
When I pressed <f5>, both in normal and insert mode, I got all the current file indented. The process is very simple, basically it works in the following way:
- gg
go to first line - =G
indent until G that is the motion parameter of the = command.
Well this was cool. It just worked fine and made all the current file indented. I was used to the just mentioned mappings for a long time but, recently, I was annoyed by a little issue this mapping had. Practically, when I pressed <f5> I lost the cursor position and I didn’t like that. So, yesterday I reached the WTF point and decided to solve this problem. After a few attempts with the jumplist and with the changelist, I found a solution I really like.
Eventually, I came up with the following:
map <silent> <F5> mmgg=G`m^
imap <silent> <F5> <Esc> mmgg=G`m^
that works exactly as the prevoius solution but, in addition, it brings the cursor back where it was before you pressed <f5>. Now I use the mark command, and the sequence is:
- mm
Put the current position in the m mark. - gg
As the previous solution. - =G
Here too. - `m
Bring the cursor to the position stored in the m mark. - ^
Go to the first non-blank character of the line.
So, nothing magic but useful. And I’d be glad to see other possible solutions.
Update:
Thanks to a comment below, the above mentioned mapping can be refactored in the following way:
map <silent> <F5> mmgg=G'm
imap <silent> <F5> <Esc> mmgg=G'm
Indeed, I’ve already updated my vimrc.