Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AStyle in Vim

I am trying to get AStyle working with Vim so that I can use the "=" key to re-indent various sections of code. For example, I'd like to be able to type my usual =iB to indent the current block of code using AStyle rather than the built in indenter.

I tried just setting equalprg=astyle in my vimrc, but the problem is that astyle only receives the selected block but thinks that it's receiving a whole file. Therefore, the indentation is completely off when I try to only indent a nested class.

I know that I can always reformat an entire file at once, but is there a way to use astyle in vim which completely replicates the original formatting behavior of vim (all my =-movement commands work - and bonus points for autoindent using astyle as well!)?

like image 340
rcv Avatar asked Jan 03 '11 20:01

rcv


1 Answers

Unless there is a version of AStyle that has a partial file formatting option, you'll need to apply the extra indentation after you run AStyle.

I'm not sure how you can do this with motions.

With visual selection, you could grab the indentation from the first line, pass the code to equalprg, and then add that indentation to all of the lines:

vnoremap = <Esc>`<dwgv=`<<C-v>`>I<C-r>"<Esc>

Breaking it down:

vnoremap -- so we can use = for equalprg
<Esc>`< -- stop selecting and go to beginning of line at beginning of selection
dw -- grab the initial indentation
gv= -- reselect and indent as normal
`<<C-v>`> -- block select the selection
I<C-r>"<Esc> -- insert the initial indentation

Maybe you can do something similar with motions?

like image 181
idbrii Avatar answered Sep 23 '22 11:09

idbrii