LoginSignup
8
7

More than 5 years have passed since last update.

vimでuncrustifyをいい感じに適用する

Posted at

C/C++やObjective-Cのコードをいい感じに整形してくれるUncrustify、最近気に入ってて使ってます。

んでこれをvimで使おうと思って設定したんだけどなんかいい感じにならない。

例えば外部コマンドを使ってフォーマットするformatprgを使って

:set formatprg=uncrustify\ -c\ ~/misc/uncrustify.cfg\ -l\ CPP\ --no-backup\ 2>/dev/null

こんな感じで設定して、gqで現在の行をフォーマット、ggVGで全選択してからgqで全体をフォーマットできます。
だけどuncrustifyは前後関係を見てうまいこと整形してくれるから1行だけフォーマットなんてしないし、ggVGで全選択するとさっきいた行まで戻るのがめんどい。

もっといい感じにできないかなーと思って探してたら、ありました。
Using Uncrustify with VIM - Stack Overflow
このAnswerのコード。フォーマットしたあと位置を復元してくれるので、めっちゃ便利。
これだ!と思ってちょろっと改変して、言語を自動検出して自動的に言語毎の設定でフォーマットするようにしました。
以下のコード

"----------------------------------------
" uncrustify
"----------------------------------------
" see http://stackoverflow.com/questions/12374200/using-uncrustify-with-vim/15513829#15513829

" 例: Shift-Fでコードのフォーマットを行う.
nnoremap <S-f> :call UncrustifyAuto()<CR>

" 例: 保存時に自動フォーマット
" autocmd BufWritePre <buffer> :call UncrustifyAuto()

" uncrustifyの設定ファイル
let g:uncrustify_cfg_file_path = '~/.uncrustifyconfig'

" uncrustifyでフォーマットする言語
let g:uncrustify_lang = ""
autocmd FileType c let g:uncrustify_lang = "c"
autocmd FileType cpp let g:uncrustify_lang = "cpp"
autocmd FileType java let g:uncrustify_lang = "java"
autocmd FileType objc let g:uncrustify_lang = "oc"
autocmd FileType cs let g:uncrustify_lang = "cs"

" 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

" 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 '.
                \shellescape(fnamemodify(g:uncrustify_cfg_file_path, ':p')))
endfunction

function! UncrustifyAuto()
    if g:uncrustify_lang != ""
        call Uncrustify(g:uncrustify_lang)
    endif
endfunction

うまいことでけた!満足
他にもっと良い感じにできるよーて人がいれば教えて下さい

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7