google / vim-codefmt

Vim plugin for syntax-aware code formatting
Apache License 2.0
1.11k stars 114 forks source link

Support multiple formatters on a single buffer #178

Closed TamaMcGlinn closed 3 years ago

TamaMcGlinn commented 3 years ago

I'm trying to run several different formatters on a single buffer when I save it. Something like:

  autocmd FileType cpp AutoFormatBuffer clang-format
  autocmd FileType cpp AutoFormatBuffer copyright

(which in fact only applies the last formatter given) I also tried:

  autocmd FileType cpp AutoFormatBuffer clang-format,copyright

But that doesn't apply either. :help AutoFormatBuffer didn't help me, but surely I'm not the only person who wants to apply two or more formatters?

TamaMcGlinn commented 3 years ago

The workaround is bit ugly, but hopefully it helps anyone coming to this issue in the meantime:

function! ApplyCppFormatters() abort
  execute 'FormatCode copyright'
  if expand('%:e') ==# 'h'
    execute 'FormatCode header_guards'
  endif
  execute 'FormatCode clang-format'
endfunction

augroup autoformat
  autocmd!
  autocmd BufWritePre *.cpp,*.h call ApplyCppFormatters()
augroup END
dbarnett commented 3 years ago

Yes, you're not alone! See #44. I'll merge these and post an update with some more details there.

dbarnett commented 3 years ago
  autocmd BufWritePre *.cpp,*.h call ApplyCppFormatters() | noautocmd write

BTW, isn't noautocmd write redundant since vim's already going to write the file after BufWritePre?

TamaMcGlinn commented 3 years ago

Correct, thank you! I had this because I had a different formatter which wasn't able to accept stdin, so it works on a post-write hook and then needs to write the file again:

autocmd BufWritePost *.ad[sb] Autoformat | noautocmd write