如何告诉Vim在保存前自动缩进



我最近开始在我的研究生级项目中使用Vim。我面临的主要问题是有时签入未缩进的代码。我觉得如果我能创建一个auto-缩进+保存+关闭的快捷方式,那么我的问题就解决了。

我的。vimrc文件:

set expandtab
set tabstop=2
set shiftwidth=2
set softtabstop=2
set pastetoggle=<F2>
syntax on
filetype indent plugin on

有没有办法创建这样的命令快捷方式&覆盖:x(保存+退出).

请告诉我。

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

如果您希望所有文件类型在保存时自动缩进,我强烈建议不要,将此钩子添加到您的.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()

同样适用于任何其他文件类型,例如Java的~/.vim/after/ftplugin/java.vim等等。

我建议首先打开autoindent以避免这个问题。在开发的每个阶段,使用适当缩进的代码要容易得多。

set autoindent

通过:help autoindent读取文档。

但是,=命令将根据文件类型的规则缩进行。您可以创建一个BufWritePre autocmd来对整个文件执行缩进。

我还没有测试过这个,不知道它实际工作得如何:

autocmd BufWritePre * :normal gg=G

阅读:help autocmd以获得有关该主题的更多信息。gg=g分解为:

  • :normal作为普通模式编辑命令执行,而不是作为:ex命令执行
  • gg移动到文件的顶部
  • =缩进到…
  • <
  • G/kbd>…

我真的不推荐这种策略。习惯使用set autoindent代替。在所有文件上定义这个autocmd(如*)可能是不明智的。它只能在某些文件类型上执行:

" Only for c++ files, for example
autocmd BufWritePre *.cpp :normal gg=G

要缩进已经存在的文件,您可以使用快捷方式gg=G(不是命令;只需按g两次,然后=,然后Shift+g),特别是因为你正在使用filetype indent…线。

Vim: gg=G左对齐,不自动缩进

我会选择

autocmd BufWritePre * :normal gg=G``

这样将缩进整个文件并返回到光标最近的位置。

  • 没有尝试添加& lt; C-o>但是double tick是一个强大的解决方案

最新更新