在 VIM 中使用 Uncrustify [英] Using Uncrustify with VIM

查看:17
本文介绍了在 VIM 中使用 Uncrustify的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my vimrc I call Uncrustify by this command:

%!uncrustify -l CPP -c D:\uncrustify\default.cfg

在一些代码之后,我收到一个 Windows 致命错误:

After that on some code I get a Windows Fatal error:

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

But when I call uncrustify on the same code in the console using the -f option, there is no error.

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

How can I change my vimrc to avoid such errors in the future? What can invoke this error?

推荐答案

为了将 Uncrustify 与 Vim 正确集成,请将以下内容添加到您的 .vimrc 中:

In order to integrate Uncrustify with Vim properly, 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

" 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++ 的设置,并在其中添加以下行:

Now you can either map this function (Uncrustify) to a combination of keys or you could do the convenient trick that I use. Create a file ~/.vim/after/ftplugin/cpp.vim where you can override any Vim settings particularly for C++ and add the following line there:

autocmd BufWritePre <buffer> :call Uncrustify('cpp')

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

This basically adds a pre-save hook. Now when you save the file with C++ code it will be automatically formatted by Uncrustify utilizing the configuration file you supplied earlier.

例如,对于 Java 也可以这样做:在 ~/.vim/after/ftplugin/java.vim 中添加:

For example, the same could be done for Java: in ~/.vim/after/ftplugin/java.vim add:

autocmd BufWritePre <buffer> :call Uncrustify('java')

你说得对.

注意:这里展示的所有内容都经过我的充分测试和每天使用.

NOTE: Everything presented here is well-tested and used every day by me.

这篇关于在 VIM 中使用 Uncrustify的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆