In visual studio, that code :

for(int x=0;x<10;x++)

becomes that code :

for (int x = 0; x < 10; x++)


as soon as you hit enter. I was wondering, is it possible, and if so, how can I make so vim does the same ?

Thanks in advance !


I'm aware of two possible approaches from within Vim.

On the fly formatting

My C and C++ snippets defined in lh-cpp (as abbreviations) and in mu-template+lh-cpp (as more traditional snippets) are expanded according to the current stylistic preferences (through another plugin: lh-style).


  • The correct style is used from the start
  • No external dependences (clang-format)


  • The formatting possibilities won't be as rich as what clang-format offers (indeed, everything has to be rewritten in ... vim script) -- BTW, I haven't implemented extra spaces around semi-colons in lh-style (and I don't see the option in clang-format either... :/)
  • Multiple Vim dependences
  • Depends on a snippet engine which is not the one 99% of Vim users use -- yet my C++ snippets are quite advanced sometimes, and I try to provide as C++ idiomatic snippets as possible

On demand/retroactive formatting

Another approach consists in fixing the style every time some specific keys (or even ENTER, IIRC) are triggered. This is the approach presented by Telno that relies on clang-format.


  • The formatting shall be close to perfection
  • Require a single vim plugin


  • Depends on an external tool
  • The formatting is applied retroactively on code already written

I used the plugin https://github.com/rhysd/vim-clang-format.git and added those lines to my vimrc :

" Clang formater things :
let g:clang_format#style_options = {
            \ "BreakBeforeBraces" : "Allman",
            \ "AccessModifierOffset" : -4,
            \ "AllowShortIfStatementsOnASingleLine" : "true",
            \ "AlwaysBreakTemplateDeclarations" : "true",
            \ "Standard" : "C++11"}

" map to <Leader>cf in C++ code
autocmd FileType c,cpp,objc nnoremap <buffer><Leader>cf:<Cu>ClangFormat<CR>
autocmd FileType c,cpp,objc vnoremap <buffer><Leader>cf :ClangFormat<CR>
" if you install vim-operator-user
autocmd FileType c,cpp,objc map <buffer><Leader>x <Plug>(operator-clang-format)
" Toggle auto formatting:
nmap <Leader>C :ClangFormatAutoToggle<CR>
  • Your spacing is wrong and you're missing a - there: <Leader>cf :<C-u>ClangFormat<CR>. Do you need the <C-u> for the normal mode mapping? Visual mode is the one that adds :'<,'> implicitly... Also, usually you'd use <LocalLeader> for a <buffer> mapping. – filbranden Aug 9 '20 at 15:03

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.