How to tell Vim to auto-indent before saving

auto-indent, vim

Solution

Add the following to your `.vimrc`:

" Restore cursor position, window position, and last search after running a
" command.
function! Preserve(command)
  " Save the last search.
  let search = @/

  " Save the current cursor position.
  let cursor_position = getpos('.')

  " Save the current window position.
  normal! H
  let window_position = getpos('.')
  call setpos('.', cursor_position)

  " Execute the command.
  execute a:command

  " Restore the last search.
  let @/ = search

  " Restore the previous window position.
  call setpos('.', window_position)
  normal! zt

  " Restore the previous cursor position.
  call setpos('.', cursor_position)
endfunction

" Re-indent the whole buffer.
function! Indent()
  call Preserve('normal gg=G')
endfunction

If you want all file types to be auto-indented on save, which I strongly recommend against, add this hook to your `.vimrc`:

" Indent on save hook
autocmd BufWritePre <buffer> call Indent()

If you want only certain file types to be auto-indented on save, which I recommend, then follow the instructions. Lets say you want C++ files to be auto-indented on save, then create `~/.vim/after/ftplugin/cpp.vim` and put this hook there:

" Indent on save hook
autocmd BufWritePre <buffer> call Indent()

The same would go for any other file types, i.e. `~/.vim/after/ftplugin/java.vim` for Java and so on.

Problem

I have recently started using Vim for my graduate level projects. The main problem I face is that sometimes I check in unindented code. I feel if I can somehow create a shortcut of auto-indent+save+close then that should solve my problem. My .vimrc file: ``` set expandtab set tabstop=2 set shiftwidth=2 set softtabstop=2 set pastetoggle=<F2> syntax on filetype indent plugin on ``` Is there any way to create such command shortcuts & override with `:x` (save+exit). Please let me know.

Original source

Related problems