Cloud
Cloud

Reputation: 19323

Bulk file re-formatting for "cpp" files with VIM

I have a number of large projects consisting of several .cpp and .h files. The indentation styles are a mess (hard-tab, spaces, and every possible mix of them), trailing whitespace at end-of-line, line-ending consolidation. I can currently resolve all these issues in VIM by opening a file, and issuing the following commands:

How could I run the above commands in batch mode? My best solution so far is to create a custom .VIMRC that runs the above commands and exits VIM when done, like in various SO questions. However, this sometimes fails due to searches failing to find a match, and the automation script then fails.

Is there a more robust approach than custom .VIMRC files, such as a string of commands passed directly at the command line to VIM?

Upvotes: 0

Views: 171

Answers (2)

Micah Elliott
Micah Elliott

Reputation: 10274

I recommend you not take a Vim-only approach to this, unless:

  • you're going to be the only developer on “a number of large projects”, or
  • you can get every other developer to start using your new shared .vimrc.

A better approach is to establish coding/editing standards and codify them into your VCS’s commit hooks.

A tool for this is the oldie-but-goodie indent (see its man page). You can create a .indent.pro file that can be shared to enforce a shared style. The Ruby project appears to enforce style this way. Note that its support for C++ may be insufficient for some of your needs.

For starters, you’d want to pick the styles you think are superior, and then run indent recursively across the projects.

Upvotes: 1

FDinoff
FDinoff

Reputation: 31439

If you want to run everything on the command line you can use the following.

vim -c 'argdo set ff=unix | %s/\s\+$//ge | normal gg=G' -c 'wqa' <list of files>

vim can take normal mode commands with -c. I used argdo to run set ff=unix | %s/\s\+$//ge | normal gg=G on every argument provided to vim. I used set ff=unix instead of :%s/^M//g since you are asking to change the file format to have unix line endings. (You could also just run dos2unix on all the files.) Next %s/\s\+$//ge is run on the whole buffer removing trailing whitespace. The e flag is necessary just incase there isn't any trailing whitespace. Lastly normal gg=G runs gg=G in normal mode.

After argdo is done we run wqa which saves and quits all the files.

(If you actually have carriage returns in the file and you can use :%s/\r//ge to remove them instead of set ff=unix)

Upvotes: 3

Related Questions