使用Uncrustify与VIM

use*_*416 13 vim uncrustify

在我的vimrc中,我通过以下命令调用Uncrustify:

%!uncrustify -l CPP -c D:\uncrustify\default.cfg
Run Code Online (Sandbox Code Playgroud)

在那之后的一些代码我得到Windows致命错误:

但是当我使用-f选项在控制台中对相同代码调用uncrustify时,没有错误.

如何更改我的vimrc以避免将来出现此类错误?什么可以调用此错误?

Ale*_*aev 17

为了正确地将Uncrustify与Vim集成,请将以下内容添加到您的.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

" Specify path to your Uncrustify configuration file.
let g:uncrustify_cfg_file_path =
    \ shellescape(fnamemodify('~/.uncrustify.cfg', ':p'))

" Don't forget to add Uncrustify executable to $PATH (on Unix) or 
" %PATH% (on Windows) for this command to work.
function! Uncrustify(language)
  call Preserve(':silent %!uncrustify'
      \ . ' -q '
      \ . ' -l ' . a:language
      \ . ' -c ' . g:uncrustify_cfg_file_path)
endfunction
Run Code Online (Sandbox Code Playgroud)

现在你可以将这个函数(Uncrustify)映射到一个键组合,或者你可以做我使用的方便技巧.创建一个文件~/.vim/after/ftplugin/cpp.vim,您可以在其中覆盖任何Vim设置,特别是对于C++,并在那里添加以下行:

autocmd BufWritePre <buffer> :call Uncrustify('cpp')
Run Code Online (Sandbox Code Playgroud)

这基本上添加了一个预保存挂钩.现在,当您使用C++代码保存文件时,Uncrustify将使用您之前提供的配置文件自动对其进行格式化.

例如,可以为Java做同样的事情:~/.vim/after/ftplugin/java.vim添加:

autocmd BufWritePre <buffer> :call Uncrustify('java')
Run Code Online (Sandbox Code Playgroud)

你明白了.

注意:此处提供的所有内容都经过了充分测试,并且每天都由我使用.