Auto indent / format code for Vim?

To indent the whole file automatically:

gg
=G

Explained:

  • gg - go to beginning of the file
  • G - go to end of the file
  • = - indent

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.


Auto Indent *.sh

Just add the following lines in ~/.vimrc

filetype indent on
set smartindent
autocmd BufRead,BufWritePre *.sh normal gg=G

Tags:

Vim