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

Ame*_*Jah 8 vim auto-indent

我最近开始将vim用于我的研究生水平项目.主要问题,我有时会检查非缩进代码.我觉得如果我能以某种方式使自动缩进+保存+关闭的快捷方式然后这应该解决我的问题.

我的.vimrc文件:

set expandtab
set tabstop=2
set shiftwidth=2
set softtabstop=2
set pastetoggle=<F2>
syntax on
filetype indent plugin on
Run Code Online (Sandbox Code Playgroud)

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

请告诉我.

Ale*_*aev 17

将以下内容添加到您的.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
Run Code Online (Sandbox Code Playgroud)

如果您希望所有文件类型在保存时自动缩进,我强烈建议您这样做,请将此挂钩添加到您的.vimrc:

" Indent on save hook
autocmd BufWritePre <buffer> call Indent()
Run Code Online (Sandbox Code Playgroud)

如果您希望在保存时仅保存某些文件类型,我建议您按照说明进行操作.假设您希望C++文件在保存时自动缩进,然后创建~/.vim/after/ftplugin/cpp.vim并将此挂钩放在那里:

" Indent on save hook
autocmd BufWritePre <buffer> call Indent()
Run Code Online (Sandbox Code Playgroud)

对于任何其他文件类型~/.vim/after/ftplugin/java.vim也是如此,例如对于Java等.


Mic*_*ski 5

我建议首先打开autoindent以避免这个问题.这是很多容易在开发的每个阶段有适当的缩进代码工作.

set autoindent
Run Code Online (Sandbox Code Playgroud)

通过阅读文档:help autoindent.

但是,该=命令将根据文件类型的规则缩进行.您可以创建BufWritePreautocmd以对整个文件执行缩进.

我没有对此进行测试,也不知道它的实际效果如何:

autocmd BufWritePre * :normal gg=G
Run Code Online (Sandbox Code Playgroud)

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

  • :normal作为普通模式编辑命令而不是:ex命令执行
  • gg 移到文件的顶部
  • = 缩进直到......
  • G ...文件的结尾.

我真的不推荐这个策略.习惯于使用set autoindent.autocmd在所有文件上定义它可能是不明智的(如同*).它只能在某些文件类型上完成:

" Only for c++ files, for example
autocmd BufWritePre *.cpp :normal gg=G
Run Code Online (Sandbox Code Playgroud)

  • 不要在脚本中使用`normal`而不使用bang,在这种情况下你写这里时,`gg = G`没有必要分解. (2认同)
  • @SimonBudin,您可以使用 `magg=G\`a` 它将在“a”寄存器上创建一个标记,重新缩进文件,然后带您返回标记“a” (2认同)