Script to indent your C and kernel files

Steps to create a script/command for indentation:

1. Create a file named "indent_cmd" without any extension. (Do not name it "indent" as there is already a command of that name in linux, which we will use too).
    # vi indent_cmd   

2. Copy the following in the file:
    indent -cbi5 -i5 -ci5 -cli5 -l100 -lps -cd50 -cs -br -ce -brs -bs -bad -bap -bbb -sob -nsc -saf -sai -saw -ts5 $1; rm "$1"~
3. Save and exit the file.
4. Now copy the file under /usr/bin.
    # cp indent_cmd /usr/bin/indent_cmd
    This we do because /usr/bin lies in teh default PATH environment variable of your Ubuntu. If this is not the case then the command would not be located by default. In that case you will have to either add /usr/bin to your PATH variable or put indent_cmd into the 'bin' folder present in your PATH environmental variable.

5. Your command is ready to be used. To use the command:
    # indent_cmd <name of the file to be indented>
indent_cmd follows the rules of GNU linux and is good for indenting C, C++ and kernel files.
Note:- It will be executed as a script of your default shell. To execute it as bash script please put '#!/bin/sh' on the first line.

Following is the detailed explanation of switches used above:

1. cbin  :- Indent braces after a case label 'n' spaces.
3. in      :- Set indentation level to n spaces.
4. cin    :- Continuation indent of n spaces.
5. clin   :- Case label indent of n spaces.
6. ln      :- Set maximum line length for non-comment lines to n. For breaking long lines.
7. lps     :- Leave space between # and preprocessor directive.
8. cd      :- Put comments to the right of the declarations in column n.
9. cs      :- Put a space after a cast operator.
10. br    :- Put braces on line with if, for, switch, etc.
11. ce    :- Cuddle else and preceding { on the same line as }.
12. brs   :- Put braces on struct declaration line.
13. bs     :- Put a space between sizeof and its argument.
14. bad   :- Force blank lines after the declarations.
15. bap   :- Force blank lines after procedure bodies.
16. bbb   :- Force blank lines before block comments.
17. sob   :- Swallow optional blank lines.
18. nsc   :- Do not put the â*â character at the left of comments.    
19. saf   :- Put a space after each for.
20. sai   :- Put a space after each if.
21. saw  :- Put a space after each while.
22. ts     :- Set tab size to n spaces.

Note: By default 'indent' command creates a <filename>~ backup file (file before indentation). The last part fo the command 'rm "$1"~' deletes this backup file. Do not use this if you want to keep the backup file.

You can do 'man indent' for further switches.

Happy Indenting!!

No comments:

Post a Comment