Last Updated: February 25, 2016
·
2.713K
· trotha01

Vim auto-indent on save

To auto-indent files on save, add this to your vimrc:

augroup autoindent
    au!
    autocmd BufWritePre * :normal migg=G`i
augroup End

If you would like to do this only for certain files, say scss files, you can change the regex:

autocmd BufWritePre * :normal migg=G`i

To

autocmd BufWritePre *.scss :normal migg=G`i

How this works:

  • autocmd BufWritePre specifies this is a command to be executed automatically before writing the buffer to file.
  • * matches the files to run this auto-command on. If we want only text files, use *.txt, or only html files, use *.html, etc.
  • :normal says to execute the following command in normal mode
  • mi puts a mark on the current line, and saves it in "i".
  • gg goes to the top of the file
  • = is the indentation command, a motion is needed following the = command
  • G tells the = command to auto-indent to the bottom of the file
  • `i says to go to the mark stored in i
  • augroup and au! are for good practive

To see more on marks:

http://vim.wikia.com/wiki/Using_marks

To see more on auto-commands:

http://vimdoc.sourceforge.net/htmldoc/autocmd.html
http://learnvimscriptthehardway.stevelosh.com/chapters/12.html

To see why this is wrapped in augroup:

http://learnvimscriptthehardway.stevelosh.com/chapters/14.html