Wednesday, August 22, 2012

How to automate the process of formatting code to meet coding standards while working with vim/emacs

It will help everybody if the code that you write follows coding standards.


Following are the challenges in doing it on a daily basis.

1 ) While writing code , people may not have the patience to enforce coding standards.
2 ) Different people will have their own personal preferences when it comes to coding standards such as K&R style, GNU style or Allman style and it takes a lot of effort to enforce a common style across all those who write code (ref : http://en.wikipedia.org/wiki/Indent_style )
3 ) A lot of code is already existing which does not follow a specific coding standard.

Under these circumstances, it would have been great if there was an automatic code formatting tool which is customizable to meet our specific requirements.

Fortunately , there is one !

That is the GNU indent tool 
(Please refer man indent || http://www.gnu.org/software/indent/manual/)

With indent, let your code be in any format ( or no format at all ), it will reformat your code for you , and present it to you in the way you need.

indent can be used in the Makefile's 'clean' section , so that the code is formatted every time you do a 'make clean'
This way it is ensured that the code is formatted with zero manual effort.

Following is an example section from Makefile (Please refer the man page to know more about what the different switches mean)

clean:
  rm -f *.o objs/*.o
  indent -kr  *.c include/*.h

Please note the following points while using indent.

1) Indent modifies your original source file . This way if your source file did contain any error (like a missing brace) indent may change your file to an illegible format. However this is not a problem as indent always backs up your original source file with the name 'original_file.c~' , as shown in the example below.

srcs]$ ls test.c*
test.c
srcs]$ indent -kr  test.c
srcs]$ ls test*
test.c  test.c~

2)Indent doesn't like the "// hi i am a comment" style of commenting. If it finds such comments it will format it to multiple lines, which will not look pretty.
Please take care to use the "/* hi i am a comment*/ " style of commenting while using indent

3)If a checked out source file is formatted with indent, the repository (svn for example) will show the file as modified even if you did not change any part of the file. However this is applicable only the first time you run indent. After the indented file is committed back to repository the first time, the file will be shown as modified only if there is a change done by the programmer.