I have the VIM Clang Format Plugin and I would like to format my code every time I save it.
This is in my current .vimrc:
" map to <Leader>cf in C++ code
autocmd FileType c,cpp,objc nnoremap <buffer><Leader>cf :<C-u>ClangFormat<CR>
autocmd FileType c,cpp,objc vnoremap <buffer><Leader>cf :ClangFormat<CR>
" Format on save
autocmd BufWritePost *
\ autocmd FileType c,cpp,objc ClangFormat
The first two lines work great. I can hit leader + cf in normal mode
and the code gets formatted. My problems are the last two lines.
My Intention:
I hit save (:wc) and BufWritePost * is triggered.
ClangFormat is only executed if the filetype is c, cpp, or objc (just as in the first two lines).
Well, it doesn't work and I can't find my mistake. Any help is appreciated.
augroup FormatOnSave
(first line),autocmd FileType c,cpp,objc :autocmd! FormatOnSave BufWritePost <buffer> :ClangFormat
(2nd line),augroup END
(3rd line). – saginaw Nov 30 '15 at 22:33" Format on save
is that the outer autocommand is not triggered until after your file is saved, and when it is triggered, it simply sets up another autocommand that will be triggered when the filetype is detected, but the filetype is detected soon after the file is loaded into the buffer. By the time you save the file, the FileType event has long passed. However, when the BufWritePost event occurs, thefiletype
option has been set, so you could test that its value is one of c, cpp, or objc. – garyjohn Dec 1 '15 at 0:47