将以下内容添加到您的.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
如果您希望所有文件类型在保存时自动缩进,我强烈建议不要这样做,请将此挂钩添加到您的.vimrc
:
" Indent on save hook
autocmd BufWritePre <buffer> call Indent()
如果您只希望某些文件类型在保存时自动缩进,我建议这样做,然后按照说明进行操作。假设您希望 C++ 文件在保存时自动缩进,然后创建~/.vim/after/ftplugin/cpp.vim
并将这个钩子放在那里:
" Indent on save hook
autocmd BufWritePre <buffer> call Indent()
任何其他文件类型~/.vim/after/ftplugin/java.vim
也是如此,例如 Java 等。