After a long time without post on blog, but always colecting ideas, the tip of today touch in a delicated area, code indent. Around all word we found ugly and mall indented codes (except in python :]), and, when working with PHP, this is a case extremely normal and really sucks.
So, one day, I start to search for a batch mode for vim, because for me, reident of PHP files with vim is awesome!. My idea is a single script that launchy vim in batch mode for each file, reindent and save.
Very well, after about 30 minutes of talk in #vim da irc.freenode.net, some people talk about ‘-c’ option, that, for some reason, I not see on vim man pages :. Now let’s tip!
Basically we use -c option (today I know that we can use +<cmd here> too, that is same as :<cmd here>) and I put it in a single script:
#!/bin/bash # usage: script
# ex: script /www/project ".html$|.php$|.inc$|.tpl$" find $1 -type f | egrep "$2" > file_list for file in $( < file_list ); do echo "$(date +'%d/%m/%Y %H:%M:%S') - start indent of $file'" >> log_indentacao vim -c ":normal gg=G" -c :w! -c :q! ---- $file && echo "$(date +'%d/%m/%Y %H:%M:%S') - end indent of '$file'" >> log_indentacao || echo "$(date +'%d/%m/%Y %H:%M:%S') - fail on indent of '$file'" >> log_indentacao done
- Line 4: find for files to indent.
- Line 7 to 10: execute vim to indent inside a for … in loop with some info for you.
This tip is very useful but not works 100% for misc files (PHP+HTML as example). Using vim in this way you can work to convert files from dos to unix, etc, and a lot of posibilities.
About vim mapping, to indent opened files, you can use follow mappings in your .vimrc:
to reindent file noremap mzgg=G`z inoremap mzgg=G`z