在我的vimrc中,我使用以下命令调用Uncrustify:
%!uncrustify -l CPP -c D:\uncrustify\default.cfg在此之后,在一些代码上,我得到了一个Windows致命错误:
但是,当我在控制台中使用-f选项对相同的代码调用uncrustify时,没有出现错误。
如何更改我的vimrc以避免将来出现此类错误?是什么导致了这个错误?
发布于 2013-03-20 09:44:19
为了将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现在,您可以将此函数(Uncrustify)映射到键的组合,也可以使用我使用的方便的技巧。创建一个~/.vim/after/ftplugin/cpp.vim文件,您可以在其中覆盖任何Vim设置,特别是针对C++的设置,并在其中添加以下行:
autocmd BufWritePre <buffer> :call Uncrustify('cpp')这基本上增加了一个保存前的钩子。现在,当您使用C++代码保存该文件时,Uncrustify将利用您先前提供的配置文件自动格式化该文件。
例如,可以对Java:在~/.vim/after/ftplugin/java.vim中添加:
autocmd BufWritePre <buffer> :call Uncrustify('java')你说对了。
注:这里展示的所有东西都经过了良好的测试,并且每天都会被我使用。
发布于 2020-07-17 17:05:16
我发现将以下代码放入.vimrc中就足够了:
let g:uncrustifyCfgFile = '~/.uncrustify.cfg'
function! UncrustifyFunc(options) range
exec a:firstline.','.a:lastline.'!uncrustify '.a:options
\.' -c '.g:uncrustifyCfgFile.' -q -l '.&filetype
endfunction
command! -range=% UncrustifyRange <line1>,<line2>call UncrustifyFunc('--frag')
command! Uncrustify let s:save_cursor = getcurpos()
\| %call UncrustifyFunc('')
\| call setpos('.', s:save_cursor)注意:这确实假设您的$PATH中有"uncrustify“二进制文件。
它还假设您的配置文件是~/.uncrustify.cfg,但是您可以通过修改g:uncrustifyCfgFile变量来更改它。
调用run
:Uncrustify它也适用于范围(这就是促使我做这个函数的原因)。视觉选择示例:
:'<,'>UncrustifyRange我只对C、CPP和JAVA感到厌烦(我认为其他语言也可以)。
发布于 2021-01-28 04:37:23
除了@Alexander Shukaev的答案之外,如果检测到错误,添加以下代码将检查uncrustify配置的正确性,而不是自动格式化:
let output = system('uncrustify -q -c ' . a:cfgfile)
if v:shell_error != 0
echo output
endif
return v:shell_error
endfunction
" Don't forget to add Uncrustify executable to $PATH (on Unix) or
" %PATH% (on Windows) for this command to work.
function! Uncrustify(language)
if CheckUncrustifyCfg(g:uncrustify_cfg_file_path)
echo "Config file" g:uncrustify_cfg_file_path "has errors"
echo "No formatting will be performed"
return
endif
call Preserve(':silent %!uncrustify'
\ . ' -q '
\ . ' -l ' . a:language
\ . ' -c ' . g:uncrustify_cfg_file_path)
endfunctionhttps://stackoverflow.com/questions/12374200
复制相似问题