tags:

views:

92

answers:

3

Hi,

I know that using VIM I can format C++ code just using

gg=G

Now I have to format 30 files, so doing it by hand becomes tedious. I had a look how to do it passing external commands to VIM, so I tried

vim -c gg=G -c wq file.cpp

but it does not work.

Can you give me a hint?

Thanks

+8  A: 

Why not load all the files up in buffers and use bufdo to execute the command on all of them at one time?

:bufdo "execute normal gg=G"
michaelmichael
how can you load up all the files in buffers? using a "for" loop in bash script? thanks
Werner
No need for a script if your shell supports file globbing. For example, if I wanted to load up all the ruby files in the directory `~/mycode`, I'd type `$ vim ~/mycode/*.rb`
michaelmichael
great! I achieved to edit them all. Now how can I save them? I tried :bufdo "execute normal wq" but it does not work
Werner
last thing, I checked that doing :bufdo "execute normal gg=G" over an individual file does not work
Werner
all you need is `:wqa`. It means write quit all.
michaelmichael
+5  A: 

Change -c gg=G to -c 'normal! gg=G'. -c switch accepts only ex mode commands, gg=G are two normal mode commands.

ZyX
+1  A: 

I prefer a slight change on the :bufdo answer. I prefer the arg list instead of the buffer list, so I don't need to worry about closing current buffers or opening up new vim session. For example:

:args ~/src/myproject/**/*.cpp | argdo execute "normal gg=G" | update
  • args sets the arglist, using wildcards (** will match the current directory as well as subdirectories)
  • | lets us run multiple commands on one line
  • argdo runs the following commands on each arg (it will swallow up the second |)
  • execute prevents normal from swallowing up the next pipe.
  • normal runs the following normal mode commands (what you were working with in the first place)
  • update is like :w, but only saves when the buffer is modified.

This :args ... | argdo ... | update pattern is very useful for any sort of project wide file manipulation (e.g. search and replace via '%s/foo/bar/ge' or setting uniform fileformat or fileencoding).

nicholas a. evans