Sign up ×

I'm trying to use Vim more and more when I can. One of my biggest grip between Vim and an IDE like Aptana is the ability to auto indent.

Is there a means of auto formatting code (HTML, CSS, PHP) so it is properly indented?

If so how do you install this into vim? I don't understand plugins very much. I tried reviewing this thread and it confused me more: How to change vim auto-indent behavior?

share|improve this question
Could you clarify what language you are trying to indent? I would expect that if it's supported by vim already it should already auto-indent without further effort. If not, you should be able to get a plugin. –  Edd Steel Sep 1 '11 at 22:37
ideally Html/css and php –  chrisjlee Sep 1 '11 at 23:50

4 Answers 4

up vote 10 down vote accepted

To indent the whole file automatically:



  • g - go to
  • gg - go to beginning of the file
  • G - go to end of the file
share|improve this answer
Could you break it down? What is g typically by itself? and =G? –  chrisjlee Sep 2 '11 at 5:47
@Chris see the edit –  takeshin Sep 2 '11 at 5:53
Thank you! I appreciate the effort. –  chrisjlee Sep 2 '11 at 5:53
Nice hint, I never knew this. However, it does a rubbish job with bash. –  Sparhawk Aug 8 '14 at 4:49

I don't know about auto-formatting existing code, but if you are writing code and need auto indent:

  • :set autoindent (or :set ai) will turn on auto-indent
  • Ctrl-d to un-indent (AKA outdent) your code
  • Tab or spaces to indent -- I personally use tab
  • :set tabwidth=4 (or :set tw=4) will control how many spaces a tab should indent code
  • The >> command will indent the current line. If you prefix it by a number, say 4>> then it will indent 4 lines, starting with the current line.
  • Likewise the << command will un-indent a line

I hope this gives you a good start.

share|improve this answer
To auto-indent existing code, use ={motion} in normal mode -- e.g. =G will indent all code from the current line to the end of the file. == will indent the current line. –  Edd Steel Sep 1 '11 at 22:36
also make sure indent plugins are being loaded (e.g. with :filetype indent on) –  jw013 Sep 2 '11 at 0:50

Auto Indent *.sh

Just add following lines in ~./vimrc

filetype indent on
set smartindent
autocmd BufRead,BufWritePre *.sh normal gg=G
share|improve this answer

This plugin makes it easier to perform formatting on your code. It integrates external formatters, and has a fallback on vim's indent functionality.

Also, notice the difference between formatting and indenting. Indenting only corrects the whitespace before every line, while formatting also deals with any other thing, such as whitespace around operators etc.

share|improve this answer

Your Answer


