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:

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 did not 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 previous 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:

So, nothing magical but useful. And I’d be glad to see other possible solutions.

Update:

Thanks to a comment, 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.