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 automatically indented when saving , which I highly recommend against , add this hook to your .vimrc :
" Indent on save hook autocmd BufWritePre <buffer> call Indent()
If you want to save only certain types of files automatically , which I recommend , follow the instructions. Suppose you want C ++ files to be automatically indented when saved, then create ~/.vim/after/ftplugin/cpp.vim and put this hook there:
" Indent on save hook autocmd BufWritePre <buffer> call Indent()
The same could be used for any other types of files, i.e. ~/.vim/after/ftplugin/java.vim for Java, etc.
source share