Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question
4  
Of note is GNU Indent which does this all by itself, and is well tested. Avoiding reinventing the wheel, etc. –  Daniel Andersson Nov 25 '12 at 10:48

2 Answers 2

up vote 5 down vote accepted

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.)

share|improve this answer
    
You have the best Vim answers :) +1 –  Ярослав Рахматуллин Sep 16 '13 at 9:26

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.