indent主要用來排版C code,因為coding風格差異其實不小(BSD/GNU/K&R/linux,其實最主要是很多人喜歡自創風格),但是如果大家都能使用特定的coding風格,相信熟悉此一風格的人很快的就能進入狀況。 但是,現在流行混搭風,有些地方用BSD,某些又跟隨gnu的風格,實在是有點小亂,慘的是,還有自創風格,雖說coding風格一致即可,不過要一群人跟隨你的風格可能也是不妥。
所以,我們可以利用indent,將code排成某特定風格,這樣大家都能很快的進入狀況。對於code的編排風格,建議先參考http://en.wikipedia.org/wiki/Indent_style,了解一下各大宗的原始風貌,再來研究indent(我也是混搭風的愛好者@@)
原始程式碼
brook@ctc-desktop:~$ cat xx.c
#include <stdio.h>
int main(int argc, char *argv[])
{
int x;
for(x=0;x<10;x++) { printf("%d\n", x); }
switch(x) {
case 1:
printf("one\n");
break;
default:
printf("default\n");
}
if(x==0) {printf("zero\n");}
else if (x==2) {printf("two\n");}
else {printf("no match\n");}
return 0;
}
K&R的風格
brook@ctc-desktop:~$ indent -kr -st xx.c
#include <stdio.h>
int main(int argc, char *argv[])
{
int x;
for (x = 0; x < 10; x++) {
printf("%d\n", x);
}
switch (x) {
case 1:
printf("one\n");
break;
default:
printf("default\n");
}
if (x == 0) {
printf("zero\n");
} else if (x == 2) {
printf("two\n");
} else {
printf("no match\n");
}
return 0;
}
gnu的風格
brook@ctc-desktop:~$ indent -gnu -st xx.c
#include <stdio.h>
int
main (int argc, char *argv[])
{
int x;
for (x = 0; x < 10; x++)
{
printf ("%d\n", x);
}
switch (x)
{
case 1:
printf ("one\n");
break;
default:
printf ("default\n");
}
if (x == 0)
{
printf ("zero\n");
}
else if (x == 2)
{
printf ("two\n");
}
else
{
printf ("no match\n");
}
return 0;
}
Linux的風格
brook@ctc-desktop:~$ indent -linux -st xx.c
#include <stdio.h>
int main(int argc, char *argv[])
{
int x;
for (x = 0; x < 10; x++) {
printf("%d\n", x);
}
switch (x) {
case 1:
printf("one\n");
break;
default:
printf("default\n");
}
if (x == 0) {
printf("zero\n");
} else if (x == 2) {
printf("two\n");
} else {
printf("no match\n");
}
return 0;
}
我常用的選項 -st, --standard-output
寫到stdout去, 可以先在螢幕上確認是否是自己要的風格.
-i, --indent-level
縮排要用幾個空白.
-cli, --case-indentation
case要往內縮幾個空白
-nut, --no-tabs
使用空白取代tab
個人偏愛的風格 indent -kr -st -i4 -cli4 -nut xx.c
brook@ctc-desktop:~$ indent -kr -st -i4 -cli4 xx.c
#include <stdio.h>
int main(int argc, char *argv[])
{
int x;
for (x = 0; x < 10; x++) {
printf("%d\n", x);
}
switch (x) {
case 1:
printf("one\n");
break;
default:
printf("default\n");
}
if (x == 0) {
printf("zero\n");
} else if (x == 2) {
printf("two\n");
} else {
printf("no match\n");
}
return 0;
}

沒有留言:
張貼留言