{"id":10586,"date":"2025-05-12T03:00:00","date_gmt":"2025-05-12T07:00:00","guid":{"rendered":"https:\/\/www.both.org\/?p=10586"},"modified":"2025-05-05T19:25:50","modified_gmt":"2025-05-05T23:25:50","slug":"how-i-use-gnu-indent","status":"publish","type":"post","link":"https:\/\/www.both.org\/?p=10586","title":{"rendered":"How I use GNU Indent"},"content":{"rendered":"<div class=\"pld-like-dislike-wrap pld-template-1\">\r\n    <div class=\"pld-like-wrap  pld-common-wrap\">\r\n    <a href=\"javascript:void(0)\" class=\"pld-like-trigger pld-like-dislike-trigger  \" title=\"\" data-post-id=\"10586\" data-trigger-type=\"like\" data-restriction=\"cookie\" data-already-liked=\"0\">\r\n                        <i class=\"fas fa-thumbs-up\"><\/i>\r\n                <\/a>\r\n    <span class=\"pld-like-count-wrap pld-count-wrap\">    <\/span>\r\n<\/div><\/div>\n<p>Compilers don\u2019t care if you use spaces or tabs and they don\u2019t care if you put instructions on new lines; as long as program statements end with a semicolon (in C-like languages) and is otherwise <em>syntactically correct<\/em>, your program should compile fine.<\/p>\n\n\n\n<p>But these are long-standing and strongly-help beliefs among many developers. In fact, you may find a patch is rejected by a program maintainer because your coding style does not match theirs.<\/p>\n\n\n\n<p>That\u2019s where it helps to have a tool to do all of the hard work for you, to reformat your source code so statements are nested and arranged correctly.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"coding-styles\">Coding styles<\/h2>\n\n\n\n<p>Throughout the history of programming, there have been several common styles of writing C source code. The original \u201cKernighan and Ritchie\u201d style, used throughout their original book that described the C programming language, was one common style. The UCB developers adopted a slightly different coding style. The GNU Project uses its own style for coding, as do the Linux kernel developers.<\/p>\n\n\n\n<p>Here\u2019s a sample program to show you what I mean. The program prints the numbers from 1 to 10. For any number less than 5, the program prints <strong>foo<\/strong>; for any numbers greater than 5, it prints <strong>bar<\/strong>. The program might be written in original \u201cK&amp;R\u201d style like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;stdio.h&gt;\n\nint main()\n{\n    int i;\n\n    for (i = 1; i &lt;= 10; i++) {\n        printf(\"%d\", i);\n        if (i &lt; 5) {\n            puts(\"foo\");\n        } else if (i &gt; 5) {\n            puts(\"bar\");\n        }\n        putchar('\\n');\n    }\n\n    return 0;\n}<\/code><\/pre>\n\n\n\n<p>Note that lines are indented by four spaces at each level. Also, brackets are inline with the <code>if<\/code> and <code>else<\/code> statements, and the <code>else<\/code> statement is \u201ccuddled\u201d next to the ending bracket for the <code>if<\/code> statement. This style was efficient to write in a book, requiring fewer lines (and thus fewer pages to print) at a time when printed books were more expensive to produce.<\/p>\n\n\n\n<p>The GNU coding style favors vertical space instead, so the program source code is easier to read on a high resolution display. The brackets for the <code>if<\/code> and <code>else<\/code> appear on the next line, indented by a few extra spaces. Also, the return type for the <code>main<\/code> function is on a different line:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;stdio.h&gt;\n\nint\nmain ()\n{\n  int i;\n\n  for (i = 1; i &lt;= 10; i++)\n    {\n      printf (\"%d\", i);\n      if (i &lt; 5)\n        {\n          puts (\"foo\");\n        }\n      else if (i &gt; 5)\n        {\n          puts (\"bar\");\n        }\n      putchar ('\\n');\n    }\n\n  return 0;\n}<\/code><\/pre>\n\n\n\n<p>The Linux kernel developers adopt a different style, preferring tabs at each indent level. Also, the <code>else<\/code> is \u201ccuddled\u201d after the closing bracket from the <code>if<\/code> block. The result is code that is more \u201cdense\u201d vertically and easier to adjust to each programmer\u2019s preferences simply by changing the tab stops in the text editor:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;stdio.h&gt;\n\nint main()\n{\n        int i;\n\n        for (i = 1; i &lt;= 10; i++) {\n                printf(\"%d\", i);\n                if (i &lt; 5) {\n                        puts(\"foo\");\n                } else if (i &gt; 5) {\n                        puts(\"bar\");\n                }\n                putchar('\\n');\n        }\n\n        return 0;\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"formatting-code-with-indent\">Formatting code with Indent<\/h2>\n\n\n\n<p>When a Unix variant was under development at the University of California at Berkeley, the UCB developers added new programs that were useful to them. One such program was Indent, which reformats C program source code according to a set of rules. This is such a useful program that the GNU Project created their own implementation, which you should find on every Linux system.<\/p>\n\n\n\n<p>I\u2019ll often create a sample program so I can write an article about it. When I do, I want to be sure that the code is easy to read, and doesn\u2019t take up too much room on the screen or in print. I\u2019ve been writing C code since the 1990s, not long after the ANSI organization adopted the C programming language standard (\u201cANSI C\u201d) so perhaps it\u2019s not too surprising that my preferred coding style is not too different from the \u201cK&amp;R C\u201d style. However, I do have a few differences due to personal preference: I don\u2019t use tabs, I like to align comments at column 40 (half-way across an 80-column terminal display) and I don\u2019t \u201ccuddle\u201d the <code>else<\/code> and the <code>if<\/code> blocks.<\/p>\n\n\n\n<p>When I need to reformat my code, I use Indent to do it for me. Because I don\u2019t want to type all of the command line options all the time, I wrote a short script to run Indent for me:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#!\/bin\/bash\nindent -kr --no-tabs -c40 --dont-cuddle-else \"$@\"<\/code><\/pre>\n\n\n\n<p>This starts Indent with the defaults for \u201cK&amp;R C\u201d style, then modifies it to never use tabs (<code>--no-tabs<\/code>) and align same-line comments at column 40 (<code>-c40)<\/code>. Finally, the command line tells Indent not to \u201ccuddle\u201d the <code>else<\/code> and <code>if<\/code> blocks together, so it starts <code>else<\/code> on a new line. The <code>\"$@\"<\/code> at the end is a Bash expansion to include any files that I might specify on the command line, so Indent can process each of them. I called this script <strong>reindent<\/strong> because it\u2019s something I can easily remember, and it\u2019s not exactly the same as the <strong>indent<\/strong> command.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"reformatting-the-foo-bar-program\">Reformatting the foo-bar program<\/h2>\n\n\n\n<p>Let\u2019s look at the sample \u201cfoo-bar\u201d program. To reformat the source code to my preferred style, I type:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ reindent foo.c<\/code><\/pre>\n\n\n\n<p>This saves a copy of the old <code>foo.c<\/code> file as <code>foo.c~<\/code> which is a nice backup in case I need to revert to it. The original <code>foo.c<\/code> gets reformatted to use my preferred style:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;stdio.h&gt;\n\nint main()\n{\n    int i;\n\n    for (i = 1; i &lt;= 10; i++) {\n        printf(\"%d\", i);\n        if (i &lt; 5) {\n            puts(\"foo\");\n        }\n        else if (i &gt; 5) {\n            puts(\"bar\");\n        }\n        putchar('\\n');\n    }\n\n    return 0;\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"reformatting-made-easy\">Reformatting made easy<\/h2>\n\n\n\n<p>Indent is also really useful for times when I might create a program very quickly, without paying too much attention to my coding style. With Indent, I know that I can always reformat my code to use my preferred style.<\/p>\n\n\n\n<p>Here\u2019s one example. I wrote a program to generate the printable ASCII characters. I wrote this using <strong>ed<\/strong>, the classic line editor. I just tapped out a quick program without any special formatting, because it was easier to write a program that way in a line editor:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;stdio.h&gt;\n\nint main()\n{\n        int r, c;\n\n        \/* body *\/\n\n        for (r=' ';r&lt;=127;r+=16) {\n                for (c=0;c&lt;16;c++) {\n                        putchar(r+c); putchar(' ');\n                }\n\n                putchar('\\n'); \/* end of line *\/\n        }\n\n        return 0;\n}<\/code><\/pre>\n\n\n\n<p>That program generates a simple ASCII table, but without any notation to tell me the <em>value<\/em> for each character:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  ! \" # $ % &amp; ' ( ) * + , - . \/ \n0 1 2 3 4 5 6 7 8 9 : ; &lt; = &gt; ? \n@ A B C D E F G H I J K L M N O \nP Q R S T U V W X Y Z &#91; \\ ] ^ _ \n` a b c d e f g h i j k l m n o \np q r s t u v w x y z { | } ~  <\/code><\/pre>\n\n\n\n<p>I made a quick edit to add a table header and labels on each row.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>-- 0 1 2 3 4 5 6 7 8 9 a b c d e f \n20   ! \" # $ % &amp; ' ( ) * + , - . \/ \n30 0 1 2 3 4 5 6 7 8 9 : ; &lt; = &gt; ? \n40 @ A B C D E F G H I J K L M N O \n50 P Q R S T U V W X Y Z &#91; \\ ] ^ _ \n60 ` a b c d e f g h i j k l m n o \n70 p q r s t u v w x y z { | } ~  <\/code><\/pre>\n\n\n\n<p>For example, this shows that the space character is 0x20, capital A is 0x41, and the underscore character is 0x5f.<\/p>\n\n\n\n<p>The easiest way to update the program was to copy the inner <code>for<\/code> loop to generate a header, then add a new line to write a label, and another line to make a placeholder on the header row. The updated program doesn\u2019t look very pretty, but is syntactically correct, and compiles without warnings:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;stdio.h&gt;\n\nint main()\n{\n        int r, c;\n\n        \/* header *\/\n\n        fputs(\"-- \", stdout);\n\n                for (c=0;c&lt;16;c++) {\n                        printf(\"%x \", c);\n                }\n\n                putchar('\\n'); \/* end of line *\/\n\n        \/* body *\/\n\n        for (r=' ';r&lt;=127;r+=16) {\n                printf(\"%x \", r);\n\n                for (c=0;c&lt;16;c++) {\n                        putchar(r+c); putchar(' ');\n                }\n\n                putchar('\\n'); \/* end of line *\/\n        }\n\n        return 0;\n}<\/code><\/pre>\n\n\n\n<p>To reformat the program to use my preferred coding style, I ran my <strong>reindent<\/strong> script and let Indent do the work for me:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ reindent ascii.c<\/code><\/pre>\n\n\n\n<p>This reformats the program source code in a way that makes it more readable and consistent:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;stdio.h&gt;\n\nint main()\n{\n    int r, c;\n\n    \/* header *\/\n\n    fputs(\"-- \", stdout);\n\n    for (c = 0; c &lt; 16; c++) {\n        printf(\"%x \", c);\n    }\n\n    putchar('\\n');                     \/* end of line *\/\n\n    \/* body *\/\n\n    for (r = ' '; r &lt;= 127; r += 16) {\n        printf(\"%x \", r);\n\n        for (c = 0; c &lt; 16; c++) {\n            putchar(r + c);\n            putchar(' ');\n        }\n\n        putchar('\\n');                 \/* end of line *\/\n    }\n\n    return 0;\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"try-gnu-indent\">Try GNU Indent<\/h2>\n\n\n\n<p>GNU Indent comes with a bazillion command line options to support all kinds of code formatting configurations. Read the <code>man indent<\/code> documentation to read more about what Indent can do for you. You can install Indent on your system using your package manager, such as <code>dnf<\/code> on Fedora Linux:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ sudo dnf install indent<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Let GNU Indent make your source code easier to read.<\/p>\n","protected":false},"author":33,"featured_media":2725,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_lmt_disableupdate":"","_lmt_disable":"","footnotes":""},"categories":[150],"tags":[152],"class_list":["post-10586","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-programming","tag-programming"],"modified_by":"Jim Hall","_links":{"self":[{"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/10586","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/users\/33"}],"replies":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10586"}],"version-history":[{"count":2,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/10586\/revisions"}],"predecessor-version":[{"id":10588,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/10586\/revisions\/10588"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/media\/2725"}],"wp:attachment":[{"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10586"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10586"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10586"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}