EDIT: Here's something that might solve the issue.
It's really a template of a possible solution (not actually tested).
function! ReindentMyCpp()
mkview!
execute 'normal! :nnoremap == :%!clang-format -style=file2g$' . "\r"
execute 'normal zz'
loadview
endfun
autocmd FileType cpp ReindentMyCpp()
BEFORE EDIT:
Here's some code that keeps the folds when you leave a buffer and restores it when you come back.
" save folds states in a file 'view'
set viewoptions=folds,cursor
autocmd BufWinLeave *.* mkview!
autocmd BufWinEnter *.* silent loadview
This works well, and might somehow be adapted to your situation. It works of course if you have some autocmd
that invokes mkview
to save the fold's state before your own autocmd
acts, and another that restores it afterwards.
I'm thinking you might want to define a function that does all three in a row (save the view in this way, do what your original autocmd
did, then restore the view in this way), then have your autocmd
invoke that function (as to save folds, do the indentation stuff, restore folds). I don't know if this will work for your problem, but it's probably worth a shot.
:h :mkview
)2g;zz
.