3

I have a c project with multiple files (more than 100), the codes are written in Whitesmiths style, but I want to change them into K&R style indentation. Is it possible to do using vim in an automated way ?

For example I have a emacs-lisp script to achieve this --

(progn 
  (find-file "{}") 
  (mark-whole-buffer) 
  (setq indent-tabs-mode nil) 
  (untabify (point-min) (point-max)) 
  (indent-region (point-min) (point-max) nil) 
  (save-buffer))

I was wondering if there is a similar trick that could be done with vim.

Update: I have found another nice tool called astyle, which supports auto-indentation for different languages (with a wide range of styles) as well.

ramgorur
  • 209

2 Answers2

5

Either pass all C files to the Vim executable vim file1.c dir/file2.c, or add them as arguments from inside Vim (see :help file-searching):

:args **/*.c **/*.h

Then, you can mass-edit them via :argdo. Vim has a built-in indenting mechanism, or it can use an external code formatter. Read up on the details at :help C-indenting.

Once you've configured the indent settings ('cindent', 'cinoptions', etc.), you can apply all files via

:argdo execute 'normal! ggVG=' | update

(ggVG selects the entire buffer in visual mode, = then re-formats.)

Ingo Karkat
  • 23,523
4

man indent *scroll scroll scroll*

   The Kernighan & Ritchie style is used  throughout  their  well-known  book
   "The  C  Programming Language".  It is enabled with the ‘-kr’ option.  The
   Kernighan & Ritchie style corresponds to the following set of options:

        -nbad -bap -bbo -nbc -br -brs -c33 -cd33 -ncdb -ce -ci4 -cli0
        -cp33 -cs -d0 -di1 -nfc1 -nfca -hnl -i4 -ip0 -l75 -lp -npcs
        -nprs -npsl -saf -sai -saw -nsc -nsob -nss

E.g.:

indent -kr source.cpp