Skip to content

Add support for indent (C autoformatter) #4817

Open
@lloeki

Description

@lloeki

Name: indent
URL: https://www.gnu.org/software/indent/

indent(1) is a program for automatically formatting C code. The GNU variant supports common style shortcuts such as -kr.

This small UNIX trickery makes it a linter as well:

$ cat > main.c <<'EOF'
#include <stdio.h>

void printNumbers(int start, int end)

{
    for (int i = start; i <= end; i++) {
        if (i % 2 == 0) {
            printf("%d is even.\n", i);
        } else {
            printf("%d is odd.\n", i);
        }
    }
}

int main() {
    int start = 1;
    int end = 10;
       printNumbers(start, end);
    return 0;
}
EOF
$ diff -u main.c <(indent -kr -ts1 main.c -o /dev/stdout)
--- main.c	2024-08-08 12:25:23.743927683 +0200
+++ /dev/fd/63	2024-08-08 12:25:26.142459754 +0200
@@ -1,7 +1,6 @@
 #include <stdio.h>
 
 void printNumbers(int start, int end)
-
 {
     for (int i = start; i <= end; i++) {
         if (i % 2 == 0) {
@@ -12,9 +11,10 @@
     }
 }
 
-int main() {
+int main()
+{
     int start = 1;
     int end = 10;
-       printNumbers(start, end);
+    printNumbers(start, end);
     return 0;
 }
$ echo $?
1
$ indent -kr -ts1 main.c
$ diff -u main.c <(indent -kr -ts1 main.c -o /dev/stdout)
$ echo $?
0

There's no message but the diff can be processed to output a simple generic "lint error" on relevant lines which would already go a long way. It could also be processed to suggest fixes.

It can also read from stdin if so desired:

cat main.c | indent -kr -ts1 /dev/stdin -o /dev/stdout

Manuals:

Both modify in place and produce backup files if no output file is provided, this is probably undesirable so the /dev/stdout trickery might be preferred.

BSD indent does not use -o for output but a mere additional argument instead: GNU vs BSD should be detected to pass things around properly.

BSD indent supports much less features too, notably it does not support common styles like -kr and not all of what's behind -kr so if BSD indent is detected it could be convenient to have high level options to mimic GNU style flags when BSD indent is detected, e.g K&R would be:

indent -nbad -bap -nbc -br -c33 -cd33 -ncdb -ce -ci4 -cli0 -d0 -di1 -nfc1 -i4 -ip -lp -npcs -npsl -nsc -nsob main.c /dev/stdout`

So having a g:ale_c_indent_style = 'kr' would automatically (e.g by setting g:ale_c_indent_options) use -kr with GNU indent and the above with BSD indent.

Metadata

Metadata

Assignees

No one assigned

    Labels

    new toolSupport for new linters, fixers, etc.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions