Using Uncrustify with VIM

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

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')

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.

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

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

You got the point.

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


I have found the placing the following code into your .vimrc to be sufficient:

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)

Note this does assume that you have "uncrustify" binary in your $PATH.

It also assumes your configure file is ~/.uncrustify.cfg however you can change that by modifiying the g:uncrustifyCfgFile variable.

To call run

:Uncrustify

It also works on ranges (which was what promoted me to make this function). Visual selection example:

:'<,'>UncrustifyRange

I have only tired it with C, CPP and JAVA (I assume others will work as well)

Tags:

Vim

Uncrustify