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.

  • 1
    I think this is a duplicate of vi.stackexchange.com/questions/3968/…. – garyjohn Nov 30 '15 at 22:33
  • 2
    Not sure it will work but you could try the following three lines of code (the second one being indented) : 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
  • @garyjohn Nope, as you can see I tried the approach in the given post. I saw it before and tried the mentioned method. – LastSecondsToLive Nov 30 '15 at 22:41
  • 1
    @LastSecondsToLive I'm really glad it helped you! However, I'm not confident writing an answer on the topic because I don't know why my solution works whereas yours don't. To be honest, I had the same problem as you in the past and found the solution here : stackoverflow.com/a/5264606 Maybe the reason why your code didn't work is because of the order : first the filetype, then the event (not the reverse). But I'm not sure. I would prefer that someone else with more knowledge on the subject writes an answer. But if no one does, and if your question is not marked as a duplicate, I'll try. – saginaw Nov 30 '15 at 22:52
  • 3
    The problem with the original command under " 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, the filetype 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.