DWQA QuestionsCategory: Development ToolHow to format this code quickly in VIM?
luofeiyu asked 2 months ago
#include<stdio.h>
int main(int argc, char *argv[])
{
int i=0;
if (i != 0) {i++; }
else {i--; };
for(i=0;i<5;i++)j++;
printf("i=%d,j=%d\n",i,j);
return 0;
}

How can the above code be quickly formatted like this?

#include 
int main(int argc ,char* argv[])
{
    int a = 4;
    int b = 5;
    int f_a = factorial(a);
    int f_b = factorial(b);
    while(1)
    {
        if(cmp(f_a,f_b))
        {
            printf("f_a is bigger than f_b\n");
        }
        else
        {
            printf("f_a is not bigger than f_b\n");
        }
        sleep(100);
    }     
    return 0;
    }
    
    Without plug-ins, can I write a simple template file to format the file?
    
    The answer of 10086 is wrong.
    ggvG
    =
    Become
    
#include<stdio.h>
int main(int argc, char *argv[])
{
        int i=0;
        if (i != 0) {i++; }
        else {i--; };
        for(i=0;i<5;i++)j++;
        printf("i=%d,j=%d\n",i,j);
        return 0;
}
9 Answers
10086 answered 2 months ago

Step one:ggvG///< first go back to the first line, then select mode, select all codes
The second step:=///In general, it is used for equal layout, which means code indentation. Under VIM multiple splits, you can also adjust the size of each split equally

laxtiz replied 2 months ago

gg=G

chuzirui answered 2 months ago

gg
vG
=

zhanglue answered 2 months ago

Yes, 10086 and tdblq didn’t pay attention to the requirement of the subject for brackets
First order

%s/ {/^M{^M/g
%s/ }/^M}/g
%s/};/}/g
%s/)\([^;]\+\);/)^M;/g
gg
=G

Lines 1 – 3 deal with curly braces
Line 4 is to solve

for(i=0;i<5;i++)j++;
Become
for(i=0;i<5;i++)
    j++;

Lines 5 to 6 are indented automatically
Be carefulThe ^ m is not directly input, but the result of “Ctrl + V” + “enter”
But these are just to solve the problem of format
The main idea is to “format” the code of a for loop to a code with while,
I guess it’s a clerical error, isn’t it?

The northwest peak answered 2 months ago

In fact, strictly speaking, VIM is uncertain. All GG = g can do is adjust the indentation in behavior units. Really, LZ needs external tools, such as indent. Suppose you have a perfect indent configuration. Then you can use%! Indent in VIM

Select the line to indent, enter the line mode with big V, and then directly press > right indent, < left indent, row by row, row by row_