Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Code formatting and indentation in VIM

Answer:

Vim support code formatting and auto indentation - if you tell Vim to know the filetype (either by file extension, or by setting the filetype)

e.g. A simple C program (test.c)


#include 

main()
{
for(int i=0;i<10;i++)
{
printf ("Hello World!\n");
}
}

Then type following in Vim command mode (by pressing Esc):

gg=G

Now the code will be formatted to:

#include 

main()
{
    for(int i=0;i<10;i++)
    {
        printf ("Hello World!\n");
    }
}

How to set the filetype in Vim

Answer:

When you created a new file by using the command vi, vim does not know the file type unless you save the file with a specific extension, e.g. test.c, or sometimes when the extension cannot be recognized by vim, you need to set the file type manually in command mode - pressing Esc + :

:set filetype=c

That is it.

Open two files side by side using vim

Answer:

If you have two files, you want to open both of them in vi/vim and edit side by side, you can do the following.

# vim -O foo.txt bar.txt

Replace text in vi with confirmation

Answer:

Similar to this article, you want to replace text, but you want to vi/vim to ask for confirmation before the actual replacements.

:%s/foo/bar/gc

Replace text in vi

Answer:

To replace a text in a file using vi/vim

Enter the command mode by typing :, and use the %s/foo/bar/g for global replacement(s).

:%s/foo/bar/g

All foo in the file will be replaced by bar